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