]> git.mxchange.org Git - friendica.git/blob - src/App.php
Move Global Functions - Part 3
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use Exception;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Network\HTTPException\InternalServerErrorException;
15
16 require_once 'boot.php';
17 require_once 'include/dba.php';
18 require_once 'include/text.php';
19
20 /**
21  *
22  * class: App
23  *
24  * @brief Our main application structure for the life of this page.
25  *
26  * Primarily deals with the URL that got us here
27  * and tries to make some sense of it, and
28  * stores our page contents and config storage
29  * and anything else that might need to be passed around
30  * before we spit the page out.
31  *
32  */
33 class App
34 {
35         public $module_loaded = false;
36         public $module_class = null;
37         public $query_string = '';
38         public $config = [];
39         public $page = [];
40         public $pager = [];
41         public $page_offset;
42         public $profile;
43         public $profile_uid;
44         public $user;
45         public $cid;
46         public $contact;
47         public $contacts;
48         public $page_contact;
49         public $content;
50         public $data = [];
51         public $error = false;
52         public $cmd = '';
53         public $argv;
54         public $argc;
55         public $module;
56         public $strings;
57         public $hooks = [];
58         public $timezone;
59         public $interactive = true;
60         public $addons;
61         public $addons_admin = [];
62         public $apps = [];
63         public $identities;
64         public $is_mobile = false;
65         public $is_tablet = false;
66         public $performance = [];
67         public $callstack = [];
68         public $theme_info = [];
69         public $nav_sel;
70         public $category;
71         // Allow themes to control internal parameters
72         // by changing App values in theme.php
73
74         public $sourcename = '';
75         public $videowidth = 425;
76         public $videoheight = 350;
77         public $force_max_items = 0;
78         public $theme_events_in_profile = true;
79
80         public $stylesheets = [];
81         public $footerScripts = [];
82
83         /**
84          * @var App\Mode The Mode of the Application
85          */
86         private $mode;
87
88         /**
89          * @var string The App base path
90          */
91         private $basePath;
92
93         /**
94          * @var string The App URL path
95          */
96         private $urlPath;
97
98         /**
99          * @var bool true, if the call is from the Friendica APP, otherwise false
100          */
101         private $isFriendicaApp;
102
103         /**
104          * @var bool true, if the call is from an backend node (f.e. worker)
105          */
106         private $isBackend;
107
108         /**
109          * @var string The name of the current theme
110          */
111         private $currentTheme;
112
113         /**
114          * @var bool check if request was an AJAX (xmlhttprequest) request
115          */
116         private $isAjax;
117
118         /**
119          * Register a stylesheet file path to be included in the <head> tag of every page.
120          * Inclusion is done in App->initHead().
121          * The path can be absolute or relative to the Friendica installation base folder.
122          *
123          * @see App->initHead()
124          *
125          * @param string $path
126          */
127         public function registerStylesheet($path)
128         {
129                 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
130
131                 $this->stylesheets[] = trim($url, '/');
132         }
133
134         /**
135          * Register a javascript file path to be included in the <footer> tag of every page.
136          * Inclusion is done in App->initFooter().
137          * The path can be absolute or relative to the Friendica installation base folder.
138          *
139          * @see App->initFooter()
140          *
141          * @param string $path
142          */
143         public function registerFooterScript($path)
144         {
145                 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
146
147                 $this->footerScripts[] = trim($url, '/');
148         }
149
150         /**
151          * @brief An array for all theme-controllable parameters
152          *
153          * Mostly unimplemented yet. Only options 'template_engine' and
154          * beyond are used.
155          */
156         public $theme = [
157                 'sourcename' => '',
158                 'videowidth' => 425,
159                 'videoheight' => 350,
160                 'force_max_items' => 0,
161                 'stylesheet' => '',
162                 'template_engine' => 'smarty3',
163         ];
164
165         /**
166          * @brief An array of registered template engines ('name'=>'class name')
167          */
168         public $template_engines = [];
169
170         /**
171          * @brief An array of instanced template engines ('name'=>'instance')
172          */
173         public $template_engine_instance = [];
174         public $process_id;
175         public $queue;
176         private $ldelim = [
177                 'internal' => '',
178                 'smarty3' => '{{'
179         ];
180         private $rdelim = [
181                 'internal' => '',
182                 'smarty3' => '}}'
183         ];
184         private $scheme;
185         private $hostname;
186
187         /**
188          * @brief App constructor.
189          *
190          * @param string $basePath Path to the app base folder
191          * @param bool $backend true, if the call is from backend, otherwise set to true (Default true)
192          *
193          * @throws Exception if the Basepath is not usable
194          */
195         public function __construct($basePath, $backend = true)
196         {
197                 if (!static::isDirectoryUsable($basePath, false)) {
198                         throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
199                 }
200
201                 BaseObject::setApp($this);
202
203                 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
204                 $this->checkBackend($backend);
205                 $this->checkFriendicaApp();
206
207                 $this->performance['start'] = microtime(true);
208                 $this->performance['database'] = 0;
209                 $this->performance['database_write'] = 0;
210                 $this->performance['cache'] = 0;
211                 $this->performance['cache_write'] = 0;
212                 $this->performance['network'] = 0;
213                 $this->performance['file'] = 0;
214                 $this->performance['rendering'] = 0;
215                 $this->performance['parser'] = 0;
216                 $this->performance['marktime'] = 0;
217                 $this->performance['markstart'] = microtime(true);
218
219                 $this->callstack['database'] = [];
220                 $this->callstack['database_write'] = [];
221                 $this->callstack['cache'] = [];
222                 $this->callstack['cache_write'] = [];
223                 $this->callstack['network'] = [];
224                 $this->callstack['file'] = [];
225                 $this->callstack['rendering'] = [];
226                 $this->callstack['parser'] = [];
227
228                 $this->mode = new App\Mode($basePath);
229
230                 $this->reload();
231
232                 set_time_limit(0);
233
234                 // This has to be quite large to deal with embedded private photos
235                 ini_set('pcre.backtrack_limit', 500000);
236
237                 $this->scheme = 'http';
238
239                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
240                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
241                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
242                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
243                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
244                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
245                 ) {
246                         $this->scheme = 'https';
247                 }
248
249                 if (x($_SERVER, 'SERVER_NAME')) {
250                         $this->hostname = $_SERVER['SERVER_NAME'];
251
252                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
253                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
254                         }
255                 }
256
257                 set_include_path(
258                         get_include_path() . PATH_SEPARATOR
259                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
260                         . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
261                         . $this->getBasePath());
262
263                 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
264                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
265                 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
266                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
267                 }
268
269                 // removing trailing / - maybe a nginx problem
270                 $this->query_string = ltrim($this->query_string, '/');
271
272                 if (!empty($_GET['pagename'])) {
273                         $this->cmd = trim($_GET['pagename'], '/\\');
274                 } elseif (!empty($_GET['q'])) {
275                         $this->cmd = trim($_GET['q'], '/\\');
276                 }
277
278                 // fix query_string
279                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
280
281                 // unix style "homedir"
282                 if (substr($this->cmd, 0, 1) === '~') {
283                         $this->cmd = 'profile/' . substr($this->cmd, 1);
284                 }
285
286                 // Diaspora style profile url
287                 if (substr($this->cmd, 0, 2) === 'u/') {
288                         $this->cmd = 'profile/' . substr($this->cmd, 2);
289                 }
290
291                 /*
292                  * Break the URL path into C style argc/argv style arguments for our
293                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
294                  * will be 3 (integer) and $this->argv will contain:
295                  *   [0] => 'module'
296                  *   [1] => 'arg1'
297                  *   [2] => 'arg2'
298                  *
299                  *
300                  * There will always be one argument. If provided a naked domain
301                  * URL, $this->argv[0] is set to "home".
302                  */
303
304                 $this->argv = explode('/', $this->cmd);
305                 $this->argc = count($this->argv);
306                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
307                         $this->module = str_replace('.', '_', $this->argv[0]);
308                         $this->module = str_replace('-', '_', $this->module);
309                 } else {
310                         $this->argc = 1;
311                         $this->argv = ['home'];
312                         $this->module = 'home';
313                 }
314
315                 // See if there is any page number information, and initialise pagination
316                 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
317                 $this->pager['itemspage'] = 50;
318                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
319
320                 if ($this->pager['start'] < 0) {
321                         $this->pager['start'] = 0;
322                 }
323                 $this->pager['total'] = 0;
324
325                 // Detect mobile devices
326                 $mobile_detect = new MobileDetect();
327                 $this->is_mobile = $mobile_detect->isMobile();
328                 $this->is_tablet = $mobile_detect->isTablet();
329
330                 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
331
332                 // Register template engines
333                 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
334         }
335
336         /**
337          * Returns the Mode of the Application
338          *
339          * @return App\Mode The Application Mode
340          *
341          * @throws InternalServerErrorException when the mode isn't created
342          */
343         public function getMode()
344         {
345                 if (empty($this->mode)) {
346                         throw new InternalServerErrorException('Mode of the Application is not defined');
347                 }
348
349                 return $this->mode;
350         }
351
352         /**
353          * Reloads the whole app instance
354          */
355         public function reload()
356         {
357                 // The order of the following calls is important to ensure proper initialization
358                 $this->loadConfigFiles();
359
360                 $this->loadDatabase();
361
362                 $this->getMode()->determine($this->getBasePath());
363
364                 $this->determineURLPath();
365
366                 Config::load();
367
368                 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
369                         Core\Addon::loadHooks();
370
371                         $this->loadAddonConfig();
372                 }
373
374                 $this->loadDefaultTimezone();
375
376                 $this->page = [
377                         'aside' => '',
378                         'bottom' => '',
379                         'content' => '',
380                         'footer' => '',
381                         'htmlhead' => '',
382                         'nav' => '',
383                         'page_title' => '',
384                         'right_aside' => '',
385                         'template' => '',
386                         'title' => ''
387                 ];
388
389                 $this->process_id = System::processID('log');
390         }
391
392         /**
393          * Load the configuration files
394          *
395          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
396          * expected local.ini.php
397          */
398         private function loadConfigFiles()
399         {
400                 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
401                 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
402
403                 // Legacy .htconfig.php support
404                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
405                         $a = $this;
406                         include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
407                 }
408
409                 // Legacy .htconfig.php support
410                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
411                         $a = $this;
412
413                         include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
414
415                         $this->setConfigValue('database', 'hostname', $db_host);
416                         $this->setConfigValue('database', 'username', $db_user);
417                         $this->setConfigValue('database', 'password', $db_pass);
418                         $this->setConfigValue('database', 'database', $db_data);
419                         if (isset($a->config['system']['db_charset'])) {
420                                 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
421                         }
422
423                         unset($db_host, $db_user, $db_pass, $db_data);
424
425                         if (isset($default_timezone)) {
426                                 $this->setConfigValue('system', 'default_timezone', $default_timezone);
427                                 unset($default_timezone);
428                         }
429
430                         if (isset($pidfile)) {
431                                 $this->setConfigValue('system', 'pidfile', $pidfile);
432                                 unset($pidfile);
433                         }
434
435                         if (isset($lang)) {
436                                 $this->setConfigValue('system', 'language', $lang);
437                                 unset($lang);
438                         }
439                 }
440
441                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
442                         $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
443                 }
444         }
445
446         /**
447          * Tries to load the specified configuration file into the App->config array.
448          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
449          *
450          * The config format is INI and the template for configuration files is the following:
451          *
452          * <?php return <<<INI
453          *
454          * [section]
455          * key = value
456          *
457          * INI;
458          * // Keep this line
459          *
460          * @param string $filepath
461          * @param bool $overwrite Force value overwrite if the config key already exists
462          * @throws Exception
463          */
464         public function loadConfigFile($filepath, $overwrite = false)
465         {
466                 if (!file_exists($filepath)) {
467                         throw new Exception('Error parsing non-existent config file ' . $filepath);
468                 }
469
470                 $contents = include($filepath);
471
472                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
473
474                 if ($config === false) {
475                         throw new Exception('Error parsing config file ' . $filepath);
476                 }
477
478                 foreach ($config as $category => $values) {
479                         foreach ($values as $key => $value) {
480                                 if ($overwrite) {
481                                         $this->setConfigValue($category, $key, $value);
482                                 } else {
483                                         $this->setDefaultConfigValue($category, $key, $value);
484                                 }
485                         }
486                 }
487         }
488
489         /**
490          * Loads addons configuration files
491          *
492          * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
493          * again to overwrite potential local addon configuration.
494          */
495         private function loadAddonConfig()
496         {
497                 // Loads addons default config
498                 Core\Addon::callHooks('load_config');
499
500                 // Load the local addon config file to overwritten default addon config values
501                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
502                         $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
503                 }
504         }
505
506         /**
507          * Loads the default timezone
508          *
509          * Include support for legacy $default_timezone
510          *
511          * @global string $default_timezone
512          */
513         private function loadDefaultTimezone()
514         {
515                 if ($this->getConfigValue('system', 'default_timezone')) {
516                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
517                 } else {
518                         global $default_timezone;
519                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
520                 }
521
522                 if ($this->timezone) {
523                         date_default_timezone_set($this->timezone);
524                 }
525         }
526
527         /**
528          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
529          */
530         private function determineURLPath()
531         {
532                 /* Relative script path to the web server root
533                  * Not all of those $_SERVER properties can be present, so we do by inverse priority order
534                  */
535                 $relative_script_path = '';
536                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL'       , $relative_script_path);
537                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI'       , $relative_script_path);
538                 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
539                 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL'         , $relative_script_path);
540
541                 $this->urlPath = $this->getConfigValue('system', 'urlpath');
542
543                 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
544                  * QUERY_STRING gives pagename=module/parameter
545                  *
546                  * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
547                  */
548                 if (!empty($relative_script_path)) {
549                         // Module
550                         if (!empty($_SERVER['QUERY_STRING'])) {
551                                 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
552                         } else {
553                                 // Root page
554                                 $path = trim($relative_script_path, '/');
555                         }
556
557                         if ($path && $path != $this->urlPath) {
558                                 $this->urlPath = $path;
559                         }
560                 }
561         }
562
563         public function loadDatabase()
564         {
565                 if (DBA::connected()) {
566                         return;
567                 }
568
569                 $db_host = $this->getConfigValue('database', 'hostname');
570                 $db_user = $this->getConfigValue('database', 'username');
571                 $db_pass = $this->getConfigValue('database', 'password');
572                 $db_data = $this->getConfigValue('database', 'database');
573                 $charset = $this->getConfigValue('database', 'charset');
574
575                 // Use environment variables for mysql if they are set beforehand
576                 if (!empty(getenv('MYSQL_HOST'))
577                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
578                         && getenv('MYSQL_PASSWORD') !== false
579                         && !empty(getenv('MYSQL_DATABASE')))
580                 {
581                         $db_host = getenv('MYSQL_HOST');
582                         if (!empty(getenv('MYSQL_PORT'))) {
583                                 $db_host .= ':' . getenv('MYSQL_PORT');
584                         }
585                         if (!empty(getenv('MYSQL_USERNAME'))) {
586                                 $db_user = getenv('MYSQL_USERNAME');
587                         } else {
588                                 $db_user = getenv('MYSQL_USER');
589                         }
590                         $db_pass = (string) getenv('MYSQL_PASSWORD');
591                         $db_data = getenv('MYSQL_DATABASE');
592                 }
593
594                 $stamp1 = microtime(true);
595
596                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
597                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
598
599                 $this->saveTimestamp($stamp1, 'network');
600         }
601
602         /**
603          * @brief Returns the base filesystem path of the App
604          *
605          * It first checks for the internal variable, then for DOCUMENT_ROOT and
606          * finally for PWD
607          *
608          * @return string
609          */
610         public function getBasePath()
611         {
612                 $basepath = $this->basePath;
613
614                 if (!$basepath) {
615                         $basepath = Config::get('system', 'basepath');
616                 }
617
618                 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
619                         $basepath = $_SERVER['DOCUMENT_ROOT'];
620                 }
621
622                 if (!$basepath && x($_SERVER, 'PWD')) {
623                         $basepath = $_SERVER['PWD'];
624                 }
625
626                 return self::getRealPath($basepath);
627         }
628
629         /**
630          * @brief Returns a normalized file path
631          *
632          * This is a wrapper for the "realpath" function.
633          * That function cannot detect the real path when some folders aren't readable.
634          * Since this could happen with some hosters we need to handle this.
635          *
636          * @param string $path The path that is about to be normalized
637          * @return string normalized path - when possible
638          */
639         public static function getRealPath($path)
640         {
641                 $normalized = realpath($path);
642
643                 if (!is_bool($normalized)) {
644                         return $normalized;
645                 } else {
646                         return $path;
647                 }
648         }
649
650         public function getScheme()
651         {
652                 return $this->scheme;
653         }
654
655         /**
656          * @brief Retrieves the Friendica instance base URL
657          *
658          * This function assembles the base URL from multiple parts:
659          * - Protocol is determined either by the request or a combination of
660          * system.ssl_policy and the $ssl parameter.
661          * - Host name is determined either by system.hostname or inferred from request
662          * - Path is inferred from SCRIPT_NAME
663          *
664          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
665          *
666          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
667          * @return string Friendica server base URL
668          */
669         public function getBaseURL($ssl = false)
670         {
671                 $scheme = $this->scheme;
672
673                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
674                         $scheme = 'https';
675                 }
676
677                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
678                 //      (and also the login link). Anything seen by an outsider will have it turned off.
679
680                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
681                         if ($ssl) {
682                                 $scheme = 'https';
683                         } else {
684                                 $scheme = 'http';
685                         }
686                 }
687
688                 if (Config::get('config', 'hostname') != '') {
689                         $this->hostname = Config::get('config', 'hostname');
690                 }
691
692                 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
693         }
694
695         /**
696          * @brief Initializes the baseurl components
697          *
698          * Clears the baseurl cache to prevent inconsistencies
699          *
700          * @param string $url
701          */
702         public function setBaseURL($url)
703         {
704                 $parsed = @parse_url($url);
705                 $hostname = '';
706
707                 if (x($parsed)) {
708                         if (!empty($parsed['scheme'])) {
709                                 $this->scheme = $parsed['scheme'];
710                         }
711
712                         if (!empty($parsed['host'])) {
713                                 $hostname = $parsed['host'];
714                         }
715
716                         if (x($parsed, 'port')) {
717                                 $hostname .= ':' . $parsed['port'];
718                         }
719                         if (x($parsed, 'path')) {
720                                 $this->urlPath = trim($parsed['path'], '\\/');
721                         }
722
723                         if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
724                                 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
725                         }
726
727                         if (Config::get('config', 'hostname') != '') {
728                                 $this->hostname = Config::get('config', 'hostname');
729                         }
730
731                         if (!isset($this->hostname) || ($this->hostname == '')) {
732                                 $this->hostname = $hostname;
733                         }
734                 }
735         }
736
737         public function getHostName()
738         {
739                 if (Config::get('config', 'hostname') != '') {
740                         $this->hostname = Config::get('config', 'hostname');
741                 }
742
743                 return $this->hostname;
744         }
745
746         public function getURLPath()
747         {
748                 return $this->urlPath;
749         }
750
751         public function setPagerTotal($n)
752         {
753                 $this->pager['total'] = intval($n);
754         }
755
756         public function setPagerItemsPage($n)
757         {
758                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
759                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
760         }
761
762         public function setPagerPage($n)
763         {
764                 $this->pager['page'] = $n;
765                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
766         }
767
768         /**
769          * Initializes App->page['htmlhead'].
770          *
771          * Includes:
772          * - Page title
773          * - Favicons
774          * - Registered stylesheets (through App->registerStylesheet())
775          * - Infinite scroll data
776          * - head.tpl template
777          */
778         public function initHead()
779         {
780                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
781
782                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
783                 if ($interval < 0) {
784                         $interval = 2147483647;
785                 }
786
787                 if ($interval < 10000) {
788                         $interval = 40000;
789                 }
790
791                 // compose the page title from the sitename and the
792                 // current module called
793                 if (!$this->module == '') {
794                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
795                 } else {
796                         $this->page['title'] = $this->config['sitename'];
797                 }
798
799                 if (!empty($this->theme['stylesheet'])) {
800                         $stylesheet = $this->theme['stylesheet'];
801                 } else {
802                         $stylesheet = $this->getCurrentThemeStylesheetPath();
803                 }
804
805                 $this->registerStylesheet($stylesheet);
806
807                 $shortcut_icon = Config::get('system', 'shortcut_icon');
808                 if ($shortcut_icon == '') {
809                         $shortcut_icon = 'images/friendica-32.png';
810                 }
811
812                 $touch_icon = Config::get('system', 'touch_icon');
813                 if ($touch_icon == '') {
814                         $touch_icon = 'images/friendica-128.png';
815                 }
816
817                 // get data wich is needed for infinite scroll on the network page
818                 $infinite_scroll = infinite_scroll_data($this->module);
819
820                 Core\Addon::callHooks('head', $this->page['htmlhead']);
821
822                 $tpl = get_markup_template('head.tpl');
823                 /* put the head template at the beginning of page['htmlhead']
824                  * since the code added by the modules frequently depends on it
825                  * being first
826                  */
827                 $this->page['htmlhead'] = replace_macros($tpl, [
828                         '$baseurl'         => $this->getBaseURL(),
829                         '$local_user'      => local_user(),
830                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
831                         '$delitem'         => L10n::t('Delete this item?'),
832                         '$showmore'        => L10n::t('show more'),
833                         '$showfewer'       => L10n::t('show fewer'),
834                         '$update_interval' => $interval,
835                         '$shortcut_icon'   => $shortcut_icon,
836                         '$touch_icon'      => $touch_icon,
837                         '$infinite_scroll' => $infinite_scroll,
838                         '$block_public'    => intval(Config::get('system', 'block_public')),
839                         '$stylesheets'     => $this->stylesheets,
840                 ]) . $this->page['htmlhead'];
841         }
842
843         /**
844          * Initializes App->page['footer'].
845          *
846          * Includes:
847          * - Javascript homebase
848          * - Mobile toggle link
849          * - Registered footer scripts (through App->registerFooterScript())
850          * - footer.tpl template
851          */
852         public function initFooter()
853         {
854                 // If you're just visiting, let javascript take you home
855                 if (!empty($_SESSION['visitor_home'])) {
856                         $homebase = $_SESSION['visitor_home'];
857                 } elseif (local_user()) {
858                         $homebase = 'profile/' . $this->user['nickname'];
859                 }
860
861                 if (isset($homebase)) {
862                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
863                 }
864
865                 /*
866                  * Add a "toggle mobile" link if we're using a mobile device
867                  */
868                 if ($this->is_mobile || $this->is_tablet) {
869                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
870                                 $link = 'toggle_mobile?address=' . curPageURL();
871                         } else {
872                                 $link = 'toggle_mobile?off=1&address=' . curPageURL();
873                         }
874                         $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
875                                 '$toggle_link' => $link,
876                                 '$toggle_text' => Core\L10n::t('toggle mobile')
877                         ]);
878                 }
879
880                 Core\Addon::callHooks('footer', $this->page['footer']);
881
882                 $tpl = get_markup_template('footer.tpl');
883                 $this->page['footer'] = replace_macros($tpl, [
884                         '$baseurl' => $this->getBaseURL(),
885                         '$footerScripts' => $this->footerScripts,
886                 ]) . $this->page['footer'];
887         }
888
889         /**
890          * @brief Removes the base url from an url. This avoids some mixed content problems.
891          *
892          * @param string $origURL
893          *
894          * @return string The cleaned url
895          */
896         public function removeBaseURL($origURL)
897         {
898                 // Remove the hostname from the url if it is an internal link
899                 $nurl = normalise_link($origURL);
900                 $base = normalise_link($this->getBaseURL());
901                 $url = str_replace($base . '/', '', $nurl);
902
903                 // if it is an external link return the orignal value
904                 if ($url == normalise_link($origURL)) {
905                         return $origURL;
906                 } else {
907                         return $url;
908                 }
909         }
910
911         /**
912          * @brief Register template engine class
913          *
914          * @param string $class
915          */
916         private function registerTemplateEngine($class)
917         {
918                 $v = get_class_vars($class);
919                 if (x($v, 'name')) {
920                         $name = $v['name'];
921                         $this->template_engines[$name] = $class;
922                 } else {
923                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
924                         die();
925                 }
926         }
927
928         /**
929          * @brief Return template engine instance.
930          *
931          * If $name is not defined, return engine defined by theme,
932          * or default
933          *
934          * @return object Template Engine instance
935          */
936         public function getTemplateEngine()
937         {
938                 $template_engine = 'smarty3';
939                 if (x($this->theme, 'template_engine')) {
940                         $template_engine = $this->theme['template_engine'];
941                 }
942
943                 if (isset($this->template_engines[$template_engine])) {
944                         if (isset($this->template_engine_instance[$template_engine])) {
945                                 return $this->template_engine_instance[$template_engine];
946                         } else {
947                                 $class = $this->template_engines[$template_engine];
948                                 $obj = new $class;
949                                 $this->template_engine_instance[$template_engine] = $obj;
950                                 return $obj;
951                         }
952                 }
953
954                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
955                 killme();
956         }
957
958         /**
959          * @brief Returns the active template engine.
960          *
961          * @return string the active template engine
962          */
963         public function getActiveTemplateEngine()
964         {
965                 return $this->theme['template_engine'];
966         }
967
968         /**
969          * sets the active template engine
970          *
971          * @param string $engine the template engine (default is Smarty3)
972          */
973         public function setActiveTemplateEngine($engine = 'smarty3')
974         {
975                 $this->theme['template_engine'] = $engine;
976         }
977
978         /**
979          * Gets the right delimiter for a template engine
980          *
981          * Currently:
982          * Internal = ''
983          * Smarty3 = '{{'
984          *
985          * @param string $engine The template engine (default is Smarty3)
986          *
987          * @return string the right delimiter
988          */
989         public function getTemplateLeftDelimiter($engine = 'smarty3')
990         {
991                 return $this->ldelim[$engine];
992         }
993
994         /**
995          * Gets the left delimiter for a template engine
996          *
997          * Currently:
998          * Internal = ''
999          * Smarty3 = '}}'
1000          *
1001          * @param string $engine The template engine (default is Smarty3)
1002          *
1003          * @return string the left delimiter
1004          */
1005         public function getTemplateRightDelimiter($engine = 'smarty3')
1006         {
1007                 return $this->rdelim[$engine];
1008         }
1009
1010         /**
1011          * Saves a timestamp for a value - f.e. a call
1012          * Necessary for profiling Friendica
1013          *
1014          * @param int $timestamp the Timestamp
1015          * @param string $value A value to profile
1016          */
1017         public function saveTimestamp($timestamp, $value)
1018         {
1019                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1020                         return;
1021                 }
1022
1023                 $duration = (float) (microtime(true) - $timestamp);
1024
1025                 if (!isset($this->performance[$value])) {
1026                         // Prevent ugly E_NOTICE
1027                         $this->performance[$value] = 0;
1028                 }
1029
1030                 $this->performance[$value] += (float) $duration;
1031                 $this->performance['marktime'] += (float) $duration;
1032
1033                 $callstack = System::callstack();
1034
1035                 if (!isset($this->callstack[$value][$callstack])) {
1036                         // Prevent ugly E_NOTICE
1037                         $this->callstack[$value][$callstack] = 0;
1038                 }
1039
1040                 $this->callstack[$value][$callstack] += (float) $duration;
1041         }
1042
1043         /**
1044          * Returns the current UserAgent as a String
1045          *
1046          * @return string the UserAgent as a String
1047          */
1048         public function getUserAgent()
1049         {
1050                 return
1051                         FRIENDICA_PLATFORM . " '" .
1052                         FRIENDICA_CODENAME . "' " .
1053                         FRIENDICA_VERSION . '-' .
1054                         DB_UPDATE_VERSION . '; ' .
1055                         $this->getBaseURL();
1056         }
1057
1058         /**
1059          * Checks, if the call is from the Friendica App
1060          *
1061          * Reason:
1062          * The friendica client has problems with the GUID in the notify. this is some workaround
1063          */
1064         private function checkFriendicaApp()
1065         {
1066                 // Friendica-Client
1067                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1068         }
1069
1070         /**
1071          *      Is the call via the Friendica app? (not a "normale" call)
1072          *
1073          * @return bool true if it's from the Friendica app
1074          */
1075         public function isFriendicaApp()
1076         {
1077                 return $this->isFriendicaApp;
1078         }
1079
1080         /**
1081          * @brief Checks if the site is called via a backend process
1082          *
1083          * This isn't a perfect solution. But we need this check very early.
1084          * So we cannot wait until the modules are loaded.
1085          *
1086          * @param string $backend true, if the backend flag was set during App initialization
1087          *
1088          */
1089         private function checkBackend($backend) {
1090                 static $backends = [
1091                         '_well_known',
1092                         'api',
1093                         'dfrn_notify',
1094                         'fetch',
1095                         'hcard',
1096                         'hostxrd',
1097                         'nodeinfo',
1098                         'noscrape',
1099                         'p',
1100                         'poco',
1101                         'post',
1102                         'proxy',
1103                         'pubsub',
1104                         'pubsubhubbub',
1105                         'receive',
1106                         'rsd_xml',
1107                         'salmon',
1108                         'statistics_json',
1109                         'xrd',
1110                 ];
1111
1112                 // Check if current module is in backend or backend flag is set
1113                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1114         }
1115
1116         /**
1117          * Returns true, if the call is from a backend node (f.e. from a worker)
1118          *
1119          * @return bool Is it a known backend?
1120          */
1121         public function isBackend()
1122         {
1123                 return $this->isBackend;
1124         }
1125
1126         /**
1127          * @brief Checks if the maximum number of database processes is reached
1128          *
1129          * @return bool Is the limit reached?
1130          */
1131         public function isMaxProcessesReached()
1132         {
1133                 // Deactivated, needs more investigating if this check really makes sense
1134                 return false;
1135
1136                 /*
1137                  * Commented out to suppress static analyzer issues
1138                  *
1139                 if ($this->is_backend()) {
1140                         $process = 'backend';
1141                         $max_processes = Config::get('system', 'max_processes_backend');
1142                         if (intval($max_processes) == 0) {
1143                                 $max_processes = 5;
1144                         }
1145                 } else {
1146                         $process = 'frontend';
1147                         $max_processes = Config::get('system', 'max_processes_frontend');
1148                         if (intval($max_processes) == 0) {
1149                                 $max_processes = 20;
1150                         }
1151                 }
1152
1153                 $processlist = DBA::processlist();
1154                 if ($processlist['list'] != '') {
1155                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1156
1157                         if ($processlist['amount'] > $max_processes) {
1158                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1159                                 return true;
1160                         }
1161                 }
1162                 return false;
1163                  */
1164         }
1165
1166         /**
1167          * @brief Checks if the minimal memory is reached
1168          *
1169          * @return bool Is the memory limit reached?
1170          */
1171         public function isMinMemoryReached()
1172         {
1173                 $min_memory = Config::get('system', 'min_memory', 0);
1174                 if ($min_memory == 0) {
1175                         return false;
1176                 }
1177
1178                 if (!is_readable('/proc/meminfo')) {
1179                         return false;
1180                 }
1181
1182                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1183
1184                 $meminfo = [];
1185                 foreach ($memdata as $line) {
1186                         $data = explode(':', $line);
1187                         if (count($data) != 2) {
1188                                 continue;
1189                         }
1190                         list($key, $val) = $data;
1191                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1192                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1193                 }
1194
1195                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1196                         return false;
1197                 }
1198
1199                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1200
1201                 $reached = ($free < $min_memory);
1202
1203                 if ($reached) {
1204                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1205                 }
1206
1207                 return $reached;
1208         }
1209
1210         /**
1211          * @brief Checks if the maximum load is reached
1212          *
1213          * @return bool Is the load reached?
1214          */
1215         public function isMaxLoadReached()
1216         {
1217                 if ($this->isBackend()) {
1218                         $process = 'backend';
1219                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1220                         if ($maxsysload < 1) {
1221                                 $maxsysload = 50;
1222                         }
1223                 } else {
1224                         $process = 'frontend';
1225                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1226                         if ($maxsysload < 1) {
1227                                 $maxsysload = 50;
1228                         }
1229                 }
1230
1231                 $load = System::currentLoad();
1232                 if ($load) {
1233                         if (intval($load) > $maxsysload) {
1234                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1235                                 return true;
1236                         }
1237                 }
1238                 return false;
1239         }
1240
1241         /**
1242          * Executes a child process with 'proc_open'
1243          *
1244          * @param string $command The command to execute
1245          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1246          */
1247         public function proc_run($command, $args)
1248         {
1249                 if (!function_exists('proc_open')) {
1250                         return;
1251                 }
1252
1253                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1254
1255                 foreach ($args as $key => $value) {
1256                         if (!is_null($value) && is_bool($value) && !$value) {
1257                                 continue;
1258                         }
1259
1260                         $cmdline .= ' --' . $key;
1261                         if (!is_null($value) && !is_bool($value)) {
1262                                 $cmdline .= ' ' . $value;
1263                         }
1264                 }
1265
1266                 if ($this->isMinMemoryReached()) {
1267                         return;
1268                 }
1269
1270                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1271                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1272                 } else {
1273                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1274                 }
1275                 if (!is_resource($resource)) {
1276                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1277                         return;
1278                 }
1279                 proc_close($resource);
1280         }
1281
1282         /**
1283          * @brief Returns the system user that is executing the script
1284          *
1285          * This mostly returns something like "www-data".
1286          *
1287          * @return string system username
1288          */
1289         private static function getSystemUser()
1290         {
1291                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1292                         return '';
1293                 }
1294
1295                 $processUser = posix_getpwuid(posix_geteuid());
1296                 return $processUser['name'];
1297         }
1298
1299         /**
1300          * @brief Checks if a given directory is usable for the system
1301          *
1302          * @return boolean the directory is usable
1303          */
1304         public static function isDirectoryUsable($directory, $check_writable = true)
1305         {
1306                 if ($directory == '') {
1307                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1308                         return false;
1309                 }
1310
1311                 if (!file_exists($directory)) {
1312                         logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1313                         return false;
1314                 }
1315
1316                 if (is_file($directory)) {
1317                         logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1318                         return false;
1319                 }
1320
1321                 if (!is_dir($directory)) {
1322                         logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1323                         return false;
1324                 }
1325
1326                 if ($check_writable && !is_writable($directory)) {
1327                         logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1328                         return false;
1329                 }
1330
1331                 return true;
1332         }
1333
1334         /**
1335          * @param string $cat     Config category
1336          * @param string $k       Config key
1337          * @param mixed  $default Default value if it isn't set
1338          *
1339          * @return string Returns the value of the Config entry
1340          */
1341         public function getConfigValue($cat, $k, $default = null)
1342         {
1343                 $return = $default;
1344
1345                 if ($cat === 'config') {
1346                         if (isset($this->config[$k])) {
1347                                 $return = $this->config[$k];
1348                         }
1349                 } else {
1350                         if (isset($this->config[$cat][$k])) {
1351                                 $return = $this->config[$cat][$k];
1352                         }
1353                 }
1354
1355                 return $return;
1356         }
1357
1358         /**
1359          * Sets a default value in the config cache. Ignores already existing keys.
1360          *
1361          * @param string $cat Config category
1362          * @param string $k   Config key
1363          * @param mixed  $v   Default value to set
1364          */
1365         private function setDefaultConfigValue($cat, $k, $v)
1366         {
1367                 if (!isset($this->config[$cat][$k])) {
1368                         $this->setConfigValue($cat, $k, $v);
1369                 }
1370         }
1371
1372         /**
1373          * Sets a value in the config cache. Accepts raw output from the config table
1374          *
1375          * @param string $cat Config category
1376          * @param string $k   Config key
1377          * @param mixed  $v   Value to set
1378          */
1379         public function setConfigValue($cat, $k, $v)
1380         {
1381                 // Only arrays are serialized in database, so we have to unserialize sparingly
1382                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1383
1384                 if ($cat === 'config') {
1385                         $this->config[$k] = $value;
1386                 } else {
1387                         if (!isset($this->config[$cat])) {
1388                                 $this->config[$cat] = [];
1389                         }
1390
1391                         $this->config[$cat][$k] = $value;
1392                 }
1393         }
1394
1395         /**
1396          * Deletes a value from the config cache
1397          *
1398          * @param string $cat Config category
1399          * @param string $k   Config key
1400          */
1401         public function deleteConfigValue($cat, $k)
1402         {
1403                 if ($cat === 'config') {
1404                         if (isset($this->config[$k])) {
1405                                 unset($this->config[$k]);
1406                         }
1407                 } else {
1408                         if (isset($this->config[$cat][$k])) {
1409                                 unset($this->config[$cat][$k]);
1410                         }
1411                 }
1412         }
1413
1414
1415         /**
1416          * Retrieves a value from the user config cache
1417          *
1418          * @param int    $uid     User Id
1419          * @param string $cat     Config category
1420          * @param string $k       Config key
1421          * @param mixed  $default Default value if key isn't set
1422          *
1423          * @return string The value of the config entry
1424          */
1425         public function getPConfigValue($uid, $cat, $k, $default = null)
1426         {
1427                 $return = $default;
1428
1429                 if (isset($this->config[$uid][$cat][$k])) {
1430                         $return = $this->config[$uid][$cat][$k];
1431                 }
1432
1433                 return $return;
1434         }
1435
1436         /**
1437          * Sets a value in the user config cache
1438          *
1439          * Accepts raw output from the pconfig table
1440          *
1441          * @param int    $uid User Id
1442          * @param string $cat Config category
1443          * @param string $k   Config key
1444          * @param mixed  $v   Value to set
1445          */
1446         public function setPConfigValue($uid, $cat, $k, $v)
1447         {
1448                 // Only arrays are serialized in database, so we have to unserialize sparingly
1449                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1450
1451                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1452                         $this->config[$uid] = [];
1453                 }
1454
1455                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1456                         $this->config[$uid][$cat] = [];
1457                 }
1458
1459                 $this->config[$uid][$cat][$k] = $value;
1460         }
1461
1462         /**
1463          * Deletes a value from the user config cache
1464          *
1465          * @param int    $uid User Id
1466          * @param string $cat Config category
1467          * @param string $k   Config key
1468          */
1469         public function deletePConfigValue($uid, $cat, $k)
1470         {
1471                 if (isset($this->config[$uid][$cat][$k])) {
1472                         unset($this->config[$uid][$cat][$k]);
1473                 }
1474         }
1475
1476         /**
1477          * Generates the site's default sender email address
1478          *
1479          * @return string
1480          */
1481         public function getSenderEmailAddress()
1482         {
1483                 $sender_email = Config::get('config', 'sender_email');
1484                 if (empty($sender_email)) {
1485                         $hostname = $this->getHostName();
1486                         if (strpos($hostname, ':')) {
1487                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1488                         }
1489
1490                         $sender_email = 'noreply@' . $hostname;
1491                 }
1492
1493                 return $sender_email;
1494         }
1495
1496         /**
1497          * Returns the current theme name.
1498          *
1499          * @return string the name of the current theme
1500          */
1501         public function getCurrentTheme()
1502         {
1503                 if ($this->getMode()->isInstall()) {
1504                         return '';
1505                 }
1506
1507                 //// @TODO Compute the current theme only once (this behavior has
1508                 /// already been implemented, but it didn't work well -
1509                 /// https://github.com/friendica/friendica/issues/5092)
1510                 $this->computeCurrentTheme();
1511
1512                 return $this->currentTheme;
1513         }
1514
1515         /**
1516          * Computes the current theme name based on the node settings, the user settings and the device type
1517          *
1518          * @throws Exception
1519          */
1520         private function computeCurrentTheme()
1521         {
1522                 $system_theme = Config::get('system', 'theme');
1523                 if (!$system_theme) {
1524                         throw new Exception(L10n::t('No system theme config value set.'));
1525                 }
1526
1527                 // Sane default
1528                 $this->currentTheme = $system_theme;
1529
1530                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1531
1532                 $page_theme = null;
1533                 // Find the theme that belongs to the user whose stuff we are looking at
1534                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1535                         // Allow folks to override user themes and always use their own on their own site.
1536                         // This works only if the user is on the same server
1537                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1538                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1539                                 $page_theme = $user['theme'];
1540                         }
1541                 }
1542
1543                 $user_theme = Core\Session::get('theme', $system_theme);
1544
1545                 // Specific mobile theme override
1546                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1547                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1548                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1549
1550                         // --- means same mobile theme as desktop
1551                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1552                                 $user_theme = $user_mobile_theme;
1553                         }
1554                 }
1555
1556                 if ($page_theme) {
1557                         $theme_name = $page_theme;
1558                 } else {
1559                         $theme_name = $user_theme;
1560                 }
1561
1562                 if ($theme_name
1563                         && in_array($theme_name, $allowed_themes)
1564                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1565                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1566                 ) {
1567                         $this->currentTheme = $theme_name;
1568                 }
1569         }
1570
1571         /**
1572          * @brief Return full URL to theme which is currently in effect.
1573          *
1574          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1575          *
1576          * @return string
1577          */
1578         public function getCurrentThemeStylesheetPath()
1579         {
1580                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1581         }
1582
1583         /**
1584          * Check if request was an AJAX (xmlhttprequest) request.
1585          *
1586          * @return boolean true if it was an AJAX request
1587          */
1588         public function isAjax()
1589         {
1590                 return $this->isAjax;
1591         }
1592
1593         /**
1594          * Returns the value of a argv key
1595          * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1596          *
1597          * @param int $position the position of the argument
1598          * @param mixed $default the default value if not found
1599          *
1600          * @return mixed returns the value of the argument
1601          */
1602         public function getArgumentValue($position, $default = '')
1603         {
1604                 if (array_key_exists($position, $this->argv)) {
1605                         return $this->argv[$position];
1606                 }
1607
1608                 return $default;
1609         }
1610
1611         /**
1612          * Sets the base url for use in cmdline programs which don't have
1613          * $_SERVER variables
1614          */
1615         public function checkURL()
1616         {
1617                 $url = Config::get('system', 'url');
1618
1619                 // if the url isn't set or the stored url is radically different
1620                 // than the currently visited url, store the current value accordingly.
1621                 // "Radically different" ignores common variations such as http vs https
1622                 // and www.example.com vs example.com.
1623                 // We will only change the url to an ip address if there is no existing setting
1624
1625                 if (empty($url) || (!link_compare($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1626                         Config::set('system', 'url', $this->getBaseURL());
1627                 }
1628         }
1629 }