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