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