]> git.mxchange.org Git - friendica.git/blob - src/App.php
845560a4d676df27d4d3548eb8d1b88b1123bd15
[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.config.php
333          */
334         private function loadConfigFiles()
335         {
336                 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
337                 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
338
339                 // Legacy .htconfig.php support
340                 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
341                         $a = $this;
342                         include $this->getBasePath() . '/.htpreconfig.php';
343                 }
344
345                 // Legacy .htconfig.php support
346                 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
347                         $a = $this;
348
349                         include $this->getBasePath() . '/.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() . '/config/local.config.php')) {
378                         $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
379                 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
380                         $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
381                 }
382         }
383
384         /**
385          * Tries to load the specified legacy configuration file into the App->config array.
386          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
387          *
388          * @deprecated since version 2018.12
389          * @param string $filepath
390          * @param bool $overwrite Force value overwrite if the config key already exists
391          * @throws Exception
392          */
393         public function loadINIConfigFile($filepath, $overwrite = false)
394         {
395                 if (!file_exists($filepath)) {
396                         throw new Exception('Error parsing non-existent INI config file ' . $filepath);
397                 }
398
399                 $contents = include($filepath);
400
401                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
402
403                 if ($config === false) {
404                         throw new Exception('Error parsing INI config file ' . $filepath);
405                 }
406
407                 $this->loadConfigArray($config, $overwrite);
408         }
409
410         /**
411          * Tries to load the specified configuration file into the App->config array.
412          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
413          *
414          * The config format is PHP array and the template for configuration files is the following:
415          *
416          * <?php return [
417          *      'section' => [
418          *          'key' => 'value',
419          *      ],
420          * ];
421          *
422          * @param string $filepath
423          * @param bool $overwrite Force value overwrite if the config key already exists
424          * @throws Exception
425          */
426         public function loadConfigFile($filepath, $overwrite = false)
427         {
428                 if (!file_exists($filepath)) {
429                         throw new Exception('Error loading non-existent config file ' . $filepath);
430                 }
431
432                 $config = include($filepath);
433
434                 if (!is_array($config)) {
435                         throw new Exception('Error loading config file ' . $filepath);
436                 }
437
438                 $this->loadConfigArray($config, $overwrite);
439         }
440
441         /**
442          * Loads addons configuration files
443          *
444          * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
445          * again to overwrite potential local addon configuration.
446          */
447         private function loadAddonConfig()
448         {
449                 // Loads addons default config
450                 Core\Hook::callAll('load_config');
451
452                 // Load the local addon config file to overwritten default addon config values
453                 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
454                         $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
455                 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
456                         $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
457                 }
458         }
459
460         /**
461          * Tries to load the specified configuration array into the App->config array.
462          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
463          *
464          * @param array $config
465          * @param bool  $overwrite Force value overwrite if the config key already exists
466          */
467         private function loadConfigArray(array $config, $overwrite = false)
468         {
469                 foreach ($config as $category => $values) {
470                         foreach ($values as $key => $value) {
471                                 if ($overwrite) {
472                                         $this->setConfigValue($category, $key, $value);
473                                 } else {
474                                         $this->setDefaultConfigValue($category, $key, $value);
475                                 }
476                         }
477                 }
478         }
479
480         /**
481          * Loads the default timezone
482          *
483          * Include support for legacy $default_timezone
484          *
485          * @global string $default_timezone
486          */
487         private function loadDefaultTimezone()
488         {
489                 if ($this->getConfigValue('system', 'default_timezone')) {
490                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
491                 } else {
492                         global $default_timezone;
493                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
494                 }
495
496                 if ($this->timezone) {
497                         date_default_timezone_set($this->timezone);
498                 }
499         }
500
501         /**
502          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
503          */
504         private function determineURLPath()
505         {
506                 /* Relative script path to the web server root
507                  * Not all of those $_SERVER properties can be present, so we do by inverse priority order
508                  */
509                 $relative_script_path = '';
510                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL'       , $relative_script_path);
511                 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI'       , $relative_script_path);
512                 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
513                 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL'         , $relative_script_path);
514                 $relative_script_path = defaults($_SERVER, 'REQUEST_URI'        , $relative_script_path);
515
516                 $this->urlPath = $this->getConfigValue('system', 'urlpath');
517
518                 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
519                  * QUERY_STRING gives pagename=module/parameter
520                  *
521                  * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
522                  */
523                 if (!empty($relative_script_path)) {
524                         // Module
525                         if (!empty($_SERVER['QUERY_STRING'])) {
526                                 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
527                         } else {
528                                 // Root page
529                                 $path = trim($relative_script_path, '/');
530                         }
531
532                         if ($path && $path != $this->urlPath) {
533                                 $this->urlPath = $path;
534                         }
535                 }
536         }
537
538         public function loadDatabase()
539         {
540                 if (DBA::connected()) {
541                         return;
542                 }
543
544                 $db_host = $this->getConfigValue('database', 'hostname');
545                 $db_user = $this->getConfigValue('database', 'username');
546                 $db_pass = $this->getConfigValue('database', 'password');
547                 $db_data = $this->getConfigValue('database', 'database');
548                 $charset = $this->getConfigValue('database', 'charset');
549
550                 // Use environment variables for mysql if they are set beforehand
551                 if (!empty(getenv('MYSQL_HOST'))
552                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
553                         && getenv('MYSQL_PASSWORD') !== false
554                         && !empty(getenv('MYSQL_DATABASE')))
555                 {
556                         $db_host = getenv('MYSQL_HOST');
557                         if (!empty(getenv('MYSQL_PORT'))) {
558                                 $db_host .= ':' . getenv('MYSQL_PORT');
559                         }
560                         if (!empty(getenv('MYSQL_USERNAME'))) {
561                                 $db_user = getenv('MYSQL_USERNAME');
562                         } else {
563                                 $db_user = getenv('MYSQL_USER');
564                         }
565                         $db_pass = (string) getenv('MYSQL_PASSWORD');
566                         $db_data = getenv('MYSQL_DATABASE');
567                 }
568
569                 $stamp1 = microtime(true);
570
571                 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
572                         // Loads DB_UPDATE_VERSION constant
573                         Database\DBStructure::definition(false);
574                 }
575
576                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
577
578                 $this->saveTimestamp($stamp1, 'network');
579         }
580
581         /**
582          * @brief Returns the base filesystem path of the App
583          *
584          * It first checks for the internal variable, then for DOCUMENT_ROOT and
585          * finally for PWD
586          *
587          * @return string
588          */
589         public function getBasePath()
590         {
591                 $basepath = $this->basePath;
592
593                 if (!$basepath) {
594                         $basepath = Core\Config::get('system', 'basepath');
595                 }
596
597                 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
598                         $basepath = $_SERVER['DOCUMENT_ROOT'];
599                 }
600
601                 if (!$basepath && !empty($_SERVER['PWD'])) {
602                         $basepath = $_SERVER['PWD'];
603                 }
604
605                 return self::getRealPath($basepath);
606         }
607
608         /**
609          * @brief Returns a normalized file path
610          *
611          * This is a wrapper for the "realpath" function.
612          * That function cannot detect the real path when some folders aren't readable.
613          * Since this could happen with some hosters we need to handle this.
614          *
615          * @param string $path The path that is about to be normalized
616          * @return string normalized path - when possible
617          */
618         public static function getRealPath($path)
619         {
620                 $normalized = realpath($path);
621
622                 if (!is_bool($normalized)) {
623                         return $normalized;
624                 } else {
625                         return $path;
626                 }
627         }
628
629         public function getScheme()
630         {
631                 return $this->scheme;
632         }
633
634         /**
635          * @brief Retrieves the Friendica instance base URL
636          *
637          * This function assembles the base URL from multiple parts:
638          * - Protocol is determined either by the request or a combination of
639          * system.ssl_policy and the $ssl parameter.
640          * - Host name is determined either by system.hostname or inferred from request
641          * - Path is inferred from SCRIPT_NAME
642          *
643          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
644          *
645          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
646          * @return string Friendica server base URL
647          */
648         public function getBaseURL($ssl = false)
649         {
650                 $scheme = $this->scheme;
651
652                 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
653                         $scheme = 'https';
654                 }
655
656                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
657                 //      (and also the login link). Anything seen by an outsider will have it turned off.
658
659                 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
660                         if ($ssl) {
661                                 $scheme = 'https';
662                         } else {
663                                 $scheme = 'http';
664                         }
665                 }
666
667                 if (Core\Config::get('config', 'hostname') != '') {
668                         $this->hostname = Core\Config::get('config', 'hostname');
669                 }
670
671                 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
672         }
673
674         /**
675          * @brief Initializes the baseurl components
676          *
677          * Clears the baseurl cache to prevent inconsistencies
678          *
679          * @param string $url
680          */
681         public function setBaseURL($url)
682         {
683                 $parsed = @parse_url($url);
684                 $hostname = '';
685
686                 if (!empty($parsed)) {
687                         if (!empty($parsed['scheme'])) {
688                                 $this->scheme = $parsed['scheme'];
689                         }
690
691                         if (!empty($parsed['host'])) {
692                                 $hostname = $parsed['host'];
693                         }
694
695                         if (!empty($parsed['port'])) {
696                                 $hostname .= ':' . $parsed['port'];
697                         }
698                         if (!empty($parsed['path'])) {
699                                 $this->urlPath = trim($parsed['path'], '\\/');
700                         }
701
702                         if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
703                                 include $this->getBasePath() . '/.htpreconfig.php';
704                         }
705
706                         if (Core\Config::get('config', 'hostname') != '') {
707                                 $this->hostname = Core\Config::get('config', 'hostname');
708                         }
709
710                         if (!isset($this->hostname) || ($this->hostname == '')) {
711                                 $this->hostname = $hostname;
712                         }
713                 }
714         }
715
716         public function getHostName()
717         {
718                 if (Core\Config::get('config', 'hostname') != '') {
719                         $this->hostname = Core\Config::get('config', 'hostname');
720                 }
721
722                 return $this->hostname;
723         }
724
725         public function getURLPath()
726         {
727                 return $this->urlPath;
728         }
729
730         /**
731          * Initializes App->page['htmlhead'].
732          *
733          * Includes:
734          * - Page title
735          * - Favicons
736          * - Registered stylesheets (through App->registerStylesheet())
737          * - Infinite scroll data
738          * - head.tpl template
739          */
740         public function initHead()
741         {
742                 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
743
744                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
745                 if ($interval < 0) {
746                         $interval = 2147483647;
747                 }
748
749                 if ($interval < 10000) {
750                         $interval = 40000;
751                 }
752
753                 // compose the page title from the sitename and the
754                 // current module called
755                 if (!$this->module == '') {
756                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
757                 } else {
758                         $this->page['title'] = $this->config['sitename'];
759                 }
760
761                 if (!empty(Core\Renderer::$theme['stylesheet'])) {
762                         $stylesheet = Core\Renderer::$theme['stylesheet'];
763                 } else {
764                         $stylesheet = $this->getCurrentThemeStylesheetPath();
765                 }
766
767                 $this->registerStylesheet($stylesheet);
768
769                 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
770                 if ($shortcut_icon == '') {
771                         $shortcut_icon = 'images/friendica-32.png';
772                 }
773
774                 $touch_icon = Core\Config::get('system', 'touch_icon');
775                 if ($touch_icon == '') {
776                         $touch_icon = 'images/friendica-128.png';
777                 }
778
779                 Core\Addon::callHooks('head', $this->page['htmlhead']);
780
781                 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
782                 /* put the head template at the beginning of page['htmlhead']
783                  * since the code added by the modules frequently depends on it
784                  * being first
785                  */
786                 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
787                         '$baseurl'         => $this->getBaseURL(),
788                         '$local_user'      => local_user(),
789                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
790                         '$delitem'         => Core\L10n::t('Delete this item?'),
791                         '$showmore'        => Core\L10n::t('show more'),
792                         '$showfewer'       => Core\L10n::t('show fewer'),
793                         '$update_interval' => $interval,
794                         '$shortcut_icon'   => $shortcut_icon,
795                         '$touch_icon'      => $touch_icon,
796                         '$block_public'    => intval(Core\Config::get('system', 'block_public')),
797                         '$stylesheets'     => $this->stylesheets,
798                 ]) . $this->page['htmlhead'];
799         }
800
801         /**
802          * Initializes App->page['footer'].
803          *
804          * Includes:
805          * - Javascript homebase
806          * - Mobile toggle link
807          * - Registered footer scripts (through App->registerFooterScript())
808          * - footer.tpl template
809          */
810         public function initFooter()
811         {
812                 // If you're just visiting, let javascript take you home
813                 if (!empty($_SESSION['visitor_home'])) {
814                         $homebase = $_SESSION['visitor_home'];
815                 } elseif (local_user()) {
816                         $homebase = 'profile/' . $this->user['nickname'];
817                 }
818
819                 if (isset($homebase)) {
820                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
821                 }
822
823                 /*
824                  * Add a "toggle mobile" link if we're using a mobile device
825                  */
826                 if ($this->is_mobile || $this->is_tablet) {
827                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
828                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
829                         } else {
830                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
831                         }
832                         $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
833                                 '$toggle_link' => $link,
834                                 '$toggle_text' => Core\L10n::t('toggle mobile')
835                         ]);
836                 }
837
838                 Core\Addon::callHooks('footer', $this->page['footer']);
839
840                 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
841                 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
842                         '$baseurl' => $this->getBaseURL(),
843                         '$footerScripts' => $this->footerScripts,
844                 ]) . $this->page['footer'];
845         }
846
847         /**
848          * @brief Removes the base url from an url. This avoids some mixed content problems.
849          *
850          * @param string $origURL
851          *
852          * @return string The cleaned url
853          */
854         public function removeBaseURL($origURL)
855         {
856                 // Remove the hostname from the url if it is an internal link
857                 $nurl = Util\Strings::normaliseLink($origURL);
858                 $base = Util\Strings::normaliseLink($this->getBaseURL());
859                 $url = str_replace($base . '/', '', $nurl);
860
861                 // if it is an external link return the orignal value
862                 if ($url == Util\Strings::normaliseLink($origURL)) {
863                         return $origURL;
864                 } else {
865                         return $url;
866                 }
867         }
868
869         /**
870          * Saves a timestamp for a value - f.e. a call
871          * Necessary for profiling Friendica
872          *
873          * @param int $timestamp the Timestamp
874          * @param string $value A value to profile
875          */
876         public function saveTimestamp($timestamp, $value)
877         {
878                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
879                         return;
880                 }
881
882                 $duration = (float) (microtime(true) - $timestamp);
883
884                 if (!isset($this->performance[$value])) {
885                         // Prevent ugly E_NOTICE
886                         $this->performance[$value] = 0;
887                 }
888
889                 $this->performance[$value] += (float) $duration;
890                 $this->performance['marktime'] += (float) $duration;
891
892                 $callstack = Core\System::callstack();
893
894                 if (!isset($this->callstack[$value][$callstack])) {
895                         // Prevent ugly E_NOTICE
896                         $this->callstack[$value][$callstack] = 0;
897                 }
898
899                 $this->callstack[$value][$callstack] += (float) $duration;
900         }
901
902         /**
903          * Returns the current UserAgent as a String
904          *
905          * @return string the UserAgent as a String
906          */
907         public function getUserAgent()
908         {
909                 return
910                         FRIENDICA_PLATFORM . " '" .
911                         FRIENDICA_CODENAME . "' " .
912                         FRIENDICA_VERSION . '-' .
913                         DB_UPDATE_VERSION . '; ' .
914                         $this->getBaseURL();
915         }
916
917         /**
918          * Checks, if the call is from the Friendica App
919          *
920          * Reason:
921          * The friendica client has problems with the GUID in the notify. this is some workaround
922          */
923         private function checkFriendicaApp()
924         {
925                 // Friendica-Client
926                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
927         }
928
929         /**
930          *      Is the call via the Friendica app? (not a "normale" call)
931          *
932          * @return bool true if it's from the Friendica app
933          */
934         public function isFriendicaApp()
935         {
936                 return $this->isFriendicaApp;
937         }
938
939         /**
940          * @brief Checks if the site is called via a backend process
941          *
942          * This isn't a perfect solution. But we need this check very early.
943          * So we cannot wait until the modules are loaded.
944          *
945          * @param string $backend true, if the backend flag was set during App initialization
946          *
947          */
948         private function checkBackend($backend) {
949                 static $backends = [
950                         '_well_known',
951                         'api',
952                         'dfrn_notify',
953                         'fetch',
954                         'hcard',
955                         'hostxrd',
956                         'nodeinfo',
957                         'noscrape',
958                         'p',
959                         'poco',
960                         'post',
961                         'proxy',
962                         'pubsub',
963                         'pubsubhubbub',
964                         'receive',
965                         'rsd_xml',
966                         'salmon',
967                         'statistics_json',
968                         'xrd',
969                 ];
970
971                 // Check if current module is in backend or backend flag is set
972                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
973         }
974
975         /**
976          * Returns true, if the call is from a backend node (f.e. from a worker)
977          *
978          * @return bool Is it a known backend?
979          */
980         public function isBackend()
981         {
982                 return $this->isBackend;
983         }
984
985         /**
986          * @brief Checks if the maximum number of database processes is reached
987          *
988          * @return bool Is the limit reached?
989          */
990         public function isMaxProcessesReached()
991         {
992                 // Deactivated, needs more investigating if this check really makes sense
993                 return false;
994
995                 /*
996                  * Commented out to suppress static analyzer issues
997                  *
998                 if ($this->is_backend()) {
999                         $process = 'backend';
1000                         $max_processes = Core\Config::get('system', 'max_processes_backend');
1001                         if (intval($max_processes) == 0) {
1002                                 $max_processes = 5;
1003                         }
1004                 } else {
1005                         $process = 'frontend';
1006                         $max_processes = Core\Config::get('system', 'max_processes_frontend');
1007                         if (intval($max_processes) == 0) {
1008                                 $max_processes = 20;
1009                         }
1010                 }
1011
1012                 $processlist = DBA::processlist();
1013                 if ($processlist['list'] != '') {
1014                         Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1015
1016                         if ($processlist['amount'] > $max_processes) {
1017                                 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1018                                 return true;
1019                         }
1020                 }
1021                 return false;
1022                  */
1023         }
1024
1025         /**
1026          * @brief Checks if the minimal memory is reached
1027          *
1028          * @return bool Is the memory limit reached?
1029          */
1030         public function isMinMemoryReached()
1031         {
1032                 $min_memory = Core\Config::get('system', 'min_memory', 0);
1033                 if ($min_memory == 0) {
1034                         return false;
1035                 }
1036
1037                 if (!is_readable('/proc/meminfo')) {
1038                         return false;
1039                 }
1040
1041                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1042
1043                 $meminfo = [];
1044                 foreach ($memdata as $line) {
1045                         $data = explode(':', $line);
1046                         if (count($data) != 2) {
1047                                 continue;
1048                         }
1049                         list($key, $val) = $data;
1050                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1051                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1052                 }
1053
1054                 if (!isset($meminfo['MemFree'])) {
1055                         return false;
1056                 }
1057
1058                 $free = $meminfo['MemFree'];
1059
1060                 $reached = ($free < $min_memory);
1061
1062                 if ($reached) {
1063                         Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1064                 }
1065
1066                 return $reached;
1067         }
1068
1069         /**
1070          * @brief Checks if the maximum load is reached
1071          *
1072          * @return bool Is the load reached?
1073          */
1074         public function isMaxLoadReached()
1075         {
1076                 if ($this->isBackend()) {
1077                         $process = 'backend';
1078                         $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1079                         if ($maxsysload < 1) {
1080                                 $maxsysload = 50;
1081                         }
1082                 } else {
1083                         $process = 'frontend';
1084                         $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1085                         if ($maxsysload < 1) {
1086                                 $maxsysload = 50;
1087                         }
1088                 }
1089
1090                 $load = Core\System::currentLoad();
1091                 if ($load) {
1092                         if (intval($load) > $maxsysload) {
1093                                 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1094                                 return true;
1095                         }
1096                 }
1097                 return false;
1098         }
1099
1100         /**
1101          * Executes a child process with 'proc_open'
1102          *
1103          * @param string $command The command to execute
1104          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1105          */
1106         public function proc_run($command, $args)
1107         {
1108                 if (!function_exists('proc_open')) {
1109                         return;
1110                 }
1111
1112                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1113
1114                 foreach ($args as $key => $value) {
1115                         if (!is_null($value) && is_bool($value) && !$value) {
1116                                 continue;
1117                         }
1118
1119                         $cmdline .= ' --' . $key;
1120                         if (!is_null($value) && !is_bool($value)) {
1121                                 $cmdline .= ' ' . $value;
1122                         }
1123                 }
1124
1125                 if ($this->isMinMemoryReached()) {
1126                         return;
1127                 }
1128
1129                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1130                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1131                 } else {
1132                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1133                 }
1134                 if (!is_resource($resource)) {
1135                         Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1136                         return;
1137                 }
1138                 proc_close($resource);
1139         }
1140
1141         /**
1142          * @brief Returns the system user that is executing the script
1143          *
1144          * This mostly returns something like "www-data".
1145          *
1146          * @return string system username
1147          */
1148         private static function getSystemUser()
1149         {
1150                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1151                         return '';
1152                 }
1153
1154                 $processUser = posix_getpwuid(posix_geteuid());
1155                 return $processUser['name'];
1156         }
1157
1158         /**
1159          * @brief Checks if a given directory is usable for the system
1160          *
1161          * @return boolean the directory is usable
1162          */
1163         public static function isDirectoryUsable($directory, $check_writable = true)
1164         {
1165                 if ($directory == '') {
1166                         Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1167                         return false;
1168                 }
1169
1170                 if (!file_exists($directory)) {
1171                         Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1172                         return false;
1173                 }
1174
1175                 if (is_file($directory)) {
1176                         Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1177                         return false;
1178                 }
1179
1180                 if (!is_dir($directory)) {
1181                         Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1182                         return false;
1183                 }
1184
1185                 if ($check_writable && !is_writable($directory)) {
1186                         Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1187                         return false;
1188                 }
1189
1190                 return true;
1191         }
1192
1193         /**
1194          * @param string $cat     Config category
1195          * @param string $k       Config key
1196          * @param mixed  $default Default value if it isn't set
1197          *
1198          * @return string Returns the value of the Config entry
1199          */
1200         public function getConfigValue($cat, $k, $default = null)
1201         {
1202                 $return = $default;
1203
1204                 if ($cat === 'config') {
1205                         if (isset($this->config[$k])) {
1206                                 $return = $this->config[$k];
1207                         }
1208                 } else {
1209                         if (isset($this->config[$cat][$k])) {
1210                                 $return = $this->config[$cat][$k];
1211                         }
1212                 }
1213
1214                 return $return;
1215         }
1216
1217         /**
1218          * Sets a default value in the config cache. Ignores already existing keys.
1219          *
1220          * @param string $cat Config category
1221          * @param string $k   Config key
1222          * @param mixed  $v   Default value to set
1223          */
1224         private function setDefaultConfigValue($cat, $k, $v)
1225         {
1226                 if (!isset($this->config[$cat][$k])) {
1227                         $this->setConfigValue($cat, $k, $v);
1228                 }
1229         }
1230
1231         /**
1232          * Sets a value in the config cache. Accepts raw output from the config table
1233          *
1234          * @param string $cat Config category
1235          * @param string $k   Config key
1236          * @param mixed  $v   Value to set
1237          */
1238         public function setConfigValue($cat, $k, $v)
1239         {
1240                 // Only arrays are serialized in database, so we have to unserialize sparingly
1241                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1242
1243                 if ($cat === 'config') {
1244                         $this->config[$k] = $value;
1245                 } else {
1246                         if (!isset($this->config[$cat])) {
1247                                 $this->config[$cat] = [];
1248                         }
1249
1250                         $this->config[$cat][$k] = $value;
1251                 }
1252         }
1253
1254         /**
1255          * Deletes a value from the config cache
1256          *
1257          * @param string $cat Config category
1258          * @param string $k   Config key
1259          */
1260         public function deleteConfigValue($cat, $k)
1261         {
1262                 if ($cat === 'config') {
1263                         if (isset($this->config[$k])) {
1264                                 unset($this->config[$k]);
1265                         }
1266                 } else {
1267                         if (isset($this->config[$cat][$k])) {
1268                                 unset($this->config[$cat][$k]);
1269                         }
1270                 }
1271         }
1272
1273
1274         /**
1275          * Retrieves a value from the user config cache
1276          *
1277          * @param int    $uid     User Id
1278          * @param string $cat     Config category
1279          * @param string $k       Config key
1280          * @param mixed  $default Default value if key isn't set
1281          *
1282          * @return string The value of the config entry
1283          */
1284         public function getPConfigValue($uid, $cat, $k, $default = null)
1285         {
1286                 $return = $default;
1287
1288                 if (isset($this->config[$uid][$cat][$k])) {
1289                         $return = $this->config[$uid][$cat][$k];
1290                 }
1291
1292                 return $return;
1293         }
1294
1295         /**
1296          * Sets a value in the user config cache
1297          *
1298          * Accepts raw output from the pconfig table
1299          *
1300          * @param int    $uid User Id
1301          * @param string $cat Config category
1302          * @param string $k   Config key
1303          * @param mixed  $v   Value to set
1304          */
1305         public function setPConfigValue($uid, $cat, $k, $v)
1306         {
1307                 // Only arrays are serialized in database, so we have to unserialize sparingly
1308                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1309
1310                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1311                         $this->config[$uid] = [];
1312                 }
1313
1314                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1315                         $this->config[$uid][$cat] = [];
1316                 }
1317
1318                 $this->config[$uid][$cat][$k] = $value;
1319         }
1320
1321         /**
1322          * Deletes a value from the user config cache
1323          *
1324          * @param int    $uid User Id
1325          * @param string $cat Config category
1326          * @param string $k   Config key
1327          */
1328         public function deletePConfigValue($uid, $cat, $k)
1329         {
1330                 if (isset($this->config[$uid][$cat][$k])) {
1331                         unset($this->config[$uid][$cat][$k]);
1332                 }
1333         }
1334
1335         /**
1336          * Generates the site's default sender email address
1337          *
1338          * @return string
1339          */
1340         public function getSenderEmailAddress()
1341         {
1342                 $sender_email = Core\Config::get('config', 'sender_email');
1343                 if (empty($sender_email)) {
1344                         $hostname = $this->getHostName();
1345                         if (strpos($hostname, ':')) {
1346                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1347                         }
1348
1349                         $sender_email = 'noreply@' . $hostname;
1350                 }
1351
1352                 return $sender_email;
1353         }
1354
1355         /**
1356          * Returns the current theme name.
1357          *
1358          * @return string the name of the current theme
1359          */
1360         public function getCurrentTheme()
1361         {
1362                 if ($this->getMode()->isInstall()) {
1363                         return '';
1364                 }
1365
1366                 //// @TODO Compute the current theme only once (this behavior has
1367                 /// already been implemented, but it didn't work well -
1368                 /// https://github.com/friendica/friendica/issues/5092)
1369                 $this->computeCurrentTheme();
1370
1371                 return $this->currentTheme;
1372         }
1373
1374         /**
1375          * Computes the current theme name based on the node settings, the user settings and the device type
1376          *
1377          * @throws Exception
1378          */
1379         private function computeCurrentTheme()
1380         {
1381                 $system_theme = Core\Config::get('system', 'theme');
1382                 if (!$system_theme) {
1383                         throw new Exception(Core\L10n::t('No system theme config value set.'));
1384                 }
1385
1386                 // Sane default
1387                 $this->currentTheme = $system_theme;
1388
1389                 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1390
1391                 $page_theme = null;
1392                 // Find the theme that belongs to the user whose stuff we are looking at
1393                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1394                         // Allow folks to override user themes and always use their own on their own site.
1395                         // This works only if the user is on the same server
1396                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1397                         if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1398                                 $page_theme = $user['theme'];
1399                         }
1400                 }
1401
1402                 $user_theme = Core\Session::get('theme', $system_theme);
1403
1404                 // Specific mobile theme override
1405                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1406                         $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1407                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1408
1409                         // --- means same mobile theme as desktop
1410                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1411                                 $user_theme = $user_mobile_theme;
1412                         }
1413                 }
1414
1415                 if ($page_theme) {
1416                         $theme_name = $page_theme;
1417                 } else {
1418                         $theme_name = $user_theme;
1419                 }
1420
1421                 if ($theme_name
1422                         && in_array($theme_name, $allowed_themes)
1423                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1424                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1425                 ) {
1426                         $this->currentTheme = $theme_name;
1427                 }
1428         }
1429
1430         /**
1431          * @brief Return full URL to theme which is currently in effect.
1432          *
1433          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1434          *
1435          * @return string
1436          */
1437         public function getCurrentThemeStylesheetPath()
1438         {
1439                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1440         }
1441
1442         /**
1443          * Check if request was an AJAX (xmlhttprequest) request.
1444          *
1445          * @return boolean true if it was an AJAX request
1446          */
1447         public function isAjax()
1448         {
1449                 return $this->isAjax;
1450         }
1451
1452         /**
1453          * Returns the value of a argv key
1454          * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1455          *
1456          * @param int $position the position of the argument
1457          * @param mixed $default the default value if not found
1458          *
1459          * @return mixed returns the value of the argument
1460          */
1461         public function getArgumentValue($position, $default = '')
1462         {
1463                 if (array_key_exists($position, $this->argv)) {
1464                         return $this->argv[$position];
1465                 }
1466
1467                 return $default;
1468         }
1469
1470         /**
1471          * Sets the base url for use in cmdline programs which don't have
1472          * $_SERVER variables
1473          */
1474         public function checkURL()
1475         {
1476                 $url = Core\Config::get('system', 'url');
1477
1478                 // if the url isn't set or the stored url is radically different
1479                 // than the currently visited url, store the current value accordingly.
1480                 // "Radically different" ignores common variations such as http vs https
1481                 // and www.example.com vs example.com.
1482                 // We will only change the url to an ip address if there is no existing setting
1483
1484                 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()))) {
1485                         Core\Config::set('system', 'url', $this->getBaseURL());
1486                 }
1487         }
1488
1489         /**
1490          * Frontend App script
1491          *
1492          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1493          * request and a representation of the response.
1494          *
1495          * This probably should change to limit the size of this monster method.
1496          */
1497         public function runFrontend()
1498         {
1499                 // Missing DB connection: ERROR
1500                 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1501                         Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1502                 }
1503
1504                 // Max Load Average reached: ERROR
1505                 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1506                         header('Retry-After: 120');
1507                         header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1508
1509                         Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1510                 }
1511
1512                 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1513                         Core\System::httpExit(404);
1514                 }
1515
1516                 if (!$this->getMode()->isInstall()) {
1517                         // Force SSL redirection
1518                         if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1519                                 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1520                                 && strpos($this->getBaseURL(), 'https://') === 0
1521                                 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1522                                 header('HTTP/1.1 302 Moved Temporarily');
1523                                 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1524                                 exit();
1525                         }
1526
1527                         Core\Session::init();
1528                         Core\Addon::callHooks('init_1');
1529                 }
1530
1531                 // Exclude the backend processes from the session management
1532                 if (!$this->isBackend()) {
1533                         $stamp1 = microtime(true);
1534                         session_start();
1535                         $this->saveTimestamp($stamp1, 'parser');
1536                         Core\L10n::setSessionVariable();
1537                         Core\L10n::setLangFromSession();
1538                 } else {
1539                         $_SESSION = [];
1540                         Core\Worker::executeIfIdle();
1541                 }
1542
1543                 // ZRL
1544                 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1545                         $this->query_string = Model\Profile::stripZrls($this->query_string);
1546                         if (!local_user()) {
1547                                 // Only continue when the given profile link seems valid
1548                                 // Valid profile links contain a path with "/profile/" and no query parameters
1549                                 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1550                                         strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1551                                         if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1552                                                 $_SESSION['my_url'] = $_GET['zrl'];
1553                                                 $_SESSION['authenticated'] = 0;
1554                                         }
1555                                         Model\Profile::zrlInit($this);
1556                                 } else {
1557                                         // Someone came with an invalid parameter, maybe as a DDoS attempt
1558                                         // We simply stop processing here
1559                                         Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1560                                         Core\System::httpExit(403, ['title' => '403 Forbidden']);
1561                                 }
1562                         }
1563                 }
1564
1565                 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1566                         $token = $_GET['owt'];
1567                         $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1568                         Model\Profile::openWebAuthInit($token);
1569                 }
1570
1571                 Module\Login::sessionAuth();
1572
1573                 if (empty($_SESSION['authenticated'])) {
1574                         header('X-Account-Management-Status: none');
1575                 }
1576
1577                 $_SESSION['sysmsg']       = defaults($_SESSION, 'sysmsg'      , []);
1578                 $_SESSION['sysmsg_info']  = defaults($_SESSION, 'sysmsg_info' , []);
1579                 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1580
1581                 /*
1582                  * check_config() is responsible for running update scripts. These automatically
1583                  * update the DB schema whenever we push a new one out. It also checks to see if
1584                  * any addons have been added or removed and reacts accordingly.
1585                  */
1586
1587                 // in install mode, any url loads install module
1588                 // but we need "view" module for stylesheet
1589                 if ($this->getMode()->isInstall() && $this->module != 'view') {
1590                         $this->module = 'install';
1591                 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1592                         $this->module = 'maintenance';
1593                 } else {
1594                         $this->checkURL();
1595                         Core\Update::check(false);
1596                         Core\Addon::loadAddons();
1597                         Core\Hook::loadHooks();
1598                 }
1599
1600                 $this->page = [
1601                         'aside' => '',
1602                         'bottom' => '',
1603                         'content' => '',
1604                         'footer' => '',
1605                         'htmlhead' => '',
1606                         'nav' => '',
1607                         'page_title' => '',
1608                         'right_aside' => '',
1609                         'template' => '',
1610                         'title' => ''
1611                 ];
1612
1613                 if (strlen($this->module)) {
1614                         // Compatibility with the Android Diaspora client
1615                         if ($this->module == 'stream') {
1616                                 $this->internalRedirect('network?f=&order=post');
1617                         }
1618
1619                         if ($this->module == 'conversations') {
1620                                 $this->internalRedirect('message');
1621                         }
1622
1623                         if ($this->module == 'commented') {
1624                                 $this->internalRedirect('network?f=&order=comment');
1625                         }
1626
1627                         if ($this->module == 'liked') {
1628                                 $this->internalRedirect('network?f=&order=comment');
1629                         }
1630
1631                         if ($this->module == 'activity') {
1632                                 $this->internalRedirect('network/?f=&conv=1');
1633                         }
1634
1635                         if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1636                                 $this->internalRedirect('bookmarklet');
1637                         }
1638
1639                         if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1640                                 $this->internalRedirect('settings');
1641                         }
1642
1643                         if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1644                                 $this->internalRedirect('search');
1645                         }
1646
1647                         // Compatibility with the Firefox App
1648                         if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1649                                 $this->module = "login";
1650                         }
1651
1652                         $privateapps = Core\Config::get('config', 'private_addons', false);
1653                         if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1654                                 //Check if module is an app and if public access to apps is allowed or not
1655                                 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1656                                         info(Core\L10n::t("You must be logged in to use addons. "));
1657                                 } else {
1658                                         include_once "addon/{$this->module}/{$this->module}.php";
1659                                         if (function_exists($this->module . '_module')) {
1660                                                 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1661                                                 $this->module_class = 'Friendica\\LegacyModule';
1662                                                 $this->module_loaded = true;
1663                                         }
1664                                 }
1665                         }
1666
1667                         // Controller class routing
1668                         if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1669                                 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1670                                 $this->module_loaded = true;
1671                         }
1672
1673                         /* If not, next look for a 'standard' program module in the 'mod' directory
1674                          * We emulate a Module class through the LegacyModule class
1675                          */
1676                         if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1677                                 LegacyModule::setModuleFile("mod/{$this->module}.php");
1678                                 $this->module_class = 'Friendica\\LegacyModule';
1679                                 $this->module_loaded = true;
1680                         }
1681
1682                         /* The URL provided does not resolve to a valid module.
1683                          *
1684                          * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1685                          * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1686                          * 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
1687                          * this will often succeed and eventually do the right thing.
1688                          *
1689                          * Otherwise we are going to emit a 404 not found.
1690                          */
1691                         if (! $this->module_loaded) {
1692                                 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1693                                 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1694                                         exit();
1695                                 }
1696
1697                                 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1698                                         Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1699                                         $this->internalRedirect($_SERVER['REQUEST_URI']);
1700                                 }
1701
1702                                 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1703
1704                                 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1705                                 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1706                                 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1707                                         '$message' =>  Core\L10n::t('Page not found.')
1708                                 ]);
1709                         }
1710                 }
1711
1712                 // Load current theme info
1713                 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1714                 if (file_exists($theme_info_file)) {
1715                         require_once $theme_info_file;
1716                 }
1717
1718                 // initialise content region
1719                 if ($this->getMode()->isNormal()) {
1720                         Core\Addon::callHooks('page_content_top', $this->page['content']);
1721                 }
1722
1723                 // Call module functions
1724                 if ($this->module_loaded) {
1725                         $this->page['page_title'] = $this->module;
1726                         $placeholder = '';
1727
1728                         Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1729
1730                         call_user_func([$this->module_class, 'init']);
1731
1732                         // "rawContent" is especially meant for technical endpoints.
1733                         // This endpoint doesn't need any theme initialization or other comparable stuff.
1734                         if (!$this->error) {
1735                                 call_user_func([$this->module_class, 'rawContent']);
1736                         }
1737
1738                         if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1739                                 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1740                                 $func($this);
1741                         }
1742
1743                         if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1744                                 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1745                                 call_user_func([$this->module_class, 'post']);
1746                         }
1747
1748                         if (! $this->error) {
1749                                 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1750                                 call_user_func([$this->module_class, 'afterpost']);
1751                         }
1752
1753                         if (! $this->error) {
1754                                 $arr = ['content' => $this->page['content']];
1755                                 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1756                                 $this->page['content'] = $arr['content'];
1757                                 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1758                                 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1759                                 $this->page['content'] .= $arr['content'];
1760                         }
1761
1762                         if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1763                                 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1764                                 $func($this);
1765                         }
1766                 }
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 (filter_var($toUrl, FILTER_VALIDATE_URL)) {
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 (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1901                         Core\System::externalRedirect($toUrl);
1902                 } else {
1903                         $this->internalRedirect($toUrl);
1904                 }
1905         }
1906 }