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