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