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