]> git.mxchange.org Git - friendica.git/blob - src/App.php
9bfb10f7ceeb7c188dcff8e8e77f60e9dfea4c30
[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                 $this->urlPath = $this->getConfigValue('system', 'urlpath');
526
527                 /* SCRIPT_URL gives /path/to/friendica/module/parameter
528                  * QUERY_STRING gives pagename=module/parameter
529                  *
530                  * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
531                  */
532                 if (!empty($_SERVER['SCRIPT_URL'])) {
533                         // Module
534                         if (!empty($_SERVER['QUERY_STRING'])) {
535                                 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
536                         } else {
537                                 // Root page
538                                 $path = trim($_SERVER['SCRIPT_URL'], '/');
539                         }
540
541                         if ($path && $path != $this->urlPath) {
542                                 $this->urlPath = $path;
543                         }
544                 }
545         }
546
547         public function loadDatabase()
548         {
549                 if (DBA::connected()) {
550                         return;
551                 }
552
553                 $db_host = $this->getConfigValue('database', 'hostname');
554                 $db_user = $this->getConfigValue('database', 'username');
555                 $db_pass = $this->getConfigValue('database', 'password');
556                 $db_data = $this->getConfigValue('database', 'database');
557                 $charset = $this->getConfigValue('database', 'charset');
558
559                 // Use environment variables for mysql if they are set beforehand
560                 if (!empty(getenv('MYSQL_HOST'))
561                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
562                         && getenv('MYSQL_PASSWORD') !== false
563                         && !empty(getenv('MYSQL_DATABASE')))
564                 {
565                         $db_host = getenv('MYSQL_HOST');
566                         if (!empty(getenv('MYSQL_PORT'))) {
567                                 $db_host .= ':' . getenv('MYSQL_PORT');
568                         }
569                         if (!empty(getenv('MYSQL_USERNAME'))) {
570                                 $db_user = getenv('MYSQL_USERNAME');
571                         } else {
572                                 $db_user = getenv('MYSQL_USER');
573                         }
574                         $db_pass = (string) getenv('MYSQL_PASSWORD');
575                         $db_data = getenv('MYSQL_DATABASE');
576                 }
577
578                 $stamp1 = microtime(true);
579
580                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
581                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
582
583                 $this->saveTimestamp($stamp1, 'network');
584         }
585
586         /**
587          * @brief Returns the base filesystem path of the App
588          *
589          * It first checks for the internal variable, then for DOCUMENT_ROOT and
590          * finally for PWD
591          *
592          * @return string
593          */
594         public function getBasePath()
595         {
596                 $basepath = $this->basePath;
597
598                 if (!$basepath) {
599                         $basepath = Config::get('system', 'basepath');
600                 }
601
602                 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
603                         $basepath = $_SERVER['DOCUMENT_ROOT'];
604                 }
605
606                 if (!$basepath && x($_SERVER, 'PWD')) {
607                         $basepath = $_SERVER['PWD'];
608                 }
609
610                 return self::getRealPath($basepath);
611         }
612
613         /**
614          * @brief Returns a normalized file path
615          *
616          * This is a wrapper for the "realpath" function.
617          * That function cannot detect the real path when some folders aren't readable.
618          * Since this could happen with some hosters we need to handle this.
619          *
620          * @param string $path The path that is about to be normalized
621          * @return string normalized path - when possible
622          */
623         public static function getRealPath($path)
624         {
625                 $normalized = realpath($path);
626
627                 if (!is_bool($normalized)) {
628                         return $normalized;
629                 } else {
630                         return $path;
631                 }
632         }
633
634         public function getScheme()
635         {
636                 return $this->scheme;
637         }
638
639         /**
640          * @brief Retrieves the Friendica instance base URL
641          *
642          * This function assembles the base URL from multiple parts:
643          * - Protocol is determined either by the request or a combination of
644          * system.ssl_policy and the $ssl parameter.
645          * - Host name is determined either by system.hostname or inferred from request
646          * - Path is inferred from SCRIPT_NAME
647          *
648          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
649          *
650          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
651          * @return string Friendica server base URL
652          */
653         public function getBaseURL($ssl = false)
654         {
655                 $scheme = $this->scheme;
656
657                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
658                         $scheme = 'https';
659                 }
660
661                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
662                 //      (and also the login link). Anything seen by an outsider will have it turned off.
663
664                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
665                         if ($ssl) {
666                                 $scheme = 'https';
667                         } else {
668                                 $scheme = 'http';
669                         }
670                 }
671
672                 if (Config::get('config', 'hostname') != '') {
673                         $this->hostname = Config::get('config', 'hostname');
674                 }
675
676                 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
677         }
678
679         /**
680          * @brief Initializes the baseurl components
681          *
682          * Clears the baseurl cache to prevent inconsistencies
683          *
684          * @param string $url
685          */
686         public function setBaseURL($url)
687         {
688                 $parsed = @parse_url($url);
689                 $hostname = '';
690
691                 if (x($parsed)) {
692                         if (!empty($parsed['scheme'])) {
693                                 $this->scheme = $parsed['scheme'];
694                         }
695
696                         if (!empty($parsed['host'])) {
697                                 $hostname = $parsed['host'];
698                         }
699
700                         if (x($parsed, 'port')) {
701                                 $hostname .= ':' . $parsed['port'];
702                         }
703                         if (x($parsed, 'path')) {
704                                 $this->urlPath = trim($parsed['path'], '\\/');
705                         }
706
707                         if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
708                                 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
709                         }
710
711                         if (Config::get('config', 'hostname') != '') {
712                                 $this->hostname = Config::get('config', 'hostname');
713                         }
714
715                         if (!isset($this->hostname) || ($this->hostname == '')) {
716                                 $this->hostname = $hostname;
717                         }
718                 }
719         }
720
721         public function getHostName()
722         {
723                 if (Config::get('config', 'hostname') != '') {
724                         $this->hostname = Config::get('config', 'hostname');
725                 }
726
727                 return $this->hostname;
728         }
729
730         public function getURLPath()
731         {
732                 return $this->urlPath;
733         }
734
735         public function setPagerTotal($n)
736         {
737                 $this->pager['total'] = intval($n);
738         }
739
740         public function setPagerItemsPage($n)
741         {
742                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
743                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
744         }
745
746         public function setPagerPage($n)
747         {
748                 $this->pager['page'] = $n;
749                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
750         }
751
752         /**
753          * Initializes App->page['htmlhead'].
754          *
755          * Includes:
756          * - Page title
757          * - Favicons
758          * - Registered stylesheets (through App->registerStylesheet())
759          * - Infinite scroll data
760          * - head.tpl template
761          */
762         public function initHead()
763         {
764                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
765
766                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
767                 if ($interval < 0) {
768                         $interval = 2147483647;
769                 }
770
771                 if ($interval < 10000) {
772                         $interval = 40000;
773                 }
774
775                 // compose the page title from the sitename and the
776                 // current module called
777                 if (!$this->module == '') {
778                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
779                 } else {
780                         $this->page['title'] = $this->config['sitename'];
781                 }
782
783                 if (!empty($this->theme['stylesheet'])) {
784                         $stylesheet = $this->theme['stylesheet'];
785                 } else {
786                         $stylesheet = $this->getCurrentThemeStylesheetPath();
787                 }
788
789                 $this->registerStylesheet($stylesheet);
790
791                 $shortcut_icon = Config::get('system', 'shortcut_icon');
792                 if ($shortcut_icon == '') {
793                         $shortcut_icon = 'images/friendica-32.png';
794                 }
795
796                 $touch_icon = Config::get('system', 'touch_icon');
797                 if ($touch_icon == '') {
798                         $touch_icon = 'images/friendica-128.png';
799                 }
800
801                 // get data wich is needed for infinite scroll on the network page
802                 $infinite_scroll = infinite_scroll_data($this->module);
803
804                 Core\Addon::callHooks('head', $this->page['htmlhead']);
805
806                 $tpl = get_markup_template('head.tpl');
807                 /* put the head template at the beginning of page['htmlhead']
808                  * since the code added by the modules frequently depends on it
809                  * being first
810                  */
811                 $this->page['htmlhead'] = replace_macros($tpl, [
812                         '$baseurl'         => $this->getBaseURL(),
813                         '$local_user'      => local_user(),
814                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
815                         '$delitem'         => L10n::t('Delete this item?'),
816                         '$showmore'        => L10n::t('show more'),
817                         '$showfewer'       => L10n::t('show fewer'),
818                         '$update_interval' => $interval,
819                         '$shortcut_icon'   => $shortcut_icon,
820                         '$touch_icon'      => $touch_icon,
821                         '$infinite_scroll' => $infinite_scroll,
822                         '$block_public'    => intval(Config::get('system', 'block_public')),
823                         '$stylesheets'     => $this->stylesheets,
824                 ]) . $this->page['htmlhead'];
825         }
826
827         /**
828          * Initializes App->page['footer'].
829          *
830          * Includes:
831          * - Javascript homebase
832          * - Mobile toggle link
833          * - Registered footer scripts (through App->registerFooterScript())
834          * - footer.tpl template
835          */
836         public function initFooter()
837         {
838                 // If you're just visiting, let javascript take you home
839                 if (!empty($_SESSION['visitor_home'])) {
840                         $homebase = $_SESSION['visitor_home'];
841                 } elseif (local_user()) {
842                         $homebase = 'profile/' . $this->user['nickname'];
843                 }
844
845                 if (isset($homebase)) {
846                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
847                 }
848
849                 /*
850                  * Add a "toggle mobile" link if we're using a mobile device
851                  */
852                 if ($this->is_mobile || $this->is_tablet) {
853                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
854                                 $link = 'toggle_mobile?address=' . curPageURL();
855                         } else {
856                                 $link = 'toggle_mobile?off=1&address=' . curPageURL();
857                         }
858                         $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
859                                 '$toggle_link' => $link,
860                                 '$toggle_text' => Core\L10n::t('toggle mobile')
861                         ]);
862                 }
863
864                 Core\Addon::callHooks('footer', $this->page['footer']);
865
866                 $tpl = get_markup_template('footer.tpl');
867                 $this->page['footer'] = replace_macros($tpl, [
868                         '$baseurl' => $this->getBaseURL(),
869                         '$footerScripts' => $this->footerScripts,
870                 ]) . $this->page['footer'];
871         }
872
873         /**
874          * @brief Removes the base url from an url. This avoids some mixed content problems.
875          *
876          * @param string $origURL
877          *
878          * @return string The cleaned url
879          */
880         public function removeBaseURL($origURL)
881         {
882                 // Remove the hostname from the url if it is an internal link
883                 $nurl = normalise_link($origURL);
884                 $base = normalise_link($this->getBaseURL());
885                 $url = str_replace($base . '/', '', $nurl);
886
887                 // if it is an external link return the orignal value
888                 if ($url == normalise_link($origURL)) {
889                         return $origURL;
890                 } else {
891                         return $url;
892                 }
893         }
894
895         /**
896          * @brief Register template engine class
897          *
898          * @param string $class
899          */
900         private function registerTemplateEngine($class)
901         {
902                 $v = get_class_vars($class);
903                 if (x($v, 'name')) {
904                         $name = $v['name'];
905                         $this->template_engines[$name] = $class;
906                 } else {
907                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
908                         die();
909                 }
910         }
911
912         /**
913          * @brief Return template engine instance.
914          *
915          * If $name is not defined, return engine defined by theme,
916          * or default
917          *
918          * @return object Template Engine instance
919          */
920         public function getTemplateEngine()
921         {
922                 $template_engine = 'smarty3';
923                 if (x($this->theme, 'template_engine')) {
924                         $template_engine = $this->theme['template_engine'];
925                 }
926
927                 if (isset($this->template_engines[$template_engine])) {
928                         if (isset($this->template_engine_instance[$template_engine])) {
929                                 return $this->template_engine_instance[$template_engine];
930                         } else {
931                                 $class = $this->template_engines[$template_engine];
932                                 $obj = new $class;
933                                 $this->template_engine_instance[$template_engine] = $obj;
934                                 return $obj;
935                         }
936                 }
937
938                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
939                 killme();
940         }
941
942         /**
943          * @brief Returns the active template engine.
944          *
945          * @return string the active template engine
946          */
947         public function getActiveTemplateEngine()
948         {
949                 return $this->theme['template_engine'];
950         }
951
952         /**
953          * sets the active template engine
954          *
955          * @param string $engine the template engine (default is Smarty3)
956          */
957         public function setActiveTemplateEngine($engine = 'smarty3')
958         {
959                 $this->theme['template_engine'] = $engine;
960         }
961
962         /**
963          * Gets the right delimiter for a template engine
964          *
965          * Currently:
966          * Internal = ''
967          * Smarty3 = '{{'
968          *
969          * @param string $engine The template engine (default is Smarty3)
970          *
971          * @return string the right delimiter
972          */
973         public function getTemplateLeftDelimiter($engine = 'smarty3')
974         {
975                 return $this->ldelim[$engine];
976         }
977
978         /**
979          * Gets the left 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 left delimiter
988          */
989         public function getTemplateRightDelimiter($engine = 'smarty3')
990         {
991                 return $this->rdelim[$engine];
992         }
993
994         /**
995          * Saves a timestamp for a value - f.e. a call
996          * Necessary for profiling Friendica
997          *
998          * @param int $timestamp the Timestamp
999          * @param string $value A value to profile
1000          */
1001         public function saveTimestamp($timestamp, $value)
1002         {
1003                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1004                         return;
1005                 }
1006
1007                 $duration = (float) (microtime(true) - $timestamp);
1008
1009                 if (!isset($this->performance[$value])) {
1010                         // Prevent ugly E_NOTICE
1011                         $this->performance[$value] = 0;
1012                 }
1013
1014                 $this->performance[$value] += (float) $duration;
1015                 $this->performance['marktime'] += (float) $duration;
1016
1017                 $callstack = System::callstack();
1018
1019                 if (!isset($this->callstack[$value][$callstack])) {
1020                         // Prevent ugly E_NOTICE
1021                         $this->callstack[$value][$callstack] = 0;
1022                 }
1023
1024                 $this->callstack[$value][$callstack] += (float) $duration;
1025         }
1026
1027         /**
1028          * Returns the current UserAgent as a String
1029          *
1030          * @return string the UserAgent as a String
1031          */
1032         public function getUserAgent()
1033         {
1034                 return
1035                         FRIENDICA_PLATFORM . " '" .
1036                         FRIENDICA_CODENAME . "' " .
1037                         FRIENDICA_VERSION . '-' .
1038                         DB_UPDATE_VERSION . '; ' .
1039                         $this->getBaseURL();
1040         }
1041
1042         /**
1043          * Checks, if the call is from the Friendica App
1044          *
1045          * Reason:
1046          * The friendica client has problems with the GUID in the notify. this is some workaround
1047          */
1048         private function checkFriendicaApp()
1049         {
1050                 // Friendica-Client
1051                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1052         }
1053
1054         /**
1055          *      Is the call via the Friendica app? (not a "normale" call)
1056          *
1057          * @return bool true if it's from the Friendica app
1058          */
1059         public function isFriendicaApp()
1060         {
1061                 return $this->isFriendicaApp;
1062         }
1063
1064         /**
1065          * @brief Checks if the site is called via a backend process
1066          *
1067          * This isn't a perfect solution. But we need this check very early.
1068          * So we cannot wait until the modules are loaded.
1069          *
1070          * @param string $backend true, if the backend flag was set during App initialization
1071          *
1072          */
1073         private function checkBackend($backend) {
1074                 static $backends = [
1075                         '_well_known',
1076                         'api',
1077                         'dfrn_notify',
1078                         'fetch',
1079                         'hcard',
1080                         'hostxrd',
1081                         'nodeinfo',
1082                         'noscrape',
1083                         'p',
1084                         'poco',
1085                         'post',
1086                         'proxy',
1087                         'pubsub',
1088                         'pubsubhubbub',
1089                         'receive',
1090                         'rsd_xml',
1091                         'salmon',
1092                         'statistics_json',
1093                         'xrd',
1094                 ];
1095
1096                 // Check if current module is in backend or backend flag is set
1097                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1098         }
1099
1100         /**
1101          * Returns true, if the call is from a backend node (f.e. from a worker)
1102          *
1103          * @return bool Is it a known backend?
1104          */
1105         public function isBackend()
1106         {
1107                 return $this->isBackend;
1108         }
1109
1110         /**
1111          * @brief Checks if the maximum number of database processes is reached
1112          *
1113          * @return bool Is the limit reached?
1114          */
1115         public function isMaxProcessesReached()
1116         {
1117                 // Deactivated, needs more investigating if this check really makes sense
1118                 return false;
1119
1120                 /*
1121                  * Commented out to suppress static analyzer issues
1122                  *
1123                 if ($this->is_backend()) {
1124                         $process = 'backend';
1125                         $max_processes = Config::get('system', 'max_processes_backend');
1126                         if (intval($max_processes) == 0) {
1127                                 $max_processes = 5;
1128                         }
1129                 } else {
1130                         $process = 'frontend';
1131                         $max_processes = Config::get('system', 'max_processes_frontend');
1132                         if (intval($max_processes) == 0) {
1133                                 $max_processes = 20;
1134                         }
1135                 }
1136
1137                 $processlist = DBA::processlist();
1138                 if ($processlist['list'] != '') {
1139                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1140
1141                         if ($processlist['amount'] > $max_processes) {
1142                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1143                                 return true;
1144                         }
1145                 }
1146                 return false;
1147                  */
1148         }
1149
1150         /**
1151          * @brief Checks if the minimal memory is reached
1152          *
1153          * @return bool Is the memory limit reached?
1154          */
1155         public function isMinMemoryReached()
1156         {
1157                 $min_memory = Config::get('system', 'min_memory', 0);
1158                 if ($min_memory == 0) {
1159                         return false;
1160                 }
1161
1162                 if (!is_readable('/proc/meminfo')) {
1163                         return false;
1164                 }
1165
1166                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1167
1168                 $meminfo = [];
1169                 foreach ($memdata as $line) {
1170                         $data = explode(':', $line);
1171                         if (count($data) != 2) {
1172                                 continue;
1173                         }
1174                         list($key, $val) = $data;
1175                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1176                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1177                 }
1178
1179                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1180                         return false;
1181                 }
1182
1183                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1184
1185                 $reached = ($free < $min_memory);
1186
1187                 if ($reached) {
1188                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1189                 }
1190
1191                 return $reached;
1192         }
1193
1194         /**
1195          * @brief Checks if the maximum load is reached
1196          *
1197          * @return bool Is the load reached?
1198          */
1199         public function isMaxLoadReached()
1200         {
1201                 if ($this->isBackend()) {
1202                         $process = 'backend';
1203                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1204                         if ($maxsysload < 1) {
1205                                 $maxsysload = 50;
1206                         }
1207                 } else {
1208                         $process = 'frontend';
1209                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1210                         if ($maxsysload < 1) {
1211                                 $maxsysload = 50;
1212                         }
1213                 }
1214
1215                 $load = current_load();
1216                 if ($load) {
1217                         if (intval($load) > $maxsysload) {
1218                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1219                                 return true;
1220                         }
1221                 }
1222                 return false;
1223         }
1224
1225         /**
1226          * Executes a child process with 'proc_open'
1227          *
1228          * @param string $command The command to execute
1229          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1230          */
1231         public function proc_run($command, $args)
1232         {
1233                 if (!function_exists('proc_open')) {
1234                         return;
1235                 }
1236
1237                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1238
1239                 foreach ($args as $key => $value) {
1240                         if (!is_null($value) && is_bool($value) && !$value) {
1241                                 continue;
1242                         }
1243
1244                         $cmdline .= ' --' . $key;
1245                         if (!is_null($value) && !is_bool($value)) {
1246                                 $cmdline .= ' ' . $value;
1247                         }
1248                 }
1249
1250                 if ($this->isMinMemoryReached()) {
1251                         return;
1252                 }
1253
1254                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1255                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1256                 } else {
1257                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1258                 }
1259                 if (!is_resource($resource)) {
1260                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1261                         return;
1262                 }
1263                 proc_close($resource);
1264         }
1265
1266         /**
1267          * @brief Returns the system user that is executing the script
1268          *
1269          * This mostly returns something like "www-data".
1270          *
1271          * @return string system username
1272          */
1273         private static function getSystemUser()
1274         {
1275                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1276                         return '';
1277                 }
1278
1279                 $processUser = posix_getpwuid(posix_geteuid());
1280                 return $processUser['name'];
1281         }
1282
1283         /**
1284          * @brief Checks if a given directory is usable for the system
1285          *
1286          * @return boolean the directory is usable
1287          */
1288         public static function isDirectoryUsable($directory, $check_writable = true)
1289         {
1290                 if ($directory == '') {
1291                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1292                         return false;
1293                 }
1294
1295                 if (!file_exists($directory)) {
1296                         logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1297                         return false;
1298                 }
1299
1300                 if (is_file($directory)) {
1301                         logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1302                         return false;
1303                 }
1304
1305                 if (!is_dir($directory)) {
1306                         logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1307                         return false;
1308                 }
1309
1310                 if ($check_writable && !is_writable($directory)) {
1311                         logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1312                         return false;
1313                 }
1314
1315                 return true;
1316         }
1317
1318         /**
1319          * @param string $cat     Config category
1320          * @param string $k       Config key
1321          * @param mixed  $default Default value if it isn't set
1322          *
1323          * @return string Returns the value of the Config entry
1324          */
1325         public function getConfigValue($cat, $k, $default = null)
1326         {
1327                 $return = $default;
1328
1329                 if ($cat === 'config') {
1330                         if (isset($this->config[$k])) {
1331                                 $return = $this->config[$k];
1332                         }
1333                 } else {
1334                         if (isset($this->config[$cat][$k])) {
1335                                 $return = $this->config[$cat][$k];
1336                         }
1337                 }
1338
1339                 return $return;
1340         }
1341
1342         /**
1343          * Sets a default value in the config cache. Ignores already existing keys.
1344          *
1345          * @param string $cat Config category
1346          * @param string $k   Config key
1347          * @param mixed  $v   Default value to set
1348          */
1349         private function setDefaultConfigValue($cat, $k, $v)
1350         {
1351                 if (!isset($this->config[$cat][$k])) {
1352                         $this->setConfigValue($cat, $k, $v);
1353                 }
1354         }
1355
1356         /**
1357          * Sets a value in the config cache. Accepts raw output from the config table
1358          *
1359          * @param string $cat Config category
1360          * @param string $k   Config key
1361          * @param mixed  $v   Value to set
1362          */
1363         public function setConfigValue($cat, $k, $v)
1364         {
1365                 // Only arrays are serialized in database, so we have to unserialize sparingly
1366                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1367
1368                 if ($cat === 'config') {
1369                         $this->config[$k] = $value;
1370                 } else {
1371                         if (!isset($this->config[$cat])) {
1372                                 $this->config[$cat] = [];
1373                         }
1374
1375                         $this->config[$cat][$k] = $value;
1376                 }
1377         }
1378
1379         /**
1380          * Deletes a value from the config cache
1381          *
1382          * @param string $cat Config category
1383          * @param string $k   Config key
1384          */
1385         public function deleteConfigValue($cat, $k)
1386         {
1387                 if ($cat === 'config') {
1388                         if (isset($this->config[$k])) {
1389                                 unset($this->config[$k]);
1390                         }
1391                 } else {
1392                         if (isset($this->config[$cat][$k])) {
1393                                 unset($this->config[$cat][$k]);
1394                         }
1395                 }
1396         }
1397
1398
1399         /**
1400          * Retrieves a value from the user config cache
1401          *
1402          * @param int    $uid     User Id
1403          * @param string $cat     Config category
1404          * @param string $k       Config key
1405          * @param mixed  $default Default value if key isn't set
1406          *
1407          * @return string The value of the config entry
1408          */
1409         public function getPConfigValue($uid, $cat, $k, $default = null)
1410         {
1411                 $return = $default;
1412
1413                 if (isset($this->config[$uid][$cat][$k])) {
1414                         $return = $this->config[$uid][$cat][$k];
1415                 }
1416
1417                 return $return;
1418         }
1419
1420         /**
1421          * Sets a value in the user config cache
1422          *
1423          * Accepts raw output from the pconfig table
1424          *
1425          * @param int    $uid User Id
1426          * @param string $cat Config category
1427          * @param string $k   Config key
1428          * @param mixed  $v   Value to set
1429          */
1430         public function setPConfigValue($uid, $cat, $k, $v)
1431         {
1432                 // Only arrays are serialized in database, so we have to unserialize sparingly
1433                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1434
1435                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1436                         $this->config[$uid] = [];
1437                 }
1438
1439                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1440                         $this->config[$uid][$cat] = [];
1441                 }
1442
1443                 $this->config[$uid][$cat][$k] = $value;
1444         }
1445
1446         /**
1447          * Deletes a value from the user config cache
1448          *
1449          * @param int    $uid User Id
1450          * @param string $cat Config category
1451          * @param string $k   Config key
1452          */
1453         public function deletePConfigValue($uid, $cat, $k)
1454         {
1455                 if (isset($this->config[$uid][$cat][$k])) {
1456                         unset($this->config[$uid][$cat][$k]);
1457                 }
1458         }
1459
1460         /**
1461          * Generates the site's default sender email address
1462          *
1463          * @return string
1464          */
1465         public function getSenderEmailAddress()
1466         {
1467                 $sender_email = Config::get('config', 'sender_email');
1468                 if (empty($sender_email)) {
1469                         $hostname = $this->getHostName();
1470                         if (strpos($hostname, ':')) {
1471                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1472                         }
1473
1474                         $sender_email = 'noreply@' . $hostname;
1475                 }
1476
1477                 return $sender_email;
1478         }
1479
1480         /**
1481          * Returns the current theme name.
1482          *
1483          * @return string the name of the current theme
1484          */
1485         public function getCurrentTheme()
1486         {
1487                 if ($this->getMode()->isInstall()) {
1488                         return '';
1489                 }
1490
1491                 //// @TODO Compute the current theme only once (this behavior has
1492                 /// already been implemented, but it didn't work well -
1493                 /// https://github.com/friendica/friendica/issues/5092)
1494                 $this->computeCurrentTheme();
1495
1496                 return $this->currentTheme;
1497         }
1498
1499         /**
1500          * Computes the current theme name based on the node settings, the user settings and the device type
1501          *
1502          * @throws Exception
1503          */
1504         private function computeCurrentTheme()
1505         {
1506                 $system_theme = Config::get('system', 'theme');
1507                 if (!$system_theme) {
1508                         throw new Exception(L10n::t('No system theme config value set.'));
1509                 }
1510
1511                 // Sane default
1512                 $this->currentTheme = $system_theme;
1513
1514                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1515
1516                 $page_theme = null;
1517                 // Find the theme that belongs to the user whose stuff we are looking at
1518                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1519                         // Allow folks to override user themes and always use their own on their own site.
1520                         // This works only if the user is on the same server
1521                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1522                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1523                                 $page_theme = $user['theme'];
1524                         }
1525                 }
1526
1527                 $user_theme = Core\Session::get('theme', $system_theme);
1528
1529                 // Specific mobile theme override
1530                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1531                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1532                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1533
1534                         // --- means same mobile theme as desktop
1535                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1536                                 $user_theme = $user_mobile_theme;
1537                         }
1538                 }
1539
1540                 if ($page_theme) {
1541                         $theme_name = $page_theme;
1542                 } else {
1543                         $theme_name = $user_theme;
1544                 }
1545
1546                 if ($theme_name
1547                         && in_array($theme_name, $allowed_themes)
1548                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1549                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1550                 ) {
1551                         $this->currentTheme = $theme_name;
1552                 }
1553         }
1554
1555         /**
1556          * @brief Return full URL to theme which is currently in effect.
1557          *
1558          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1559          *
1560          * @return string
1561          */
1562         public function getCurrentThemeStylesheetPath()
1563         {
1564                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1565         }
1566 }