]> git.mxchange.org Git - friendica.git/blob - src/App.php
Move $apps out of App
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use DOMDocument;
9 use DOMXPath;
10 use Exception;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException\InternalServerErrorException;
13
14 require_once 'boot.php';
15 require_once 'include/text.php';
16
17 /**
18  *
19  * class: App
20  *
21  * @brief Our main application structure for the life of this page.
22  *
23  * Primarily deals with the URL that got us here
24  * and tries to make some sense of it, and
25  * stores our page contents and config storage
26  * and anything else that might need to be passed around
27  * before we spit the page out.
28  *
29  */
30 class App
31 {
32         public $module_loaded = false;
33         public $module_class = null;
34         public $query_string = '';
35         public $config = [];
36         public $page = [];
37         public $pager = [];
38         public $page_offset;
39         public $profile;
40         public $profile_uid;
41         public $user;
42         public $cid;
43         public $contact;
44         public $contacts;
45         public $page_contact;
46         public $content;
47         public $data = [];
48         public $error = false;
49         public $cmd = '';
50         public $argv;
51         public $argc;
52         public $module;
53         public $hooks = [];
54         public $timezone;
55         public $interactive = true;
56         public $addons;
57         public $addons_admin = [];
58         public $identities;
59         public $is_mobile = false;
60         public $is_tablet = false;
61         public $performance = [];
62         public $callstack = [];
63         public $theme_info = [];
64         public $category;
65         // Allow themes to control internal parameters
66         // by changing App values in theme.php
67
68         public $sourcename = '';
69         public $videowidth = 425;
70         public $videoheight = 350;
71         public $force_max_items = 0;
72         public $theme_events_in_profile = true;
73
74         public $stylesheets = [];
75         public $footerScripts = [];
76
77         /**
78          * @var App\Mode The Mode of the Application
79          */
80         private $mode;
81
82         /**
83          * @var string The App base path
84          */
85         private $basePath;
86
87         /**
88          * @var string The App URL path
89          */
90         private $urlPath;
91
92         /**
93          * @var bool true, if the call is from the Friendica APP, otherwise false
94          */
95         private $isFriendicaApp;
96
97         /**
98          * @var bool true, if the call is from an backend node (f.e. worker)
99          */
100         private $isBackend;
101
102         /**
103          * @var string The name of the current theme
104          */
105         private $currentTheme;
106
107         /**
108          * @var bool check if request was an AJAX (xmlhttprequest) request
109          */
110         private $isAjax;
111
112         /**
113          * Register a stylesheet file path to be included in the <head> tag of every page.
114          * Inclusion is done in App->initHead().
115          * The path can be absolute or relative to the Friendica installation base folder.
116          *
117          * @see initHead()
118          *
119          * @param string $path
120          */
121         public function registerStylesheet($path)
122         {
123                 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
124
125                 $this->stylesheets[] = trim($url, '/');
126         }
127
128         /**
129          * Register a javascript file path to be included in the <footer> tag of every page.
130          * Inclusion is done in App->initFooter().
131          * The path can be absolute or relative to the Friendica installation base folder.
132          *
133          * @see initFooter()
134          *
135          * @param string $path
136          */
137         public function registerFooterScript($path)
138         {
139                 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
140
141                 $this->footerScripts[] = trim($url, '/');
142         }
143
144         /**
145          * @brief An array for all theme-controllable parameters
146          *
147          * Mostly unimplemented yet. Only options 'template_engine' and
148          * beyond are used.
149          */
150         public $theme = [
151                 'sourcename' => '',
152                 'videowidth' => 425,
153                 'videoheight' => 350,
154                 'force_max_items' => 0,
155                 'stylesheet' => '',
156                 'template_engine' => 'smarty3',
157         ];
158
159         /**
160          * @brief An array of registered template engines ('name'=>'class name')
161          */
162         public $template_engines = [];
163
164         /**
165          * @brief An array of instanced template engines ('name'=>'instance')
166          */
167         public $template_engine_instance = [];
168         public $process_id;
169         public $queue;
170         private $ldelim = [
171                 'internal' => '',
172                 'smarty3' => '{{'
173         ];
174         private $rdelim = [
175                 'internal' => '',
176                 'smarty3' => '}}'
177         ];
178         private $scheme;
179         private $hostname;
180
181         /**
182          * @brief App constructor.
183          *
184          * @param string $basePath  Path to the app base folder
185          * @param bool   $isBackend Whether it is used for backend or frontend (Default true=backend)
186          *
187          * @throws Exception if the Basepath is not usable
188          */
189         public function __construct($basePath, $isBackend = true)
190         {
191                 if (!static::isDirectoryUsable($basePath, false)) {
192                         throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
193                 }
194
195                 BaseObject::setApp($this);
196
197                 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
198                 $this->checkBackend($isBackend);
199                 $this->checkFriendicaApp();
200
201                 $this->performance['start'] = microtime(true);
202                 $this->performance['database'] = 0;
203                 $this->performance['database_write'] = 0;
204                 $this->performance['cache'] = 0;
205                 $this->performance['cache_write'] = 0;
206                 $this->performance['network'] = 0;
207                 $this->performance['file'] = 0;
208                 $this->performance['rendering'] = 0;
209                 $this->performance['parser'] = 0;
210                 $this->performance['marktime'] = 0;
211                 $this->performance['markstart'] = microtime(true);
212
213                 $this->callstack['database'] = [];
214                 $this->callstack['database_write'] = [];
215                 $this->callstack['cache'] = [];
216                 $this->callstack['cache_write'] = [];
217                 $this->callstack['network'] = [];
218                 $this->callstack['file'] = [];
219                 $this->callstack['rendering'] = [];
220                 $this->callstack['parser'] = [];
221
222                 $this->mode = new App\Mode($basePath);
223
224                 $this->reload();
225
226                 set_time_limit(0);
227
228                 // This has to be quite large to deal with embedded private photos
229                 ini_set('pcre.backtrack_limit', 500000);
230
231                 $this->scheme = 'http';
232
233                 if (!empty($_SERVER['HTTPS']) ||
234                         !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
235                         !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
236                         !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
237                         !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
238                         !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
239                 ) {
240                         $this->scheme = 'https';
241                 }
242
243                 if (!empty($_SERVER['SERVER_NAME'])) {
244                         $this->hostname = $_SERVER['SERVER_NAME'];
245
246                         if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
247                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
248                         }
249                 }
250
251                 set_include_path(
252                         get_include_path() . PATH_SEPARATOR
253                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
254                         . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
255                         . $this->getBasePath());
256
257                 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
258                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
259                 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
260                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
261                 }
262
263                 // removing trailing / - maybe a nginx problem
264                 $this->query_string = ltrim($this->query_string, '/');
265
266                 if (!empty($_GET['pagename'])) {
267                         $this->cmd = trim($_GET['pagename'], '/\\');
268                 } elseif (!empty($_GET['q'])) {
269                         $this->cmd = trim($_GET['q'], '/\\');
270                 }
271
272                 // fix query_string
273                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
274
275                 // unix style "homedir"
276                 if (substr($this->cmd, 0, 1) === '~') {
277                         $this->cmd = 'profile/' . substr($this->cmd, 1);
278                 }
279
280                 // Diaspora style profile url
281                 if (substr($this->cmd, 0, 2) === 'u/') {
282                         $this->cmd = 'profile/' . substr($this->cmd, 2);
283                 }
284
285                 /*
286                  * Break the URL path into C style argc/argv style arguments for our
287                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
288                  * will be 3 (integer) and $this->argv will contain:
289                  *   [0] => 'module'
290                  *   [1] => 'arg1'
291                  *   [2] => 'arg2'
292                  *
293                  *
294                  * There will always be one argument. If provided a naked domain
295                  * URL, $this->argv[0] is set to "home".
296                  */
297
298                 $this->argv = explode('/', $this->cmd);
299                 $this->argc = count($this->argv);
300                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
301                         $this->module = str_replace('.', '_', $this->argv[0]);
302                         $this->module = str_replace('-', '_', $this->module);
303                 } else {
304                         $this->argc = 1;
305                         $this->argv = ['home'];
306                         $this->module = 'home';
307                 }
308
309                 // See if there is any page number information, and initialise pagination
310                 $this->pager['page'] = !empty($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
311                 $this->pager['itemspage'] = 50;
312                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
313
314                 if ($this->pager['start'] < 0) {
315                         $this->pager['start'] = 0;
316                 }
317                 $this->pager['total'] = 0;
318
319                 // Detect mobile devices
320                 $mobile_detect = new MobileDetect();
321                 $this->is_mobile = $mobile_detect->isMobile();
322                 $this->is_tablet = $mobile_detect->isTablet();
323
324                 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
325
326                 // Register template engines
327                 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
328         }
329
330         /**
331          * Returns the Mode of the Application
332          *
333          * @return App\Mode The Application Mode
334          *
335          * @throws InternalServerErrorException when the mode isn't created
336          */
337         public function getMode()
338         {
339                 if (empty($this->mode)) {
340                         throw new InternalServerErrorException('Mode of the Application is not defined');
341                 }
342
343                 return $this->mode;
344         }
345
346         /**
347          * Reloads the whole app instance
348          */
349         public function reload()
350         {
351                 // The order of the following calls is important to ensure proper initialization
352                 $this->loadConfigFiles();
353
354                 $this->loadDatabase();
355
356                 $this->getMode()->determine($this->getBasePath());
357
358                 $this->determineURLPath();
359
360                 Core\Config::load();
361
362                 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
363                         Core\Addon::loadHooks();
364
365                         $this->loadAddonConfig();
366                 }
367
368                 $this->loadDefaultTimezone();
369
370                 Core\L10n::init();
371
372                 $this->process_id = Core\System::processID('log');
373         }
374
375         /**
376          * Load the configuration files
377          *
378          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
379          * expected local.ini.php
380          */
381         private function loadConfigFiles()
382         {
383                 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
384                 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
385
386                 // Legacy .htconfig.php support
387                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
388                         $a = $this;
389                         include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
390                 }
391
392                 // Legacy .htconfig.php support
393                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
394                         $a = $this;
395
396                         include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
397
398                         $this->setConfigValue('database', 'hostname', $db_host);
399                         $this->setConfigValue('database', 'username', $db_user);
400                         $this->setConfigValue('database', 'password', $db_pass);
401                         $this->setConfigValue('database', 'database', $db_data);
402                         if (isset($a->config['system']['db_charset'])) {
403                                 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
404                         }
405
406                         unset($db_host, $db_user, $db_pass, $db_data);
407
408                         if (isset($default_timezone)) {
409                                 $this->setConfigValue('system', 'default_timezone', $default_timezone);
410                                 unset($default_timezone);
411                         }
412
413                         if (isset($pidfile)) {
414                                 $this->setConfigValue('system', 'pidfile', $pidfile);
415                                 unset($pidfile);
416                         }
417
418                         if (isset($lang)) {
419                                 $this->setConfigValue('system', 'language', $lang);
420                                 unset($lang);
421                         }
422                 }
423
424                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
425                         $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
426                 }
427         }
428
429         /**
430          * Tries to load the specified configuration file into the App->config array.
431          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
432          *
433          * The config format is INI and the template for configuration files is the following:
434          *
435          * <?php return <<<INI
436          *
437          * [section]
438          * key = value
439          *
440          * INI;
441          * // Keep this line
442          *
443          * @param string $filepath
444          * @param bool $overwrite Force value overwrite if the config key already exists
445          * @throws Exception
446          */
447         public function loadConfigFile($filepath, $overwrite = false)
448         {
449                 if (!file_exists($filepath)) {
450                         throw new Exception('Error parsing non-existent config file ' . $filepath);
451                 }
452
453                 $contents = include($filepath);
454
455                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
456
457                 if ($config === false) {
458                         throw new Exception('Error parsing config file ' . $filepath);
459                 }
460
461                 foreach ($config as $category => $values) {
462                         foreach ($values as $key => $value) {
463                                 if ($overwrite) {
464                                         $this->setConfigValue($category, $key, $value);
465                                 } else {
466                                         $this->setDefaultConfigValue($category, $key, $value);
467                                 }
468                         }
469                 }
470         }
471
472         /**
473          * Loads addons configuration files
474          *
475          * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
476          * again to overwrite potential local addon configuration.
477          */
478         private function loadAddonConfig()
479         {
480                 // Loads addons default config
481                 Core\Addon::callHooks('load_config');
482
483                 // Load the local addon config file to overwritten default addon config values
484                 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
485                         $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
486                 }
487         }
488
489         /**
490          * Loads the default timezone
491          *
492          * Include support for legacy $default_timezone
493          *
494          * @global string $default_timezone
495          */
496         private function loadDefaultTimezone()
497         {
498                 if ($this->getConfigValue('system', 'default_timezone')) {
499                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
500                 } else {
501                         global $default_timezone;
502                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
503                 }
504
505                 if ($this->timezone) {
506                         date_default_timezone_set($this->timezone);
507                 }
508         }
509
510         /**
511          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
512          */
513         private function determineURLPath()
514         {
515                 /* Relative script path to the web server root
516                  * Not all of those $_SERVER properties can be present, so we do by inverse priority order
517                  */
518                 $relative_script_path = '';
519                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL'       , $relative_script_path);
520                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI'       , $relative_script_path);
521                 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
522                 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL'         , $relative_script_path);
523
524                 $this->urlPath = $this->getConfigValue('system', 'urlpath');
525
526                 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
527                  * QUERY_STRING gives pagename=module/parameter
528                  *
529                  * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
530                  */
531                 if (!empty($relative_script_path)) {
532                         // Module
533                         if (!empty($_SERVER['QUERY_STRING'])) {
534                                 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
535                         } else {
536                                 // Root page
537                                 $path = trim($relative_script_path, '/');
538                         }
539
540                         if ($path && $path != $this->urlPath) {
541                                 $this->urlPath = $path;
542                         }
543                 }
544         }
545
546         public function loadDatabase()
547         {
548                 if (DBA::connected()) {
549                         return;
550                 }
551
552                 $db_host = $this->getConfigValue('database', 'hostname');
553                 $db_user = $this->getConfigValue('database', 'username');
554                 $db_pass = $this->getConfigValue('database', 'password');
555                 $db_data = $this->getConfigValue('database', 'database');
556                 $charset = $this->getConfigValue('database', 'charset');
557
558                 // Use environment variables for mysql if they are set beforehand
559                 if (!empty(getenv('MYSQL_HOST'))
560                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
561                         && getenv('MYSQL_PASSWORD') !== false
562                         && !empty(getenv('MYSQL_DATABASE')))
563                 {
564                         $db_host = getenv('MYSQL_HOST');
565                         if (!empty(getenv('MYSQL_PORT'))) {
566                                 $db_host .= ':' . getenv('MYSQL_PORT');
567                         }
568                         if (!empty(getenv('MYSQL_USERNAME'))) {
569                                 $db_user = getenv('MYSQL_USERNAME');
570                         } else {
571                                 $db_user = getenv('MYSQL_USER');
572                         }
573                         $db_pass = (string) getenv('MYSQL_PASSWORD');
574                         $db_data = getenv('MYSQL_DATABASE');
575                 }
576
577                 $stamp1 = microtime(true);
578
579                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
580                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
581
582                 $this->saveTimestamp($stamp1, 'network');
583         }
584
585         /**
586          * @brief Returns the base filesystem path of the App
587          *
588          * It first checks for the internal variable, then for DOCUMENT_ROOT and
589          * finally for PWD
590          *
591          * @return string
592          */
593         public function getBasePath()
594         {
595                 $basepath = $this->basePath;
596
597                 if (!$basepath) {
598                         $basepath = Core\Config::get('system', 'basepath');
599                 }
600
601                 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
602                         $basepath = $_SERVER['DOCUMENT_ROOT'];
603                 }
604
605                 if (!$basepath && !empty($_SERVER['PWD'])) {
606                         $basepath = $_SERVER['PWD'];
607                 }
608
609                 return self::getRealPath($basepath);
610         }
611
612         /**
613          * @brief Returns a normalized file path
614          *
615          * This is a wrapper for the "realpath" function.
616          * That function cannot detect the real path when some folders aren't readable.
617          * Since this could happen with some hosters we need to handle this.
618          *
619          * @param string $path The path that is about to be normalized
620          * @return string normalized path - when possible
621          */
622         public static function getRealPath($path)
623         {
624                 $normalized = realpath($path);
625
626                 if (!is_bool($normalized)) {
627                         return $normalized;
628                 } else {
629                         return $path;
630                 }
631         }
632
633         public function getScheme()
634         {
635                 return $this->scheme;
636         }
637
638         /**
639          * @brief Retrieves the Friendica instance base URL
640          *
641          * This function assembles the base URL from multiple parts:
642          * - Protocol is determined either by the request or a combination of
643          * system.ssl_policy and the $ssl parameter.
644          * - Host name is determined either by system.hostname or inferred from request
645          * - Path is inferred from SCRIPT_NAME
646          *
647          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
648          *
649          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
650          * @return string Friendica server base URL
651          */
652         public function getBaseURL($ssl = false)
653         {
654                 $scheme = $this->scheme;
655
656                 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
657                         $scheme = 'https';
658                 }
659
660                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
661                 //      (and also the login link). Anything seen by an outsider will have it turned off.
662
663                 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
664                         if ($ssl) {
665                                 $scheme = 'https';
666                         } else {
667                                 $scheme = 'http';
668                         }
669                 }
670
671                 if (Core\Config::get('config', 'hostname') != '') {
672                         $this->hostname = Core\Config::get('config', 'hostname');
673                 }
674
675                 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
676         }
677
678         /**
679          * @brief Initializes the baseurl components
680          *
681          * Clears the baseurl cache to prevent inconsistencies
682          *
683          * @param string $url
684          */
685         public function setBaseURL($url)
686         {
687                 $parsed = @parse_url($url);
688                 $hostname = '';
689
690                 if (!empty($parsed)) {
691                         if (!empty($parsed['scheme'])) {
692                                 $this->scheme = $parsed['scheme'];
693                         }
694
695                         if (!empty($parsed['host'])) {
696                                 $hostname = $parsed['host'];
697                         }
698
699                         if (!empty($parsed['port'])) {
700                                 $hostname .= ':' . $parsed['port'];
701                         }
702                         if (!empty($parsed['path'])) {
703                                 $this->urlPath = trim($parsed['path'], '\\/');
704                         }
705
706                         if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
707                                 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
708                         }
709
710                         if (Core\Config::get('config', 'hostname') != '') {
711                                 $this->hostname = Core\Config::get('config', 'hostname');
712                         }
713
714                         if (!isset($this->hostname) || ($this->hostname == '')) {
715                                 $this->hostname = $hostname;
716                         }
717                 }
718         }
719
720         public function getHostName()
721         {
722                 if (Core\Config::get('config', 'hostname') != '') {
723                         $this->hostname = Core\Config::get('config', 'hostname');
724                 }
725
726                 return $this->hostname;
727         }
728
729         public function getURLPath()
730         {
731                 return $this->urlPath;
732         }
733
734         public function setPagerTotal($n)
735         {
736                 $this->pager['total'] = intval($n);
737         }
738
739         public function setPagerItemsPage($n)
740         {
741                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
742                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
743         }
744
745         public function setPagerPage($n)
746         {
747                 $this->pager['page'] = $n;
748                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
749         }
750
751         /**
752          * Initializes App->page['htmlhead'].
753          *
754          * Includes:
755          * - Page title
756          * - Favicons
757          * - Registered stylesheets (through App->registerStylesheet())
758          * - Infinite scroll data
759          * - head.tpl template
760          */
761         public function initHead()
762         {
763                 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
764
765                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
766                 if ($interval < 0) {
767                         $interval = 2147483647;
768                 }
769
770                 if ($interval < 10000) {
771                         $interval = 40000;
772                 }
773
774                 // compose the page title from the sitename and the
775                 // current module called
776                 if (!$this->module == '') {
777                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
778                 } else {
779                         $this->page['title'] = $this->config['sitename'];
780                 }
781
782                 if (!empty($this->theme['stylesheet'])) {
783                         $stylesheet = $this->theme['stylesheet'];
784                 } else {
785                         $stylesheet = $this->getCurrentThemeStylesheetPath();
786                 }
787
788                 $this->registerStylesheet($stylesheet);
789
790                 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
791                 if ($shortcut_icon == '') {
792                         $shortcut_icon = 'images/friendica-32.png';
793                 }
794
795                 $touch_icon = Core\Config::get('system', 'touch_icon');
796                 if ($touch_icon == '') {
797                         $touch_icon = 'images/friendica-128.png';
798                 }
799
800                 // get data wich is needed for infinite scroll on the network page
801                 $infinite_scroll = infinite_scroll_data($this->module);
802
803                 Core\Addon::callHooks('head', $this->page['htmlhead']);
804
805                 $tpl = get_markup_template('head.tpl');
806                 /* put the head template at the beginning of page['htmlhead']
807                  * since the code added by the modules frequently depends on it
808                  * being first
809                  */
810                 $this->page['htmlhead'] = replace_macros($tpl, [
811                         '$baseurl'         => $this->getBaseURL(),
812                         '$local_user'      => local_user(),
813                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
814                         '$delitem'         => Core\L10n::t('Delete this item?'),
815                         '$showmore'        => Core\L10n::t('show more'),
816                         '$showfewer'       => Core\L10n::t('show fewer'),
817                         '$update_interval' => $interval,
818                         '$shortcut_icon'   => $shortcut_icon,
819                         '$touch_icon'      => $touch_icon,
820                         '$infinite_scroll' => $infinite_scroll,
821                         '$block_public'    => intval(Core\Config::get('system', 'block_public')),
822                         '$stylesheets'     => $this->stylesheets,
823                 ]) . $this->page['htmlhead'];
824         }
825
826         /**
827          * Initializes App->page['footer'].
828          *
829          * Includes:
830          * - Javascript homebase
831          * - Mobile toggle link
832          * - Registered footer scripts (through App->registerFooterScript())
833          * - footer.tpl template
834          */
835         public function initFooter()
836         {
837                 // If you're just visiting, let javascript take you home
838                 if (!empty($_SESSION['visitor_home'])) {
839                         $homebase = $_SESSION['visitor_home'];
840                 } elseif (local_user()) {
841                         $homebase = 'profile/' . $this->user['nickname'];
842                 }
843
844                 if (isset($homebase)) {
845                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
846                 }
847
848                 /*
849                  * Add a "toggle mobile" link if we're using a mobile device
850                  */
851                 if ($this->is_mobile || $this->is_tablet) {
852                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
853                                 $link = 'toggle_mobile?address=' . curPageURL();
854                         } else {
855                                 $link = 'toggle_mobile?off=1&address=' . curPageURL();
856                         }
857                         $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
858                                 '$toggle_link' => $link,
859                                 '$toggle_text' => Core\L10n::t('toggle mobile')
860                         ]);
861                 }
862
863                 Core\Addon::callHooks('footer', $this->page['footer']);
864
865                 $tpl = get_markup_template('footer.tpl');
866                 $this->page['footer'] = replace_macros($tpl, [
867                         '$baseurl' => $this->getBaseURL(),
868                         '$footerScripts' => $this->footerScripts,
869                 ]) . $this->page['footer'];
870         }
871
872         /**
873          * @brief Removes the base url from an url. This avoids some mixed content problems.
874          *
875          * @param string $origURL
876          *
877          * @return string The cleaned url
878          */
879         public function removeBaseURL($origURL)
880         {
881                 // Remove the hostname from the url if it is an internal link
882                 $nurl = normalise_link($origURL);
883                 $base = normalise_link($this->getBaseURL());
884                 $url = str_replace($base . '/', '', $nurl);
885
886                 // if it is an external link return the orignal value
887                 if ($url == normalise_link($origURL)) {
888                         return $origURL;
889                 } else {
890                         return $url;
891                 }
892         }
893
894         /**
895          * @brief Register template engine class
896          *
897          * @param string $class
898          */
899         private function registerTemplateEngine($class)
900         {
901                 $v = get_class_vars($class);
902                 if (!empty($v['name'])) {
903                         $name = $v['name'];
904                         $this->template_engines[$name] = $class;
905                 } else {
906                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
907                         die();
908                 }
909         }
910
911         /**
912          * @brief Return template engine instance.
913          *
914          * If $name is not defined, return engine defined by theme,
915          * or default
916          *
917          * @return object Template Engine instance
918          */
919         public function getTemplateEngine()
920         {
921                 $template_engine = defaults($this->theme, 'template_engine', 'smarty3');
922
923                 if (isset($this->template_engines[$template_engine])) {
924                         if (isset($this->template_engine_instance[$template_engine])) {
925                                 return $this->template_engine_instance[$template_engine];
926                         } else {
927                                 $class = $this->template_engines[$template_engine];
928                                 $obj = new $class;
929                                 $this->template_engine_instance[$template_engine] = $obj;
930                                 return $obj;
931                         }
932                 }
933
934                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
935                 exit();
936         }
937
938         /**
939          * @brief Returns the active template engine.
940          *
941          * @return string the active template engine
942          */
943         public function getActiveTemplateEngine()
944         {
945                 return $this->theme['template_engine'];
946         }
947
948         /**
949          * sets the active template engine
950          *
951          * @param string $engine the template engine (default is Smarty3)
952          */
953         public function setActiveTemplateEngine($engine = 'smarty3')
954         {
955                 $this->theme['template_engine'] = $engine;
956         }
957
958         /**
959          * Gets the right delimiter for a template engine
960          *
961          * Currently:
962          * Internal = ''
963          * Smarty3 = '{{'
964          *
965          * @param string $engine The template engine (default is Smarty3)
966          *
967          * @return string the right delimiter
968          */
969         public function getTemplateLeftDelimiter($engine = 'smarty3')
970         {
971                 return $this->ldelim[$engine];
972         }
973
974         /**
975          * Gets the left delimiter for a template engine
976          *
977          * Currently:
978          * Internal = ''
979          * Smarty3 = '}}'
980          *
981          * @param string $engine The template engine (default is Smarty3)
982          *
983          * @return string the left delimiter
984          */
985         public function getTemplateRightDelimiter($engine = 'smarty3')
986         {
987                 return $this->rdelim[$engine];
988         }
989
990         /**
991          * Saves a timestamp for a value - f.e. a call
992          * Necessary for profiling Friendica
993          *
994          * @param int $timestamp the Timestamp
995          * @param string $value A value to profile
996          */
997         public function saveTimestamp($timestamp, $value)
998         {
999                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1000                         return;
1001                 }
1002
1003                 $duration = (float) (microtime(true) - $timestamp);
1004
1005                 if (!isset($this->performance[$value])) {
1006                         // Prevent ugly E_NOTICE
1007                         $this->performance[$value] = 0;
1008                 }
1009
1010                 $this->performance[$value] += (float) $duration;
1011                 $this->performance['marktime'] += (float) $duration;
1012
1013                 $callstack = Core\System::callstack();
1014
1015                 if (!isset($this->callstack[$value][$callstack])) {
1016                         // Prevent ugly E_NOTICE
1017                         $this->callstack[$value][$callstack] = 0;
1018                 }
1019
1020                 $this->callstack[$value][$callstack] += (float) $duration;
1021         }
1022
1023         /**
1024          * Returns the current UserAgent as a String
1025          *
1026          * @return string the UserAgent as a String
1027          */
1028         public function getUserAgent()
1029         {
1030                 return
1031                         FRIENDICA_PLATFORM . " '" .
1032                         FRIENDICA_CODENAME . "' " .
1033                         FRIENDICA_VERSION . '-' .
1034                         DB_UPDATE_VERSION . '; ' .
1035                         $this->getBaseURL();
1036         }
1037
1038         /**
1039          * Checks, if the call is from the Friendica App
1040          *
1041          * Reason:
1042          * The friendica client has problems with the GUID in the notify. this is some workaround
1043          */
1044         private function checkFriendicaApp()
1045         {
1046                 // Friendica-Client
1047                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1048         }
1049
1050         /**
1051          *      Is the call via the Friendica app? (not a "normale" call)
1052          *
1053          * @return bool true if it's from the Friendica app
1054          */
1055         public function isFriendicaApp()
1056         {
1057                 return $this->isFriendicaApp;
1058         }
1059
1060         /**
1061          * @brief Checks if the site is called via a backend process
1062          *
1063          * This isn't a perfect solution. But we need this check very early.
1064          * So we cannot wait until the modules are loaded.
1065          *
1066          * @param string $backend true, if the backend flag was set during App initialization
1067          *
1068          */
1069         private function checkBackend($backend) {
1070                 static $backends = [
1071                         '_well_known',
1072                         'api',
1073                         'dfrn_notify',
1074                         'fetch',
1075                         'hcard',
1076                         'hostxrd',
1077                         'nodeinfo',
1078                         'noscrape',
1079                         'p',
1080                         'poco',
1081                         'post',
1082                         'proxy',
1083                         'pubsub',
1084                         'pubsubhubbub',
1085                         'receive',
1086                         'rsd_xml',
1087                         'salmon',
1088                         'statistics_json',
1089                         'xrd',
1090                 ];
1091
1092                 // Check if current module is in backend or backend flag is set
1093                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1094         }
1095
1096         /**
1097          * Returns true, if the call is from a backend node (f.e. from a worker)
1098          *
1099          * @return bool Is it a known backend?
1100          */
1101         public function isBackend()
1102         {
1103                 return $this->isBackend;
1104         }
1105
1106         /**
1107          * @brief Checks if the maximum number of database processes is reached
1108          *
1109          * @return bool Is the limit reached?
1110          */
1111         public function isMaxProcessesReached()
1112         {
1113                 // Deactivated, needs more investigating if this check really makes sense
1114                 return false;
1115
1116                 /*
1117                  * Commented out to suppress static analyzer issues
1118                  *
1119                 if ($this->is_backend()) {
1120                         $process = 'backend';
1121                         $max_processes = Core\Config::get('system', 'max_processes_backend');
1122                         if (intval($max_processes) == 0) {
1123                                 $max_processes = 5;
1124                         }
1125                 } else {
1126                         $process = 'frontend';
1127                         $max_processes = Core\Config::get('system', 'max_processes_frontend');
1128                         if (intval($max_processes) == 0) {
1129                                 $max_processes = 20;
1130                         }
1131                 }
1132
1133                 $processlist = DBA::processlist();
1134                 if ($processlist['list'] != '') {
1135                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1136
1137                         if ($processlist['amount'] > $max_processes) {
1138                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1139                                 return true;
1140                         }
1141                 }
1142                 return false;
1143                  */
1144         }
1145
1146         /**
1147          * @brief Checks if the minimal memory is reached
1148          *
1149          * @return bool Is the memory limit reached?
1150          */
1151         public function isMinMemoryReached()
1152         {
1153                 $min_memory = Core\Config::get('system', 'min_memory', 0);
1154                 if ($min_memory == 0) {
1155                         return false;
1156                 }
1157
1158                 if (!is_readable('/proc/meminfo')) {
1159                         return false;
1160                 }
1161
1162                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1163
1164                 $meminfo = [];
1165                 foreach ($memdata as $line) {
1166                         $data = explode(':', $line);
1167                         if (count($data) != 2) {
1168                                 continue;
1169                         }
1170                         list($key, $val) = $data;
1171                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1172                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1173                 }
1174
1175                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1176                         return false;
1177                 }
1178
1179                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1180
1181                 $reached = ($free < $min_memory);
1182
1183                 if ($reached) {
1184                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1185                 }
1186
1187                 return $reached;
1188         }
1189
1190         /**
1191          * @brief Checks if the maximum load is reached
1192          *
1193          * @return bool Is the load reached?
1194          */
1195         public function isMaxLoadReached()
1196         {
1197                 if ($this->isBackend()) {
1198                         $process = 'backend';
1199                         $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1200                         if ($maxsysload < 1) {
1201                                 $maxsysload = 50;
1202                         }
1203                 } else {
1204                         $process = 'frontend';
1205                         $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1206                         if ($maxsysload < 1) {
1207                                 $maxsysload = 50;
1208                         }
1209                 }
1210
1211                 $load = Core\System::currentLoad();
1212                 if ($load) {
1213                         if (intval($load) > $maxsysload) {
1214                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1215                                 return true;
1216                         }
1217                 }
1218                 return false;
1219         }
1220
1221         /**
1222          * Executes a child process with 'proc_open'
1223          *
1224          * @param string $command The command to execute
1225          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1226          */
1227         public function proc_run($command, $args)
1228         {
1229                 if (!function_exists('proc_open')) {
1230                         return;
1231                 }
1232
1233                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1234
1235                 foreach ($args as $key => $value) {
1236                         if (!is_null($value) && is_bool($value) && !$value) {
1237                                 continue;
1238                         }
1239
1240                         $cmdline .= ' --' . $key;
1241                         if (!is_null($value) && !is_bool($value)) {
1242                                 $cmdline .= ' ' . $value;
1243                         }
1244                 }
1245
1246                 if ($this->isMinMemoryReached()) {
1247                         return;
1248                 }
1249
1250                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1251                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1252                 } else {
1253                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1254                 }
1255                 if (!is_resource($resource)) {
1256                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1257                         return;
1258                 }
1259                 proc_close($resource);
1260         }
1261
1262         /**
1263          * @brief Returns the system user that is executing the script
1264          *
1265          * This mostly returns something like "www-data".
1266          *
1267          * @return string system username
1268          */
1269         private static function getSystemUser()
1270         {
1271                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1272                         return '';
1273                 }
1274
1275                 $processUser = posix_getpwuid(posix_geteuid());
1276                 return $processUser['name'];
1277         }
1278
1279         /**
1280          * @brief Checks if a given directory is usable for the system
1281          *
1282          * @return boolean the directory is usable
1283          */
1284         public static function isDirectoryUsable($directory, $check_writable = true)
1285         {
1286                 if ($directory == '') {
1287                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1288                         return false;
1289                 }
1290
1291                 if (!file_exists($directory)) {
1292                         logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1293                         return false;
1294                 }
1295
1296                 if (is_file($directory)) {
1297                         logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1298                         return false;
1299                 }
1300
1301                 if (!is_dir($directory)) {
1302                         logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1303                         return false;
1304                 }
1305
1306                 if ($check_writable && !is_writable($directory)) {
1307                         logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1308                         return false;
1309                 }
1310
1311                 return true;
1312         }
1313
1314         /**
1315          * @param string $cat     Config category
1316          * @param string $k       Config key
1317          * @param mixed  $default Default value if it isn't set
1318          *
1319          * @return string Returns the value of the Config entry
1320          */
1321         public function getConfigValue($cat, $k, $default = null)
1322         {
1323                 $return = $default;
1324
1325                 if ($cat === 'config') {
1326                         if (isset($this->config[$k])) {
1327                                 $return = $this->config[$k];
1328                         }
1329                 } else {
1330                         if (isset($this->config[$cat][$k])) {
1331                                 $return = $this->config[$cat][$k];
1332                         }
1333                 }
1334
1335                 return $return;
1336         }
1337
1338         /**
1339          * Sets a default value in the config cache. Ignores already existing keys.
1340          *
1341          * @param string $cat Config category
1342          * @param string $k   Config key
1343          * @param mixed  $v   Default value to set
1344          */
1345         private function setDefaultConfigValue($cat, $k, $v)
1346         {
1347                 if (!isset($this->config[$cat][$k])) {
1348                         $this->setConfigValue($cat, $k, $v);
1349                 }
1350         }
1351
1352         /**
1353          * Sets a value in the config cache. Accepts raw output from the config table
1354          *
1355          * @param string $cat Config category
1356          * @param string $k   Config key
1357          * @param mixed  $v   Value to set
1358          */
1359         public function setConfigValue($cat, $k, $v)
1360         {
1361                 // Only arrays are serialized in database, so we have to unserialize sparingly
1362                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1363
1364                 if ($cat === 'config') {
1365                         $this->config[$k] = $value;
1366                 } else {
1367                         if (!isset($this->config[$cat])) {
1368                                 $this->config[$cat] = [];
1369                         }
1370
1371                         $this->config[$cat][$k] = $value;
1372                 }
1373         }
1374
1375         /**
1376          * Deletes a value from the config cache
1377          *
1378          * @param string $cat Config category
1379          * @param string $k   Config key
1380          */
1381         public function deleteConfigValue($cat, $k)
1382         {
1383                 if ($cat === 'config') {
1384                         if (isset($this->config[$k])) {
1385                                 unset($this->config[$k]);
1386                         }
1387                 } else {
1388                         if (isset($this->config[$cat][$k])) {
1389                                 unset($this->config[$cat][$k]);
1390                         }
1391                 }
1392         }
1393
1394
1395         /**
1396          * Retrieves a value from the user config cache
1397          *
1398          * @param int    $uid     User Id
1399          * @param string $cat     Config category
1400          * @param string $k       Config key
1401          * @param mixed  $default Default value if key isn't set
1402          *
1403          * @return string The value of the config entry
1404          */
1405         public function getPConfigValue($uid, $cat, $k, $default = null)
1406         {
1407                 $return = $default;
1408
1409                 if (isset($this->config[$uid][$cat][$k])) {
1410                         $return = $this->config[$uid][$cat][$k];
1411                 }
1412
1413                 return $return;
1414         }
1415
1416         /**
1417          * Sets a value in the user config cache
1418          *
1419          * Accepts raw output from the pconfig table
1420          *
1421          * @param int    $uid User Id
1422          * @param string $cat Config category
1423          * @param string $k   Config key
1424          * @param mixed  $v   Value to set
1425          */
1426         public function setPConfigValue($uid, $cat, $k, $v)
1427         {
1428                 // Only arrays are serialized in database, so we have to unserialize sparingly
1429                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1430
1431                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1432                         $this->config[$uid] = [];
1433                 }
1434
1435                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1436                         $this->config[$uid][$cat] = [];
1437                 }
1438
1439                 $this->config[$uid][$cat][$k] = $value;
1440         }
1441
1442         /**
1443          * Deletes a value from the user config cache
1444          *
1445          * @param int    $uid User Id
1446          * @param string $cat Config category
1447          * @param string $k   Config key
1448          */
1449         public function deletePConfigValue($uid, $cat, $k)
1450         {
1451                 if (isset($this->config[$uid][$cat][$k])) {
1452                         unset($this->config[$uid][$cat][$k]);
1453                 }
1454         }
1455
1456         /**
1457          * Generates the site's default sender email address
1458          *
1459          * @return string
1460          */
1461         public function getSenderEmailAddress()
1462         {
1463                 $sender_email = Core\Config::get('config', 'sender_email');
1464                 if (empty($sender_email)) {
1465                         $hostname = $this->getHostName();
1466                         if (strpos($hostname, ':')) {
1467                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1468                         }
1469
1470                         $sender_email = 'noreply@' . $hostname;
1471                 }
1472
1473                 return $sender_email;
1474         }
1475
1476         /**
1477          * Returns the current theme name.
1478          *
1479          * @return string the name of the current theme
1480          */
1481         public function getCurrentTheme()
1482         {
1483                 if ($this->getMode()->isInstall()) {
1484                         return '';
1485                 }
1486
1487                 //// @TODO Compute the current theme only once (this behavior has
1488                 /// already been implemented, but it didn't work well -
1489                 /// https://github.com/friendica/friendica/issues/5092)
1490                 $this->computeCurrentTheme();
1491
1492                 return $this->currentTheme;
1493         }
1494
1495         /**
1496          * Computes the current theme name based on the node settings, the user settings and the device type
1497          *
1498          * @throws Exception
1499          */
1500         private function computeCurrentTheme()
1501         {
1502                 $system_theme = Core\Config::get('system', 'theme');
1503                 if (!$system_theme) {
1504                         throw new Exception(Core\L10n::t('No system theme config value set.'));
1505                 }
1506
1507                 // Sane default
1508                 $this->currentTheme = $system_theme;
1509
1510                 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1511
1512                 $page_theme = null;
1513                 // Find the theme that belongs to the user whose stuff we are looking at
1514                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1515                         // Allow folks to override user themes and always use their own on their own site.
1516                         // This works only if the user is on the same server
1517                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1518                         if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1519                                 $page_theme = $user['theme'];
1520                         }
1521                 }
1522
1523                 $user_theme = Core\Session::get('theme', $system_theme);
1524
1525                 // Specific mobile theme override
1526                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1527                         $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1528                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1529
1530                         // --- means same mobile theme as desktop
1531                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1532                                 $user_theme = $user_mobile_theme;
1533                         }
1534                 }
1535
1536                 if ($page_theme) {
1537                         $theme_name = $page_theme;
1538                 } else {
1539                         $theme_name = $user_theme;
1540                 }
1541
1542                 if ($theme_name
1543                         && in_array($theme_name, $allowed_themes)
1544                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1545                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1546                 ) {
1547                         $this->currentTheme = $theme_name;
1548                 }
1549         }
1550
1551         /**
1552          * @brief Return full URL to theme which is currently in effect.
1553          *
1554          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1555          *
1556          * @return string
1557          */
1558         public function getCurrentThemeStylesheetPath()
1559         {
1560                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1561         }
1562
1563         /**
1564          * Check if request was an AJAX (xmlhttprequest) request.
1565          *
1566          * @return boolean true if it was an AJAX request
1567          */
1568         public function isAjax()
1569         {
1570                 return $this->isAjax;
1571         }
1572
1573         /**
1574          * Returns the value of a argv key
1575          * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1576          *
1577          * @param int $position the position of the argument
1578          * @param mixed $default the default value if not found
1579          *
1580          * @return mixed returns the value of the argument
1581          */
1582         public function getArgumentValue($position, $default = '')
1583         {
1584                 if (array_key_exists($position, $this->argv)) {
1585                         return $this->argv[$position];
1586                 }
1587
1588                 return $default;
1589         }
1590
1591         /**
1592          * Sets the base url for use in cmdline programs which don't have
1593          * $_SERVER variables
1594          */
1595         public function checkURL()
1596         {
1597                 $url = Core\Config::get('system', 'url');
1598
1599                 // if the url isn't set or the stored url is radically different
1600                 // than the currently visited url, store the current value accordingly.
1601                 // "Radically different" ignores common variations such as http vs https
1602                 // and www.example.com vs example.com.
1603                 // We will only change the url to an ip address if there is no existing setting
1604
1605                 if (empty($url) || (!link_compare($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1606                         Core\Config::set('system', 'url', $this->getBaseURL());
1607                 }
1608         }
1609
1610         /**
1611          * Frontend App script
1612          *
1613          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1614          * request and a representation of the response.
1615          *
1616          * This probably should change to limit the size of this monster method.
1617          */
1618         public function runFrontend()
1619         {
1620                 // Missing DB connection: ERROR
1621                 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1622                         Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1623                 }
1624
1625                 // Max Load Average reached: ERROR
1626                 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1627                         header('Retry-After: 120');
1628                         header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1629
1630                         Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1631                 }
1632
1633                 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1634                         Core\System::httpExit(404);
1635                 }
1636
1637                 if (!$this->getMode()->isInstall()) {
1638                         // Force SSL redirection
1639                         if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1640                                 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1641                                 && strpos($this->getBaseURL(), 'https://') === 0
1642                                 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1643                                 header('HTTP/1.1 302 Moved Temporarily');
1644                                 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1645                                 exit();
1646                         }
1647
1648                         Core\Session::init();
1649                         Core\Addon::callHooks('init_1');
1650                 }
1651
1652                 // Exclude the backend processes from the session management
1653                 if (!$this->isBackend()) {
1654                         $stamp1 = microtime(true);
1655                         session_start();
1656                         $this->saveTimestamp($stamp1, 'parser');
1657                         Core\L10n::setSessionVariable();
1658                         Core\L10n::setLangFromSession();
1659                 } else {
1660                         $_SESSION = [];
1661                         Core\Worker::executeIfIdle();
1662                 }
1663
1664                 // ZRL
1665                 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1666                         $this->query_string = Model\Profile::stripZrls($this->query_string);
1667                         if (!local_user()) {
1668                                 // Only continue when the given profile link seems valid
1669                                 // Valid profile links contain a path with "/profile/" and no query parameters
1670                                 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1671                                         strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1672                                         if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1673                                                 $_SESSION['my_url'] = $_GET['zrl'];
1674                                                 $_SESSION['authenticated'] = 0;
1675                                         }
1676                                         Model\Profile::zrlInit($this);
1677                                 } else {
1678                                         // Someone came with an invalid parameter, maybe as a DDoS attempt
1679                                         // We simply stop processing here
1680                                         logger("Invalid ZRL parameter " . $_GET['zrl'], LOGGER_DEBUG);
1681                                         Core\System::httpExit(403, ['title' => '403 Forbidden']);
1682                                 }
1683                         }
1684                 }
1685
1686                 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1687                         $token = $_GET['owt'];
1688                         $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1689                         Model\Profile::openWebAuthInit($token);
1690                 }
1691
1692                 Module\Login::sessionAuth();
1693
1694                 if (empty($_SESSION['authenticated'])) {
1695                         header('X-Account-Management-Status: none');
1696                 }
1697
1698                 $_SESSION['sysmsg']       = defaults($_SESSION, 'sysmsg'      , []);
1699                 $_SESSION['sysmsg_info']  = defaults($_SESSION, 'sysmsg_info' , []);
1700                 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1701
1702                 /*
1703                  * check_config() is responsible for running update scripts. These automatically
1704                  * update the DB schema whenever we push a new one out. It also checks to see if
1705                  * any addons have been added or removed and reacts accordingly.
1706                  */
1707
1708                 // in install mode, any url loads install module
1709                 // but we need "view" module for stylesheet
1710                 if ($this->getMode()->isInstall() && $this->module != 'view') {
1711                         $this->module = 'install';
1712                 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1713                         $this->module = 'maintenance';
1714                 } else {
1715                         $this->checkURL();
1716                         check_db(false);
1717                         Core\Addon::check();
1718                 }
1719
1720                 $this->page = [
1721                         'aside' => '',
1722                         'bottom' => '',
1723                         'content' => '',
1724                         'footer' => '',
1725                         'htmlhead' => '',
1726                         'nav' => '',
1727                         'page_title' => '',
1728                         'right_aside' => '',
1729                         'template' => '',
1730                         'title' => ''
1731                 ];
1732
1733                 if (strlen($this->module)) {
1734                         // Compatibility with the Android Diaspora client
1735                         if ($this->module == 'stream') {
1736                                 goaway('network?f=&order=post');
1737                         }
1738
1739                         if ($this->module == 'conversations') {
1740                                 goaway('message');
1741                         }
1742
1743                         if ($this->module == 'commented') {
1744                                 goaway('network?f=&order=comment');
1745                         }
1746
1747                         if ($this->module == 'liked') {
1748                                 goaway('network?f=&order=comment');
1749                         }
1750
1751                         if ($this->module == 'activity') {
1752                                 goaway('network/?f=&conv=1');
1753                         }
1754
1755                         if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1756                                 goaway('bookmarklet');
1757                         }
1758
1759                         if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1760                                 goaway('settings');
1761                         }
1762
1763                         if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1764                                 goaway('search');
1765                         }
1766
1767                         // Compatibility with the Firefox App
1768                         if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1769                                 $this->module = "login";
1770                         }
1771
1772                         $privateapps = Core\Config::get('config', 'private_addons', false);
1773                         if (is_array($this->addons) && in_array($this->module, $this->addons) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1774                                 //Check if module is an app and if public access to apps is allowed or not
1775                                 if ((!local_user()) && Core\Addon::isApp($this->module) && $privateapps) {
1776                                         info(Core\L10n::t("You must be logged in to use addons. "));
1777                                 } else {
1778                                         include_once "addon/{$this->module}/{$this->module}.php";
1779                                         if (function_exists($this->module . '_module')) {
1780                                                 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1781                                                 $this->module_class = 'Friendica\\LegacyModule';
1782                                                 $this->module_loaded = true;
1783                                         }
1784                                 }
1785                         }
1786
1787                         // Controller class routing
1788                         if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1789                                 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1790                                 $this->module_loaded = true;
1791                         }
1792
1793                         /* If not, next look for a 'standard' program module in the 'mod' directory
1794                          * We emulate a Module class through the LegacyModule class
1795                          */
1796                         if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1797                                 LegacyModule::setModuleFile("mod/{$this->module}.php");
1798                                 $this->module_class = 'Friendica\\LegacyModule';
1799                                 $this->module_loaded = true;
1800                         }
1801
1802                         /* The URL provided does not resolve to a valid module.
1803                          *
1804                          * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1805                          * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1806                          * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
1807                          * this will often succeed and eventually do the right thing.
1808                          *
1809                          * Otherwise we are going to emit a 404 not found.
1810                          */
1811                         if (! $this->module_loaded) {
1812                                 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1813                                 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1814                                         exit();
1815                                 }
1816
1817                                 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1818                                         logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1819                                         goaway($this->getBaseURL() . $_SERVER['REQUEST_URI']);
1820                                 }
1821
1822                                 logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
1823
1824                                 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1825                                 $tpl = get_markup_template("404.tpl");
1826                                 $this->page['content'] = replace_macros($tpl, [
1827                                         '$message' =>  Core\L10n::t('Page not found.')
1828                                 ]);
1829                         }
1830                 }
1831
1832                 // Load current theme info
1833                 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1834                 if (file_exists($theme_info_file)) {
1835                         require_once $theme_info_file;
1836                 }
1837
1838                 // initialise content region
1839                 if ($this->getMode()->isNormal()) {
1840                         Core\Addon::callHooks('page_content_top', $this->page['content']);
1841                 }
1842
1843                 // Call module functions
1844                 if ($this->module_loaded) {
1845                         $this->page['page_title'] = $this->module;
1846                         $placeholder = '';
1847
1848                         Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1849
1850                         call_user_func([$this->module_class, 'init']);
1851
1852                         // "rawContent" is especially meant for technical endpoints.
1853                         // This endpoint doesn't need any theme initialization or other comparable stuff.
1854                         if (!$this->error) {
1855                                 call_user_func([$this->module_class, 'rawContent']);
1856                         }
1857
1858                         if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1859                                 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1860                                 $func($this);
1861                         }
1862
1863                         if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1864                                 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1865                                 call_user_func([$this->module_class, 'post']);
1866                         }
1867
1868                         if (! $this->error) {
1869                                 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1870                                 call_user_func([$this->module_class, 'afterpost']);
1871                         }
1872
1873                         if (! $this->error) {
1874                                 $arr = ['content' => $this->page['content']];
1875                                 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1876                                 $this->page['content'] = $arr['content'];
1877                                 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1878                                 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1879                                 $this->page['content'] .= $arr['content'];
1880                         }
1881
1882                         if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1883                                 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1884                                 $func($this);
1885                         }
1886                 }
1887
1888                 /* Create the page head after setting the language
1889                  * and getting any auth credentials.
1890                  *
1891                  * Moved initHead() and initFooter() to after
1892                  * all the module functions have executed so that all
1893                  * theme choices made by the modules can take effect.
1894                  */
1895                 $this->initHead();
1896
1897                 /* Build the page ending -- this is stuff that goes right before
1898                  * the closing </body> tag
1899                  */
1900                 $this->initFooter();
1901
1902                 /* now that we've been through the module content, see if the page reported
1903                  * a permission problem and if so, a 403 response would seem to be in order.
1904                  */
1905                 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1906                         header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1907                 }
1908
1909                 // Report anything which needs to be communicated in the notification area (before the main body)
1910                 Core\Addon::callHooks('page_end', $this->page['content']);
1911
1912                 // Add the navigation (menu) template
1913                 if ($this->module != 'install' && $this->module != 'maintenance') {
1914                         $this->page['htmlhead'] .= replace_macros(get_markup_template('nav_head.tpl'), []);
1915                         $this->page['nav']       = Content\Nav::build($this);
1916                 }
1917
1918                 // Build the page - now that we have all the components
1919                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1920                         $doc = new DOMDocument();
1921
1922                         $target = new DOMDocument();
1923                         $target->loadXML("<root></root>");
1924
1925                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1926
1927                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1928                         @$doc->loadHTML($content);
1929
1930                         $xpath = new DOMXPath($doc);
1931
1932                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
1933
1934                         foreach ($list as $item) {
1935                                 $item = $target->importNode($item, true);
1936
1937                                 // And then append it to the target
1938                                 $target->documentElement->appendChild($item);
1939                         }
1940                 }
1941
1942                 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1943                         header("Content-type: text/html; charset=utf-8");
1944
1945                         echo substr($target->saveHTML(), 6, -8);
1946
1947                         exit();
1948                 }
1949
1950                 $page    = $this->page;
1951                 $profile = $this->profile;
1952
1953                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1954                 header("Content-type: text/html; charset=utf-8");
1955
1956                 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1957                         header("Strict-Transport-Security: max-age=31536000");
1958                 }
1959
1960                 // Some security stuff
1961                 header('X-Content-Type-Options: nosniff');
1962                 header('X-XSS-Protection: 1; mode=block');
1963                 header('X-Permitted-Cross-Domain-Policies: none');
1964                 header('X-Frame-Options: sameorigin');
1965
1966                 // Things like embedded OSM maps don't work, when this is enabled
1967                 // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
1968
1969                 /* We use $_GET["mode"] for special page templates. So we will check if we have
1970                  * to load another page template than the default one.
1971                  * The page templates are located in /view/php/ or in the theme directory.
1972                  */
1973                 if (isset($_GET["mode"])) {
1974                         $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1975                 }
1976
1977                 // If there is no page template use the default page template
1978                 if (empty($template)) {
1979                         $template = Core\Theme::getPathForFile("default.php");
1980                 }
1981
1982                 // Theme templates expect $a as an App instance
1983                 $a = $this;
1984
1985                 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1986                 require_once $template;
1987         }
1988 }