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