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