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