]> git.mxchange.org Git - friendica.git/blob - src/App.php
f698d06c8280dca36a6dc3e7fb85f57a74d330c3
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use DOMDocument;
9 use DOMXPath;
10 use Exception;
11 use FastRoute\RouteCollector;
12 use Friendica\Core\Config\Cache\IConfigCache;
13 use Friendica\Core\Config\Configuration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Theme;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Profile;
18 use Friendica\Network\HTTPException\InternalServerErrorException;
19 use Friendica\Util\Config\ConfigFileLoader;
20 use Friendica\Util\HTTPSignature;
21 use Friendica\Util\Profiler;
22 use Friendica\Util\Strings;
23 use Psr\Log\LoggerInterface;
24
25 /**
26  *
27  * class: App
28  *
29  * @brief Our main application structure for the life of this page.
30  *
31  * Primarily deals with the URL that got us here
32  * and tries to make some sense of it, and
33  * stores our page contents and config storage
34  * and anything else that might need to be passed around
35  * before we spit the page out.
36  *
37  */
38 class App
39 {
40         public $module_class = null;
41         public $query_string = '';
42         public $page = [];
43         public $profile;
44         public $profile_uid;
45         public $user;
46         public $cid;
47         public $contact;
48         public $contacts;
49         public $page_contact;
50         public $content;
51         public $data = [];
52         public $error = false;
53         public $cmd = '';
54         public $argv;
55         public $argc;
56         public $module;
57         public $timezone;
58         public $interactive = true;
59         public $identities;
60         public $is_mobile = false;
61         public $is_tablet = false;
62         public $theme_info = [];
63         public $category;
64         // Allow themes to control internal parameters
65         // by changing App values in theme.php
66
67         public $sourcename = '';
68         public $videowidth = 425;
69         public $videoheight = 350;
70         public $force_max_items = 0;
71         public $theme_events_in_profile = true;
72
73         public $stylesheets = [];
74         public $footerScripts = [];
75
76         /**
77          * @var App\Mode The Mode of the Application
78          */
79         private $mode;
80
81         /**
82          * @var string The App URL path
83          */
84         private $urlPath;
85
86         /**
87          * @var bool true, if the call is from the Friendica APP, otherwise false
88          */
89         private $isFriendicaApp;
90
91         /**
92          * @var bool true, if the call is from an backend node (f.e. worker)
93          */
94         private $isBackend;
95
96         /**
97          * @var string The name of the current theme
98          */
99         private $currentTheme;
100
101         /**
102          * @var bool check if request was an AJAX (xmlhttprequest) request
103          */
104         private $isAjax;
105
106         /**
107          * @var MobileDetect
108          */
109         public $mobileDetect;
110
111         /**
112          * @var Configuration The config
113          */
114         private $config;
115
116         /**
117          * @var LoggerInterface The logger
118          */
119         private $logger;
120
121         /**
122          * @var Profiler The profiler of this app
123          */
124         private $profiler;
125
126         /**
127          * Returns the current config cache of this node
128          *
129          * @return IConfigCache
130          */
131         public function getConfigCache()
132         {
133                 return $this->config->getCache();
134         }
135
136         /**
137          * The basepath of this app
138          *
139          * @return string
140          */
141         public function getBasePath()
142         {
143                 return $this->config->get('system', 'basepath');
144         }
145
146         /**
147          * The Logger of this app
148          *
149          * @return LoggerInterface
150          */
151         public function getLogger()
152         {
153                 return $this->logger;
154         }
155
156         /**
157          * The profiler of this app
158          *
159          * @return Profiler
160          */
161         public function getProfiler()
162         {
163                 return $this->profiler;
164         }
165
166         /**
167          * Returns the Mode of the Application
168          *
169          * @return App\Mode The Application Mode
170          */
171         public function getMode()
172         {
173                 return $this->mode;
174         }
175
176         /**
177          * Register a stylesheet file path to be included in the <head> tag of every page.
178          * Inclusion is done in App->initHead().
179          * The path can be absolute or relative to the Friendica installation base folder.
180          *
181          * @see initHead()
182          *
183          * @param string $path
184          * @throws InternalServerErrorException
185          */
186         public function registerStylesheet($path)
187         {
188                 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
189                         $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
190                 }
191
192                 $this->stylesheets[] = trim($path, '/');
193         }
194
195         /**
196          * Register a javascript file path to be included in the <footer> tag of every page.
197          * Inclusion is done in App->initFooter().
198          * The path can be absolute or relative to the Friendica installation base folder.
199          *
200          * @see initFooter()
201          *
202          * @param string $path
203          * @throws InternalServerErrorException
204          */
205         public function registerFooterScript($path)
206         {
207                 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
208
209                 $this->footerScripts[] = trim($url, '/');
210         }
211
212         public $queue;
213         private $scheme;
214         private $hostname;
215
216         /**
217          * @brief App constructor.
218          *
219          * @param Configuration    $config    The Configuration
220          * @param App\Mode         $mode      The mode of this Friendica app
221          * @param LoggerInterface  $logger    The current app logger
222          * @param Profiler         $profiler  The profiler of this application
223          * @param bool             $isBackend Whether it is used for backend or frontend (Default true=backend)
224          *
225          * @throws Exception if the Basepath is not usable
226          */
227         public function __construct(Configuration $config, App\Mode $mode, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
228         {
229                 BaseObject::setApp($this);
230
231                 $this->logger   = $logger;
232                 $this->config   = $config;
233                 $this->profiler = $profiler;
234                 $this->mode     = $mode;
235
236                 $this->checkBackend($isBackend);
237                 $this->checkFriendicaApp();
238
239                 $this->profiler->reset();
240
241                 $this->reload();
242
243                 set_time_limit(0);
244
245                 // This has to be quite large to deal with embedded private photos
246                 ini_set('pcre.backtrack_limit', 500000);
247
248                 $this->scheme = 'http';
249
250                 if (!empty($_SERVER['HTTPS']) ||
251                         !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
252                         !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
253                         !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
254                         !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
255                         !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
256                 ) {
257                         $this->scheme = 'https';
258                 }
259
260                 if (!empty($_SERVER['SERVER_NAME'])) {
261                         $this->hostname = $_SERVER['SERVER_NAME'];
262
263                         if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
264                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
265                         }
266                 }
267
268                 set_include_path(
269                         get_include_path() . PATH_SEPARATOR
270                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
271                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
272                         . $this->getBasePath());
273
274                 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
275                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
276                 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
277                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
278                 }
279
280                 // removing trailing / - maybe a nginx problem
281                 $this->query_string = ltrim($this->query_string, '/');
282
283                 if (!empty($_GET['pagename'])) {
284                         $this->cmd = trim($_GET['pagename'], '/\\');
285                 } elseif (!empty($_GET['q'])) {
286                         $this->cmd = trim($_GET['q'], '/\\');
287                 }
288
289                 // fix query_string
290                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
291
292                 // unix style "homedir"
293                 if (substr($this->cmd, 0, 1) === '~') {
294                         $this->cmd = 'profile/' . substr($this->cmd, 1);
295                 }
296
297                 // Diaspora style profile url
298                 if (substr($this->cmd, 0, 2) === 'u/') {
299                         $this->cmd = 'profile/' . substr($this->cmd, 2);
300                 }
301
302                 /*
303                  * Break the URL path into C style argc/argv style arguments for our
304                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
305                  * will be 3 (integer) and $this->argv will contain:
306                  *   [0] => 'module'
307                  *   [1] => 'arg1'
308                  *   [2] => 'arg2'
309                  *
310                  *
311                  * There will always be one argument. If provided a naked domain
312                  * URL, $this->argv[0] is set to "home".
313                  */
314
315                 $this->argv = explode('/', $this->cmd);
316                 $this->argc = count($this->argv);
317                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
318                         $this->module = str_replace('.', '_', $this->argv[0]);
319                         $this->module = str_replace('-', '_', $this->module);
320                 } else {
321                         $this->argc = 1;
322                         $this->argv = ['home'];
323                         $this->module = 'home';
324                 }
325
326                 // Detect mobile devices
327                 $mobile_detect = new MobileDetect();
328
329                 $this->mobileDetect = $mobile_detect;
330
331                 $this->is_mobile = $mobile_detect->isMobile();
332                 $this->is_tablet = $mobile_detect->isTablet();
333
334                 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
335
336                 // Register template engines
337                 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
338         }
339
340         /**
341          * Reloads the whole app instance
342          */
343         public function reload()
344         {
345                 $this->determineURLPath();
346
347                 $this->getMode()->determine($this->getBasePath());
348
349                 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
350                         $loader = new ConfigFileLoader($this->getBasePath(), $this->getMode());
351                         $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
352
353                         $this->profiler->update(
354                                 $this->config->get('system', 'profiler', false),
355                                 $this->config->get('rendertime', 'callstack', false));
356
357                         Core\Hook::loadHooks();
358                         $loader = new ConfigFileLoader($this->getBasePath(), $this->mode);
359                         Core\Hook::callAll('load_config', $loader);
360                 }
361
362                 $this->loadDefaultTimezone();
363
364                 Core\L10n::init();
365         }
366
367         /**
368          * Loads the default timezone
369          *
370          * Include support for legacy $default_timezone
371          *
372          * @global string $default_timezone
373          */
374         private function loadDefaultTimezone()
375         {
376                 if ($this->config->get('system', 'default_timezone')) {
377                         $this->timezone = $this->config->get('system', 'default_timezone');
378                 } else {
379                         global $default_timezone;
380                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
381                 }
382
383                 if ($this->timezone) {
384                         date_default_timezone_set($this->timezone);
385                 }
386         }
387
388         /**
389          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
390          */
391         private function determineURLPath()
392         {
393                 /*
394                  * The automatic path detection in this function is currently deactivated,
395                  * see issue https://github.com/friendica/friendica/issues/6679
396                  *
397                  * The problem is that the function seems to be confused with some url.
398                  * These then confuses the detection which changes the url path.
399                  */
400
401                 /* Relative script path to the web server root
402                  * Not all of those $_SERVER properties can be present, so we do by inverse priority order
403                  */
404 /*
405                 $relative_script_path = '';
406                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL'       , $relative_script_path);
407                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI'       , $relative_script_path);
408                 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
409                 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL'         , $relative_script_path);
410                 $relative_script_path = defaults($_SERVER, 'REQUEST_URI'        , $relative_script_path);
411 */
412                 $this->urlPath = $this->config->get('system', 'urlpath');
413
414                 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
415                  * QUERY_STRING gives pagename=module/parameter
416                  *
417                  * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
418                  */
419 /*
420                 if (!empty($relative_script_path)) {
421                         // Module
422                         if (!empty($_SERVER['QUERY_STRING'])) {
423                                 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
424                         } else {
425                                 // Root page
426                                 $path = trim($relative_script_path, '/');
427                         }
428
429                         if ($path && $path != $this->urlPath) {
430                                 $this->urlPath = $path;
431                         }
432                 }
433 */
434         }
435
436         public function getScheme()
437         {
438                 return $this->scheme;
439         }
440
441         /**
442          * @brief Retrieves the Friendica instance base URL
443          *
444          * This function assembles the base URL from multiple parts:
445          * - Protocol is determined either by the request or a combination of
446          * system.ssl_policy and the $ssl parameter.
447          * - Host name is determined either by system.hostname or inferred from request
448          * - Path is inferred from SCRIPT_NAME
449          *
450          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
451          *
452          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
453          * @return string Friendica server base URL
454          * @throws InternalServerErrorException
455          */
456         public function getBaseURL($ssl = false)
457         {
458                 $scheme = $this->scheme;
459
460                 if ($this->config->get('system', 'ssl_policy') == SSL_POLICY_FULL) {
461                         $scheme = 'https';
462                 }
463
464                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
465                 //      (and also the login link). Anything seen by an outsider will have it turned off.
466
467                 if ($this->config->get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
468                         if ($ssl) {
469                                 $scheme = 'https';
470                         } else {
471                                 $scheme = 'http';
472                         }
473                 }
474
475                 if ($this->config->get('config', 'hostname') != '') {
476                         $this->hostname = $this->config->get('config', 'hostname');
477                 }
478
479                 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
480         }
481
482         /**
483          * @brief Initializes the baseurl components
484          *
485          * Clears the baseurl cache to prevent inconsistencies
486          *
487          * @param string $url
488          * @throws InternalServerErrorException
489          */
490         public function setBaseURL($url)
491         {
492                 $parsed = @parse_url($url);
493                 $hostname = '';
494
495                 if (!empty($parsed)) {
496                         if (!empty($parsed['scheme'])) {
497                                 $this->scheme = $parsed['scheme'];
498                         }
499
500                         if (!empty($parsed['host'])) {
501                                 $hostname = $parsed['host'];
502                         }
503
504                         if (!empty($parsed['port'])) {
505                                 $hostname .= ':' . $parsed['port'];
506                         }
507                         if (!empty($parsed['path'])) {
508                                 $this->urlPath = trim($parsed['path'], '\\/');
509                         }
510
511                         if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
512                                 include $this->getBasePath() . '/.htpreconfig.php';
513                         }
514
515                         if ($this->config->get('config', 'hostname') != '') {
516                                 $this->hostname = $this->config->get('config', 'hostname');
517                         }
518
519                         if (!isset($this->hostname) || ($this->hostname == '')) {
520                                 $this->hostname = $hostname;
521                         }
522                 }
523         }
524
525         public function getHostName()
526         {
527                 if ($this->config->get('config', 'hostname') != '') {
528                         $this->hostname = $this->config->get('config', 'hostname');
529                 }
530
531                 return $this->hostname;
532         }
533
534         public function getURLPath()
535         {
536                 return $this->urlPath;
537         }
538
539         /**
540          * Initializes App->page['htmlhead'].
541          *
542          * Includes:
543          * - Page title
544          * - Favicons
545          * - Registered stylesheets (through App->registerStylesheet())
546          * - Infinite scroll data
547          * - head.tpl template
548          */
549         public function initHead()
550         {
551                 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
552
553                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
554                 if ($interval < 0) {
555                         $interval = 2147483647;
556                 }
557
558                 if ($interval < 10000) {
559                         $interval = 40000;
560                 }
561
562                 // Default title: current module called
563                 if (empty($this->page['title']) && $this->module) {
564                         $this->page['title'] = ucfirst($this->module);
565                 }
566
567                 // Prepend the sitename to the page title
568                 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
569
570                 if (!empty(Core\Renderer::$theme['stylesheet'])) {
571                         $stylesheet = Core\Renderer::$theme['stylesheet'];
572                 } else {
573                         $stylesheet = $this->getCurrentThemeStylesheetPath();
574                 }
575
576                 $this->registerStylesheet($stylesheet);
577
578                 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
579                 if ($shortcut_icon == '') {
580                         $shortcut_icon = 'images/friendica-32.png';
581                 }
582
583                 $touch_icon = $this->config->get('system', 'touch_icon');
584                 if ($touch_icon == '') {
585                         $touch_icon = 'images/friendica-128.png';
586                 }
587
588                 Core\Hook::callAll('head', $this->page['htmlhead']);
589
590                 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
591                 /* put the head template at the beginning of page['htmlhead']
592                  * since the code added by the modules frequently depends on it
593                  * being first
594                  */
595                 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
596                         '$baseurl'         => $this->getBaseURL(),
597                         '$local_user'      => local_user(),
598                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
599                         '$delitem'         => Core\L10n::t('Delete this item?'),
600                         '$update_interval' => $interval,
601                         '$shortcut_icon'   => $shortcut_icon,
602                         '$touch_icon'      => $touch_icon,
603                         '$block_public'    => intval($this->config->get('system', 'block_public')),
604                         '$stylesheets'     => $this->stylesheets,
605                 ]) . $this->page['htmlhead'];
606         }
607
608         /**
609          * Initializes App->page['footer'].
610          *
611          * Includes:
612          * - Javascript homebase
613          * - Mobile toggle link
614          * - Registered footer scripts (through App->registerFooterScript())
615          * - footer.tpl template
616          */
617         public function initFooter()
618         {
619                 // If you're just visiting, let javascript take you home
620                 if (!empty($_SESSION['visitor_home'])) {
621                         $homebase = $_SESSION['visitor_home'];
622                 } elseif (local_user()) {
623                         $homebase = 'profile/' . $this->user['nickname'];
624                 }
625
626                 if (isset($homebase)) {
627                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
628                 }
629
630                 /*
631                  * Add a "toggle mobile" link if we're using a mobile device
632                  */
633                 if ($this->is_mobile || $this->is_tablet) {
634                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
635                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
636                         } else {
637                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
638                         }
639                         $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
640                                 '$toggle_link' => $link,
641                                 '$toggle_text' => Core\L10n::t('toggle mobile')
642                         ]);
643                 }
644
645                 Core\Hook::callAll('footer', $this->page['footer']);
646
647                 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
648                 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
649                         '$baseurl' => $this->getBaseURL(),
650                         '$footerScripts' => $this->footerScripts,
651                 ]) . $this->page['footer'];
652         }
653
654         /**
655          * @brief Removes the base url from an url. This avoids some mixed content problems.
656          *
657          * @param string $origURL
658          *
659          * @return string The cleaned url
660          * @throws InternalServerErrorException
661          */
662         public function removeBaseURL($origURL)
663         {
664                 // Remove the hostname from the url if it is an internal link
665                 $nurl = Util\Strings::normaliseLink($origURL);
666                 $base = Util\Strings::normaliseLink($this->getBaseURL());
667                 $url = str_replace($base . '/', '', $nurl);
668
669                 // if it is an external link return the orignal value
670                 if ($url == Util\Strings::normaliseLink($origURL)) {
671                         return $origURL;
672                 } else {
673                         return $url;
674                 }
675         }
676
677         /**
678          * Returns the current UserAgent as a String
679          *
680          * @return string the UserAgent as a String
681          * @throws InternalServerErrorException
682          */
683         public function getUserAgent()
684         {
685                 return
686                         FRIENDICA_PLATFORM . " '" .
687                         FRIENDICA_CODENAME . "' " .
688                         FRIENDICA_VERSION . '-' .
689                         DB_UPDATE_VERSION . '; ' .
690                         $this->getBaseURL();
691         }
692
693         /**
694          * Checks, if the call is from the Friendica App
695          *
696          * Reason:
697          * The friendica client has problems with the GUID in the notify. this is some workaround
698          */
699         private function checkFriendicaApp()
700         {
701                 // Friendica-Client
702                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
703         }
704
705         /**
706          *      Is the call via the Friendica app? (not a "normale" call)
707          *
708          * @return bool true if it's from the Friendica app
709          */
710         public function isFriendicaApp()
711         {
712                 return $this->isFriendicaApp;
713         }
714
715         /**
716          * @brief Checks if the site is called via a backend process
717          *
718          * This isn't a perfect solution. But we need this check very early.
719          * So we cannot wait until the modules are loaded.
720          *
721          * @param string $backend true, if the backend flag was set during App initialization
722          *
723          */
724         private function checkBackend($backend) {
725                 static $backends = [
726                         '_well_known',
727                         'api',
728                         'dfrn_notify',
729                         'fetch',
730                         'hcard',
731                         'hostxrd',
732                         'manifest',
733                         'nodeinfo',
734                         'noscrape',
735                         'p',
736                         'poco',
737                         'post',
738                         'proxy',
739                         'pubsub',
740                         'pubsubhubbub',
741                         'receive',
742                         'rsd_xml',
743                         'salmon',
744                         'statistics_json',
745                         'xrd',
746                 ];
747
748                 // Check if current module is in backend or backend flag is set
749                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
750         }
751
752         /**
753          * Returns true, if the call is from a backend node (f.e. from a worker)
754          *
755          * @return bool Is it a known backend?
756          */
757         public function isBackend()
758         {
759                 return $this->isBackend;
760         }
761
762         /**
763          * @brief Checks if the maximum number of database processes is reached
764          *
765          * @return bool Is the limit reached?
766          */
767         public function isMaxProcessesReached()
768         {
769                 // Deactivated, needs more investigating if this check really makes sense
770                 return false;
771
772                 /*
773                  * Commented out to suppress static analyzer issues
774                  *
775                 if ($this->is_backend()) {
776                         $process = 'backend';
777                         $max_processes = $this->config->get('system', 'max_processes_backend');
778                         if (intval($max_processes) == 0) {
779                                 $max_processes = 5;
780                         }
781                 } else {
782                         $process = 'frontend';
783                         $max_processes = $this->config->get('system', 'max_processes_frontend');
784                         if (intval($max_processes) == 0) {
785                                 $max_processes = 20;
786                         }
787                 }
788
789                 $processlist = DBA::processlist();
790                 if ($processlist['list'] != '') {
791                         Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
792
793                         if ($processlist['amount'] > $max_processes) {
794                                 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
795                                 return true;
796                         }
797                 }
798                 return false;
799                  */
800         }
801
802         /**
803          * @brief Checks if the minimal memory is reached
804          *
805          * @return bool Is the memory limit reached?
806          * @throws InternalServerErrorException
807          */
808         public function isMinMemoryReached()
809         {
810                 $min_memory = $this->config->get('system', 'min_memory', 0);
811                 if ($min_memory == 0) {
812                         return false;
813                 }
814
815                 if (!is_readable('/proc/meminfo')) {
816                         return false;
817                 }
818
819                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
820
821                 $meminfo = [];
822                 foreach ($memdata as $line) {
823                         $data = explode(':', $line);
824                         if (count($data) != 2) {
825                                 continue;
826                         }
827                         list($key, $val) = $data;
828                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
829                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
830                 }
831
832                 if (!isset($meminfo['MemFree'])) {
833                         return false;
834                 }
835
836                 $free = $meminfo['MemFree'];
837
838                 $reached = ($free < $min_memory);
839
840                 if ($reached) {
841                         Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
842                 }
843
844                 return $reached;
845         }
846
847         /**
848          * @brief Checks if the maximum load is reached
849          *
850          * @return bool Is the load reached?
851          * @throws InternalServerErrorException
852          */
853         public function isMaxLoadReached()
854         {
855                 if ($this->isBackend()) {
856                         $process = 'backend';
857                         $maxsysload = intval($this->config->get('system', 'maxloadavg'));
858                         if ($maxsysload < 1) {
859                                 $maxsysload = 50;
860                         }
861                 } else {
862                         $process = 'frontend';
863                         $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
864                         if ($maxsysload < 1) {
865                                 $maxsysload = 50;
866                         }
867                 }
868
869                 $load = Core\System::currentLoad();
870                 if ($load) {
871                         if (intval($load) > $maxsysload) {
872                                 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
873                                 return true;
874                         }
875                 }
876                 return false;
877         }
878
879         /**
880          * Executes a child process with 'proc_open'
881          *
882          * @param string $command The command to execute
883          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
884          * @throws InternalServerErrorException
885          */
886         public function proc_run($command, $args)
887         {
888                 if (!function_exists('proc_open')) {
889                         return;
890                 }
891
892                 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
893
894                 foreach ($args as $key => $value) {
895                         if (!is_null($value) && is_bool($value) && !$value) {
896                                 continue;
897                         }
898
899                         $cmdline .= ' --' . $key;
900                         if (!is_null($value) && !is_bool($value)) {
901                                 $cmdline .= ' ' . $value;
902                         }
903                 }
904
905                 if ($this->isMinMemoryReached()) {
906                         return;
907                 }
908
909                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
910                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
911                 } else {
912                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
913                 }
914                 if (!is_resource($resource)) {
915                         Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
916                         return;
917                 }
918                 proc_close($resource);
919         }
920
921         /**
922          * Generates the site's default sender email address
923          *
924          * @return string
925          * @throws InternalServerErrorException
926          */
927         public function getSenderEmailAddress()
928         {
929                 $sender_email = $this->config->get('config', 'sender_email');
930                 if (empty($sender_email)) {
931                         $hostname = $this->getHostName();
932                         if (strpos($hostname, ':')) {
933                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
934                         }
935
936                         $sender_email = 'noreply@' . $hostname;
937                 }
938
939                 return $sender_email;
940         }
941
942         /**
943          * Returns the current theme name.
944          *
945          * @return string the name of the current theme
946          * @throws InternalServerErrorException
947          */
948         public function getCurrentTheme()
949         {
950                 if ($this->getMode()->isInstall()) {
951                         return '';
952                 }
953
954                 if (!$this->currentTheme) {
955                         $this->computeCurrentTheme();
956                 }
957
958                 return $this->currentTheme;
959         }
960
961         public function setCurrentTheme($theme)
962         {
963                 $this->currentTheme = $theme;
964         }
965
966         /**
967          * Computes the current theme name based on the node settings, the user settings and the device type
968          *
969          * @throws Exception
970          */
971         private function computeCurrentTheme()
972         {
973                 $system_theme = $this->config->get('system', 'theme');
974                 if (!$system_theme) {
975                         throw new Exception(Core\L10n::t('No system theme config value set.'));
976                 }
977
978                 // Sane default
979                 $this->currentTheme = $system_theme;
980
981                 $page_theme = null;
982                 // Find the theme that belongs to the user whose stuff we are looking at
983                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
984                         // Allow folks to override user themes and always use their own on their own site.
985                         // This works only if the user is on the same server
986                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
987                         if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
988                                 $page_theme = $user['theme'];
989                         }
990                 }
991
992                 $user_theme = Core\Session::get('theme', $system_theme);
993
994                 // Specific mobile theme override
995                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
996                         $system_mobile_theme = $this->config->get('system', 'mobile-theme');
997                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
998
999                         // --- means same mobile theme as desktop
1000                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1001                                 $user_theme = $user_mobile_theme;
1002                         }
1003                 }
1004
1005                 if ($page_theme) {
1006                         $theme_name = $page_theme;
1007                 } else {
1008                         $theme_name = $user_theme;
1009                 }
1010
1011                 $theme_name = Strings::sanitizeFilePathItem($theme_name);
1012                 if ($theme_name
1013                         && in_array($theme_name, Theme::getAllowedList())
1014                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1015                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1016                 ) {
1017                         $this->currentTheme = $theme_name;
1018                 }
1019         }
1020
1021         /**
1022          * @brief Return full URL to theme which is currently in effect.
1023          *
1024          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1025          *
1026          * @return string
1027          * @throws InternalServerErrorException
1028          */
1029         public function getCurrentThemeStylesheetPath()
1030         {
1031                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1032         }
1033
1034         /**
1035          * Check if request was an AJAX (xmlhttprequest) request.
1036          *
1037          * @return boolean true if it was an AJAX request
1038          */
1039         public function isAjax()
1040         {
1041                 return $this->isAjax;
1042         }
1043
1044         /**
1045          * Returns the value of a argv key
1046          * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1047          *
1048          * @param int $position the position of the argument
1049          * @param mixed $default the default value if not found
1050          *
1051          * @return mixed returns the value of the argument
1052          */
1053         public function getArgumentValue($position, $default = '')
1054         {
1055                 if (array_key_exists($position, $this->argv)) {
1056                         return $this->argv[$position];
1057                 }
1058
1059                 return $default;
1060         }
1061
1062         /**
1063          * Sets the base url for use in cmdline programs which don't have
1064          * $_SERVER variables
1065          */
1066         public function checkURL()
1067         {
1068                 $url = $this->config->get('system', 'url');
1069
1070                 // if the url isn't set or the stored url is radically different
1071                 // than the currently visited url, store the current value accordingly.
1072                 // "Radically different" ignores common variations such as http vs https
1073                 // and www.example.com vs example.com.
1074                 // We will only change the url to an ip address if there is no existing setting
1075
1076                 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1077                         $this->config->set('system', 'url', $this->getBaseURL());
1078                 }
1079         }
1080
1081         /**
1082          * Frontend App script
1083          *
1084          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1085          * request and a representation of the response.
1086          *
1087          * This probably should change to limit the size of this monster method.
1088          */
1089         public function runFrontend()
1090         {
1091                 // Missing DB connection: ERROR
1092                 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1093                         Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1094                 }
1095
1096                 // Max Load Average reached: ERROR
1097                 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1098                         header('Retry-After: 120');
1099                         header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1100
1101                         Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1102                 }
1103
1104                 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1105                         Core\System::httpExit(404);
1106                 }
1107
1108                 if (!$this->getMode()->isInstall()) {
1109                         // Force SSL redirection
1110                         if ($this->config->get('system', 'force_ssl') && ($this->getScheme() == "http")
1111                                 && intval($this->config->get('system', 'ssl_policy')) == SSL_POLICY_FULL
1112                                 && strpos($this->getBaseURL(), 'https://') === 0
1113                                 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1114                                 header('HTTP/1.1 302 Moved Temporarily');
1115                                 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1116                                 exit();
1117                         }
1118
1119                         Core\Session::init();
1120                         Core\Hook::callAll('init_1');
1121                 }
1122
1123                 // Exclude the backend processes from the session management
1124                 if (!$this->isBackend()) {
1125                         $stamp1 = microtime(true);
1126                         session_start();
1127                         $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1128                         Core\L10n::setSessionVariable();
1129                         Core\L10n::setLangFromSession();
1130                 } else {
1131                         $_SESSION = [];
1132                         Core\Worker::executeIfIdle();
1133                 }
1134
1135                 if ($this->getMode()->isNormal()) {
1136                         $requester = HTTPSignature::getSigner('', $_SERVER);
1137                         if (!empty($requester)) {
1138                                 Profile::addVisitorCookieForHandle($requester);
1139                         }
1140                 }
1141
1142                 // ZRL
1143                 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1144                         $this->query_string = Model\Profile::stripZrls($this->query_string);
1145                         if (!local_user()) {
1146                                 // Only continue when the given profile link seems valid
1147                                 // Valid profile links contain a path with "/profile/" and no query parameters
1148                                 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1149                                         strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1150                                         if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1151                                                 $_SESSION['my_url'] = $_GET['zrl'];
1152                                                 $_SESSION['authenticated'] = 0;
1153                                         }
1154                                         Model\Profile::zrlInit($this);
1155                                 } else {
1156                                         // Someone came with an invalid parameter, maybe as a DDoS attempt
1157                                         // We simply stop processing here
1158                                         Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1159                                         Core\System::httpExit(403, ['title' => '403 Forbidden']);
1160                                 }
1161                         }
1162                 }
1163
1164                 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1165                         $token = $_GET['owt'];
1166                         $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1167                         Model\Profile::openWebAuthInit($token);
1168                 }
1169
1170                 Module\Login::sessionAuth();
1171
1172                 if (empty($_SESSION['authenticated'])) {
1173                         header('X-Account-Management-Status: none');
1174                 }
1175
1176                 $_SESSION['sysmsg']       = defaults($_SESSION, 'sysmsg'      , []);
1177                 $_SESSION['sysmsg_info']  = defaults($_SESSION, 'sysmsg_info' , []);
1178                 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1179
1180                 /*
1181                  * check_config() is responsible for running update scripts. These automatically
1182                  * update the DB schema whenever we push a new one out. It also checks to see if
1183                  * any addons have been added or removed and reacts accordingly.
1184                  */
1185
1186                 // in install mode, any url loads install module
1187                 // but we need "view" module for stylesheet
1188                 if ($this->getMode()->isInstall() && $this->module != 'view') {
1189                         $this->module = 'install';
1190                 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1191                         $this->module = 'maintenance';
1192                 } else {
1193                         $this->checkURL();
1194                         Core\Update::check($this->getBasePath(), false, $this->getMode());
1195                         Core\Addon::loadAddons();
1196                         Core\Hook::loadHooks();
1197                 }
1198
1199                 $this->page = [
1200                         'aside' => '',
1201                         'bottom' => '',
1202                         'content' => '',
1203                         'footer' => '',
1204                         'htmlhead' => '',
1205                         'nav' => '',
1206                         'page_title' => '',
1207                         'right_aside' => '',
1208                         'template' => '',
1209                         'title' => ''
1210                 ];
1211
1212                 if (strlen($this->module)) {
1213                         // Compatibility with the Android Diaspora client
1214                         if ($this->module == 'stream') {
1215                                 $this->internalRedirect('network?f=&order=post');
1216                         }
1217
1218                         if ($this->module == 'conversations') {
1219                                 $this->internalRedirect('message');
1220                         }
1221
1222                         if ($this->module == 'commented') {
1223                                 $this->internalRedirect('network?f=&order=comment');
1224                         }
1225
1226                         if ($this->module == 'liked') {
1227                                 $this->internalRedirect('network?f=&order=comment');
1228                         }
1229
1230                         if ($this->module == 'activity') {
1231                                 $this->internalRedirect('network/?f=&conv=1');
1232                         }
1233
1234                         if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1235                                 $this->internalRedirect('bookmarklet');
1236                         }
1237
1238                         if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1239                                 $this->internalRedirect('settings');
1240                         }
1241
1242                         if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1243                                 $this->internalRedirect('search');
1244                         }
1245
1246                         // Compatibility with the Firefox App
1247                         if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1248                                 $this->module = "login";
1249                         }
1250
1251                         $router = new App\Router();
1252                         $this->collectRoutes($router->routeCollector);
1253
1254                         $this->module_class = $router->getModuleClass($this->cmd);
1255
1256                         $privateapps = $this->config->get('config', 'private_addons', false);
1257                         if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1258                                 //Check if module is an app and if public access to apps is allowed or not
1259                                 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1260                                         info(Core\L10n::t("You must be logged in to use addons. "));
1261                                 } else {
1262                                         include_once "addon/{$this->module}/{$this->module}.php";
1263                                         if (function_exists($this->module . '_module')) {
1264                                                 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1265                                                 $this->module_class = 'Friendica\\LegacyModule';
1266                                         }
1267                                 }
1268                         }
1269
1270                         // Controller class routing
1271                         if (!$this->module_class && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1272                                 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1273                         }
1274
1275                         /* If not, next look for a 'standard' program module in the 'mod' directory
1276                          * We emulate a Module class through the LegacyModule class
1277                          */
1278                         if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
1279                                 LegacyModule::setModuleFile("mod/{$this->module}.php");
1280                                 $this->module_class = 'Friendica\\LegacyModule';
1281                         }
1282
1283                         /* The URL provided does not resolve to a valid module.
1284                          *
1285                          * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1286                          * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1287                          * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
1288                          * this will often succeed and eventually do the right thing.
1289                          *
1290                          * Otherwise we are going to emit a 404 not found.
1291                          */
1292                         if (!$this->module_class) {
1293                                 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1294                                 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1295                                         exit();
1296                                 }
1297
1298                                 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1299                                         Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1300                                         $this->internalRedirect($_SERVER['REQUEST_URI']);
1301                                 }
1302
1303                                 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1304
1305                                 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1306                                 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1307                                 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1308                                         '$message' =>  Core\L10n::t('Page not found.')
1309                                 ]);
1310                         }
1311                 }
1312
1313                 $content = '';
1314
1315                 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1316                 if ($this->module_class) {
1317                         $this->page['page_title'] = $this->module;
1318                         $placeholder = '';
1319
1320                         Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1321
1322                         call_user_func([$this->module_class, 'init']);
1323
1324                         // "rawContent" is especially meant for technical endpoints.
1325                         // This endpoint doesn't need any theme initialization or other comparable stuff.
1326                         if (!$this->error) {
1327                                 call_user_func([$this->module_class, 'rawContent']);
1328                         }
1329                 }
1330
1331                 // Load current theme info after module has been initialized as theme could have been set in module
1332                 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1333                 if (file_exists($theme_info_file)) {
1334                         require_once $theme_info_file;
1335                 }
1336
1337                 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1338                         $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1339                         $func($this);
1340                 }
1341
1342                 if ($this->module_class) {
1343                         if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1344                                 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1345                                 call_user_func([$this->module_class, 'post']);
1346                         }
1347
1348                         if (! $this->error) {
1349                                 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1350                                 call_user_func([$this->module_class, 'afterpost']);
1351                         }
1352
1353                         if (! $this->error) {
1354                                 $arr = ['content' => $content];
1355                                 Core\Hook::callAll($this->module . '_mod_content', $arr);
1356                                 $content = $arr['content'];
1357                                 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1358                                 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1359                                 $content .= $arr['content'];
1360                         }
1361                 }
1362
1363                 // initialise content region
1364                 if ($this->getMode()->isNormal()) {
1365                         Core\Hook::callAll('page_content_top', $this->page['content']);
1366                 }
1367
1368                 $this->page['content'] .= $content;
1369
1370                 /* Create the page head after setting the language
1371                  * and getting any auth credentials.
1372                  *
1373                  * Moved initHead() and initFooter() to after
1374                  * all the module functions have executed so that all
1375                  * theme choices made by the modules can take effect.
1376                  */
1377                 $this->initHead();
1378
1379                 /* Build the page ending -- this is stuff that goes right before
1380                  * the closing </body> tag
1381                  */
1382                 $this->initFooter();
1383
1384                 /* now that we've been through the module content, see if the page reported
1385                  * a permission problem and if so, a 403 response would seem to be in order.
1386                  */
1387                 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1388                         header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1389                 }
1390
1391                 // Report anything which needs to be communicated in the notification area (before the main body)
1392                 Core\Hook::callAll('page_end', $this->page['content']);
1393
1394                 // Add the navigation (menu) template
1395                 if ($this->module != 'install' && $this->module != 'maintenance') {
1396                         $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1397                         $this->page['nav']       = Content\Nav::build($this);
1398                 }
1399
1400                 // Build the page - now that we have all the components
1401                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1402                         $doc = new DOMDocument();
1403
1404                         $target = new DOMDocument();
1405                         $target->loadXML("<root></root>");
1406
1407                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1408
1409                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1410                         @$doc->loadHTML($content);
1411
1412                         $xpath = new DOMXPath($doc);
1413
1414                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
1415
1416                         foreach ($list as $item) {
1417                                 $item = $target->importNode($item, true);
1418
1419                                 // And then append it to the target
1420                                 $target->documentElement->appendChild($item);
1421                         }
1422
1423                         if ($_GET["mode"] == "raw") {
1424                                 header("Content-type: text/html; charset=utf-8");
1425
1426                                 echo substr($target->saveHTML(), 6, -8);
1427
1428                                 exit();
1429                         }
1430                 }
1431
1432                 $page    = $this->page;
1433                 $profile = $this->profile;
1434
1435                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1436                 header("Content-type: text/html; charset=utf-8");
1437
1438                 if ($this->config->get('system', 'hsts') && ($this->config->get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1439                         header("Strict-Transport-Security: max-age=31536000");
1440                 }
1441
1442                 // Some security stuff
1443                 header('X-Content-Type-Options: nosniff');
1444                 header('X-XSS-Protection: 1; mode=block');
1445                 header('X-Permitted-Cross-Domain-Policies: none');
1446                 header('X-Frame-Options: sameorigin');
1447
1448                 // Things like embedded OSM maps don't work, when this is enabled
1449                 // 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'");
1450
1451                 /* We use $_GET["mode"] for special page templates. So we will check if we have
1452                  * to load another page template than the default one.
1453                  * The page templates are located in /view/php/ or in the theme directory.
1454                  */
1455                 if (isset($_GET["mode"])) {
1456                         $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1457                 }
1458
1459                 // If there is no page template use the default page template
1460                 if (empty($template)) {
1461                         $template = Core\Theme::getPathForFile("default.php");
1462                 }
1463
1464                 // Theme templates expect $a as an App instance
1465                 $a = $this;
1466
1467                 // Used as is in view/php/default.php
1468                 $lang = Core\L10n::getCurrentLang();
1469
1470                 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1471                 require_once $template;
1472         }
1473
1474         /**
1475          * Redirects to another module relative to the current Friendica base.
1476          * If you want to redirect to a external URL, use System::externalRedirectTo()
1477          *
1478          * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1479          * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1480          *
1481          * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1482          */
1483         public function internalRedirect($toUrl = '', $ssl = false)
1484         {
1485                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1486                         throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1487                 }
1488
1489                 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1490                 Core\System::externalRedirect($redirectTo);
1491         }
1492
1493         /**
1494          * Automatically redirects to relative or absolute URL
1495          * Should only be used if it isn't clear if the URL is either internal or external
1496          *
1497          * @param string $toUrl The target URL
1498          * @throws InternalServerErrorException
1499          */
1500         public function redirect($toUrl)
1501         {
1502                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1503                         Core\System::externalRedirect($toUrl);
1504                 } else {
1505                         $this->internalRedirect($toUrl);
1506                 }
1507         }
1508
1509         /**
1510          * @brief Static declaration of Friendica routes.
1511          *
1512          * Supports:
1513          * - Route groups
1514          * - Variable parts
1515          * Disregards:
1516          * - HTTP method other than GET
1517          * - Named parameters
1518          *
1519          * Handler must be the name of a class extending Friendica\BaseModule.
1520          *
1521          * @param RouteCollector $routeCollector
1522          * @throws InternalServerErrorException
1523          */
1524         private function collectRoutes(RouteCollector $routeCollector)
1525         {
1526                 Hook::callAll('route_collection', $routeCollector);
1527         }
1528 }