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