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