]> git.mxchange.org Git - friendica.git/blob - src/App.php
Rename App Methods
[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 basepath
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 type $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 $orig_url
877          *
878          * @return string The cleaned url
879          */
880         public function removeBaseURL($orig_url)
881         {
882                 // Remove the hostname from the url if it is an internal link
883                 $nurl = normalise_link($orig_url);
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($orig_url)) {
889                         return $orig_url;
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
946          */
947         public function getActiveTemplateEngine()
948         {
949                 return $this->theme['template_engine'];
950         }
951
952         public function setActiveTemplateEngine($engine = 'smarty3')
953         {
954                 $this->theme['template_engine'] = $engine;
955         }
956
957         public function getTemplateLdelim($engine = 'smarty3')
958         {
959                 return $this->ldelim[$engine];
960         }
961
962         public function getTemplateRdelim($engine = 'smarty3')
963         {
964                 return $this->rdelim[$engine];
965         }
966
967         /**
968          * Saves a timestamp for a value - f.e. a call
969          * Necessary for profiling Friendica
970          *
971          * @param int $timestamp the Timestamp
972          * @param string $value A value to profile
973          */
974         public function saveTimestamp($timestamp, $value)
975         {
976                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
977                         return;
978                 }
979
980                 $duration = (float) (microtime(true) - $timestamp);
981
982                 if (!isset($this->performance[$value])) {
983                         // Prevent ugly E_NOTICE
984                         $this->performance[$value] = 0;
985                 }
986
987                 $this->performance[$value] += (float) $duration;
988                 $this->performance['marktime'] += (float) $duration;
989
990                 $callstack = System::callstack();
991
992                 if (!isset($this->callstack[$value][$callstack])) {
993                         // Prevent ugly E_NOTICE
994                         $this->callstack[$value][$callstack] = 0;
995                 }
996
997                 $this->callstack[$value][$callstack] += (float) $duration;
998         }
999
1000         /**
1001          * Returns the current UserAgent as a String
1002          *
1003          * @return string the UserAgent as a String
1004          */
1005         public function getUserAgent()
1006         {
1007                 return
1008                         FRIENDICA_PLATFORM . " '" .
1009                         FRIENDICA_CODENAME . "' " .
1010                         FRIENDICA_VERSION . '-' .
1011                         DB_UPDATE_VERSION . '; ' .
1012                         $this->getBaseURL();
1013         }
1014
1015         /**
1016          * Checks, if the call is from the Friendica App
1017          *
1018          * Reason:
1019          * The friendica client has problems with the GUID in the notify. this is some workaround
1020          */
1021         private function checkFriendicaApp()
1022         {
1023                 // Friendica-Client
1024                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1025         }
1026
1027         /**
1028          *      Is the call via the Friendica app? (not a "normale" call)
1029          *
1030          * @return bool true if it's from the Friendica app
1031          */
1032         public function isFriendicaApp()
1033         {
1034                 return $this->isFriendicaApp;
1035         }
1036
1037         /**
1038          * @brief Checks if the site is called via a backend process
1039          *
1040          * This isn't a perfect solution. But we need this check very early.
1041          * So we cannot wait until the modules are loaded.
1042          *
1043          */
1044         private function checkBackend($backend) {
1045                 static $backends = [
1046                         '_well_known',
1047                         'api',
1048                         'dfrn_notify',
1049                         'fetch',
1050                         'hcard',
1051                         'hostxrd',
1052                         'nodeinfo',
1053                         'noscrape',
1054                         'p',
1055                         'poco',
1056                         'post',
1057                         'proxy',
1058                         'pubsub',
1059                         'pubsubhubbub',
1060                         'receive',
1061                         'rsd_xml',
1062                         'salmon',
1063                         'statistics_json',
1064                         'xrd',
1065                 ];
1066
1067                 // Check if current module is in backend or backend flag is set
1068                 $this->isBackend = (in_array($this->module, $backends) || $this->isBackend);
1069         }
1070
1071         /**
1072          * Returns true, if the call is from a backend node (f.e. from a worker)
1073          *
1074          * @return bool Is it a known backend?
1075          */
1076         public function isBackend()
1077         {
1078                 return $this->isBackend;
1079         }
1080
1081         /**
1082          * @brief Checks if the maximum number of database processes is reached
1083          *
1084          * @return bool Is the limit reached?
1085          */
1086         public function isMaxProcessesReached()
1087         {
1088                 // Deactivated, needs more investigating if this check really makes sense
1089                 return false;
1090
1091                 /*
1092                  * Commented out to suppress static analyzer issues
1093                  *
1094                 if ($this->is_backend()) {
1095                         $process = 'backend';
1096                         $max_processes = Config::get('system', 'max_processes_backend');
1097                         if (intval($max_processes) == 0) {
1098                                 $max_processes = 5;
1099                         }
1100                 } else {
1101                         $process = 'frontend';
1102                         $max_processes = Config::get('system', 'max_processes_frontend');
1103                         if (intval($max_processes) == 0) {
1104                                 $max_processes = 20;
1105                         }
1106                 }
1107
1108                 $processlist = DBA::processlist();
1109                 if ($processlist['list'] != '') {
1110                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1111
1112                         if ($processlist['amount'] > $max_processes) {
1113                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1114                                 return true;
1115                         }
1116                 }
1117                 return false;
1118                  */
1119         }
1120
1121         /**
1122          * @brief Checks if the minimal memory is reached
1123          *
1124          * @return bool Is the memory limit reached?
1125          */
1126         public function isMinMemoryReached()
1127         {
1128                 $min_memory = Config::get('system', 'min_memory', 0);
1129                 if ($min_memory == 0) {
1130                         return false;
1131                 }
1132
1133                 if (!is_readable('/proc/meminfo')) {
1134                         return false;
1135                 }
1136
1137                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1138
1139                 $meminfo = [];
1140                 foreach ($memdata as $line) {
1141                         $data = explode(':', $line);
1142                         if (count($data) != 2) {
1143                                 continue;
1144                         }
1145                         list($key, $val) = $data;
1146                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1147                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1148                 }
1149
1150                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1151                         return false;
1152                 }
1153
1154                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1155
1156                 $reached = ($free < $min_memory);
1157
1158                 if ($reached) {
1159                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1160                 }
1161
1162                 return $reached;
1163         }
1164
1165         /**
1166          * @brief Checks if the maximum load is reached
1167          *
1168          * @return bool Is the load reached?
1169          */
1170         public function isMaxLoadReached()
1171         {
1172                 if ($this->isBackend()) {
1173                         $process = 'backend';
1174                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1175                         if ($maxsysload < 1) {
1176                                 $maxsysload = 50;
1177                         }
1178                 } else {
1179                         $process = 'frontend';
1180                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1181                         if ($maxsysload < 1) {
1182                                 $maxsysload = 50;
1183                         }
1184                 }
1185
1186                 $load = current_load();
1187                 if ($load) {
1188                         if (intval($load) > $maxsysload) {
1189                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1190                                 return true;
1191                         }
1192                 }
1193                 return false;
1194         }
1195
1196         /**
1197          * Executes a child process with 'proc_open'
1198          *
1199          * @param string $command The command to execute
1200          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1201          */
1202         public function proc_run($command, $args)
1203         {
1204                 if (!function_exists('proc_open')) {
1205                         return;
1206                 }
1207
1208                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1209
1210                 foreach ($args as $key => $value) {
1211                         if (!is_null($value) && is_bool($value) && !$value) {
1212                                 continue;
1213                         }
1214
1215                         $cmdline .= ' --' . $key;
1216                         if (!is_null($value) && !is_bool($value)) {
1217                                 $cmdline .= ' ' . $value;
1218                         }
1219                 }
1220
1221                 if ($this->isMinMemoryReached()) {
1222                         return;
1223                 }
1224
1225                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1226                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1227                 } else {
1228                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1229                 }
1230                 if (!is_resource($resource)) {
1231                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1232                         return;
1233                 }
1234                 proc_close($resource);
1235         }
1236
1237         /**
1238          * @brief Returns the system user that is executing the script
1239          *
1240          * This mostly returns something like "www-data".
1241          *
1242          * @return string system username
1243          */
1244         private static function getSystemUser()
1245         {
1246                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1247                         return '';
1248                 }
1249
1250                 $processUser = posix_getpwuid(posix_geteuid());
1251                 return $processUser['name'];
1252         }
1253
1254         /**
1255          * @brief Checks if a given directory is usable for the system
1256          *
1257          * @return boolean the directory is usable
1258          */
1259         public static function isDirectoryUsable($directory, $check_writable = true)
1260         {
1261                 if ($directory == '') {
1262                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1263                         return false;
1264                 }
1265
1266                 if (!file_exists($directory)) {
1267                         logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1268                         return false;
1269                 }
1270
1271                 if (is_file($directory)) {
1272                         logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1273                         return false;
1274                 }
1275
1276                 if (!is_dir($directory)) {
1277                         logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1278                         return false;
1279                 }
1280
1281                 if ($check_writable && !is_writable($directory)) {
1282                         logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1283                         return false;
1284                 }
1285
1286                 return true;
1287         }
1288
1289         /**
1290          * @param string $cat     Config category
1291          * @param string $k       Config key
1292          * @param mixed  $default Default value if it isn't set
1293          *
1294          * @return string Returns the value of the Config entry
1295          */
1296         public function getConfigValue($cat, $k, $default = null)
1297         {
1298                 $return = $default;
1299
1300                 if ($cat === 'config') {
1301                         if (isset($this->config[$k])) {
1302                                 $return = $this->config[$k];
1303                         }
1304                 } else {
1305                         if (isset($this->config[$cat][$k])) {
1306                                 $return = $this->config[$cat][$k];
1307                         }
1308                 }
1309
1310                 return $return;
1311         }
1312
1313         /**
1314          * Sets a default value in the config cache. Ignores already existing keys.
1315          *
1316          * @param string $cat Config category
1317          * @param string $k   Config key
1318          * @param mixed  $v   Default value to set
1319          */
1320         private function setDefaultConfigValue($cat, $k, $v)
1321         {
1322                 if (!isset($this->config[$cat][$k])) {
1323                         $this->setConfigValue($cat, $k, $v);
1324                 }
1325         }
1326
1327         /**
1328          * Sets a value in the config cache. Accepts raw output from the config table
1329          *
1330          * @param string $cat Config category
1331          * @param string $k   Config key
1332          * @param mixed  $v   Value to set
1333          */
1334         public function setConfigValue($cat, $k, $v)
1335         {
1336                 // Only arrays are serialized in database, so we have to unserialize sparingly
1337                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1338
1339                 if ($cat === 'config') {
1340                         $this->config[$k] = $value;
1341                 } else {
1342                         if (!isset($this->config[$cat])) {
1343                                 $this->config[$cat] = [];
1344                         }
1345
1346                         $this->config[$cat][$k] = $value;
1347                 }
1348         }
1349
1350         /**
1351          * Deletes a value from the config cache
1352          *
1353          * @param string $cat Config category
1354          * @param string $k   Config key
1355          */
1356         public function deleteConfigValue($cat, $k)
1357         {
1358                 if ($cat === 'config') {
1359                         if (isset($this->config[$k])) {
1360                                 unset($this->config[$k]);
1361                         }
1362                 } else {
1363                         if (isset($this->config[$cat][$k])) {
1364                                 unset($this->config[$cat][$k]);
1365                         }
1366                 }
1367         }
1368
1369
1370         /**
1371          * Retrieves a value from the user config cache
1372          *
1373          * @param int    $uid     User Id
1374          * @param string $cat     Config category
1375          * @param string $k       Config key
1376          * @param mixed  $default Default value if key isn't set
1377          *
1378          * @return string The value of the config entry
1379          */
1380         public function getPConfigValue($uid, $cat, $k, $default = null)
1381         {
1382                 $return = $default;
1383
1384                 if (isset($this->config[$uid][$cat][$k])) {
1385                         $return = $this->config[$uid][$cat][$k];
1386                 }
1387
1388                 return $return;
1389         }
1390
1391         /**
1392          * Sets a value in the user config cache
1393          *
1394          * Accepts raw output from the pconfig table
1395          *
1396          * @param int    $uid User Id
1397          * @param string $cat Config category
1398          * @param string $k   Config key
1399          * @param mixed  $v   Value to set
1400          */
1401         public function setPConfigValue($uid, $cat, $k, $v)
1402         {
1403                 // Only arrays are serialized in database, so we have to unserialize sparingly
1404                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1405
1406                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1407                         $this->config[$uid] = [];
1408                 }
1409
1410                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1411                         $this->config[$uid][$cat] = [];
1412                 }
1413
1414                 $this->config[$uid][$cat][$k] = $value;
1415         }
1416
1417         /**
1418          * Deletes a value from the user config cache
1419          *
1420          * @param int    $uid User Id
1421          * @param string $cat Config category
1422          * @param string $k   Config key
1423          */
1424         public function deletePConfigValue($uid, $cat, $k)
1425         {
1426                 if (isset($this->config[$uid][$cat][$k])) {
1427                         unset($this->config[$uid][$cat][$k]);
1428                 }
1429         }
1430
1431         /**
1432          * Generates the site's default sender email address
1433          *
1434          * @return string
1435          */
1436         public function getSenderEmailAddress()
1437         {
1438                 $sender_email = Config::get('config', 'sender_email');
1439                 if (empty($sender_email)) {
1440                         $hostname = $this->getHostName();
1441                         if (strpos($hostname, ':')) {
1442                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1443                         }
1444
1445                         $sender_email = 'noreply@' . $hostname;
1446                 }
1447
1448                 return $sender_email;
1449         }
1450
1451         /**
1452          * Returns the current theme name.
1453          *
1454          * @return string the name of the current theme
1455          */
1456         public function getCurrentTheme()
1457         {
1458                 if ($this->getMode()->isInstall()) {
1459                         return '';
1460                 }
1461
1462                 //// @TODO Compute the current theme only once (this behavior has
1463                 /// already been implemented, but it didn't work well -
1464                 /// https://github.com/friendica/friendica/issues/5092)
1465                 $this->computeCurrentTheme();
1466
1467                 return $this->currentTheme;
1468         }
1469
1470         /**
1471          * Computes the current theme name based on the node settings, the user settings and the device type
1472          *
1473          * @throws Exception
1474          */
1475         private function computeCurrentTheme()
1476         {
1477                 $system_theme = Config::get('system', 'theme');
1478                 if (!$system_theme) {
1479                         throw new Exception(L10n::t('No system theme config value set.'));
1480                 }
1481
1482                 // Sane default
1483                 $this->currentTheme = $system_theme;
1484
1485                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1486
1487                 $page_theme = null;
1488                 // Find the theme that belongs to the user whose stuff we are looking at
1489                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1490                         // Allow folks to override user themes and always use their own on their own site.
1491                         // This works only if the user is on the same server
1492                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1493                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1494                                 $page_theme = $user['theme'];
1495                         }
1496                 }
1497
1498                 $user_theme = Core\Session::get('theme', $system_theme);
1499
1500                 // Specific mobile theme override
1501                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1502                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1503                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1504
1505                         // --- means same mobile theme as desktop
1506                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1507                                 $user_theme = $user_mobile_theme;
1508                         }
1509                 }
1510
1511                 if ($page_theme) {
1512                         $theme_name = $page_theme;
1513                 } else {
1514                         $theme_name = $user_theme;
1515                 }
1516
1517                 if ($theme_name
1518                         && in_array($theme_name, $allowed_themes)
1519                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1520                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1521                 ) {
1522                         $this->currentTheme = $theme_name;
1523                 }
1524         }
1525
1526         /**
1527          * @brief Return full URL to theme which is currently in effect.
1528          *
1529          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1530          *
1531          * @return string
1532          */
1533         public function getCurrentThemeStylesheetPath()
1534         {
1535                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1536         }
1537 }