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