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