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