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