]> git.mxchange.org Git - friendica.git/blob - src/App.php
Merge pull request #5829 from annando/develop
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use Exception;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14
15 require_once 'boot.php';
16 require_once 'include/dba.php';
17 require_once 'include/text.php';
18
19 /**
20  *
21  * class: App
22  *
23  * @brief Our main application structure for the life of this page.
24  *
25  * Primarily deals with the URL that got us here
26  * and tries to make some sense of it, and
27  * stores our page contents and config storage
28  * and anything else that might need to be passed around
29  * before we spit the page out.
30  *
31  */
32 class App
33 {
34         public $module_loaded = false;
35         public $module_class = null;
36         public $query_string = '';
37         public $config = [];
38         public $page = [];
39         public $pager = [];
40         public $page_offset;
41         public $profile;
42         public $profile_uid;
43         public $user;
44         public $cid;
45         public $contact;
46         public $contacts;
47         public $page_contact;
48         public $content;
49         public $data = [];
50         public $error = false;
51         public $cmd = '';
52         public $argv;
53         public $argc;
54         public $module;
55         public $strings;
56         public $basepath;
57         public $urlpath;
58         public $hooks = [];
59         public $timezone;
60         public $interactive = true;
61         public $addons;
62         public $addons_admin = [];
63         public $apps = [];
64         public $identities;
65         public $is_mobile = false;
66         public $is_tablet = false;
67         public $is_friendica_app;
68         public $performance = [];
69         public $callstack = [];
70         public $theme_info = [];
71         public $backend = true;
72         public $nav_sel;
73         public $category;
74         // Allow themes to control internal parameters
75         // by changing App values in theme.php
76
77         public $sourcename = '';
78         public $videowidth = 425;
79         public $videoheight = 350;
80         public $force_max_items = 0;
81         public $theme_events_in_profile = true;
82
83         public $stylesheets = [];
84         public $footerScripts = [];
85
86         /**
87          * Register a stylesheet file path to be included in the <head> tag of every page.
88          * Inclusion is done in App->initHead().
89          * The path can be absolute or relative to the Friendica installation base folder.
90          *
91          * @see App->initHead()
92          *
93          * @param string $path
94          */
95         public function registerStylesheet($path)
96         {
97                 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
98
99                 $this->stylesheets[] = trim($url, '/');
100         }
101
102         /**
103          * Register a javascript file path to be included in the <footer> tag of every page.
104          * Inclusion is done in App->initFooter().
105          * The path can be absolute or relative to the Friendica installation base folder.
106          *
107          * @see App->initFooter()
108          *
109          * @param string $path
110          */
111         public function registerFooterScript($path)
112         {
113                 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
114
115                 $this->footerScripts[] = trim($url, '/');
116         }
117
118         /**
119          * @brief An array for all theme-controllable parameters
120          *
121          * Mostly unimplemented yet. Only options 'template_engine' and
122          * beyond are used.
123          */
124         public $theme = [
125                 'sourcename' => '',
126                 'videowidth' => 425,
127                 'videoheight' => 350,
128                 'force_max_items' => 0,
129                 'stylesheet' => '',
130                 'template_engine' => 'smarty3',
131         ];
132
133         /**
134          * @brief An array of registered template engines ('name'=>'class name')
135          */
136         public $template_engines = [];
137
138         /**
139          * @brief An array of instanced template engines ('name'=>'instance')
140          */
141         public $template_engine_instance = [];
142         public $process_id;
143         public $queue;
144         private $ldelim = [
145                 'internal' => '',
146                 'smarty3' => '{{'
147         ];
148         private $rdelim = [
149                 'internal' => '',
150                 'smarty3' => '}}'
151         ];
152         private $scheme;
153         private $hostname;
154         private $curl_code;
155         private $curl_content_type;
156         private $curl_headers;
157
158         /**
159          * @brief App constructor.
160          *
161          * @param string $basepath Path to the app base folder
162          *
163          * @throws Exception if the Basepath is not usable
164          */
165         public function __construct($basepath)
166         {
167                 if (!static::directory_usable($basepath, false)) {
168                         throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
169                 }
170
171                 BaseObject::setApp($this);
172
173                 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
174
175                 $this->performance['start'] = microtime(true);
176                 $this->performance['database'] = 0;
177                 $this->performance['database_write'] = 0;
178                 $this->performance['cache'] = 0;
179                 $this->performance['cache_write'] = 0;
180                 $this->performance['network'] = 0;
181                 $this->performance['file'] = 0;
182                 $this->performance['rendering'] = 0;
183                 $this->performance['parser'] = 0;
184                 $this->performance['marktime'] = 0;
185                 $this->performance['markstart'] = microtime(true);
186
187                 $this->callstack['database'] = [];
188                 $this->callstack['database_write'] = [];
189                 $this->callstack['cache'] = [];
190                 $this->callstack['cache_write'] = [];
191                 $this->callstack['network'] = [];
192                 $this->callstack['file'] = [];
193                 $this->callstack['rendering'] = [];
194                 $this->callstack['parser'] = [];
195
196                 $this->reload();
197
198                 set_time_limit(0);
199
200                 // This has to be quite large to deal with embedded private photos
201                 ini_set('pcre.backtrack_limit', 500000);
202
203                 $this->scheme = 'http';
204
205                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
206                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
207                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
208                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
209                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
210                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
211                 ) {
212                         $this->scheme = 'https';
213                 }
214
215                 if (x($_SERVER, 'SERVER_NAME')) {
216                         $this->hostname = $_SERVER['SERVER_NAME'];
217
218                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
219                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
220                         }
221                 }
222
223                 set_include_path(
224                         get_include_path() . PATH_SEPARATOR
225                         . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
226                         . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
227                         . $this->basepath);
228
229                 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
230                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
231                 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
232                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
233                 }
234
235                 // removing trailing / - maybe a nginx problem
236                 $this->query_string = ltrim($this->query_string, '/');
237
238                 if (!empty($_GET['pagename'])) {
239                         $this->cmd = trim($_GET['pagename'], '/\\');
240                 } elseif (!empty($_GET['q'])) {
241                         $this->cmd = trim($_GET['q'], '/\\');
242                 }
243
244                 // fix query_string
245                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
246
247                 // unix style "homedir"
248                 if (substr($this->cmd, 0, 1) === '~') {
249                         $this->cmd = 'profile/' . substr($this->cmd, 1);
250                 }
251
252                 // Diaspora style profile url
253                 if (substr($this->cmd, 0, 2) === 'u/') {
254                         $this->cmd = 'profile/' . substr($this->cmd, 2);
255                 }
256
257                 /*
258                  * Break the URL path into C style argc/argv style arguments for our
259                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
260                  * will be 3 (integer) and $this->argv will contain:
261                  *   [0] => 'module'
262                  *   [1] => 'arg1'
263                  *   [2] => 'arg2'
264                  *
265                  *
266                  * There will always be one argument. If provided a naked domain
267                  * URL, $this->argv[0] is set to "home".
268                  */
269
270                 $this->argv = explode('/', $this->cmd);
271                 $this->argc = count($this->argv);
272                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
273                         $this->module = str_replace('.', '_', $this->argv[0]);
274                         $this->module = str_replace('-', '_', $this->module);
275                 } else {
276                         $this->argc = 1;
277                         $this->argv = ['home'];
278                         $this->module = 'home';
279                 }
280
281                 // See if there is any page number information, and initialise pagination
282                 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
283                 $this->pager['itemspage'] = 50;
284                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
285
286                 if ($this->pager['start'] < 0) {
287                         $this->pager['start'] = 0;
288                 }
289                 $this->pager['total'] = 0;
290
291                 // Detect mobile devices
292                 $mobile_detect = new MobileDetect();
293                 $this->is_mobile = $mobile_detect->isMobile();
294                 $this->is_tablet = $mobile_detect->isTablet();
295
296                 // Friendica-Client
297                 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
298
299                 // Register template engines
300                 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
301         }
302
303         /**
304          * Reloads the whole app instance
305          */
306         public function reload()
307         {
308                 // The order of the following calls is important to ensure proper initialization
309                 $this->loadConfigFiles();
310
311                 $this->loadDatabase();
312
313                 App\Mode::determine($this->basepath);
314
315                 $this->determineUrlPath();
316
317                 Config::load();
318
319                 if (App\Mode::has(App\Mode::DBAVAILABLE)) {
320                         Core\Addon::loadHooks();
321
322                         $this->loadAddonConfig();
323                 }
324
325                 $this->loadDefaultTimezone();
326
327                 $this->page = [
328                         'aside' => '',
329                         'bottom' => '',
330                         'content' => '',
331                         'footer' => '',
332                         'htmlhead' => '',
333                         'nav' => '',
334                         'page_title' => '',
335                         'right_aside' => '',
336                         'template' => '',
337                         'title' => ''
338                 ];
339
340                 $this->process_id = System::processID('log');
341         }
342
343         /**
344          * Load the configuration files
345          *
346          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
347          * expected local.ini.php
348          */
349         private function loadConfigFiles()
350         {
351                 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
352                 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
353
354                 // Legacy .htconfig.php support
355                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
356                         $a = $this;
357                         include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
358                 }
359
360                 // Legacy .htconfig.php support
361                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
362                         $a = $this;
363
364                         include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
365
366                         $this->setConfigValue('database', 'hostname', $db_host);
367                         $this->setConfigValue('database', 'username', $db_user);
368                         $this->setConfigValue('database', 'password', $db_pass);
369                         $this->setConfigValue('database', 'database', $db_data);
370                         if (isset($a->config['system']['db_charset'])) {
371                                 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
372                         }
373
374                         unset($db_host, $db_user, $db_pass, $db_data);
375
376                         if (isset($default_timezone)) {
377                                 $this->setConfigValue('system', 'default_timezone', $default_timezone);
378                                 unset($default_timezone);
379                         }
380
381                         if (isset($pidfile)) {
382                                 $this->setConfigValue('system', 'pidfile', $pidfile);
383                                 unset($pidfile);
384                         }
385
386                         if (isset($lang)) {
387                                 $this->setConfigValue('system', 'language', $lang);
388                                 unset($lang);
389                         }
390                 }
391
392                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
393                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
394                 }
395         }
396
397         /**
398          * Tries to load the specified configuration file into the App->config array.
399          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
400          *
401          * The config format is INI and the template for configuration files is the following:
402          *
403          * <?php return <<<INI
404          *
405          * [section]
406          * key = value
407          *
408          * INI;
409          * // Keep this line
410          *
411          * @param type $filepath
412          * @param bool $overwrite Force value overwrite if the config key already exists
413          * @throws Exception
414          */
415         public function loadConfigFile($filepath, $overwrite = false)
416         {
417                 if (!file_exists($filepath)) {
418                         throw new Exception('Error parsing non-existent config file ' . $filepath);
419                 }
420
421                 $contents = include($filepath);
422
423                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
424
425                 if ($config === false) {
426                         throw new Exception('Error parsing config file ' . $filepath);
427                 }
428
429                 foreach ($config as $category => $values) {
430                         foreach ($values as $key => $value) {
431                                 if ($overwrite) {
432                                         $this->setConfigValue($category, $key, $value);
433                                 } else {
434                                         $this->setDefaultConfigValue($category, $key, $value);
435                                 }
436                         }
437                 }
438         }
439
440         /**
441          * Loads addons configuration files
442          *
443          * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
444          * again to overwrite potential local addon configuration.
445          */
446         private function loadAddonConfig()
447         {
448                 // Loads addons default config
449                 Core\Addon::callHooks('load_config');
450
451                 // Load the local addon config file to overwritten default addon config values
452                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
453                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
454                 }
455         }
456
457         /**
458          * Loads the default timezone
459          *
460          * Include support for legacy $default_timezone
461          *
462          * @global string $default_timezone
463          */
464         private function loadDefaultTimezone()
465         {
466                 if ($this->getConfigValue('system', 'default_timezone')) {
467                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
468                 } else {
469                         global $default_timezone;
470                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
471                 }
472
473                 if ($this->timezone) {
474                         date_default_timezone_set($this->timezone);
475                 }
476         }
477
478         /**
479          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
480          */
481         private function determineUrlPath()
482         {
483                 $this->urlpath = $this->getConfigValue('system', 'urlpath');
484
485                 /* SCRIPT_URL gives /path/to/friendica/module/parameter
486                  * QUERY_STRING gives pagename=module/parameter
487                  *
488                  * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
489                  */
490                 if (!empty($_SERVER['SCRIPT_URL'])) {
491                         // Module
492                         if (!empty($_SERVER['QUERY_STRING'])) {
493                                 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
494                         } else {
495                                 // Root page
496                                 $path = trim($_SERVER['SCRIPT_URL'], '/');
497                         }
498
499                         if ($path && $path != $this->urlpath) {
500                                 $this->urlpath = $path;
501                         }
502                 }
503         }
504
505         public function loadDatabase()
506         {
507                 if (DBA::connected()) {
508                         return;
509                 }
510
511                 $db_host = $this->getConfigValue('database', 'hostname');
512                 $db_user = $this->getConfigValue('database', 'username');
513                 $db_pass = $this->getConfigValue('database', 'password');
514                 $db_data = $this->getConfigValue('database', 'database');
515                 $charset = $this->getConfigValue('database', 'charset');
516
517                 // Use environment variables for mysql if they are set beforehand
518                 if (!empty(getenv('MYSQL_HOST'))
519                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
520                         && getenv('MYSQL_PASSWORD') !== false
521                         && !empty(getenv('MYSQL_DATABASE')))
522                 {
523                         $db_host = getenv('MYSQL_HOST');
524                         if (!empty(getenv('MYSQL_PORT'))) {
525                                 $db_host .= ':' . getenv('MYSQL_PORT');
526                         }
527                         if (!empty(getenv('MYSQL_USERNAME'))) {
528                                 $db_user = getenv('MYSQL_USERNAME');
529                         } else {
530                                 $db_user = getenv('MYSQL_USER');
531                         }
532                         $db_pass = (string) getenv('MYSQL_PASSWORD');
533                         $db_data = getenv('MYSQL_DATABASE');
534                 }
535
536                 $stamp1 = microtime(true);
537
538                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
539                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
540
541                 $this->save_timestamp($stamp1, 'network');
542         }
543
544         /**
545          * @brief Returns the base filesystem path of the App
546          *
547          * It first checks for the internal variable, then for DOCUMENT_ROOT and
548          * finally for PWD
549          *
550          * @return string
551          */
552         public function get_basepath()
553         {
554                 $basepath = $this->basepath;
555
556                 if (!$basepath) {
557                         $basepath = Config::get('system', 'basepath');
558                 }
559
560                 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
561                         $basepath = $_SERVER['DOCUMENT_ROOT'];
562                 }
563
564                 if (!$basepath && x($_SERVER, 'PWD')) {
565                         $basepath = $_SERVER['PWD'];
566                 }
567
568                 return self::realpath($basepath);
569         }
570
571         /**
572          * @brief Returns a normalized file path
573          *
574          * This is a wrapper for the "realpath" function.
575          * That function cannot detect the real path when some folders aren't readable.
576          * Since this could happen with some hosters we need to handle this.
577          *
578          * @param string $path The path that is about to be normalized
579          * @return string normalized path - when possible
580          */
581         public static function realpath($path)
582         {
583                 $normalized = realpath($path);
584
585                 if (!is_bool($normalized)) {
586                         return $normalized;
587                 } else {
588                         return $path;
589                 }
590         }
591
592         public function get_scheme()
593         {
594                 return $this->scheme;
595         }
596
597         /**
598          * @brief Retrieves the Friendica instance base URL
599          *
600          * This function assembles the base URL from multiple parts:
601          * - Protocol is determined either by the request or a combination of
602          * system.ssl_policy and the $ssl parameter.
603          * - Host name is determined either by system.hostname or inferred from request
604          * - Path is inferred from SCRIPT_NAME
605          *
606          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
607          *
608          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
609          * @return string Friendica server base URL
610          */
611         public function get_baseurl($ssl = false)
612         {
613                 $scheme = $this->scheme;
614
615                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
616                         $scheme = 'https';
617                 }
618
619                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
620                 //      (and also the login link). Anything seen by an outsider will have it turned off.
621
622                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
623                         if ($ssl) {
624                                 $scheme = 'https';
625                         } else {
626                                 $scheme = 'http';
627                         }
628                 }
629
630                 if (Config::get('config', 'hostname') != '') {
631                         $this->hostname = Config::get('config', 'hostname');
632                 }
633
634                 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
635         }
636
637         /**
638          * @brief Initializes the baseurl components
639          *
640          * Clears the baseurl cache to prevent inconsistencies
641          *
642          * @param string $url
643          */
644         public function set_baseurl($url)
645         {
646                 $parsed = @parse_url($url);
647                 $hostname = '';
648
649                 if (x($parsed)) {
650                         if (!empty($parsed['scheme'])) {
651                                 $this->scheme = $parsed['scheme'];
652                         }
653
654                         if (!empty($parsed['host'])) {
655                                 $hostname = $parsed['host'];
656                         }
657
658                         if (x($parsed, 'port')) {
659                                 $hostname .= ':' . $parsed['port'];
660                         }
661                         if (x($parsed, 'path')) {
662                                 $this->urlpath = trim($parsed['path'], '\\/');
663                         }
664
665                         if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
666                                 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
667                         }
668
669                         if (Config::get('config', 'hostname') != '') {
670                                 $this->hostname = Config::get('config', 'hostname');
671                         }
672
673                         if (!isset($this->hostname) || ($this->hostname == '')) {
674                                 $this->hostname = $hostname;
675                         }
676                 }
677         }
678
679         public function get_hostname()
680         {
681                 if (Config::get('config', 'hostname') != '') {
682                         $this->hostname = Config::get('config', 'hostname');
683                 }
684
685                 return $this->hostname;
686         }
687
688         public function get_path()
689         {
690                 return $this->urlpath;
691         }
692
693         public function set_pager_total($n)
694         {
695                 $this->pager['total'] = intval($n);
696         }
697
698         public function set_pager_itemspage($n)
699         {
700                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
701                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
702         }
703
704         public function set_pager_page($n)
705         {
706                 $this->pager['page'] = $n;
707                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
708         }
709
710         /**
711          * Initializes App->page['htmlhead'].
712          *
713          * Includes:
714          * - Page title
715          * - Favicons
716          * - Registered stylesheets (through App->registerStylesheet())
717          * - Infinite scroll data
718          * - head.tpl template
719          */
720         public function initHead()
721         {
722                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
723
724                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
725                 if ($interval < 0) {
726                         $interval = 2147483647;
727                 }
728
729                 if ($interval < 10000) {
730                         $interval = 40000;
731                 }
732
733                 // compose the page title from the sitename and the
734                 // current module called
735                 if (!$this->module == '') {
736                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
737                 } else {
738                         $this->page['title'] = $this->config['sitename'];
739                 }
740
741                 if (!empty($this->theme['stylesheet'])) {
742                         $stylesheet = $this->theme['stylesheet'];
743                 } else {
744                         $stylesheet = $this->getCurrentThemeStylesheetPath();
745                 }
746
747                 $this->registerStylesheet($stylesheet);
748
749                 $shortcut_icon = Config::get('system', 'shortcut_icon');
750                 if ($shortcut_icon == '') {
751                         $shortcut_icon = 'images/friendica-32.png';
752                 }
753
754                 $touch_icon = Config::get('system', 'touch_icon');
755                 if ($touch_icon == '') {
756                         $touch_icon = 'images/friendica-128.png';
757                 }
758
759                 // get data wich is needed for infinite scroll on the network page
760                 $infinite_scroll = infinite_scroll_data($this->module);
761
762                 Core\Addon::callHooks('head', $this->page['htmlhead']);
763
764                 $tpl = get_markup_template('head.tpl');
765                 /* put the head template at the beginning of page['htmlhead']
766                  * since the code added by the modules frequently depends on it
767                  * being first
768                  */
769                 $this->page['htmlhead'] = replace_macros($tpl, [
770                         '$baseurl'         => $this->get_baseurl(),
771                         '$local_user'      => local_user(),
772                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
773                         '$delitem'         => L10n::t('Delete this item?'),
774                         '$showmore'        => L10n::t('show more'),
775                         '$showfewer'       => L10n::t('show fewer'),
776                         '$update_interval' => $interval,
777                         '$shortcut_icon'   => $shortcut_icon,
778                         '$touch_icon'      => $touch_icon,
779                         '$infinite_scroll' => $infinite_scroll,
780                         '$block_public'    => intval(Config::get('system', 'block_public')),
781                         '$stylesheets'     => $this->stylesheets,
782                 ]) . $this->page['htmlhead'];
783         }
784
785         /**
786          * Initializes App->page['footer'].
787          *
788          * Includes:
789          * - Javascript homebase
790          * - Mobile toggle link
791          * - Registered footer scripts (through App->registerFooterScript())
792          * - footer.tpl template
793          */
794         public function initFooter()
795         {
796                 // If you're just visiting, let javascript take you home
797                 if (!empty($_SESSION['visitor_home'])) {
798                         $homebase = $_SESSION['visitor_home'];
799                 } elseif (local_user()) {
800                         $homebase = 'profile/' . $this->user['nickname'];
801                 }
802
803                 if (isset($homebase)) {
804                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
805                 }
806
807                 /*
808                  * Add a "toggle mobile" link if we're using a mobile device
809                  */
810                 if ($this->is_mobile || $this->is_tablet) {
811                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
812                                 $link = 'toggle_mobile?address=' . curPageURL();
813                         } else {
814                                 $link = 'toggle_mobile?off=1&address=' . curPageURL();
815                         }
816                         $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
817                                 '$toggle_link' => $link,
818                                 '$toggle_text' => Core\L10n::t('toggle mobile')
819                         ]);
820                 }
821
822                 Core\Addon::callHooks('footer', $this->page['footer']);
823
824                 $tpl = get_markup_template('footer.tpl');
825                 $this->page['footer'] = replace_macros($tpl, [
826                         '$baseurl' => $this->get_baseurl(),
827                         '$footerScripts' => $this->footerScripts,
828                 ]) . $this->page['footer'];
829         }
830
831         public function set_curl_code($code)
832         {
833                 $this->curl_code = $code;
834         }
835
836         public function get_curl_code()
837         {
838                 return $this->curl_code;
839         }
840
841         public function set_curl_content_type($content_type)
842         {
843                 $this->curl_content_type = $content_type;
844         }
845
846         public function get_curl_content_type()
847         {
848                 return $this->curl_content_type;
849         }
850
851         public function set_curl_headers($headers)
852         {
853                 $this->curl_headers = $headers;
854         }
855
856         public function get_curl_headers()
857         {
858                 return $this->curl_headers;
859         }
860
861         /**
862          * @brief Removes the base url from an url. This avoids some mixed content problems.
863          *
864          * @param string $orig_url
865          *
866          * @return string The cleaned url
867          */
868         public function remove_baseurl($orig_url)
869         {
870                 // Remove the hostname from the url if it is an internal link
871                 $nurl = normalise_link($orig_url);
872                 $base = normalise_link($this->get_baseurl());
873                 $url = str_replace($base . '/', '', $nurl);
874
875                 // if it is an external link return the orignal value
876                 if ($url == normalise_link($orig_url)) {
877                         return $orig_url;
878                 } else {
879                         return $url;
880                 }
881         }
882
883         /**
884          * @brief Register template engine class
885          *
886          * @param string $class
887          */
888         private function register_template_engine($class)
889         {
890                 $v = get_class_vars($class);
891                 if (x($v, 'name')) {
892                         $name = $v['name'];
893                         $this->template_engines[$name] = $class;
894                 } else {
895                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
896                         die();
897                 }
898         }
899
900         /**
901          * @brief Return template engine instance.
902          *
903          * If $name is not defined, return engine defined by theme,
904          * or default
905          *
906          * @return object Template Engine instance
907          */
908         public function template_engine()
909         {
910                 $template_engine = 'smarty3';
911                 if (x($this->theme, 'template_engine')) {
912                         $template_engine = $this->theme['template_engine'];
913                 }
914
915                 if (isset($this->template_engines[$template_engine])) {
916                         if (isset($this->template_engine_instance[$template_engine])) {
917                                 return $this->template_engine_instance[$template_engine];
918                         } else {
919                                 $class = $this->template_engines[$template_engine];
920                                 $obj = new $class;
921                                 $this->template_engine_instance[$template_engine] = $obj;
922                                 return $obj;
923                         }
924                 }
925
926                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
927                 killme();
928         }
929
930         /**
931          * @brief Returns the active template engine.
932          *
933          * @return string
934          */
935         public function get_template_engine()
936         {
937                 return $this->theme['template_engine'];
938         }
939
940         public function set_template_engine($engine = 'smarty3')
941         {
942                 $this->theme['template_engine'] = $engine;
943         }
944
945         public function get_template_ldelim($engine = 'smarty3')
946         {
947                 return $this->ldelim[$engine];
948         }
949
950         public function get_template_rdelim($engine = 'smarty3')
951         {
952                 return $this->rdelim[$engine];
953         }
954
955         public function save_timestamp($stamp, $value)
956         {
957                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
958                         return;
959                 }
960
961                 $duration = (float) (microtime(true) - $stamp);
962
963                 if (!isset($this->performance[$value])) {
964                         // Prevent ugly E_NOTICE
965                         $this->performance[$value] = 0;
966                 }
967
968                 $this->performance[$value] += (float) $duration;
969                 $this->performance['marktime'] += (float) $duration;
970
971                 $callstack = System::callstack();
972
973                 if (!isset($this->callstack[$value][$callstack])) {
974                         // Prevent ugly E_NOTICE
975                         $this->callstack[$value][$callstack] = 0;
976                 }
977
978                 $this->callstack[$value][$callstack] += (float) $duration;
979         }
980
981         public function get_useragent()
982         {
983                 return
984                         FRIENDICA_PLATFORM . " '" .
985                         FRIENDICA_CODENAME . "' " .
986                         FRIENDICA_VERSION . '-' .
987                         DB_UPDATE_VERSION . '; ' .
988                         $this->get_baseurl();
989         }
990
991         public function is_friendica_app()
992         {
993                 return $this->is_friendica_app;
994         }
995
996         /**
997          * @brief Checks if the site is called via a backend process
998          *
999          * This isn't a perfect solution. But we need this check very early.
1000          * So we cannot wait until the modules are loaded.
1001          *
1002          * @return bool Is it a known backend?
1003          */
1004         public function is_backend()
1005         {
1006                 static $backends = [
1007                         '_well_known',
1008                         'api',
1009                         'dfrn_notify',
1010                         'fetch',
1011                         'hcard',
1012                         'hostxrd',
1013                         'nodeinfo',
1014                         'noscrape',
1015                         'p',
1016                         'poco',
1017                         'post',
1018                         'proxy',
1019                         'pubsub',
1020                         'pubsubhubbub',
1021                         'receive',
1022                         'rsd_xml',
1023                         'salmon',
1024                         'statistics_json',
1025                         'xrd',
1026                 ];
1027
1028                 // Check if current module is in backend or backend flag is set
1029                 return (in_array($this->module, $backends) || $this->backend);
1030         }
1031
1032         /**
1033          * @brief Checks if the maximum number of database processes is reached
1034          *
1035          * @return bool Is the limit reached?
1036          */
1037         public function isMaxProcessesReached()
1038         {
1039                 // Deactivated, needs more investigating if this check really makes sense
1040                 return false;
1041
1042                 /*
1043                  * Commented out to suppress static analyzer issues
1044                  *
1045                 if ($this->is_backend()) {
1046                         $process = 'backend';
1047                         $max_processes = Config::get('system', 'max_processes_backend');
1048                         if (intval($max_processes) == 0) {
1049                                 $max_processes = 5;
1050                         }
1051                 } else {
1052                         $process = 'frontend';
1053                         $max_processes = Config::get('system', 'max_processes_frontend');
1054                         if (intval($max_processes) == 0) {
1055                                 $max_processes = 20;
1056                         }
1057                 }
1058
1059                 $processlist = DBA::processlist();
1060                 if ($processlist['list'] != '') {
1061                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1062
1063                         if ($processlist['amount'] > $max_processes) {
1064                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1065                                 return true;
1066                         }
1067                 }
1068                 return false;
1069                  */
1070         }
1071
1072         /**
1073          * @brief Checks if the minimal memory is reached
1074          *
1075          * @return bool Is the memory limit reached?
1076          */
1077         public function min_memory_reached()
1078         {
1079                 $min_memory = Config::get('system', 'min_memory', 0);
1080                 if ($min_memory == 0) {
1081                         return false;
1082                 }
1083
1084                 if (!is_readable('/proc/meminfo')) {
1085                         return false;
1086                 }
1087
1088                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1089
1090                 $meminfo = [];
1091                 foreach ($memdata as $line) {
1092                         $data = explode(':', $line);
1093                         if (count($data) != 2) {
1094                                 continue;
1095                         }
1096                         list($key, $val) = $data;
1097                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1098                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1099                 }
1100
1101                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1102                         return false;
1103                 }
1104
1105                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1106
1107                 $reached = ($free < $min_memory);
1108
1109                 if ($reached) {
1110                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1111                 }
1112
1113                 return $reached;
1114         }
1115
1116         /**
1117          * @brief Checks if the maximum load is reached
1118          *
1119          * @return bool Is the load reached?
1120          */
1121         public function isMaxLoadReached()
1122         {
1123                 if ($this->is_backend()) {
1124                         $process = 'backend';
1125                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1126                         if ($maxsysload < 1) {
1127                                 $maxsysload = 50;
1128                         }
1129                 } else {
1130                         $process = 'frontend';
1131                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1132                         if ($maxsysload < 1) {
1133                                 $maxsysload = 50;
1134                         }
1135                 }
1136
1137                 $load = current_load();
1138                 if ($load) {
1139                         if (intval($load) > $maxsysload) {
1140                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1141                                 return true;
1142                         }
1143                 }
1144                 return false;
1145         }
1146
1147         /**
1148          * Executes a child process with 'proc_open'
1149          *
1150          * @param string $command The command to execute
1151          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1152          */
1153         public function proc_run($command, $args)
1154         {
1155                 if (!function_exists('proc_open')) {
1156                         return;
1157                 }
1158
1159                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1160
1161                 foreach ($args as $key => $value) {
1162                         if (!is_null($value) && is_bool($value) && !$value) {
1163                                 continue;
1164                         }
1165
1166                         $cmdline .= ' --' . $key;
1167                         if (!is_null($value) && !is_bool($value)) {
1168                                 $cmdline .= ' ' . $value;
1169                         }
1170                 }
1171
1172                 if ($this->min_memory_reached()) {
1173                         return;
1174                 }
1175
1176                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1177                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1178                 } else {
1179                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1180                 }
1181                 if (!is_resource($resource)) {
1182                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1183                         return;
1184                 }
1185                 proc_close($resource);
1186         }
1187
1188         /**
1189          * @brief Returns the system user that is executing the script
1190          *
1191          * This mostly returns something like "www-data".
1192          *
1193          * @return string system username
1194          */
1195         private static function systemuser()
1196         {
1197                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1198                         return '';
1199                 }
1200
1201                 $processUser = posix_getpwuid(posix_geteuid());
1202                 return $processUser['name'];
1203         }
1204
1205         /**
1206          * @brief Checks if a given directory is usable for the system
1207          *
1208          * @return boolean the directory is usable
1209          */
1210         public static function directory_usable($directory, $check_writable = true)
1211         {
1212                 if ($directory == '') {
1213                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1214                         return false;
1215                 }
1216
1217                 if (!file_exists($directory)) {
1218                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1219                         return false;
1220                 }
1221
1222                 if (is_file($directory)) {
1223                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1224                         return false;
1225                 }
1226
1227                 if (!is_dir($directory)) {
1228                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1229                         return false;
1230                 }
1231
1232                 if ($check_writable && !is_writable($directory)) {
1233                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1234                         return false;
1235                 }
1236
1237                 return true;
1238         }
1239
1240         /**
1241          * @param string $cat     Config category
1242          * @param string $k       Config key
1243          * @param mixed  $default Default value if it isn't set
1244          */
1245         public function getConfigValue($cat, $k, $default = null)
1246         {
1247                 $return = $default;
1248
1249                 if ($cat === 'config') {
1250                         if (isset($this->config[$k])) {
1251                                 $return = $this->config[$k];
1252                         }
1253                 } else {
1254                         if (isset($this->config[$cat][$k])) {
1255                                 $return = $this->config[$cat][$k];
1256                         }
1257                 }
1258
1259                 return $return;
1260         }
1261
1262         /**
1263          * Sets a default value in the config cache. Ignores already existing keys.
1264          *
1265          * @param string $cat Config category
1266          * @param string $k   Config key
1267          * @param mixed  $v   Default value to set
1268          */
1269         private function setDefaultConfigValue($cat, $k, $v)
1270         {
1271                 if (!isset($this->config[$cat][$k])) {
1272                         $this->setConfigValue($cat, $k, $v);
1273                 }
1274         }
1275
1276         /**
1277          * Sets a value in the config cache. Accepts raw output from the config table
1278          *
1279          * @param string $cat Config category
1280          * @param string $k   Config key
1281          * @param mixed  $v   Value to set
1282          */
1283         public function setConfigValue($cat, $k, $v)
1284         {
1285                 // Only arrays are serialized in database, so we have to unserialize sparingly
1286                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1287
1288                 if ($cat === 'config') {
1289                         $this->config[$k] = $value;
1290                 } else {
1291                         if (!isset($this->config[$cat])) {
1292                                 $this->config[$cat] = [];
1293                         }
1294
1295                         $this->config[$cat][$k] = $value;
1296                 }
1297         }
1298
1299         /**
1300          * Deletes a value from the config cache
1301          *
1302          * @param string $cat Config category
1303          * @param string $k   Config key
1304          */
1305         public function deleteConfigValue($cat, $k)
1306         {
1307                 if ($cat === 'config') {
1308                         if (isset($this->config[$k])) {
1309                                 unset($this->config[$k]);
1310                         }
1311                 } else {
1312                         if (isset($this->config[$cat][$k])) {
1313                                 unset($this->config[$cat][$k]);
1314                         }
1315                 }
1316         }
1317
1318
1319         /**
1320          * Retrieves a value from the user config cache
1321          *
1322          * @param int    $uid     User Id
1323          * @param string $cat     Config category
1324          * @param string $k       Config key
1325          * @param mixed  $default Default value if key isn't set
1326          */
1327         public function getPConfigValue($uid, $cat, $k, $default = null)
1328         {
1329                 $return = $default;
1330
1331                 if (isset($this->config[$uid][$cat][$k])) {
1332                         $return = $this->config[$uid][$cat][$k];
1333                 }
1334
1335                 return $return;
1336         }
1337
1338         /**
1339          * Sets a value in the user config cache
1340          *
1341          * Accepts raw output from the pconfig table
1342          *
1343          * @param int    $uid User Id
1344          * @param string $cat Config category
1345          * @param string $k   Config key
1346          * @param mixed  $v   Value to set
1347          */
1348         public function setPConfigValue($uid, $cat, $k, $v)
1349         {
1350                 // Only arrays are serialized in database, so we have to unserialize sparingly
1351                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1352
1353                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1354                         $this->config[$uid] = [];
1355                 }
1356
1357                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1358                         $this->config[$uid][$cat] = [];
1359                 }
1360
1361                 $this->config[$uid][$cat][$k] = $value;
1362         }
1363
1364         /**
1365          * Deletes a value from the user config cache
1366          *
1367          * @param int    $uid User Id
1368          * @param string $cat Config category
1369          * @param string $k   Config key
1370          */
1371         public function deletePConfigValue($uid, $cat, $k)
1372         {
1373                 if (isset($this->config[$uid][$cat][$k])) {
1374                         unset($this->config[$uid][$cat][$k]);
1375                 }
1376         }
1377
1378         /**
1379          * Generates the site's default sender email address
1380          *
1381          * @return string
1382          */
1383         public function getSenderEmailAddress()
1384         {
1385                 $sender_email = Config::get('config', 'sender_email');
1386                 if (empty($sender_email)) {
1387                         $hostname = $this->get_hostname();
1388                         if (strpos($hostname, ':')) {
1389                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1390                         }
1391
1392                         $sender_email = 'noreply@' . $hostname;
1393                 }
1394
1395                 return $sender_email;
1396         }
1397
1398         /**
1399          * Returns the current theme name.
1400          *
1401          * @return string
1402          */
1403         public function getCurrentTheme()
1404         {
1405                 if (App\Mode::isInstall()) {
1406                         return '';
1407                 }
1408
1409                 //// @TODO Compute the current theme only once (this behavior has
1410                 /// already been implemented, but it didn't work well -
1411                 /// https://github.com/friendica/friendica/issues/5092)
1412                 $this->computeCurrentTheme();
1413
1414                 return $this->current_theme;
1415         }
1416
1417         /**
1418          * Computes the current theme name based on the node settings, the user settings and the device type
1419          *
1420          * @throws Exception
1421          */
1422         private function computeCurrentTheme()
1423         {
1424                 $system_theme = Config::get('system', 'theme');
1425                 if (!$system_theme) {
1426                         throw new Exception(L10n::t('No system theme config value set.'));
1427                 }
1428
1429                 // Sane default
1430                 $this->current_theme = $system_theme;
1431
1432                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1433
1434                 $page_theme = null;
1435                 // Find the theme that belongs to the user whose stuff we are looking at
1436                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1437                         // Allow folks to override user themes and always use their own on their own site.
1438                         // This works only if the user is on the same server
1439                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1440                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1441                                 $page_theme = $user['theme'];
1442                         }
1443                 }
1444
1445                 $user_theme = Core\Session::get('theme', $system_theme);
1446
1447                 // Specific mobile theme override
1448                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1449                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1450                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1451
1452                         // --- means same mobile theme as desktop
1453                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1454                                 $user_theme = $user_mobile_theme;
1455                         }
1456                 }
1457
1458                 if ($page_theme) {
1459                         $theme_name = $page_theme;
1460                 } else {
1461                         $theme_name = $user_theme;
1462                 }
1463
1464                 if ($theme_name
1465                         && in_array($theme_name, $allowed_themes)
1466                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1467                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1468                 ) {
1469                         $this->current_theme = $theme_name;
1470                 }
1471         }
1472
1473         /**
1474          * @brief Return full URL to theme which is currently in effect.
1475          *
1476          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1477          *
1478          * @return string
1479          */
1480         public function getCurrentThemeStylesheetPath()
1481         {
1482                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1483         }
1484 }