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