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