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