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