]> git.mxchange.org Git - friendica.git/blob - src/App.php
Remove startup() function
[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 = ($_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
416                 if (x($parsed)) {
417                         $this->scheme = $parsed['scheme'];
418
419                         $hostname = $parsed['host'];
420                         if (x($parsed, 'port')) {
421                                 $hostname .= ':' . $parsed['port'];
422                         }
423                         if (x($parsed, 'path')) {
424                                 $this->path = trim($parsed['path'], '\\/');
425                         }
426
427                         if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
428                                 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
429                         }
430
431                         if (Config::get('config', 'hostname') != '') {
432                                 $this->hostname = Config::get('config', 'hostname');
433                         }
434
435                         if (!isset($this->hostname) || ( $this->hostname == '')) {
436                                 $this->hostname = $hostname;
437                         }
438                 }
439         }
440
441         public function get_hostname()
442         {
443                 if (Config::get('config', 'hostname') != '') {
444                         $this->hostname = Config::get('config', 'hostname');
445                 }
446
447                 return $this->hostname;
448         }
449
450         public function get_path()
451         {
452                 return $this->path;
453         }
454
455         public function set_pager_total($n)
456         {
457                 $this->pager['total'] = intval($n);
458         }
459
460         public function set_pager_itemspage($n)
461         {
462                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
463                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
464         }
465
466         public function set_pager_page($n)
467         {
468                 $this->pager['page'] = $n;
469                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
470         }
471
472         public function init_pagehead()
473         {
474                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
475
476                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
477                 if ($interval < 0) {
478                         $interval = 2147483647;
479                 }
480
481                 if ($interval < 10000) {
482                         $interval = 40000;
483                 }
484
485                 // compose the page title from the sitename and the
486                 // current module called
487                 if (!$this->module == '') {
488                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
489                 } else {
490                         $this->page['title'] = $this->config['sitename'];
491                 }
492
493                 /* put the head template at the beginning of page['htmlhead']
494                  * since the code added by the modules frequently depends on it
495                  * being first
496                  */
497                 if (!isset($this->page['htmlhead'])) {
498                         $this->page['htmlhead'] = '';
499                 }
500
501                 // If we're using Smarty, then doing replace_macros() will replace
502                 // any unrecognized variables with a blank string. Since we delay
503                 // replacing $stylesheet until later, we need to replace it now
504                 // with another variable name
505                 if ($this->theme['template_engine'] === 'smarty3') {
506                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
507                 } else {
508                         $stylesheet = '$stylesheet';
509                 }
510
511                 $shortcut_icon = Config::get('system', 'shortcut_icon');
512                 if ($shortcut_icon == '') {
513                         $shortcut_icon = 'images/friendica-32.png';
514                 }
515
516                 $touch_icon = Config::get('system', 'touch_icon');
517                 if ($touch_icon == '') {
518                         $touch_icon = 'images/friendica-128.png';
519                 }
520
521                 // get data wich is needed for infinite scroll on the network page
522                 $invinite_scroll = infinite_scroll_data($this->module);
523
524                 $tpl = get_markup_template('head.tpl');
525                 $this->page['htmlhead'] = replace_macros($tpl, [
526                         '$baseurl'         => $this->get_baseurl(),
527                         '$local_user'      => local_user(),
528                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
529                         '$delitem'         => L10n::t('Delete this item?'),
530                         '$showmore'        => L10n::t('show more'),
531                         '$showfewer'       => L10n::t('show fewer'),
532                         '$update_interval' => $interval,
533                         '$shortcut_icon'   => $shortcut_icon,
534                         '$touch_icon'      => $touch_icon,
535                         '$stylesheet'      => $stylesheet,
536                         '$infinite_scroll' => $invinite_scroll,
537                 ]) . $this->page['htmlhead'];
538         }
539
540         public function init_page_end()
541         {
542                 if (!isset($this->page['end'])) {
543                         $this->page['end'] = '';
544                 }
545                 $tpl = get_markup_template('end.tpl');
546                 $this->page['end'] = replace_macros($tpl, [
547                         '$baseurl' => $this->get_baseurl()
548                 ]) . $this->page['end'];
549         }
550
551         public function set_curl_code($code)
552         {
553                 $this->curl_code = $code;
554         }
555
556         public function get_curl_code()
557         {
558                 return $this->curl_code;
559         }
560
561         public function set_curl_content_type($content_type)
562         {
563                 $this->curl_content_type = $content_type;
564         }
565
566         public function get_curl_content_type()
567         {
568                 return $this->curl_content_type;
569         }
570
571         public function set_curl_headers($headers)
572         {
573                 $this->curl_headers = $headers;
574         }
575
576         public function get_curl_headers()
577         {
578                 return $this->curl_headers;
579         }
580
581         /**
582          * @brief Removes the base url from an url. This avoids some mixed content problems.
583          *
584          * @param string $orig_url
585          *
586          * @return string The cleaned url
587          */
588         public function remove_baseurl($orig_url)
589         {
590                 // Remove the hostname from the url if it is an internal link
591                 $nurl = normalise_link($orig_url);
592                 $base = normalise_link($this->get_baseurl());
593                 $url = str_replace($base . '/', '', $nurl);
594
595                 // if it is an external link return the orignal value
596                 if ($url == normalise_link($orig_url)) {
597                         return $orig_url;
598                 } else {
599                         return $url;
600                 }
601         }
602
603         /**
604          * @brief Register template engine class
605          *
606          * @param string $class
607          */
608         private function register_template_engine($class)
609         {
610                 $v = get_class_vars($class);
611                 if (x($v, 'name')) {
612                         $name = $v['name'];
613                         $this->template_engines[$name] = $class;
614                 } else {
615                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
616                         die();
617                 }
618         }
619
620         /**
621          * @brief Return template engine instance.
622          *
623          * If $name is not defined, return engine defined by theme,
624          * or default
625          *
626          * @return object Template Engine instance
627          */
628         public function template_engine()
629         {
630                 $template_engine = 'smarty3';
631                 if (x($this->theme, 'template_engine')) {
632                         $template_engine = $this->theme['template_engine'];
633                 }
634
635                 if (isset($this->template_engines[$template_engine])) {
636                         if (isset($this->template_engine_instance[$template_engine])) {
637                                 return $this->template_engine_instance[$template_engine];
638                         } else {
639                                 $class = $this->template_engines[$template_engine];
640                                 $obj = new $class;
641                                 $this->template_engine_instance[$template_engine] = $obj;
642                                 return $obj;
643                         }
644                 }
645
646                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
647                 killme();
648         }
649
650         /**
651          * @brief Returns the active template engine.
652          *
653          * @return string
654          */
655         public function get_template_engine()
656         {
657                 return $this->theme['template_engine'];
658         }
659
660         public function set_template_engine($engine = 'smarty3')
661         {
662                 $this->theme['template_engine'] = $engine;
663         }
664
665         public function get_template_ldelim($engine = 'smarty3')
666         {
667                 return $this->ldelim[$engine];
668         }
669
670         public function get_template_rdelim($engine = 'smarty3')
671         {
672                 return $this->rdelim[$engine];
673         }
674
675         public function save_timestamp($stamp, $value)
676         {
677                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
678                         return;
679                 }
680
681                 $duration = (float) (microtime(true) - $stamp);
682
683                 if (!isset($this->performance[$value])) {
684                         // Prevent ugly E_NOTICE
685                         $this->performance[$value] = 0;
686                 }
687
688                 $this->performance[$value] += (float) $duration;
689                 $this->performance['marktime'] += (float) $duration;
690
691                 $callstack = System::callstack();
692
693                 if (!isset($this->callstack[$value][$callstack])) {
694                         // Prevent ugly E_NOTICE
695                         $this->callstack[$value][$callstack] = 0;
696                 }
697
698                 $this->callstack[$value][$callstack] += (float) $duration;
699         }
700
701         public function get_useragent()
702         {
703                 return
704                         FRIENDICA_PLATFORM . " '" .
705                         FRIENDICA_CODENAME . "' " .
706                         FRIENDICA_VERSION . '-' .
707                         DB_UPDATE_VERSION . '; ' .
708                         $this->get_baseurl();
709         }
710
711         public function is_friendica_app()
712         {
713                 return $this->is_friendica_app;
714         }
715
716         /**
717          * @brief Checks if the site is called via a backend process
718          *
719          * This isn't a perfect solution. But we need this check very early.
720          * So we cannot wait until the modules are loaded.
721          *
722          * @return bool Is it a known backend?
723          */
724         public function is_backend()
725         {
726                 static $backends = [
727                         '_well_known',
728                         'api',
729                         'dfrn_notify',
730                         'fetch',
731                         'hcard',
732                         'hostxrd',
733                         'nodeinfo',
734                         'noscrape',
735                         'p',
736                         'poco',
737                         'post',
738                         'proxy',
739                         'pubsub',
740                         'pubsubhubbub',
741                         'receive',
742                         'rsd_xml',
743                         'salmon',
744                         'statistics_json',
745                         'xrd',
746                 ];
747
748                 // Check if current module is in backend or backend flag is set
749                 return (in_array($this->module, $backends) || $this->backend);
750         }
751
752         /**
753          * @brief Checks if the maximum number of database processes is reached
754          *
755          * @return bool Is the limit reached?
756          */
757         public function max_processes_reached()
758         {
759                 // Deactivated, needs more investigating if this check really makes sense
760                 return false;
761
762                 /*
763                  * Commented out to suppress static analyzer issues
764                  *
765                 if ($this->is_backend()) {
766                         $process = 'backend';
767                         $max_processes = Config::get('system', 'max_processes_backend');
768                         if (intval($max_processes) == 0) {
769                                 $max_processes = 5;
770                         }
771                 } else {
772                         $process = 'frontend';
773                         $max_processes = Config::get('system', 'max_processes_frontend');
774                         if (intval($max_processes) == 0) {
775                                 $max_processes = 20;
776                         }
777                 }
778
779                 $processlist = DBM::processlist();
780                 if ($processlist['list'] != '') {
781                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
782
783                         if ($processlist['amount'] > $max_processes) {
784                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
785                                 return true;
786                         }
787                 }
788                 return false;
789                  */
790         }
791
792         /**
793          * @brief Checks if the minimal memory is reached
794          *
795          * @return bool Is the memory limit reached?
796          */
797         public function min_memory_reached()
798         {
799                 $min_memory = Config::get('system', 'min_memory', 0);
800                 if ($min_memory == 0) {
801                         return false;
802                 }
803
804                 if (!is_readable('/proc/meminfo')) {
805                         return false;
806                 }
807
808                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
809
810                 $meminfo = [];
811                 foreach ($memdata as $line) {
812                         list($key, $val) = explode(':', $line);
813                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
814                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
815                 }
816
817                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
818                         return false;
819                 }
820
821                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
822
823                 $reached = ($free < $min_memory);
824
825                 if ($reached) {
826                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
827                 }
828
829                 return $reached;
830         }
831
832         /**
833          * @brief Checks if the maximum load is reached
834          *
835          * @return bool Is the load reached?
836          */
837         public function maxload_reached()
838         {
839                 if ($this->is_backend()) {
840                         $process = 'backend';
841                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
842                         if ($maxsysload < 1) {
843                                 $maxsysload = 50;
844                         }
845                 } else {
846                         $process = 'frontend';
847                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
848                         if ($maxsysload < 1) {
849                                 $maxsysload = 50;
850                         }
851                 }
852
853                 $load = current_load();
854                 if ($load) {
855                         if (intval($load) > $maxsysload) {
856                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
857                                 return true;
858                         }
859                 }
860                 return false;
861         }
862
863         public function proc_run($args)
864         {
865                 if (!function_exists('proc_open')) {
866                         return;
867                 }
868
869                 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
870
871                 for ($x = 0; $x < count($args); $x ++) {
872                         $args[$x] = escapeshellarg($args[$x]);
873                 }
874
875                 $cmdline = implode(' ', $args);
876
877                 if ($this->min_memory_reached()) {
878                         return;
879                 }
880
881                 if (Config::get('system', 'proc_windows')) {
882                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
883                 } else {
884                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
885                 }
886                 if (!is_resource($resource)) {
887                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
888                         return;
889                 }
890                 proc_close($resource);
891         }
892
893         /**
894          * @brief Returns the system user that is executing the script
895          *
896          * This mostly returns something like "www-data".
897          *
898          * @return string system username
899          */
900         private static function systemuser()
901         {
902                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
903                         return '';
904                 }
905
906                 $processUser = posix_getpwuid(posix_geteuid());
907                 return $processUser['name'];
908         }
909
910         /**
911          * @brief Checks if a given directory is usable for the system
912          *
913          * @return boolean the directory is usable
914          */
915         public static function directory_usable($directory, $check_writable = true)
916         {
917                 if ($directory == '') {
918                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
919                         return false;
920                 }
921
922                 if (!file_exists($directory)) {
923                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
924                         return false;
925                 }
926
927                 if (is_file($directory)) {
928                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
929                         return false;
930                 }
931
932                 if (!is_dir($directory)) {
933                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
934                         return false;
935                 }
936
937                 if ($check_writable && !is_writable($directory)) {
938                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
939                         return false;
940                 }
941
942                 return true;
943         }
944
945         /**
946          * @param string $cat     Config category
947          * @param string $k       Config key
948          * @param mixed  $default Default value if it isn't set
949          */
950         public function getConfigValue($cat, $k, $default = null)
951         {
952                 $return = $default;
953
954                 if ($cat === 'config') {
955                         if (isset($this->config[$k])) {
956                                 $return = $this->config[$k];
957                         }
958                 } else {
959                         if (isset($this->config[$cat][$k])) {
960                                 $return = $this->config[$cat][$k];
961                         }
962                 }
963
964                 return $return;
965         }
966
967         /**
968          * Sets a value in the config cache. Accepts raw output from the config table
969          *
970          * @param string $cat Config category
971          * @param string $k   Config key
972          * @param mixed  $v   Value to set
973          */
974         public function setConfigValue($cat, $k, $v)
975         {
976                 // Only arrays are serialized in database, so we have to unserialize sparingly
977                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
978
979                 if ($cat === 'config') {
980                         $this->config[$k] = $value;
981                 } else {
982                         if (!isset($this->config[$cat])) {
983                                 $this->config[$cat] = [];
984                         }
985
986                         $this->config[$cat][$k] = $value;
987                 }
988         }
989
990         /**
991          * Deletes a value from the config cache
992          *
993          * @param string $cat Config category
994          * @param string $k   Config key
995          */
996         public function deleteConfigValue($cat, $k)
997         {
998                 if ($cat === 'config') {
999                         if (isset($this->config[$k])) {
1000                                 unset($this->config[$k]);
1001                         }
1002                 } else {
1003                         if (isset($this->config[$cat][$k])) {
1004                                 unset($this->config[$cat][$k]);
1005                         }
1006                 }
1007         }
1008
1009
1010         /**
1011          * Retrieves a value from the user config cache
1012          *
1013          * @param int    $uid     User Id
1014          * @param string $cat     Config category
1015          * @param string $k       Config key
1016          * @param mixed  $default Default value if key isn't set
1017          */
1018         public function getPConfigValue($uid, $cat, $k, $default = null)
1019         {
1020                 $return = $default;
1021
1022                 if (isset($this->config[$uid][$cat][$k])) {
1023                         $return = $this->config[$uid][$cat][$k];
1024                 }
1025
1026                 return $return;
1027         }
1028
1029         /**
1030          * Sets a value in the user config cache
1031          *
1032          * Accepts raw output from the pconfig table
1033          *
1034          * @param int    $uid User Id
1035          * @param string $cat Config category
1036          * @param string $k   Config key
1037          * @param mixed  $v   Value to set
1038          */
1039         public function setPConfigValue($uid, $cat, $k, $v)
1040         {
1041                 // Only arrays are serialized in database, so we have to unserialize sparingly
1042                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1043
1044                 if (!isset($this->config[$uid])) {
1045                         $this->config[$uid] = [];
1046                 }
1047
1048                 if (!isset($this->config[$uid][$cat])) {
1049                         $this->config[$uid][$cat] = [];
1050                 }
1051
1052                 $this->config[$uid][$cat][$k] = $value;
1053         }
1054
1055         /**
1056          * Deletes a value from the user config cache
1057          *
1058          * @param int    $uid User Id
1059          * @param string $cat Config category
1060          * @param string $k   Config key
1061          */
1062         public function deletePConfigValue($uid, $cat, $k)
1063         {
1064                 if (isset($this->config[$uid][$cat][$k])) {
1065                         unset($this->config[$uid][$cat][$k]);
1066                 }
1067         }
1068
1069         /**
1070          * Generates the site's default sender email address
1071          *
1072          * @return string
1073          */
1074         public function getSenderEmailAddress()
1075         {
1076                 $sender_email = Config::get('config', 'sender_email');
1077                 if (empty($sender_email)) {
1078                         $hostname = $this->get_hostname();
1079                         if (strpos($hostname, ':')) {
1080                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1081                         }
1082
1083                         $sender_email = 'noreply@' . $hostname;
1084                 }
1085
1086                 return $sender_email;
1087         }
1088
1089         /**
1090          * @note Checks, if the App is in the Maintenance-Mode
1091          *
1092          * @return boolean
1093          */
1094         public function checkMaintenanceMode()
1095         {
1096                 if (Config::get('system', 'maintenance')) {
1097                         $this->mode = App::MODE_MAINTENANCE;
1098                         return true;
1099                 }
1100
1101                 return false;
1102         }
1103
1104         /**
1105          * Returns the current theme name.
1106          *
1107          * @return string
1108          */
1109         public function getCurrentTheme()
1110         {
1111                 if ($this->mode == App::MODE_INSTALL) {
1112                         return '';
1113                 }
1114
1115                 //// @TODO Compute the current theme only once (this behavior has
1116                 /// already been implemented, but it didn't work well -
1117                 /// https://github.com/friendica/friendica/issues/5092)
1118                 $this->computeCurrentTheme();
1119
1120                 return $this->current_theme;
1121         }
1122
1123         /**
1124          * Computes the current theme name based on the node settings, the user settings and the device type
1125          *
1126          * @throws Exception
1127          */
1128         private function computeCurrentTheme()
1129         {
1130                 $system_theme = Config::get('system', 'theme');
1131                 if (!$system_theme) {
1132                         throw new Exception(L10n::t('No system theme config value set.'));
1133                 }
1134
1135                 // Sane default
1136                 $this->current_theme = $system_theme;
1137
1138                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1139
1140                 $page_theme = null;
1141                 // Find the theme that belongs to the user whose stuff we are looking at
1142                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1143                         // Allow folks to override user themes and always use their own on their own site.
1144                         // This works only if the user is on the same server
1145                         $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1146                         if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1147                                 $page_theme = $user['theme'];
1148                         }
1149                 }
1150
1151                 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1152                 // Specific mobile theme override
1153                 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1154                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1155                         $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1156
1157                         // --- means same mobile theme as desktop
1158                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1159                                 $user_theme = $user_mobile_theme;
1160                         }
1161                 }
1162
1163                 if ($page_theme) {
1164                         $theme_name = $page_theme;
1165                 } else {
1166                         $theme_name = $user_theme;
1167                 }
1168
1169                 if ($theme_name
1170                         && in_array($theme_name, $allowed_themes)
1171                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1172                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1173                 ) {
1174                         $this->current_theme = $theme_name;
1175                 }
1176         }
1177
1178         /**
1179          * @brief Return full URL to theme which is currently in effect.
1180          *
1181          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1182          *
1183          * @return string
1184          */
1185         public function getCurrentThemeStylesheetPath()
1186         {
1187                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1188         }
1189 }