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