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