]> git.mxchange.org Git - friendica.git/blob - src/App.php
479813703c780027af4b9df639711d49ae24e83c
[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
15 require_once 'boot.php';
16 require_once 'include/dba.php';
17 require_once 'include/text.php';
18
19 /**
20  *
21  * class: App
22  *
23  * @brief Our main application structure for the life of this page.
24  *
25  * Primarily deals with the URL that got us here
26  * and tries to make some sense of it, and
27  * stores our page contents and config storage
28  * and anything else that might need to be passed around
29  * before we spit the page out.
30  *
31  */
32 class App
33 {
34         const MODE_LOCALCONFIGPRESENT = 1;
35         const MODE_DBAVAILABLE = 2;
36         const MODE_DBCONFIGAVAILABLE = 4;
37         const MODE_MAINTENANCEDISABLED = 8;
38
39         /**
40          * @deprecated since version 2008.08 Use App->isInstallMode() instead to check for install mode.
41          */
42         const MODE_INSTALL = 0;
43
44         /**
45          * @deprecated since version 2008.08 Use the precise mode constant to check for a specific capability instead.
46          */
47         const MODE_NORMAL = App::MODE_LOCALCONFIGPRESENT | App::MODE_DBAVAILABLE | App::MODE_DBCONFIGAVAILABLE | App::MODE_MAINTENANCEDISABLED;
48
49         public $module_loaded = false;
50         public $module_class = null;
51         public $query_string = '';
52         public $config = [];
53         public $page = [];
54         public $pager = [];
55         public $page_offset;
56         public $profile;
57         public $profile_uid;
58         public $user;
59         public $cid;
60         public $contact;
61         public $contacts;
62         public $page_contact;
63         public $content;
64         public $data = [];
65         public $error = false;
66         public $cmd = '';
67         public $argv;
68         public $argc;
69         public $module;
70         public $mode = App::MODE_INSTALL;
71         public $strings;
72         public $basepath;
73         public $urlpath;
74         public $hooks = [];
75         public $timezone;
76         public $interactive = true;
77         public $addons;
78         public $addons_admin = [];
79         public $apps = [];
80         public $identities;
81         public $is_mobile = false;
82         public $is_tablet = false;
83         public $is_friendica_app;
84         public $performance = [];
85         public $callstack = [];
86         public $theme_info = [];
87         public $backend = true;
88         public $nav_sel;
89         public $category;
90         // Allow themes to control internal parameters
91         // by changing App values in theme.php
92
93         public $sourcename = '';
94         public $videowidth = 425;
95         public $videoheight = 350;
96         public $force_max_items = 0;
97         public $theme_events_in_profile = true;
98
99         public $stylesheets = [];
100         public $footerScripts = [];
101
102         public function registerStylesheet($path)
103         {
104                 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
105
106                 $this->stylesheets[] = trim($url, '/');
107         }
108
109         public function registerFooterScript($path)
110         {
111                 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
112
113                 $this->footerScripts[] = trim($url, '/');
114         }
115
116         /**
117          * @brief An array for all theme-controllable parameters
118          *
119          * Mostly unimplemented yet. Only options 'template_engine' and
120          * beyond are used.
121          */
122         public $theme = [
123                 'sourcename' => '',
124                 'videowidth' => 425,
125                 'videoheight' => 350,
126                 'force_max_items' => 0,
127                 'stylesheet' => '',
128                 'template_engine' => 'smarty3',
129         ];
130
131         /**
132          * @brief An array of registered template engines ('name'=>'class name')
133          */
134         public $template_engines = [];
135
136         /**
137          * @brief An array of instanced template engines ('name'=>'instance')
138          */
139         public $template_engine_instance = [];
140         public $process_id;
141         public $queue;
142         private $ldelim = [
143                 'internal' => '',
144                 'smarty3' => '{{'
145         ];
146         private $rdelim = [
147                 'internal' => '',
148                 'smarty3' => '}}'
149         ];
150         private $scheme;
151         private $hostname;
152         private $curl_code;
153         private $curl_content_type;
154         private $curl_headers;
155
156         /**
157          * @brief App constructor.
158          *
159          * @param string $basepath Path to the app base folder
160          *
161          * @throws Exception if the Basepath is not usable
162          */
163         public function __construct($basepath)
164         {
165                 if (!static::directory_usable($basepath, false)) {
166                         throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
167                 }
168
169                 BaseObject::setApp($this);
170
171                 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
172
173                 $this->performance['start'] = microtime(true);
174                 $this->performance['database'] = 0;
175                 $this->performance['database_write'] = 0;
176                 $this->performance['cache'] = 0;
177                 $this->performance['cache_write'] = 0;
178                 $this->performance['network'] = 0;
179                 $this->performance['file'] = 0;
180                 $this->performance['rendering'] = 0;
181                 $this->performance['parser'] = 0;
182                 $this->performance['marktime'] = 0;
183                 $this->performance['markstart'] = microtime(true);
184
185                 $this->callstack['database'] = [];
186                 $this->callstack['database_write'] = [];
187                 $this->callstack['cache'] = [];
188                 $this->callstack['cache_write'] = [];
189                 $this->callstack['network'] = [];
190                 $this->callstack['file'] = [];
191                 $this->callstack['rendering'] = [];
192                 $this->callstack['parser'] = [];
193
194                 $this->reload();
195
196                 set_time_limit(0);
197
198                 // This has to be quite large to deal with embedded private photos
199                 ini_set('pcre.backtrack_limit', 500000);
200
201                 $this->scheme = 'http';
202
203                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
204                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
205                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
206                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
207                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
208                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
209                 ) {
210                         $this->scheme = 'https';
211                 }
212
213                 if (x($_SERVER, 'SERVER_NAME')) {
214                         $this->hostname = $_SERVER['SERVER_NAME'];
215
216                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
217                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
218                         }
219                 }
220
221                 set_include_path(
222                         get_include_path() . PATH_SEPARATOR
223                         . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
224                         . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
225                         . $this->basepath);
226
227                 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
228                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
229                 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
230                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
231                 }
232
233                 // removing trailing / - maybe a nginx problem
234                 $this->query_string = ltrim($this->query_string, '/');
235
236                 if (!empty($_GET['pagename'])) {
237                         $this->cmd = trim($_GET['pagename'], '/\\');
238                 } elseif (!empty($_GET['q'])) {
239                         $this->cmd = trim($_GET['q'], '/\\');
240                 }
241
242                 // fix query_string
243                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
244
245                 // unix style "homedir"
246                 if (substr($this->cmd, 0, 1) === '~') {
247                         $this->cmd = 'profile/' . substr($this->cmd, 1);
248                 }
249
250                 // Diaspora style profile url
251                 if (substr($this->cmd, 0, 2) === 'u/') {
252                         $this->cmd = 'profile/' . substr($this->cmd, 2);
253                 }
254
255                 /*
256                  * Break the URL path into C style argc/argv style arguments for our
257                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
258                  * will be 3 (integer) and $this->argv will contain:
259                  *   [0] => 'module'
260                  *   [1] => 'arg1'
261                  *   [2] => 'arg2'
262                  *
263                  *
264                  * There will always be one argument. If provided a naked domain
265                  * URL, $this->argv[0] is set to "home".
266                  */
267
268                 $this->argv = explode('/', $this->cmd);
269                 $this->argc = count($this->argv);
270                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
271                         $this->module = str_replace('.', '_', $this->argv[0]);
272                         $this->module = str_replace('-', '_', $this->module);
273                 } else {
274                         $this->argc = 1;
275                         $this->argv = ['home'];
276                         $this->module = 'home';
277                 }
278
279                 // See if there is any page number information, and initialise pagination
280                 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
281                 $this->pager['itemspage'] = 50;
282                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
283
284                 if ($this->pager['start'] < 0) {
285                         $this->pager['start'] = 0;
286                 }
287                 $this->pager['total'] = 0;
288
289                 // Detect mobile devices
290                 $mobile_detect = new MobileDetect();
291                 $this->is_mobile = $mobile_detect->isMobile();
292                 $this->is_tablet = $mobile_detect->isTablet();
293
294                 // Friendica-Client
295                 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
296
297                 // Register template engines
298                 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
299         }
300
301         /**
302          * Reloads the whole app instance
303          */
304         public function reload()
305         {
306                 // The order of the following calls is important to ensure proper initialization
307                 $this->loadConfigFiles();
308
309                 $this->loadDatabase();
310
311                 $this->determineMode();
312
313                 $this->determineUrlPath();
314
315                 Config::load();
316
317                 if ($this->mode & self::MODE_DBAVAILABLE) {
318                         Core\Addon::loadHooks();
319
320                         $this->loadAddonConfig();
321                 }
322
323                 $this->loadDefaultTimezone();
324
325                 $this->page = [
326                         'aside' => '',
327                         'bottom' => '',
328                         'content' => '',
329                         'footer' => '',
330                         'htmlhead' => '',
331                         'nav' => '',
332                         'page_title' => '',
333                         'right_aside' => '',
334                         'template' => '',
335                         'title' => ''
336                 ];
337
338                 $this->process_id = System::processID('log');
339         }
340
341         /**
342          * Load the configuration files
343          *
344          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
345          * expected local.ini.php
346          */
347         private function loadConfigFiles()
348         {
349                 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
350                 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
351
352                 // Legacy .htconfig.php support
353                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
354                         $a = $this;
355                         include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
356                 }
357
358                 // Legacy .htconfig.php support
359                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
360                         $a = $this;
361
362                         include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
363
364                         $this->setConfigValue('database', 'hostname', $db_host);
365                         $this->setConfigValue('database', 'username', $db_user);
366                         $this->setConfigValue('database', 'password', $db_pass);
367                         $this->setConfigValue('database', 'database', $db_data);
368                         if (isset($a->config['system']['db_charset'])) {
369                                 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
370                         }
371
372                         unset($db_host, $db_user, $db_pass, $db_data);
373
374                         if (isset($default_timezone)) {
375                                 $this->setConfigValue('system', 'default_timezone', $default_timezone);
376                                 unset($default_timezone);
377                         }
378
379                         if (isset($pidfile)) {
380                                 $this->setConfigValue('system', 'pidfile', $pidfile);
381                                 unset($pidfile);
382                         }
383
384                         if (isset($lang)) {
385                                 $this->setConfigValue('system', 'language', $lang);
386                                 unset($lang);
387                         }
388                 }
389
390                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
391                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
392                 }
393         }
394
395         /**
396          * Tries to load the specified configuration file into the App->config array.
397          * Overwrites previously set values.
398          *
399          * The config format is INI and the template for configuration files is the following:
400          *
401          * <?php return <<<INI
402          *
403          * [section]
404          * key = value
405          *
406          * INI;
407          * // Keep this line
408          *
409          * @param type $filepath
410          * @throws Exception
411          */
412         public function loadConfigFile($filepath)
413         {
414                 if (!file_exists($filepath)) {
415                         throw new Exception('Error parsing non-existent config file ' . $filepath);
416                 }
417
418                 $contents = include($filepath);
419
420                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
421
422                 if ($config === false) {
423                         throw new Exception('Error parsing config file ' . $filepath);
424                 }
425
426                 foreach ($config as $category => $values) {
427                         foreach ($values as $key => $value) {
428                                 $this->setConfigValue($category, $key, $value);
429                         }
430                 }
431         }
432
433         /**
434          * Loads addons configuration files
435          *
436          * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
437          * again to overwrite potential local addon configuration.
438          */
439         private function loadAddonConfig()
440         {
441                 // Loads addons default config
442                 Core\Addon::callHooks('load_config');
443
444                 // Load the local addon config file to overwritten default addon config values
445                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
446                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
447                 }
448         }
449
450         /**
451          * Loads the default timezone
452          *
453          * Include support for legacy $default_timezone
454          *
455          * @global string $default_timezone
456          */
457         private function loadDefaultTimezone()
458         {
459                 if ($this->getConfigValue('system', 'default_timezone')) {
460                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
461                 } else {
462                         global $default_timezone;
463                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
464                 }
465
466                 if ($this->timezone) {
467                         date_default_timezone_set($this->timezone);
468                 }
469         }
470
471         /**
472          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
473          */
474         private function determineUrlPath()
475         {
476                 $this->urlpath = $this->getConfigValue('system', 'urlpath');
477
478                 /* SCRIPT_URL gives /path/to/friendica/module/parameter
479                  * QUERY_STRING gives pagename=module/parameter
480                  *
481                  * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
482                  */
483                 if (!empty($_SERVER['SCRIPT_URL'])) {
484                         // Module
485                         if (!empty($_SERVER['QUERY_STRING'])) {
486                                 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
487                         } else {
488                                 // Root page
489                                 $path = trim($_SERVER['SCRIPT_URL'], '/');
490                         }
491
492                         if ($path && $path != $this->urlpath) {
493                                 $this->urlpath = $path;
494                         }
495                 }
496         }
497
498         /**
499          * Sets the App mode
500          *
501          * - App::MODE_INSTALL    : Either the database connection can't be established or the config table doesn't exist
502          * - App::MODE_MAINTENANCE: The maintenance mode has been set
503          * - App::MODE_NORMAL     : Normal run with all features enabled
504          *
505          * @return type
506          */
507         private function determineMode()
508         {
509                 $this->mode = 0;
510
511                 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
512                         && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
513                         return;
514                 }
515
516                 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
517
518                 if (!DBA::connected()) {
519                         return;
520                 }
521
522                 $this->mode |= App::MODE_DBAVAILABLE;
523
524                 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
525                         return;
526                 }
527
528                 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
529
530                 if (Config::get('system', 'maintenance')) {
531                         return;
532                 }
533
534                 $this->mode |= App::MODE_MAINTENANCEDISABLED;
535         }
536
537         public function loadDatabase()
538         {
539                 if (DBA::connected()) {
540                         return;
541                 }
542
543                 $db_host = $this->getConfigValue('database', 'hostname');
544                 $db_user = $this->getConfigValue('database', 'username');
545                 $db_pass = $this->getConfigValue('database', 'password');
546                 $db_data = $this->getConfigValue('database', 'database');
547                 $charset = $this->getConfigValue('database', 'charset');
548
549                 // Use environment variables for mysql if they are set beforehand
550                 if (!empty(getenv('MYSQL_HOST'))
551                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
552                         && getenv('MYSQL_PASSWORD') !== false
553                         && !empty(getenv('MYSQL_DATABASE')))
554                 {
555                         $db_host = getenv('MYSQL_HOST');
556                         if (!empty(getenv('MYSQL_PORT'))) {
557                                 $db_host .= ':' . getenv('MYSQL_PORT');
558                         }
559                         if (!empty(getenv('MYSQL_USERNAME'))) {
560                                 $db_user = getenv('MYSQL_USERNAME');
561                         } else {
562                                 $db_user = getenv('MYSQL_USER');
563                         }
564                         $db_pass = (string) getenv('MYSQL_PASSWORD');
565                         $db_data = getenv('MYSQL_DATABASE');
566                 }
567
568                 $stamp1 = microtime(true);
569
570                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
571                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
572
573                 $this->save_timestamp($stamp1, 'network');
574         }
575
576         /**
577          * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
578          *
579          * @return bool
580          */
581         public function isInstallMode()
582         {
583                 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
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 get_basepath()
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::realpath($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 realpath($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 get_scheme()
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 get_baseurl($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->urlpath) ? '/' . $this->urlpath : '' );
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 set_baseurl($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->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
708                                 include $this->basepath . 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 get_hostname()
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 get_path()
731         {
732                 return $this->urlpath;
733         }
734
735         public function set_pager_total($n)
736         {
737                 $this->pager['total'] = intval($n);
738         }
739
740         public function set_pager_itemspage($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 set_pager_page($n)
747         {
748                 $this->pager['page'] = $n;
749                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
750         }
751
752         public function initHead()
753         {
754                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
755
756                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
757                 if ($interval < 0) {
758                         $interval = 2147483647;
759                 }
760
761                 if ($interval < 10000) {
762                         $interval = 40000;
763                 }
764
765                 // compose the page title from the sitename and the
766                 // current module called
767                 if (!$this->module == '') {
768                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
769                 } else {
770                         $this->page['title'] = $this->config['sitename'];
771                 }
772
773                 /* put the head template at the beginning of page['htmlhead']
774                  * since the code added by the modules frequently depends on it
775                  * being first
776                  */
777
778                 // If we're using Smarty, then doing replace_macros() will replace
779                 // any unrecognized variables with a blank string. Since we delay
780                 // replacing $stylesheet until later, we need to replace it now
781                 // with another variable name
782                 if ($this->theme['template_engine'] === 'smarty3') {
783                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
784                 } else {
785                         $stylesheet = '$stylesheet';
786                 }
787
788                 $shortcut_icon = Config::get('system', 'shortcut_icon');
789                 if ($shortcut_icon == '') {
790                         $shortcut_icon = 'images/friendica-32.png';
791                 }
792
793                 $touch_icon = Config::get('system', 'touch_icon');
794                 if ($touch_icon == '') {
795                         $touch_icon = 'images/friendica-128.png';
796                 }
797
798                 // get data wich is needed for infinite scroll on the network page
799                 $infinite_scroll = infinite_scroll_data($this->module);
800
801                 Core\Addon::callHooks('head', $this->page['htmlhead']);
802
803                 $tpl = get_markup_template('head.tpl');
804                 $this->page['htmlhead'] = replace_macros($tpl, [
805                         '$baseurl'         => $this->get_baseurl(),
806                         '$local_user'      => local_user(),
807                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
808                         '$delitem'         => L10n::t('Delete this item?'),
809                         '$showmore'        => L10n::t('show more'),
810                         '$showfewer'       => L10n::t('show fewer'),
811                         '$update_interval' => $interval,
812                         '$shortcut_icon'   => $shortcut_icon,
813                         '$touch_icon'      => $touch_icon,
814                         '$stylesheet'      => $stylesheet,
815                         '$infinite_scroll' => $infinite_scroll,
816                         '$block_public'    => intval(Config::get('system', 'block_public')),
817                         '$stylesheets'     => $this->stylesheets,
818                 ]) . $this->page['htmlhead'];
819         }
820
821         public function initFooter()
822         {
823                 if (!isset($this->page['footer'])) {
824                         $this->page['footer'] = '';
825                 }
826
827                 // If you're just visiting, let javascript take you home
828                 if (!empty($_SESSION['visitor_home'])) {
829                         $homebase = $_SESSION['visitor_home'];
830                 } elseif (local_user()) {
831                         $homebase = 'profile/' . $a->user['nickname'];
832                 }
833
834                 if (isset($homebase)) {
835                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
836                 }
837
838                 /*
839                  * Add a "toggle mobile" link if we're using a mobile device
840                  */
841                 if ($this->is_mobile || $this->is_tablet) {
842                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
843                                 $link = 'toggle_mobile?address=' . curPageURL();
844                         } else {
845                                 $link = 'toggle_mobile?off=1&address=' . curPageURL();
846                         }
847                         $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
848                                 '$toggle_link' => $link,
849                                 '$toggle_text' => Core\L10n::t('toggle mobile')
850                         ]);
851                 }
852
853                 Core\Addon::callHooks('footer', $this->page['footer']);
854
855                 $tpl = get_markup_template('footer.tpl');
856                 $this->page['footer'] = replace_macros($tpl, [
857                         '$baseurl' => $this->get_baseurl(),
858                         '$footerScripts' => $this->footerScripts,
859                 ]) . $this->page['footer'];
860         }
861
862         public function set_curl_code($code)
863         {
864                 $this->curl_code = $code;
865         }
866
867         public function get_curl_code()
868         {
869                 return $this->curl_code;
870         }
871
872         public function set_curl_content_type($content_type)
873         {
874                 $this->curl_content_type = $content_type;
875         }
876
877         public function get_curl_content_type()
878         {
879                 return $this->curl_content_type;
880         }
881
882         public function set_curl_headers($headers)
883         {
884                 $this->curl_headers = $headers;
885         }
886
887         public function get_curl_headers()
888         {
889                 return $this->curl_headers;
890         }
891
892         /**
893          * @brief Removes the base url from an url. This avoids some mixed content problems.
894          *
895          * @param string $orig_url
896          *
897          * @return string The cleaned url
898          */
899         public function remove_baseurl($orig_url)
900         {
901                 // Remove the hostname from the url if it is an internal link
902                 $nurl = normalise_link($orig_url);
903                 $base = normalise_link($this->get_baseurl());
904                 $url = str_replace($base . '/', '', $nurl);
905
906                 // if it is an external link return the orignal value
907                 if ($url == normalise_link($orig_url)) {
908                         return $orig_url;
909                 } else {
910                         return $url;
911                 }
912         }
913
914         /**
915          * @brief Register template engine class
916          *
917          * @param string $class
918          */
919         private function register_template_engine($class)
920         {
921                 $v = get_class_vars($class);
922                 if (x($v, 'name')) {
923                         $name = $v['name'];
924                         $this->template_engines[$name] = $class;
925                 } else {
926                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
927                         die();
928                 }
929         }
930
931         /**
932          * @brief Return template engine instance.
933          *
934          * If $name is not defined, return engine defined by theme,
935          * or default
936          *
937          * @return object Template Engine instance
938          */
939         public function template_engine()
940         {
941                 $template_engine = 'smarty3';
942                 if (x($this->theme, 'template_engine')) {
943                         $template_engine = $this->theme['template_engine'];
944                 }
945
946                 if (isset($this->template_engines[$template_engine])) {
947                         if (isset($this->template_engine_instance[$template_engine])) {
948                                 return $this->template_engine_instance[$template_engine];
949                         } else {
950                                 $class = $this->template_engines[$template_engine];
951                                 $obj = new $class;
952                                 $this->template_engine_instance[$template_engine] = $obj;
953                                 return $obj;
954                         }
955                 }
956
957                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
958                 killme();
959         }
960
961         /**
962          * @brief Returns the active template engine.
963          *
964          * @return string
965          */
966         public function get_template_engine()
967         {
968                 return $this->theme['template_engine'];
969         }
970
971         public function set_template_engine($engine = 'smarty3')
972         {
973                 $this->theme['template_engine'] = $engine;
974         }
975
976         public function get_template_ldelim($engine = 'smarty3')
977         {
978                 return $this->ldelim[$engine];
979         }
980
981         public function get_template_rdelim($engine = 'smarty3')
982         {
983                 return $this->rdelim[$engine];
984         }
985
986         public function save_timestamp($stamp, $value)
987         {
988                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
989                         return;
990                 }
991
992                 $duration = (float) (microtime(true) - $stamp);
993
994                 if (!isset($this->performance[$value])) {
995                         // Prevent ugly E_NOTICE
996                         $this->performance[$value] = 0;
997                 }
998
999                 $this->performance[$value] += (float) $duration;
1000                 $this->performance['marktime'] += (float) $duration;
1001
1002                 $callstack = System::callstack();
1003
1004                 if (!isset($this->callstack[$value][$callstack])) {
1005                         // Prevent ugly E_NOTICE
1006                         $this->callstack[$value][$callstack] = 0;
1007                 }
1008
1009                 $this->callstack[$value][$callstack] += (float) $duration;
1010         }
1011
1012         public function get_useragent()
1013         {
1014                 return
1015                         FRIENDICA_PLATFORM . " '" .
1016                         FRIENDICA_CODENAME . "' " .
1017                         FRIENDICA_VERSION . '-' .
1018                         DB_UPDATE_VERSION . '; ' .
1019                         $this->get_baseurl();
1020         }
1021
1022         public function is_friendica_app()
1023         {
1024                 return $this->is_friendica_app;
1025         }
1026
1027         /**
1028          * @brief Checks if the site is called via a backend process
1029          *
1030          * This isn't a perfect solution. But we need this check very early.
1031          * So we cannot wait until the modules are loaded.
1032          *
1033          * @return bool Is it a known backend?
1034          */
1035         public function is_backend()
1036         {
1037                 static $backends = [
1038                         '_well_known',
1039                         'api',
1040                         'dfrn_notify',
1041                         'fetch',
1042                         'hcard',
1043                         'hostxrd',
1044                         'nodeinfo',
1045                         'noscrape',
1046                         'p',
1047                         'poco',
1048                         'post',
1049                         'proxy',
1050                         'pubsub',
1051                         'pubsubhubbub',
1052                         'receive',
1053                         'rsd_xml',
1054                         'salmon',
1055                         'statistics_json',
1056                         'xrd',
1057                 ];
1058
1059                 // Check if current module is in backend or backend flag is set
1060                 return (in_array($this->module, $backends) || $this->backend);
1061         }
1062
1063         /**
1064          * @brief Checks if the maximum number of database processes is reached
1065          *
1066          * @return bool Is the limit reached?
1067          */
1068         public function isMaxProcessesReached()
1069         {
1070                 // Deactivated, needs more investigating if this check really makes sense
1071                 return false;
1072
1073                 /*
1074                  * Commented out to suppress static analyzer issues
1075                  *
1076                 if ($this->is_backend()) {
1077                         $process = 'backend';
1078                         $max_processes = Config::get('system', 'max_processes_backend');
1079                         if (intval($max_processes) == 0) {
1080                                 $max_processes = 5;
1081                         }
1082                 } else {
1083                         $process = 'frontend';
1084                         $max_processes = Config::get('system', 'max_processes_frontend');
1085                         if (intval($max_processes) == 0) {
1086                                 $max_processes = 20;
1087                         }
1088                 }
1089
1090                 $processlist = DBA::processlist();
1091                 if ($processlist['list'] != '') {
1092                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1093
1094                         if ($processlist['amount'] > $max_processes) {
1095                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1096                                 return true;
1097                         }
1098                 }
1099                 return false;
1100                  */
1101         }
1102
1103         /**
1104          * @brief Checks if the minimal memory is reached
1105          *
1106          * @return bool Is the memory limit reached?
1107          */
1108         public function min_memory_reached()
1109         {
1110                 $min_memory = Config::get('system', 'min_memory', 0);
1111                 if ($min_memory == 0) {
1112                         return false;
1113                 }
1114
1115                 if (!is_readable('/proc/meminfo')) {
1116                         return false;
1117                 }
1118
1119                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1120
1121                 $meminfo = [];
1122                 foreach ($memdata as $line) {
1123                         list($key, $val) = explode(':', $line);
1124                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1125                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1126                 }
1127
1128                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1129                         return false;
1130                 }
1131
1132                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1133
1134                 $reached = ($free < $min_memory);
1135
1136                 if ($reached) {
1137                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1138                 }
1139
1140                 return $reached;
1141         }
1142
1143         /**
1144          * @brief Checks if the maximum load is reached
1145          *
1146          * @return bool Is the load reached?
1147          */
1148         public function isMaxLoadReached()
1149         {
1150                 if ($this->is_backend()) {
1151                         $process = 'backend';
1152                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1153                         if ($maxsysload < 1) {
1154                                 $maxsysload = 50;
1155                         }
1156                 } else {
1157                         $process = 'frontend';
1158                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1159                         if ($maxsysload < 1) {
1160                                 $maxsysload = 50;
1161                         }
1162                 }
1163
1164                 $load = current_load();
1165                 if ($load) {
1166                         if (intval($load) > $maxsysload) {
1167                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1168                                 return true;
1169                         }
1170                 }
1171                 return false;
1172         }
1173
1174         /**
1175          * Executes a child process with 'proc_open'
1176          *
1177          * @param string $command The command to execute
1178          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1179          */
1180         public function proc_run($command, $args)
1181         {
1182                 if (!function_exists('proc_open')) {
1183                         return;
1184                 }
1185
1186                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1187
1188                 foreach ($args as $key => $value) {
1189                         if (!is_null($value) && is_bool($value) && !$value) {
1190                                 continue;
1191                         }
1192
1193                         $cmdline .= ' --' . $key;
1194                         if (!is_null($value) && !is_bool($value)) {
1195                                 $cmdline .= ' ' . $value;
1196                         }
1197                 }
1198
1199                 if ($this->min_memory_reached()) {
1200                         return;
1201                 }
1202
1203                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1204                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1205                 } else {
1206                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1207                 }
1208                 if (!is_resource($resource)) {
1209                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1210                         return;
1211                 }
1212                 proc_close($resource);
1213         }
1214
1215         /**
1216          * @brief Returns the system user that is executing the script
1217          *
1218          * This mostly returns something like "www-data".
1219          *
1220          * @return string system username
1221          */
1222         private static function systemuser()
1223         {
1224                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1225                         return '';
1226                 }
1227
1228                 $processUser = posix_getpwuid(posix_geteuid());
1229                 return $processUser['name'];
1230         }
1231
1232         /**
1233          * @brief Checks if a given directory is usable for the system
1234          *
1235          * @return boolean the directory is usable
1236          */
1237         public static function directory_usable($directory, $check_writable = true)
1238         {
1239                 if ($directory == '') {
1240                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1241                         return false;
1242                 }
1243
1244                 if (!file_exists($directory)) {
1245                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1246                         return false;
1247                 }
1248
1249                 if (is_file($directory)) {
1250                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1251                         return false;
1252                 }
1253
1254                 if (!is_dir($directory)) {
1255                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1256                         return false;
1257                 }
1258
1259                 if ($check_writable && !is_writable($directory)) {
1260                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1261                         return false;
1262                 }
1263
1264                 return true;
1265         }
1266
1267         /**
1268          * @param string $cat     Config category
1269          * @param string $k       Config key
1270          * @param mixed  $default Default value if it isn't set
1271          */
1272         public function getConfigValue($cat, $k, $default = null)
1273         {
1274                 $return = $default;
1275
1276                 if ($cat === 'config') {
1277                         if (isset($this->config[$k])) {
1278                                 $return = $this->config[$k];
1279                         }
1280                 } else {
1281                         if (isset($this->config[$cat][$k])) {
1282                                 $return = $this->config[$cat][$k];
1283                         }
1284                 }
1285
1286                 return $return;
1287         }
1288
1289         /**
1290          * Sets a value in the config cache. Accepts raw output from the config table
1291          *
1292          * @param string $cat Config category
1293          * @param string $k   Config key
1294          * @param mixed  $v   Value to set
1295          */
1296         public function setConfigValue($cat, $k, $v)
1297         {
1298                 // Only arrays are serialized in database, so we have to unserialize sparingly
1299                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1300
1301                 if ($cat === 'config') {
1302                         $this->config[$k] = $value;
1303                 } else {
1304                         if (!isset($this->config[$cat])) {
1305                                 $this->config[$cat] = [];
1306                         }
1307
1308                         $this->config[$cat][$k] = $value;
1309                 }
1310         }
1311
1312         /**
1313          * Deletes a value from the config cache
1314          *
1315          * @param string $cat Config category
1316          * @param string $k   Config key
1317          */
1318         public function deleteConfigValue($cat, $k)
1319         {
1320                 if ($cat === 'config') {
1321                         if (isset($this->config[$k])) {
1322                                 unset($this->config[$k]);
1323                         }
1324                 } else {
1325                         if (isset($this->config[$cat][$k])) {
1326                                 unset($this->config[$cat][$k]);
1327                         }
1328                 }
1329         }
1330
1331
1332         /**
1333          * Retrieves a value from the user config cache
1334          *
1335          * @param int    $uid     User Id
1336          * @param string $cat     Config category
1337          * @param string $k       Config key
1338          * @param mixed  $default Default value if key isn't set
1339          */
1340         public function getPConfigValue($uid, $cat, $k, $default = null)
1341         {
1342                 $return = $default;
1343
1344                 if (isset($this->config[$uid][$cat][$k])) {
1345                         $return = $this->config[$uid][$cat][$k];
1346                 }
1347
1348                 return $return;
1349         }
1350
1351         /**
1352          * Sets a value in the user config cache
1353          *
1354          * Accepts raw output from the pconfig table
1355          *
1356          * @param int    $uid User Id
1357          * @param string $cat Config category
1358          * @param string $k   Config key
1359          * @param mixed  $v   Value to set
1360          */
1361         public function setPConfigValue($uid, $cat, $k, $v)
1362         {
1363                 // Only arrays are serialized in database, so we have to unserialize sparingly
1364                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1365
1366                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1367                         $this->config[$uid] = [];
1368                 }
1369
1370                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1371                         $this->config[$uid][$cat] = [];
1372                 }
1373
1374                 $this->config[$uid][$cat][$k] = $value;
1375         }
1376
1377         /**
1378          * Deletes a value from the user config cache
1379          *
1380          * @param int    $uid User Id
1381          * @param string $cat Config category
1382          * @param string $k   Config key
1383          */
1384         public function deletePConfigValue($uid, $cat, $k)
1385         {
1386                 if (isset($this->config[$uid][$cat][$k])) {
1387                         unset($this->config[$uid][$cat][$k]);
1388                 }
1389         }
1390
1391         /**
1392          * Generates the site's default sender email address
1393          *
1394          * @return string
1395          */
1396         public function getSenderEmailAddress()
1397         {
1398                 $sender_email = Config::get('config', 'sender_email');
1399                 if (empty($sender_email)) {
1400                         $hostname = $this->get_hostname();
1401                         if (strpos($hostname, ':')) {
1402                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1403                         }
1404
1405                         $sender_email = 'noreply@' . $hostname;
1406                 }
1407
1408                 return $sender_email;
1409         }
1410
1411         /**
1412          * Returns the current theme name.
1413          *
1414          * @return string
1415          */
1416         public function getCurrentTheme()
1417         {
1418                 if ($this->isInstallMode()) {
1419                         return '';
1420                 }
1421
1422                 //// @TODO Compute the current theme only once (this behavior has
1423                 /// already been implemented, but it didn't work well -
1424                 /// https://github.com/friendica/friendica/issues/5092)
1425                 $this->computeCurrentTheme();
1426
1427                 return $this->current_theme;
1428         }
1429
1430         /**
1431          * Computes the current theme name based on the node settings, the user settings and the device type
1432          *
1433          * @throws Exception
1434          */
1435         private function computeCurrentTheme()
1436         {
1437                 $system_theme = Config::get('system', 'theme');
1438                 if (!$system_theme) {
1439                         throw new Exception(L10n::t('No system theme config value set.'));
1440                 }
1441
1442                 // Sane default
1443                 $this->current_theme = $system_theme;
1444
1445                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1446
1447                 $page_theme = null;
1448                 // Find the theme that belongs to the user whose stuff we are looking at
1449                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1450                         // Allow folks to override user themes and always use their own on their own site.
1451                         // This works only if the user is on the same server
1452                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1453                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1454                                 $page_theme = $user['theme'];
1455                         }
1456                 }
1457
1458                 $user_theme = Core\Session::get('theme', $system_theme);
1459
1460                 // Specific mobile theme override
1461                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1462                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1463                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1464
1465                         // --- means same mobile theme as desktop
1466                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1467                                 $user_theme = $user_mobile_theme;
1468                         }
1469                 }
1470
1471                 if ($page_theme) {
1472                         $theme_name = $page_theme;
1473                 } else {
1474                         $theme_name = $user_theme;
1475                 }
1476
1477                 if ($theme_name
1478                         && in_array($theme_name, $allowed_themes)
1479                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1480                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1481                 ) {
1482                         $this->current_theme = $theme_name;
1483                 }
1484         }
1485
1486         /**
1487          * @brief Return full URL to theme which is currently in effect.
1488          *
1489          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1490          *
1491          * @return string
1492          */
1493         public function getCurrentThemeStylesheetPath()
1494         {
1495                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1496         }
1497 }