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