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