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