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