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