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