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