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