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