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