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