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