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