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