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