]> git.mxchange.org Git - friendica.git/blob - src/App.php
62b5f12e2cffeff3f8db6c867c0c067fc90f071b
[friendica.git] / src / App.php
1 <?php
2
3 namespace Friendica;
4
5 use Friendica\Core\Cache;
6 use Friendica\Core\Config;
7 use Friendica\Core\PConfig;
8 use Friendica\Core\System;
9
10 use Detection\MobileDetect;
11
12 use Exception;
13
14 require_once 'boot.php';
15 require_once 'include/text.php';
16
17 /**
18  *
19  * class: App
20  *
21  * @brief Our main application structure for the life of this page.
22  *
23  * Primarily deals with the URL that got us here
24  * and tries to make some sense of it, and
25  * stores our page contents and config storage
26  * and anything else that might need to be passed around
27  * before we spit the page out.
28  *
29  */
30 class App {
31
32         public $module_loaded = false;
33         public $module_class = null;
34         public $query_string;
35         public $config;
36         public $page;
37         public $page_offset;
38         public $profile;
39         public $profile_uid;
40         public $user;
41         public $cid;
42         public $contact;
43         public $contacts;
44         public $page_contact;
45         public $content;
46         public $data = [];
47         public $error = false;
48         public $cmd;
49         public $argv;
50         public $argc;
51         public $module;
52         public $pager;
53         public $strings;
54         public $basepath;
55         public $path;
56         public $hooks;
57         public $timezone;
58         public $interactive = true;
59         public $plugins;
60         public $plugins_admin = [];
61         public $apps = [];
62         public $identities;
63         public $is_mobile = false;
64         public $is_tablet = false;
65         public $is_friendica_app;
66         public $performance = [];
67         public $callstack = [];
68         public $theme_info = [];
69         public $backend = true;
70         public $nav_sel;
71         public $category;
72         // Allow themes to control internal parameters
73         // by changing App values in theme.php
74
75         public $sourcename = '';
76         public $videowidth = 425;
77         public $videoheight = 350;
78         public $force_max_items = 0;
79         public $theme_events_in_profile = true;
80
81         /**
82          * @brief An array for all theme-controllable parameters
83          *
84          * Mostly unimplemented yet. Only options 'template_engine' and
85          * beyond are used.
86          */
87         public $theme = [
88                 'sourcename' => '',
89                 'videowidth' => 425,
90                 'videoheight' => 350,
91                 'force_max_items' => 0,
92                 'stylesheet' => '',
93                 'template_engine' => 'smarty3',
94         ];
95
96         /**
97          * @brief An array of registered template engines ('name'=>'class name')
98          */
99         public $template_engines = [];
100
101         /**
102          * @brief An array of instanced template engines ('name'=>'instance')
103          */
104         public $template_engine_instance = [];
105         public $process_id;
106         public $queue;
107         private $ldelim = [
108                 'internal' => '',
109                 'smarty3' => '{{'
110         ];
111         private $rdelim = [
112                 'internal' => '',
113                 'smarty3' => '}}'
114         ];
115         private $scheme;
116         private $hostname;
117         private $db;
118         private $curl_code;
119         private $curl_content_type;
120         private $curl_headers;
121         private $cached_profile_image;
122         private $cached_profile_picdate;
123         private static $a;
124
125         /**
126          * @brief App constructor.
127          *
128          * @param string $basepath Path to the app base folder
129          */
130         function __construct($basepath) {
131
132                 global $default_timezone;
133
134                 $hostname = '';
135
136                 if (! static::directory_usable($basepath, false)) {
137                         throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
138                 }
139
140                 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
141
142                 if (file_exists($this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php')) {
143                         include $this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php';
144                 }
145
146                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
147
148                 date_default_timezone_set($this->timezone);
149
150                 $this->performance['start'] = microtime(true);
151                 $this->performance['database'] = 0;
152                 $this->performance['database_write'] = 0;
153                 $this->performance['network'] = 0;
154                 $this->performance['file'] = 0;
155                 $this->performance['rendering'] = 0;
156                 $this->performance['parser'] = 0;
157                 $this->performance['marktime'] = 0;
158                 $this->performance['markstart'] = microtime(true);
159
160                 $this->callstack['database'] = [];
161                 $this->callstack['database_write'] = [];
162                 $this->callstack['network'] = [];
163                 $this->callstack['file'] = [];
164                 $this->callstack['rendering'] = [];
165                 $this->callstack['parser'] = [];
166
167                 $this->config = [];
168                 $this->page = [];
169                 $this->pager = [];
170
171                 $this->query_string = '';
172
173                 $this->process_id = uniqid('log', true);
174
175                 startup();
176
177                 $this->scheme = 'http';
178
179                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
180                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
181                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
182                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
183                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
184                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
185                 ) {
186                         $this->scheme = 'https';
187                 }
188
189                 if (x($_SERVER, 'SERVER_NAME')) {
190                         $this->hostname = $_SERVER['SERVER_NAME'];
191
192                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
193                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
194                         }
195                         /*
196                          * Figure out if we are running at the top of a domain
197                          * or in a sub-directory and adjust accordingly
198                          */
199
200                         /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
201                         $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
202                         if (isset($path) && strlen($path) && ($path != $this->path)) {
203                                 $this->path = $path;
204                         }
205                 }
206
207                 if ($hostname != '') {
208                         $this->hostname = $hostname;
209                 }
210
211                 set_include_path(
212                         get_include_path() . PATH_SEPARATOR
213                         . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
214                         . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
215                         . $this->basepath);
216
217
218                 if (is_array($_SERVER['argv']) && $_SERVER['argc'] > 1 && substr(end($_SERVER['argv']), 0, 4) == 'http') {
219                         $this->set_baseurl(array_pop($_SERVER['argv']));
220                         $_SERVER['argc'] --;
221                 }
222
223                 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
224                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
225
226                         // removing trailing / - maybe a nginx problem
227                         $this->query_string = ltrim($this->query_string, '/');
228                 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
229                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
230
231                         // removing trailing / - maybe a nginx problem
232                         $this->query_string = ltrim($this->query_string, '/');
233                 }
234
235                 if (x($_GET, 'pagename')) {
236                         $this->cmd = trim($_GET['pagename'], '/\\');
237                 } elseif (x($_GET, 'q')) {
238                         $this->cmd = trim($_GET['q'], '/\\');
239                 }
240
241                 // fix query_string
242                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
243
244                 // unix style "homedir"
245                 if (substr($this->cmd, 0, 1) === '~') {
246                         $this->cmd = 'profile/' . substr($this->cmd, 1);
247                 }
248
249                 // Diaspora style profile url
250                 if (substr($this->cmd, 0, 2) === 'u/') {
251                         $this->cmd = 'profile/' . substr($this->cmd, 2);
252                 }
253
254                 /*
255                  * Break the URL path into C style argc/argv style arguments for our
256                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
257                  * will be 3 (integer) and $this->argv will contain:
258                  *   [0] => 'module'
259                  *   [1] => 'arg1'
260                  *   [2] => 'arg2'
261                  *
262                  *
263                  * There will always be one argument. If provided a naked domain
264                  * URL, $this->argv[0] is set to "home".
265                  */
266
267                 $this->argv = explode('/', $this->cmd);
268                 $this->argc = count($this->argv);
269                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
270                         $this->module = str_replace('.', '_', $this->argv[0]);
271                         $this->module = str_replace('-', '_', $this->module);
272                 } else {
273                         $this->argc = 1;
274                         $this->argv = ['home'];
275                         $this->module = 'home';
276                 }
277
278                 // See if there is any page number information, and initialise pagination
279                 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
280                 $this->pager['itemspage'] = 50;
281                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
282
283                 if ($this->pager['start'] < 0) {
284                         $this->pager['start'] = 0;
285                 }
286                 $this->pager['total'] = 0;
287
288                 // Detect mobile devices
289                 $mobile_detect = new MobileDetect();
290                 $this->is_mobile = $mobile_detect->isMobile();
291                 $this->is_tablet = $mobile_detect->isTablet();
292
293                 // Friendica-Client
294                 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
295
296                 // Register template engines
297                 $dc = get_declared_classes();
298                 foreach ($dc as $k) {
299                         if (in_array('Friendica\Render\ITemplateEngine', class_implements($k))) {
300                                 $this->register_template_engine($k);
301                         }
302                 }
303
304                 self::$a = $this;
305         }
306
307         /**
308          * @brief Returns the base filesystem path of the App
309          *
310          * It first checks for the internal variable, then for DOCUMENT_ROOT and
311          * finally for PWD
312          *
313          * @return string
314          */
315         public function get_basepath() {
316                 $basepath = $this->basepath;
317
318                 if (! $basepath) {
319                         $basepath = Config::get('system', 'basepath');
320                 }
321
322                 if (! $basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
323                         $basepath = $_SERVER['DOCUMENT_ROOT'];
324                 }
325
326                 if (! $basepath && x($_SERVER, 'PWD')) {
327                         $basepath = $_SERVER['PWD'];
328                 }
329
330                 return self::realpath($basepath);
331         }
332
333         /**
334          * @brief Returns a normalized file path
335          *
336          * This is a wrapper for the "realpath" function.
337          * That function cannot detect the real path when some folders aren't readable.
338          * Since this could happen with some hosters we need to handle this.
339          *
340          * @param string $path The path that is about to be normalized
341          * @return string normalized path - when possible
342          */
343         public static function realpath($path) {
344                 $normalized = realpath($path);
345
346                 if (!is_bool($normalized)) {
347                         return $normalized;
348                 } else {
349                         return $path;
350                 }
351         }
352
353         function get_scheme() {
354                 return $this->scheme;
355         }
356
357         /**
358          * @brief Retrieves the Friendica instance base URL
359          *
360          * This function assembles the base URL from multiple parts:
361          * - Protocol is determined either by the request or a combination of
362          * system.ssl_policy and the $ssl parameter.
363          * - Host name is determined either by system.hostname or inferred from request
364          * - Path is inferred from SCRIPT_NAME
365          *
366          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
367          *
368          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
369          * @return string Friendica server base URL
370          */
371         function get_baseurl($ssl = false) {
372                 $scheme = $this->scheme;
373
374                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
375                         $scheme = 'https';
376                 }
377
378                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
379                 //      (and also the login link). Anything seen by an outsider will have it turned off.
380
381                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
382                         if ($ssl) {
383                                 $scheme = 'https';
384                         } else {
385                                 $scheme = 'http';
386                         }
387                 }
388
389                 if (Config::get('config', 'hostname') != '') {
390                         $this->hostname = Config::get('config', 'hostname');
391                 }
392
393                 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
394         }
395
396         /**
397          * @brief Initializes the baseurl components
398          *
399          * Clears the baseurl cache to prevent inconstistencies
400          *
401          * @param string $url
402          */
403         function set_baseurl($url) {
404                 $parsed = @parse_url($url);
405
406                 if ($parsed) {
407                         $this->scheme = $parsed['scheme'];
408
409                         $hostname = $parsed['host'];
410                         if (x($parsed, 'port')) {
411                                 $hostname .= ':' . $parsed['port'];
412                         }
413                         if (x($parsed, 'path')) {
414                                 $this->path = trim($parsed['path'], '\\/');
415                         }
416
417                         if (file_exists($this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php')) {
418                                 include $this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php';
419                         }
420
421                         if (Config::get('config', 'hostname') != '') {
422                                 $this->hostname = Config::get('config', 'hostname');
423                         }
424
425                         if (!isset($this->hostname) || ( $this->hostname == '')) {
426                                 $this->hostname = $hostname;
427                         }
428                 }
429         }
430
431         function get_hostname() {
432                 if (Config::get('config', 'hostname') != '') {
433                         $this->hostname = Config::get('config', 'hostname');
434                 }
435
436                 return $this->hostname;
437         }
438
439         function set_hostname($h) {
440                 $this->hostname = $h;
441         }
442
443         function set_path($p) {
444                 $this->path = trim(trim($p), '/');
445         }
446
447         function get_path() {
448                 return $this->path;
449         }
450
451         function set_pager_total($n) {
452                 $this->pager['total'] = intval($n);
453         }
454
455         function set_pager_itemspage($n) {
456                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
457                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
458         }
459
460         function set_pager_page($n) {
461                 $this->pager['page'] = $n;
462                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
463         }
464
465         function init_pagehead() {
466                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
467
468                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
469                 if ($interval < 0) {
470                         $interval = 2147483647;
471                 }
472
473                 if ($interval < 10000) {
474                         $interval = 40000;
475                 }
476
477                 // compose the page title from the sitename and the
478                 // current module called
479                 if (!$this->module == '') {
480                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
481                 } else {
482                         $this->page['title'] = $this->config['sitename'];
483                 }
484
485                 /* put the head template at the beginning of page['htmlhead']
486                  * since the code added by the modules frequently depends on it
487                  * being first
488                  */
489                 if (!isset($this->page['htmlhead'])) {
490                         $this->page['htmlhead'] = '';
491                 }
492
493                 // If we're using Smarty, then doing replace_macros() will replace
494                 // any unrecognized variables with a blank string. Since we delay
495                 // replacing $stylesheet until later, we need to replace it now
496                 // with another variable name
497                 if ($this->theme['template_engine'] === 'smarty3') {
498                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
499                 } else {
500                         $stylesheet = '$stylesheet';
501                 }
502
503                 $shortcut_icon = Config::get('system', 'shortcut_icon');
504                 if ($shortcut_icon == '') {
505                         $shortcut_icon = 'images/friendica-32.png';
506                 }
507
508                 $touch_icon = Config::get('system', 'touch_icon');
509                 if ($touch_icon == '') {
510                         $touch_icon = 'images/friendica-128.png';
511                 }
512
513                 // get data wich is needed for infinite scroll on the network page
514                 $invinite_scroll = infinite_scroll_data($this->module);
515
516                 $tpl = get_markup_template('head.tpl');
517                 $this->page['htmlhead'] = replace_macros($tpl, [
518                                 '$baseurl' => $this->get_baseurl(),
519                                 '$local_user' => local_user(),
520                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
521                                 '$delitem' => t('Delete this item?'),
522                                 '$showmore' => t('show more'),
523                                 '$showfewer' => t('show fewer'),
524                                 '$update_interval' => $interval,
525                                 '$shortcut_icon' => $shortcut_icon,
526                                 '$touch_icon' => $touch_icon,
527                                 '$stylesheet' => $stylesheet,
528                                 '$infinite_scroll' => $invinite_scroll,
529                         ]) . $this->page['htmlhead'];
530         }
531
532         function init_page_end() {
533                 if (!isset($this->page['end'])) {
534                         $this->page['end'] = '';
535                 }
536                 $tpl = get_markup_template('end.tpl');
537                 $this->page['end'] = replace_macros($tpl, [
538                                 '$baseurl' => $this->get_baseurl()
539                         ]) . $this->page['end'];
540         }
541
542         function set_curl_code($code) {
543                 $this->curl_code = $code;
544         }
545
546         function get_curl_code() {
547                 return $this->curl_code;
548         }
549
550         function set_curl_content_type($content_type) {
551                 $this->curl_content_type = $content_type;
552         }
553
554         function get_curl_content_type() {
555                 return $this->curl_content_type;
556         }
557
558         function set_curl_headers($headers) {
559                 $this->curl_headers = $headers;
560         }
561
562         function get_curl_headers() {
563                 return $this->curl_headers;
564         }
565
566         function get_cached_avatar_image($avatar_image) {
567                 return $avatar_image;
568         }
569
570         /**
571          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
572          *
573          * @param string $orig_url
574          *
575          * @return string The cleaned url
576          */
577         function remove_baseurl($orig_url) {
578
579                 // Remove the hostname from the url if it is an internal link
580                 $nurl = normalise_link($orig_url);
581                 $base = normalise_link($this->get_baseurl());
582                 $url = str_replace($base . '/', '', $nurl);
583
584                 // if it is an external link return the orignal value
585                 if ($url == normalise_link($orig_url)) {
586                         return $orig_url;
587                 } else {
588                         return $url;
589                 }
590         }
591
592         /**
593          * @brief Register template engine class
594          *
595          * If $name is '', is used class static property $class::$name
596          *
597          * @param string $class
598          * @param string $name
599          */
600         function register_template_engine($class, $name = '') {
601                 /// @TODO Really === and not just == ?
602                 if ($name === '') {
603                         $v = get_class_vars($class);
604                         if (x($v, 'name'))
605                                 $name = $v['name'];
606                 }
607                 if ($name === '') {
608                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
609                         killme();
610                 }
611                 $this->template_engines[$name] = $class;
612         }
613
614         /**
615          * @brief Return template engine instance.
616          *
617          * If $name is not defined, return engine defined by theme,
618          * or default
619          *
620          * @param string $name Template engine name
621          * @return object Template Engine instance
622          */
623         function template_engine($name = '') {
624                 /// @TODO really type-check included?
625                 if ($name !== '') {
626                         $template_engine = $name;
627                 } else {
628                         $template_engine = 'smarty3';
629                         if (x($this->theme, 'template_engine')) {
630                                 $template_engine = $this->theme['template_engine'];
631                         }
632                 }
633
634                 if (isset($this->template_engines[$template_engine])) {
635                         if (isset($this->template_engine_instance[$template_engine])) {
636                                 return $this->template_engine_instance[$template_engine];
637                         } else {
638                                 $class = $this->template_engines[$template_engine];
639                                 $obj = new $class;
640                                 $this->template_engine_instance[$template_engine] = $obj;
641                                 return $obj;
642                         }
643                 }
644
645                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
646                 killme();
647         }
648
649         /**
650          * @brief Returns the active template engine.
651          *
652          * @return string
653          */
654         function get_template_engine() {
655                 return $this->theme['template_engine'];
656         }
657
658         function set_template_engine($engine = 'smarty3') {
659                 $this->theme['template_engine'] = $engine;
660         }
661
662         function get_template_ldelim($engine = 'smarty3') {
663                 return $this->ldelim[$engine];
664         }
665
666         function get_template_rdelim($engine = 'smarty3') {
667                 return $this->rdelim[$engine];
668         }
669
670         function save_timestamp($stamp, $value) {
671                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
672                         return;
673                 }
674
675                 $duration = (float) (microtime(true) - $stamp);
676
677                 if (!isset($this->performance[$value])) {
678                         // Prevent ugly E_NOTICE
679                         $this->performance[$value] = 0;
680                 }
681
682                 $this->performance[$value] += (float) $duration;
683                 $this->performance['marktime'] += (float) $duration;
684
685                 $callstack = System::callstack();
686
687                 if (!isset($this->callstack[$value][$callstack])) {
688                         // Prevent ugly E_NOTICE
689                         $this->callstack[$value][$callstack] = 0;
690                 }
691
692                 $this->callstack[$value][$callstack] += (float) $duration;
693         }
694
695         function get_useragent() {
696                 return
697                         FRIENDICA_PLATFORM . " '" .
698                         FRIENDICA_CODENAME . "' " .
699                         FRIENDICA_VERSION . '-' .
700                         DB_UPDATE_VERSION . '; ' .
701                         $this->get_baseurl();
702         }
703
704         function is_friendica_app() {
705                 return $this->is_friendica_app;
706         }
707
708         /**
709          * @brief Checks if the site is called via a backend process
710          *
711          * This isn't a perfect solution. But we need this check very early.
712          * So we cannot wait until the modules are loaded.
713          *
714          * @return bool Is it a known backend?
715          */
716         function is_backend() {
717                 static $backends = [];
718                 $backends[] = '_well_known';
719                 $backends[] = 'api';
720                 $backends[] = 'dfrn_notify';
721                 $backends[] = 'fetch';
722                 $backends[] = 'hcard';
723                 $backends[] = 'hostxrd';
724                 $backends[] = 'nodeinfo';
725                 $backends[] = 'noscrape';
726                 $backends[] = 'p';
727                 $backends[] = 'poco';
728                 $backends[] = 'post';
729                 $backends[] = 'proxy';
730                 $backends[] = 'pubsub';
731                 $backends[] = 'pubsubhubbub';
732                 $backends[] = 'receive';
733                 $backends[] = 'rsd_xml';
734                 $backends[] = 'salmon';
735                 $backends[] = 'statistics_json';
736                 $backends[] = 'xrd';
737
738                 // Check if current module is in backend or backend flag is set
739                 return (in_array($this->module, $backends) || $this->backend);
740         }
741
742         /**
743          * @brief Checks if the maximum number of database processes is reached
744          *
745          * @return bool Is the limit reached?
746          */
747         function max_processes_reached() {
748                 // Deactivated, needs more investigating if this check really makes sense
749                 return false;
750
751                 if ($this->is_backend()) {
752                         $process = 'backend';
753                         $max_processes = Config::get('system', 'max_processes_backend');
754                         if (intval($max_processes) == 0) {
755                                 $max_processes = 5;
756                         }
757                 } else {
758                         $process = 'frontend';
759                         $max_processes = Config::get('system', 'max_processes_frontend');
760                         if (intval($max_processes) == 0) {
761                                 $max_processes = 20;
762                         }
763                 }
764
765                 $processlist = DBM::processlist();
766                 if ($processlist['list'] != '') {
767                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
768
769                         if ($processlist['amount'] > $max_processes) {
770                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
771                                 return true;
772                         }
773                 }
774                 return false;
775         }
776
777         /**
778          * @brief Checks if the minimal memory is reached
779          *
780          * @return bool Is the memory limit reached?
781          */
782         public function min_memory_reached() {
783                 $min_memory = Config::get('system', 'min_memory', 0);
784                 if ($min_memory == 0) {
785                         return false;
786                 }
787
788                 if (!is_readable('/proc/meminfo')) {
789                         return false;
790                 }
791
792                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
793
794                 $meminfo = [];
795                 foreach ($memdata as $line) {
796                         list($key, $val) = explode(':', $line);
797                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
798                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
799                 }
800
801                 if (!isset($meminfo['MemAvailable']) || ! isset($meminfo['MemFree'])) {
802                         return false;
803                 }
804
805                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
806
807                 $reached = ($free < $min_memory);
808
809                 if ($reached) {
810                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
811                 }
812
813                 return $reached;
814         }
815
816         /**
817          * @brief Checks if the maximum load is reached
818          *
819          * @return bool Is the load reached?
820          */
821         function maxload_reached() {
822
823                 if ($this->is_backend()) {
824                         $process = 'backend';
825                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
826                         if ($maxsysload < 1) {
827                                 $maxsysload = 50;
828                         }
829                 } else {
830                         $process = 'frontend';
831                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
832                         if ($maxsysload < 1) {
833                                 $maxsysload = 50;
834                         }
835                 }
836
837                 $load = current_load();
838                 if ($load) {
839                         if (intval($load) > $maxsysload) {
840                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
841                                 return true;
842                         }
843                 }
844                 return false;
845         }
846
847         function proc_run($args) {
848
849                 if (!function_exists('proc_open')) {
850                         return;
851                 }
852
853                 // If the last worker fork was less than 2 seconds before then don't fork another one.
854                 // This should prevent the forking of masses of workers.
855                 $cachekey = 'app:proc_run:started';
856                 $result = Cache::get($cachekey);
857
858                 if (!is_null($result) && ( time() - $result) < 2) {
859                         return;
860                 }
861
862                 // Set the timestamp of the last proc_run
863                 Cache::set($cachekey, time(), CACHE_MINUTE);
864
865                 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
866
867                 // add baseurl to args. cli scripts can't construct it
868                 $args[] = $this->get_baseurl();
869
870                 for ($x = 0; $x < count($args); $x ++) {
871                         $args[$x] = escapeshellarg($args[$x]);
872                 }
873
874                 $cmdline = implode($args, ' ');
875
876                 if ($this->min_memory_reached()) {
877                         return;
878                 }
879
880                 if (Config::get('system', 'proc_windows')) {
881                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
882                 } else {
883                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
884                 }
885                 if (!is_resource($resource)) {
886                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
887                         return;
888                 }
889                 proc_close($resource);
890         }
891
892         /**
893          * @brief Returns the system user that is executing the script
894          *
895          * This mostly returns something like "www-data".
896          *
897          * @return string system username
898          */
899         static function systemuser() {
900                 if (!function_exists('posix_getpwuid') || ! function_exists('posix_geteuid')) {
901                         return '';
902                 }
903
904                 $processUser = posix_getpwuid(posix_geteuid());
905                 return $processUser['name'];
906         }
907
908         /**
909          * @brief Checks if a given directory is usable for the system
910          *
911          * @return boolean the directory is usable
912          */
913         static function directory_usable($directory, $check_writable = true) {
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                 if (is_file($directory)) {
924                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
925                         return false;
926                 }
927                 if (!is_dir($directory)) {
928                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
929                         return false;
930                 }
931                 if ($check_writable && !is_writable($directory)) {
932                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
933                         return false;
934                 }
935                 return true;
936         }
937 }