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