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