]> git.mxchange.org Git - friendica.git/blob - src/App.php
e5ac5dda3cc926a87ef8d5d479842bd17780d6f3
[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 Friendica\Core\Config\Cache\ConfigCacheLoader;
12 use Friendica\Core\Config\Cache\IConfigCache;
13 use Friendica\Core\Config\Configuration;
14 use Friendica\Database\DBA;
15 use Friendica\Network\HTTPException\InternalServerErrorException;
16 use Friendica\Util\Profiler;
17 use Psr\Log\LoggerInterface;
18
19 /**
20  *
21  * class: App
22  *
23  * @brief Our main application structure for the life of this page.
24  *
25  * Primarily deals with the URL that got us here
26  * and tries to make some sense of it, and
27  * stores our page contents and config storage
28  * and anything else that might need to be passed around
29  * before we spit the page out.
30  *
31  */
32 class App
33 {
34         public $module_loaded = false;
35         public $module_class = null;
36         public $query_string = '';
37         public $page = [];
38         public $profile;
39         public $profile_uid;
40         public $user;
41         public $cid;
42         public $contact;
43         public $contacts;
44         public $page_contact;
45         public $content;
46         public $data = [];
47         public $error = false;
48         public $cmd = '';
49         public $argv;
50         public $argc;
51         public $module;
52         public $timezone;
53         public $interactive = true;
54         public $identities;
55         public $is_mobile = false;
56         public $is_tablet = false;
57         public $theme_info = [];
58         public $category;
59         // Allow themes to control internal parameters
60         // by changing App values in theme.php
61
62         public $sourcename = '';
63         public $videowidth = 425;
64         public $videoheight = 350;
65         public $force_max_items = 0;
66         public $theme_events_in_profile = true;
67
68         public $stylesheets = [];
69         public $footerScripts = [];
70
71         /**
72          * @var App\Mode The Mode of the Application
73          */
74         private $mode;
75
76         /**
77          * @var string The App base path
78          */
79         private $basePath;
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->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          * Register a stylesheet file path to be included in the <head> tag of every page.
168          * Inclusion is done in App->initHead().
169          * The path can be absolute or relative to the Friendica installation base folder.
170          *
171          * @see initHead()
172          *
173          * @param string $path
174          * @throws InternalServerErrorException
175          */
176         public function registerStylesheet($path)
177         {
178                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
179
180                 $this->stylesheets[] = trim($url, '/');
181         }
182
183         /**
184          * Register a javascript file path to be included in the <footer> tag of every page.
185          * Inclusion is done in App->initFooter().
186          * The path can be absolute or relative to the Friendica installation base folder.
187          *
188          * @see initFooter()
189          *
190          * @param string $path
191          * @throws InternalServerErrorException
192          */
193         public function registerFooterScript($path)
194         {
195                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
196
197                 $this->footerScripts[] = trim($url, '/');
198         }
199
200         public $process_id;
201         public $queue;
202         private $scheme;
203         private $hostname;
204
205         /**
206          * @brief App constructor.
207          *
208          * @param string           $basePath   The basedir of the app
209          * @param Configuration    $config    The Configuration
210          * @param LoggerInterface  $logger    The current app logger
211          * @param Profiler         $profiler  The profiler of this application
212          * @param bool             $isBackend Whether it is used for backend or frontend (Default true=backend)
213          *
214          * @throws Exception if the Basepath is not usable
215          */
216         public function __construct($basePath, Configuration $config, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
217         {
218                 BaseObject::setApp($this);
219
220                 $this->logger   = $logger;
221                 $this->config   = $config;
222                 $this->profiler = $profiler;
223                 $cfgBasePath = $this->config->get('system', 'basepath');
224                 $this->basePath = (isset($cfgBasePath) && $cfgBasePath !== '') ? $cfgBasePath : $basePath;
225
226                 if (!Core\System::isDirectoryUsable($this->basePath, false)) {
227                         throw new Exception('Basepath \'' . $this->basePath . '\' isn\'t usable.');
228                 }
229                 $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR);
230
231                 $this->checkBackend($isBackend);
232                 $this->checkFriendicaApp();
233
234                 $this->profiler->reset();
235
236                 $this->mode = new App\Mode($this->basePath);
237
238                 $this->reload();
239
240                 set_time_limit(0);
241
242                 // This has to be quite large to deal with embedded private photos
243                 ini_set('pcre.backtrack_limit', 500000);
244
245                 $this->scheme = 'http';
246
247                 if (!empty($_SERVER['HTTPS']) ||
248                         !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
249                         !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
250                         !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
251                         !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
252                         !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
253                 ) {
254                         $this->scheme = 'https';
255                 }
256
257                 if (!empty($_SERVER['SERVER_NAME'])) {
258                         $this->hostname = $_SERVER['SERVER_NAME'];
259
260                         if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
261                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
262                         }
263                 }
264
265                 set_include_path(
266                         get_include_path() . PATH_SEPARATOR
267                         . $this->basePath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
268                         . $this->basePath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
269                         . $this->basePath);
270
271                 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
272                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
273                 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
274                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
275                 }
276
277                 // removing trailing / - maybe a nginx problem
278                 $this->query_string = ltrim($this->query_string, '/');
279
280                 if (!empty($_GET['pagename'])) {
281                         $this->cmd = trim($_GET['pagename'], '/\\');
282                 } elseif (!empty($_GET['q'])) {
283                         $this->cmd = trim($_GET['q'], '/\\');
284                 }
285
286                 // fix query_string
287                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
288
289                 // unix style "homedir"
290                 if (substr($this->cmd, 0, 1) === '~') {
291                         $this->cmd = 'profile/' . substr($this->cmd, 1);
292                 }
293
294                 // Diaspora style profile url
295                 if (substr($this->cmd, 0, 2) === 'u/') {
296                         $this->cmd = 'profile/' . substr($this->cmd, 2);
297                 }
298
299                 /*
300                  * Break the URL path into C style argc/argv style arguments for our
301                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
302                  * will be 3 (integer) and $this->argv will contain:
303                  *   [0] => 'module'
304                  *   [1] => 'arg1'
305                  *   [2] => 'arg2'
306                  *
307                  *
308                  * There will always be one argument. If provided a naked domain
309                  * URL, $this->argv[0] is set to "home".
310                  */
311
312                 $this->argv = explode('/', $this->cmd);
313                 $this->argc = count($this->argv);
314                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
315                         $this->module = str_replace('.', '_', $this->argv[0]);
316                         $this->module = str_replace('-', '_', $this->module);
317                 } else {
318                         $this->argc = 1;
319                         $this->argv = ['home'];
320                         $this->module = 'home';
321                 }
322
323                 // Detect mobile devices
324                 $mobile_detect = new MobileDetect();
325
326                 $this->mobileDetect = $mobile_detect;
327
328                 $this->is_mobile = $mobile_detect->isMobile();
329                 $this->is_tablet = $mobile_detect->isTablet();
330
331                 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
332
333                 // Register template engines
334                 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
335         }
336
337         /**
338          * Returns the Mode of the Application
339          *
340          * @return App\Mode The Application Mode
341          *
342          * @throws InternalServerErrorException when the mode isn't created
343          */
344         public function getMode()
345         {
346                 if (empty($this->mode)) {
347                         throw new InternalServerErrorException('Mode of the Application is not defined');
348                 }
349
350                 return $this->mode;
351         }
352
353         /**
354          * Reloads the whole app instance
355          */
356         public function reload()
357         {
358                 $this->determineURLPath();
359
360                 $this->getMode()->determine($this->basePath);
361
362                 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
363                         Core\Hook::loadHooks();
364                         $loader = new ConfigCacheLoader($this->basePath);
365                         Core\Hook::callAll('load_config', $loader);
366                         $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
367                 }
368
369                 $this->loadDefaultTimezone();
370
371                 Core\L10n::init();
372
373                 $this->process_id = Core\System::processID('log');
374         }
375
376         /**
377          * Loads the default timezone
378          *
379          * Include support for legacy $default_timezone
380          *
381          * @global string $default_timezone
382          */
383         private function loadDefaultTimezone()
384         {
385                 if ($this->config->get('system', 'default_timezone')) {
386                         $this->timezone = $this->config->get('system', 'default_timezone');
387                 } else {
388                         global $default_timezone;
389                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
390                 }
391
392                 if ($this->timezone) {
393                         date_default_timezone_set($this->timezone);
394                 }
395         }
396
397         /**
398          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
399          */
400         private function determineURLPath()
401         {
402                 /*
403                  * The automatic path detection in this function is currently deactivated,
404                  * see issue https://github.com/friendica/friendica/issues/6679
405                  *
406                  * The problem is that the function seems to be confused with some url.
407                  * These then confuses the detection which changes the url path.
408                  */
409
410                 /* Relative script path to the web server root
411                  * Not all of those $_SERVER properties can be present, so we do by inverse priority order
412                  */
413 /*
414                 $relative_script_path = '';
415                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL'       , $relative_script_path);
416                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI'       , $relative_script_path);
417                 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
418                 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL'         , $relative_script_path);
419                 $relative_script_path = defaults($_SERVER, 'REQUEST_URI'        , $relative_script_path);
420 */
421                 $this->urlPath = $this->config->get('system', 'urlpath');
422
423                 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
424                  * QUERY_STRING gives pagename=module/parameter
425                  *
426                  * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
427                  */
428 /*
429                 if (!empty($relative_script_path)) {
430                         // Module
431                         if (!empty($_SERVER['QUERY_STRING'])) {
432                                 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
433                         } else {
434                                 // Root page
435                                 $path = trim($relative_script_path, '/');
436                         }
437
438                         if ($path && $path != $this->urlPath) {
439                                 $this->urlPath = $path;
440                         }
441                 }
442 */
443         }
444
445         public function getScheme()
446         {
447                 return $this->scheme;
448         }
449
450         /**
451          * @brief Retrieves the Friendica instance base URL
452          *
453          * This function assembles the base URL from multiple parts:
454          * - Protocol is determined either by the request or a combination of
455          * system.ssl_policy and the $ssl parameter.
456          * - Host name is determined either by system.hostname or inferred from request
457          * - Path is inferred from SCRIPT_NAME
458          *
459          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
460          *
461          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
462          * @return string Friendica server base URL
463          * @throws InternalServerErrorException
464          */
465         public function getBaseURL($ssl = false)
466         {
467                 $scheme = $this->scheme;
468
469                 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
470                         $scheme = 'https';
471                 }
472
473                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
474                 //      (and also the login link). Anything seen by an outsider will have it turned off.
475
476                 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
477                         if ($ssl) {
478                                 $scheme = 'https';
479                         } else {
480                                 $scheme = 'http';
481                         }
482                 }
483
484                 if (Core\Config::get('config', 'hostname') != '') {
485                         $this->hostname = Core\Config::get('config', 'hostname');
486                 }
487
488                 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
489         }
490
491         /**
492          * @brief Initializes the baseurl components
493          *
494          * Clears the baseurl cache to prevent inconsistencies
495          *
496          * @param string $url
497          * @throws InternalServerErrorException
498          */
499         public function setBaseURL($url)
500         {
501                 $parsed = @parse_url($url);
502                 $hostname = '';
503
504                 if (!empty($parsed)) {
505                         if (!empty($parsed['scheme'])) {
506                                 $this->scheme = $parsed['scheme'];
507                         }
508
509                         if (!empty($parsed['host'])) {
510                                 $hostname = $parsed['host'];
511                         }
512
513                         if (!empty($parsed['port'])) {
514                                 $hostname .= ':' . $parsed['port'];
515                         }
516                         if (!empty($parsed['path'])) {
517                                 $this->urlPath = trim($parsed['path'], '\\/');
518                         }
519
520                         if (file_exists($this->basePath . '/.htpreconfig.php')) {
521                                 include $this->basePath . '/.htpreconfig.php';
522                         }
523
524                         if (Core\Config::get('config', 'hostname') != '') {
525                                 $this->hostname = Core\Config::get('config', 'hostname');
526                         }
527
528                         if (!isset($this->hostname) || ($this->hostname == '')) {
529                                 $this->hostname = $hostname;
530                         }
531                 }
532         }
533
534         public function getHostName()
535         {
536                 if (Core\Config::get('config', 'hostname') != '') {
537                         $this->hostname = Core\Config::get('config', 'hostname');
538                 }
539
540                 return $this->hostname;
541         }
542
543         public function getURLPath()
544         {
545                 return $this->urlPath;
546         }
547
548         /**
549          * Initializes App->page['htmlhead'].
550          *
551          * Includes:
552          * - Page title
553          * - Favicons
554          * - Registered stylesheets (through App->registerStylesheet())
555          * - Infinite scroll data
556          * - head.tpl template
557          */
558         public function initHead()
559         {
560                 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
561
562                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
563                 if ($interval < 0) {
564                         $interval = 2147483647;
565                 }
566
567                 if ($interval < 10000) {
568                         $interval = 40000;
569                 }
570
571                 // compose the page title from the sitename and the
572                 // current module called
573                 if (!$this->module == '') {
574                         $this->page['title'] = $this->config->get('config', 'sitename') . ' (' . $this->module . ')';
575                 } else {
576                         $this->page['title'] = $this->config->get('config', 'sitename');
577                 }
578
579                 if (!empty(Core\Renderer::$theme['stylesheet'])) {
580                         $stylesheet = Core\Renderer::$theme['stylesheet'];
581                 } else {
582                         $stylesheet = $this->getCurrentThemeStylesheetPath();
583                 }
584
585                 $this->registerStylesheet($stylesheet);
586
587                 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
588                 if ($shortcut_icon == '') {
589                         $shortcut_icon = 'images/friendica-32.png';
590                 }
591
592                 $touch_icon = Core\Config::get('system', 'touch_icon');
593                 if ($touch_icon == '') {
594                         $touch_icon = 'images/friendica-128.png';
595                 }
596
597                 Core\Hook::callAll('head', $this->page['htmlhead']);
598
599                 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
600                 /* put the head template at the beginning of page['htmlhead']
601                  * since the code added by the modules frequently depends on it
602                  * being first
603                  */
604                 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
605                         '$baseurl'         => $this->getBaseURL(),
606                         '$local_user'      => local_user(),
607                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
608                         '$delitem'         => Core\L10n::t('Delete this item?'),
609                         '$update_interval' => $interval,
610                         '$shortcut_icon'   => $shortcut_icon,
611                         '$touch_icon'      => $touch_icon,
612                         '$block_public'    => intval(Core\Config::get('system', 'block_public')),
613                         '$stylesheets'     => $this->stylesheets,
614                 ]) . $this->page['htmlhead'];
615         }
616
617         /**
618          * Initializes App->page['footer'].
619          *
620          * Includes:
621          * - Javascript homebase
622          * - Mobile toggle link
623          * - Registered footer scripts (through App->registerFooterScript())
624          * - footer.tpl template
625          */
626         public function initFooter()
627         {
628                 // If you're just visiting, let javascript take you home
629                 if (!empty($_SESSION['visitor_home'])) {
630                         $homebase = $_SESSION['visitor_home'];
631                 } elseif (local_user()) {
632                         $homebase = 'profile/' . $this->user['nickname'];
633                 }
634
635                 if (isset($homebase)) {
636                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
637                 }
638
639                 /*
640                  * Add a "toggle mobile" link if we're using a mobile device
641                  */
642                 if ($this->is_mobile || $this->is_tablet) {
643                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
644                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
645                         } else {
646                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
647                         }
648                         $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
649                                 '$toggle_link' => $link,
650                                 '$toggle_text' => Core\L10n::t('toggle mobile')
651                         ]);
652                 }
653
654                 Core\Hook::callAll('footer', $this->page['footer']);
655
656                 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
657                 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
658                         '$baseurl' => $this->getBaseURL(),
659                         '$footerScripts' => $this->footerScripts,
660                 ]) . $this->page['footer'];
661         }
662
663         /**
664          * @brief Removes the base url from an url. This avoids some mixed content problems.
665          *
666          * @param string $origURL
667          *
668          * @return string The cleaned url
669          * @throws InternalServerErrorException
670          */
671         public function removeBaseURL($origURL)
672         {
673                 // Remove the hostname from the url if it is an internal link
674                 $nurl = Util\Strings::normaliseLink($origURL);
675                 $base = Util\Strings::normaliseLink($this->getBaseURL());
676                 $url = str_replace($base . '/', '', $nurl);
677
678                 // if it is an external link return the orignal value
679                 if ($url == Util\Strings::normaliseLink($origURL)) {
680                         return $origURL;
681                 } else {
682                         return $url;
683                 }
684         }
685
686         /**
687          * Returns the current UserAgent as a String
688          *
689          * @return string the UserAgent as a String
690          * @throws InternalServerErrorException
691          */
692         public function getUserAgent()
693         {
694                 return
695                         FRIENDICA_PLATFORM . " '" .
696                         FRIENDICA_CODENAME . "' " .
697                         FRIENDICA_VERSION . '-' .
698                         DB_UPDATE_VERSION . '; ' .
699                         $this->getBaseURL();
700         }
701
702         /**
703          * Checks, if the call is from the Friendica App
704          *
705          * Reason:
706          * The friendica client has problems with the GUID in the notify. this is some workaround
707          */
708         private function checkFriendicaApp()
709         {
710                 // Friendica-Client
711                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
712         }
713
714         /**
715          *      Is the call via the Friendica app? (not a "normale" call)
716          *
717          * @return bool true if it's from the Friendica app
718          */
719         public function isFriendicaApp()
720         {
721                 return $this->isFriendicaApp;
722         }
723
724         /**
725          * @brief Checks if the site is called via a backend process
726          *
727          * This isn't a perfect solution. But we need this check very early.
728          * So we cannot wait until the modules are loaded.
729          *
730          * @param string $backend true, if the backend flag was set during App initialization
731          *
732          */
733         private function checkBackend($backend) {
734                 static $backends = [
735                         '_well_known',
736                         'api',
737                         'dfrn_notify',
738                         'fetch',
739                         'hcard',
740                         'hostxrd',
741                         'nodeinfo',
742                         'noscrape',
743                         'p',
744                         'poco',
745                         'post',
746                         'proxy',
747                         'pubsub',
748                         'pubsubhubbub',
749                         'receive',
750                         'rsd_xml',
751                         'salmon',
752                         'statistics_json',
753                         'xrd',
754                 ];
755
756                 // Check if current module is in backend or backend flag is set
757                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
758         }
759
760         /**
761          * Returns true, if the call is from a backend node (f.e. from a worker)
762          *
763          * @return bool Is it a known backend?
764          */
765         public function isBackend()
766         {
767                 return $this->isBackend;
768         }
769
770         /**
771          * @brief Checks if the maximum number of database processes is reached
772          *
773          * @return bool Is the limit reached?
774          */
775         public function isMaxProcessesReached()
776         {
777                 // Deactivated, needs more investigating if this check really makes sense
778                 return false;
779
780                 /*
781                  * Commented out to suppress static analyzer issues
782                  *
783                 if ($this->is_backend()) {
784                         $process = 'backend';
785                         $max_processes = Core\Config::get('system', 'max_processes_backend');
786                         if (intval($max_processes) == 0) {
787                                 $max_processes = 5;
788                         }
789                 } else {
790                         $process = 'frontend';
791                         $max_processes = Core\Config::get('system', 'max_processes_frontend');
792                         if (intval($max_processes) == 0) {
793                                 $max_processes = 20;
794                         }
795                 }
796
797                 $processlist = DBA::processlist();
798                 if ($processlist['list'] != '') {
799                         Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
800
801                         if ($processlist['amount'] > $max_processes) {
802                                 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
803                                 return true;
804                         }
805                 }
806                 return false;
807                  */
808         }
809
810         /**
811          * @brief Checks if the minimal memory is reached
812          *
813          * @return bool Is the memory limit reached?
814          * @throws InternalServerErrorException
815          */
816         public function isMinMemoryReached()
817         {
818                 $min_memory = Core\Config::get('system', 'min_memory', 0);
819                 if ($min_memory == 0) {
820                         return false;
821                 }
822
823                 if (!is_readable('/proc/meminfo')) {
824                         return false;
825                 }
826
827                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
828
829                 $meminfo = [];
830                 foreach ($memdata as $line) {
831                         $data = explode(':', $line);
832                         if (count($data) != 2) {
833                                 continue;
834                         }
835                         list($key, $val) = $data;
836                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
837                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
838                 }
839
840                 if (!isset($meminfo['MemFree'])) {
841                         return false;
842                 }
843
844                 $free = $meminfo['MemFree'];
845
846                 $reached = ($free < $min_memory);
847
848                 if ($reached) {
849                         Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
850                 }
851
852                 return $reached;
853         }
854
855         /**
856          * @brief Checks if the maximum load is reached
857          *
858          * @return bool Is the load reached?
859          * @throws InternalServerErrorException
860          */
861         public function isMaxLoadReached()
862         {
863                 if ($this->isBackend()) {
864                         $process = 'backend';
865                         $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
866                         if ($maxsysload < 1) {
867                                 $maxsysload = 50;
868                         }
869                 } else {
870                         $process = 'frontend';
871                         $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
872                         if ($maxsysload < 1) {
873                                 $maxsysload = 50;
874                         }
875                 }
876
877                 $load = Core\System::currentLoad();
878                 if ($load) {
879                         if (intval($load) > $maxsysload) {
880                                 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
881                                 return true;
882                         }
883                 }
884                 return false;
885         }
886
887         /**
888          * Executes a child process with 'proc_open'
889          *
890          * @param string $command The command to execute
891          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
892          * @throws InternalServerErrorException
893          */
894         public function proc_run($command, $args)
895         {
896                 if (!function_exists('proc_open')) {
897                         return;
898                 }
899
900                 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
901
902                 foreach ($args as $key => $value) {
903                         if (!is_null($value) && is_bool($value) && !$value) {
904                                 continue;
905                         }
906
907                         $cmdline .= ' --' . $key;
908                         if (!is_null($value) && !is_bool($value)) {
909                                 $cmdline .= ' ' . $value;
910                         }
911                 }
912
913                 if ($this->isMinMemoryReached()) {
914                         return;
915                 }
916
917                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
918                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
919                 } else {
920                         $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
921                 }
922                 if (!is_resource($resource)) {
923                         Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
924                         return;
925                 }
926                 proc_close($resource);
927         }
928
929         /**
930          * Generates the site's default sender email address
931          *
932          * @return string
933          * @throws InternalServerErrorException
934          */
935         public function getSenderEmailAddress()
936         {
937                 $sender_email = Core\Config::get('config', 'sender_email');
938                 if (empty($sender_email)) {
939                         $hostname = $this->getHostName();
940                         if (strpos($hostname, ':')) {
941                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
942                         }
943
944                         $sender_email = 'noreply@' . $hostname;
945                 }
946
947                 return $sender_email;
948         }
949
950         /**
951          * Returns the current theme name.
952          *
953          * @return string the name of the current theme
954          * @throws InternalServerErrorException
955          */
956         public function getCurrentTheme()
957         {
958                 if ($this->getMode()->isInstall()) {
959                         return '';
960                 }
961
962                 if (!$this->currentTheme) {
963                         $this->computeCurrentTheme();
964                 }
965
966                 return $this->currentTheme;
967         }
968
969         public function setCurrentTheme($theme)
970         {
971                 $this->currentTheme = $theme;
972         }
973
974         /**
975          * Computes the current theme name based on the node settings, the user settings and the device type
976          *
977          * @throws Exception
978          */
979         private function computeCurrentTheme()
980         {
981                 $system_theme = Core\Config::get('system', 'theme');
982                 if (!$system_theme) {
983                         throw new Exception(Core\L10n::t('No system theme config value set.'));
984                 }
985
986                 // Sane default
987                 $this->currentTheme = $system_theme;
988
989                 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
990
991                 $page_theme = null;
992                 // Find the theme that belongs to the user whose stuff we are looking at
993                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
994                         // Allow folks to override user themes and always use their own on their own site.
995                         // This works only if the user is on the same server
996                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
997                         if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
998                                 $page_theme = $user['theme'];
999                         }
1000                 }
1001
1002                 $user_theme = Core\Session::get('theme', $system_theme);
1003
1004                 // Specific mobile theme override
1005                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1006                         $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1007                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1008
1009                         // --- means same mobile theme as desktop
1010                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1011                                 $user_theme = $user_mobile_theme;
1012                         }
1013                 }
1014
1015                 if ($page_theme) {
1016                         $theme_name = $page_theme;
1017                 } else {
1018                         $theme_name = $user_theme;
1019                 }
1020
1021                 if ($theme_name
1022                         && in_array($theme_name, $allowed_themes)
1023                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1024                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1025                 ) {
1026                         $this->currentTheme = $theme_name;
1027                 }
1028         }
1029
1030         /**
1031          * @brief Return full URL to theme which is currently in effect.
1032          *
1033          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1034          *
1035          * @return string
1036          * @throws InternalServerErrorException
1037          */
1038         public function getCurrentThemeStylesheetPath()
1039         {
1040                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1041         }
1042
1043         /**
1044          * Check if request was an AJAX (xmlhttprequest) request.
1045          *
1046          * @return boolean true if it was an AJAX request
1047          */
1048         public function isAjax()
1049         {
1050                 return $this->isAjax;
1051         }
1052
1053         /**
1054          * Returns the value of a argv key
1055          * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1056          *
1057          * @param int $position the position of the argument
1058          * @param mixed $default the default value if not found
1059          *
1060          * @return mixed returns the value of the argument
1061          */
1062         public function getArgumentValue($position, $default = '')
1063         {
1064                 if (array_key_exists($position, $this->argv)) {
1065                         return $this->argv[$position];
1066                 }
1067
1068                 return $default;
1069         }
1070
1071         /**
1072          * Sets the base url for use in cmdline programs which don't have
1073          * $_SERVER variables
1074          */
1075         public function checkURL()
1076         {
1077                 $url = Core\Config::get('system', 'url');
1078
1079                 // if the url isn't set or the stored url is radically different
1080                 // than the currently visited url, store the current value accordingly.
1081                 // "Radically different" ignores common variations such as http vs https
1082                 // and www.example.com vs example.com.
1083                 // We will only change the url to an ip address if there is no existing setting
1084
1085                 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()))) {
1086                         Core\Config::set('system', 'url', $this->getBaseURL());
1087                 }
1088         }
1089
1090         /**
1091          * Frontend App script
1092          *
1093          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1094          * request and a representation of the response.
1095          *
1096          * This probably should change to limit the size of this monster method.
1097          */
1098         public function runFrontend()
1099         {
1100                 // Missing DB connection: ERROR
1101                 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1102                         Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1103                 }
1104
1105                 // Max Load Average reached: ERROR
1106                 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1107                         header('Retry-After: 120');
1108                         header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1109
1110                         Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1111                 }
1112
1113                 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1114                         Core\System::httpExit(404);
1115                 }
1116
1117                 if (!$this->getMode()->isInstall()) {
1118                         // Force SSL redirection
1119                         if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1120                                 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1121                                 && strpos($this->getBaseURL(), 'https://') === 0
1122                                 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1123                                 header('HTTP/1.1 302 Moved Temporarily');
1124                                 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1125                                 exit();
1126                         }
1127
1128                         Core\Session::init();
1129                         Core\Hook::callAll('init_1');
1130                 }
1131
1132                 // Exclude the backend processes from the session management
1133                 if (!$this->isBackend()) {
1134                         $stamp1 = microtime(true);
1135                         session_start();
1136                         $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1137                         Core\L10n::setSessionVariable();
1138                         Core\L10n::setLangFromSession();
1139                 } else {
1140                         $_SESSION = [];
1141                         Core\Worker::executeIfIdle();
1142                 }
1143
1144                 // ZRL
1145                 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1146                         $this->query_string = Model\Profile::stripZrls($this->query_string);
1147                         if (!local_user()) {
1148                                 // Only continue when the given profile link seems valid
1149                                 // Valid profile links contain a path with "/profile/" and no query parameters
1150                                 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1151                                         strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1152                                         if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1153                                                 $_SESSION['my_url'] = $_GET['zrl'];
1154                                                 $_SESSION['authenticated'] = 0;
1155                                         }
1156                                         Model\Profile::zrlInit($this);
1157                                 } else {
1158                                         // Someone came with an invalid parameter, maybe as a DDoS attempt
1159                                         // We simply stop processing here
1160                                         Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1161                                         Core\System::httpExit(403, ['title' => '403 Forbidden']);
1162                                 }
1163                         }
1164                 }
1165
1166                 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1167                         $token = $_GET['owt'];
1168                         $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1169                         Model\Profile::openWebAuthInit($token);
1170                 }
1171
1172                 Module\Login::sessionAuth();
1173
1174                 if (empty($_SESSION['authenticated'])) {
1175                         header('X-Account-Management-Status: none');
1176                 }
1177
1178                 $_SESSION['sysmsg']       = defaults($_SESSION, 'sysmsg'      , []);
1179                 $_SESSION['sysmsg_info']  = defaults($_SESSION, 'sysmsg_info' , []);
1180                 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1181
1182                 /*
1183                  * check_config() is responsible for running update scripts. These automatically
1184                  * update the DB schema whenever we push a new one out. It also checks to see if
1185                  * any addons have been added or removed and reacts accordingly.
1186                  */
1187
1188                 // in install mode, any url loads install module
1189                 // but we need "view" module for stylesheet
1190                 if ($this->getMode()->isInstall() && $this->module != 'view') {
1191                         $this->module = 'install';
1192                 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1193                         $this->module = 'maintenance';
1194                 } else {
1195                         $this->checkURL();
1196                         Core\Update::check($this->basePath, false);
1197                         Core\Addon::loadAddons();
1198                         Core\Hook::loadHooks();
1199                 }
1200
1201                 $this->page = [
1202                         'aside' => '',
1203                         'bottom' => '',
1204                         'content' => '',
1205                         'footer' => '',
1206                         'htmlhead' => '',
1207                         'nav' => '',
1208                         'page_title' => '',
1209                         'right_aside' => '',
1210                         'template' => '',
1211                         'title' => ''
1212                 ];
1213
1214                 if (strlen($this->module)) {
1215                         // Compatibility with the Android Diaspora client
1216                         if ($this->module == 'stream') {
1217                                 $this->internalRedirect('network?f=&order=post');
1218                         }
1219
1220                         if ($this->module == 'conversations') {
1221                                 $this->internalRedirect('message');
1222                         }
1223
1224                         if ($this->module == 'commented') {
1225                                 $this->internalRedirect('network?f=&order=comment');
1226                         }
1227
1228                         if ($this->module == 'liked') {
1229                                 $this->internalRedirect('network?f=&order=comment');
1230                         }
1231
1232                         if ($this->module == 'activity') {
1233                                 $this->internalRedirect('network/?f=&conv=1');
1234                         }
1235
1236                         if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1237                                 $this->internalRedirect('bookmarklet');
1238                         }
1239
1240                         if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1241                                 $this->internalRedirect('settings');
1242                         }
1243
1244                         if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1245                                 $this->internalRedirect('search');
1246                         }
1247
1248                         // Compatibility with the Firefox App
1249                         if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1250                                 $this->module = "login";
1251                         }
1252
1253                         $privateapps = Core\Config::get('config', 'private_addons', false);
1254                         if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1255                                 //Check if module is an app and if public access to apps is allowed or not
1256                                 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1257                                         info(Core\L10n::t("You must be logged in to use addons. "));
1258                                 } else {
1259                                         include_once "addon/{$this->module}/{$this->module}.php";
1260                                         if (function_exists($this->module . '_module')) {
1261                                                 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1262                                                 $this->module_class = 'Friendica\\LegacyModule';
1263                                                 $this->module_loaded = true;
1264                                         }
1265                                 }
1266                         }
1267
1268                         // Controller class routing
1269                         if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1270                                 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1271                                 $this->module_loaded = true;
1272                         }
1273
1274                         /* If not, next look for a 'standard' program module in the 'mod' directory
1275                          * We emulate a Module class through the LegacyModule class
1276                          */
1277                         if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1278                                 LegacyModule::setModuleFile("mod/{$this->module}.php");
1279                                 $this->module_class = 'Friendica\\LegacyModule';
1280                                 $this->module_loaded = true;
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_loaded) {
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_loaded) {
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_loaded) {
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 (Core\Config::get('system', 'hsts') && (Core\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 }