]> git.mxchange.org Git - friendica.git/blob - src/App.php
a5c6f34227e7216713301712736912d6bb89c691
[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 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                 $scheme = $this->scheme;
374
375                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
376                         $scheme = 'https';
377                 }
378
379                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
380                 //      (and also the login link). Anything seen by an outsider will have it turned off.
381
382                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
383                         if ($ssl) {
384                                 $scheme = 'https';
385                         } else {
386                                 $scheme = 'http';
387                         }
388                 }
389
390                 if (Config::get('config', 'hostname') != '') {
391                         $this->hostname = Config::get('config', 'hostname');
392                 }
393
394                 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
395         }
396
397         /**
398          * @brief Initializes the baseurl components
399          *
400          * Clears the baseurl cache to prevent inconstistencies
401          *
402          * @param string $url
403          */
404         function set_baseurl($url) {
405                 $parsed = @parse_url($url);
406
407                 if ($parsed) {
408                         $this->scheme = $parsed['scheme'];
409
410                         $hostname = $parsed['host'];
411                         if (x($parsed, 'port')) {
412                                 $hostname .= ':' . $parsed['port'];
413                         }
414                         if (x($parsed, 'path')) {
415                                 $this->path = trim($parsed['path'], '\\/');
416                         }
417
418                         if (file_exists('.htpreconfig.php')) {
419                                 include '.htpreconfig.php';
420                         }
421
422                         if (Config::get('config', 'hostname') != '') {
423                                 $this->hostname = Config::get('config', 'hostname');
424                         }
425
426                         if (!isset($this->hostname) || ( $this->hostname == '')) {
427                                 $this->hostname = $hostname;
428                         }
429                 }
430         }
431
432         function get_hostname() {
433                 if (Config::get('config', 'hostname') != '') {
434                         $this->hostname = Config::get('config', 'hostname');
435                 }
436
437                 return $this->hostname;
438         }
439
440         function set_hostname($h) {
441                 $this->hostname = $h;
442         }
443
444         function set_path($p) {
445                 $this->path = trim(trim($p), '/');
446         }
447
448         function get_path() {
449                 return $this->path;
450         }
451
452         function set_pager_total($n) {
453                 $this->pager['total'] = intval($n);
454         }
455
456         function set_pager_itemspage($n) {
457                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
458                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
459         }
460
461         function set_pager_page($n) {
462                 $this->pager['page'] = $n;
463                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
464         }
465
466         function init_pagehead() {
467                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
468
469                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
470                 if ($interval < 0) {
471                         $interval = 2147483647;
472                 }
473
474                 if ($interval < 10000) {
475                         $interval = 40000;
476                 }
477
478                 // compose the page title from the sitename and the
479                 // current module called
480                 if (!$this->module == '') {
481                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
482                 } else {
483                         $this->page['title'] = $this->config['sitename'];
484                 }
485
486                 /* put the head template at the beginning of page['htmlhead']
487                  * since the code added by the modules frequently depends on it
488                  * being first
489                  */
490                 if (!isset($this->page['htmlhead'])) {
491                         $this->page['htmlhead'] = '';
492                 }
493
494                 // If we're using Smarty, then doing replace_macros() will replace
495                 // any unrecognized variables with a blank string. Since we delay
496                 // replacing $stylesheet until later, we need to replace it now
497                 // with another variable name
498                 if ($this->theme['template_engine'] === 'smarty3') {
499                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
500                 } else {
501                         $stylesheet = '$stylesheet';
502                 }
503
504                 $shortcut_icon = Config::get('system', 'shortcut_icon');
505                 if ($shortcut_icon == '') {
506                         $shortcut_icon = 'images/friendica-32.png';
507                 }
508
509                 $touch_icon = Config::get('system', 'touch_icon');
510                 if ($touch_icon == '') {
511                         $touch_icon = 'images/friendica-128.png';
512                 }
513
514                 // get data wich is needed for infinite scroll on the network page
515                 $invinite_scroll = infinite_scroll_data($this->module);
516
517                 $tpl = get_markup_template('head.tpl');
518                 $this->page['htmlhead'] = replace_macros($tpl, array(
519                                 '$baseurl' => $this->get_baseurl(),
520                                 '$local_user' => local_user(),
521                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
522                                 '$delitem' => t('Delete this item?'),
523                                 '$showmore' => t('show more'),
524                                 '$showfewer' => t('show fewer'),
525                                 '$update_interval' => $interval,
526                                 '$shortcut_icon' => $shortcut_icon,
527                                 '$touch_icon' => $touch_icon,
528                                 '$stylesheet' => $stylesheet,
529                                 '$infinite_scroll' => $invinite_scroll,
530                         )) . $this->page['htmlhead'];
531         }
532
533         function init_page_end() {
534                 if (!isset($this->page['end'])) {
535                         $this->page['end'] = '';
536                 }
537                 $tpl = get_markup_template('end.tpl');
538                 $this->page['end'] = replace_macros($tpl, array(
539                                 '$baseurl' => $this->get_baseurl()
540                         )) . $this->page['end'];
541         }
542
543         function set_curl_code($code) {
544                 $this->curl_code = $code;
545         }
546
547         function get_curl_code() {
548                 return $this->curl_code;
549         }
550
551         function set_curl_content_type($content_type) {
552                 $this->curl_content_type = $content_type;
553         }
554
555         function get_curl_content_type() {
556                 return $this->curl_content_type;
557         }
558
559         function set_curl_headers($headers) {
560                 $this->curl_headers = $headers;
561         }
562
563         function get_curl_headers() {
564                 return $this->curl_headers;
565         }
566
567         function get_cached_avatar_image($avatar_image) {
568                 return $avatar_image;
569         }
570
571         /**
572          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
573          *
574          * @param string $orig_url
575          *
576          * @return string The cleaned url
577          */
578         function remove_baseurl($orig_url) {
579
580                 // Remove the hostname from the url if it is an internal link
581                 $nurl = normalise_link($orig_url);
582                 $base = normalise_link($this->get_baseurl());
583                 $url = str_replace($base . '/', '', $nurl);
584
585                 // if it is an external link return the orignal value
586                 if ($url == normalise_link($orig_url)) {
587                         return $orig_url;
588                 } else {
589                         return $url;
590                 }
591         }
592
593         /**
594          * @brief Register template engine class
595          *
596          * If $name is '', is used class static property $class::$name
597          *
598          * @param string $class
599          * @param string $name
600          */
601         function register_template_engine($class, $name = '') {
602                 /// @TODO Really === and not just == ?
603                 if ($name === '') {
604                         $v = get_class_vars($class);
605                         if (x($v, 'name'))
606                                 $name = $v['name'];
607                 }
608                 if ($name === '') {
609                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
610                         killme();
611                 }
612                 $this->template_engines[$name] = $class;
613         }
614
615         /**
616          * @brief Return template engine instance.
617          *
618          * If $name is not defined, return engine defined by theme,
619          * or default
620          *
621          * @param strin $name Template engine name
622          * @return object Template Engine instance
623          */
624         function template_engine($name = '') {
625                 /// @TODO really type-check included?
626                 if ($name !== '') {
627                         $template_engine = $name;
628                 } else {
629                         $template_engine = 'smarty3';
630                         if (x($this->theme, 'template_engine')) {
631                                 $template_engine = $this->theme['template_engine'];
632                         }
633                 }
634
635                 if (isset($this->template_engines[$template_engine])) {
636                         if (isset($this->template_engine_instance[$template_engine])) {
637                                 return $this->template_engine_instance[$template_engine];
638                         } else {
639                                 $class = $this->template_engines[$template_engine];
640                                 $obj = new $class;
641                                 $this->template_engine_instance[$template_engine] = $obj;
642                                 return $obj;
643                         }
644                 }
645
646                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
647                 killme();
648         }
649
650         /**
651          * @brief Returns the active template engine.
652          *
653          * @return string
654          */
655         function get_template_engine() {
656                 return $this->theme['template_engine'];
657         }
658
659         function set_template_engine($engine = 'smarty3') {
660                 $this->theme['template_engine'] = $engine;
661         }
662
663         function get_template_ldelim($engine = 'smarty3') {
664                 return $this->ldelim[$engine];
665         }
666
667         function get_template_rdelim($engine = 'smarty3') {
668                 return $this->rdelim[$engine];
669         }
670
671         function save_timestamp($stamp, $value) {
672                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
673                         return;
674                 }
675
676                 $duration = (float) (microtime(true) - $stamp);
677
678                 if (!isset($this->performance[$value])) {
679                         // Prevent ugly E_NOTICE
680                         $this->performance[$value] = 0;
681                 }
682
683                 $this->performance[$value] += (float) $duration;
684                 $this->performance['marktime'] += (float) $duration;
685
686                 $callstack = $this->callstack();
687
688                 if (!isset($this->callstack[$value][$callstack])) {
689                         // Prevent ugly E_NOTICE
690                         $this->callstack[$value][$callstack] = 0;
691                 }
692
693                 $this->callstack[$value][$callstack] += (float) $duration;
694         }
695
696         /**
697          * @brief Log active processes into the "process" table
698          */
699         function start_process() {
700                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
701
702                 $command = basename($trace[0]['file']);
703
704                 $this->remove_inactive_processes();
705
706                 dba::transaction();
707
708                 $r = q('SELECT `pid` FROM `process` WHERE `pid` = %d', intval(getmypid()));
709                 if (!dbm::is_result($r)) {
710                         dba::insert('process', array('pid' => getmypid(), 'command' => $command, 'created' => datetime_convert()));
711                 }
712                 dba::commit();
713         }
714
715         /**
716          * @brief Remove inactive processes
717          */
718         function remove_inactive_processes() {
719                 dba::transaction();
720
721                 $r = q('SELECT `pid` FROM `process`');
722                 if (dbm::is_result($r)) {
723                         foreach ($r AS $process) {
724                                 if (!posix_kill($process['pid'], 0)) {
725                                         q('DELETE FROM `process` WHERE `pid` = %d', intval($process['pid']));
726                                 }
727                         }
728                 }
729                 dba::commit();
730         }
731
732         /**
733          * @brief Remove the active process from the "process" table
734          */
735         function end_process() {
736                 q('DELETE FROM `process` WHERE `pid` = %d', intval(getmypid()));
737         }
738
739         /**
740          * @brief Returns a string with a callstack. Can be used for logging.
741          *
742          * @return string
743          */
744         function callstack($depth = 4) {
745                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $depth + 2);
746
747                 // We remove the first two items from the list since they contain data that we don't need.
748                 array_shift($trace);
749                 array_shift($trace);
750
751                 $callstack = array();
752                 foreach ($trace AS $func) {
753                         if (!empty($func['class'])) {
754                                 $callstack[] = $func['class'].'::'.$func['function'];
755                         } else {
756                                 $callstack[] = $func['function'];
757                         }
758                 }
759
760                 return implode(', ', $callstack);
761         }
762
763         function get_useragent() {
764                 return
765                         FRIENDICA_PLATFORM . " '" .
766                         FRIENDICA_CODENAME . "' " .
767                         FRIENDICA_VERSION . '-' .
768                         DB_UPDATE_VERSION . '; ' .
769                         $this->get_baseurl();
770         }
771
772         function is_friendica_app() {
773                 return $this->is_friendica_app;
774         }
775
776         /**
777          * @brief Checks if the site is called via a backend process
778          *
779          * This isn't a perfect solution. But we need this check very early.
780          * So we cannot wait until the modules are loaded.
781          *
782          * @return bool Is it a known backend?
783          */
784         function is_backend() {
785                 static $backends = array();
786                 $backends[] = '_well_known';
787                 $backends[] = 'api';
788                 $backends[] = 'dfrn_notify';
789                 $backends[] = 'fetch';
790                 $backends[] = 'hcard';
791                 $backends[] = 'hostxrd';
792                 $backends[] = 'nodeinfo';
793                 $backends[] = 'noscrape';
794                 $backends[] = 'p';
795                 $backends[] = 'poco';
796                 $backends[] = 'post';
797                 $backends[] = 'proxy';
798                 $backends[] = 'pubsub';
799                 $backends[] = 'pubsubhubbub';
800                 $backends[] = 'receive';
801                 $backends[] = 'rsd_xml';
802                 $backends[] = 'salmon';
803                 $backends[] = 'statistics_json';
804                 $backends[] = 'xrd';
805
806                 // Check if current module is in backend or backend flag is set
807                 return (in_array($this->module, $backends) || $this->backend);
808         }
809
810         /**
811          * @brief Checks if the maximum number of database processes is reached
812          *
813          * @return bool Is the limit reached?
814          */
815         function max_processes_reached() {
816                 // Deactivated, needs more investigating if this check really makes sense
817                 return false;
818
819                 if ($this->is_backend()) {
820                         $process = 'backend';
821                         $max_processes = Config::get('system', 'max_processes_backend');
822                         if (intval($max_processes) == 0) {
823                                 $max_processes = 5;
824                         }
825                 } else {
826                         $process = 'frontend';
827                         $max_processes = Config::get('system', 'max_processes_frontend');
828                         if (intval($max_processes) == 0) {
829                                 $max_processes = 20;
830                         }
831                 }
832
833                 $processlist = dbm::processlist();
834                 if ($processlist['list'] != '') {
835                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
836
837                         if ($processlist['amount'] > $max_processes) {
838                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
839                                 return true;
840                         }
841                 }
842                 return false;
843         }
844
845         /**
846          * @brief Checks if the minimal memory is reached
847          *
848          * @return bool Is the memory limit reached?
849          */
850         public function min_memory_reached() {
851                 $min_memory = Config::get('system', 'min_memory', 0);
852                 if ($min_memory == 0) {
853                         return false;
854                 }
855
856                 if (!is_readable('/proc/meminfo')) {
857                         return false;
858                 }
859
860                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
861
862                 $meminfo = array();
863                 foreach ($memdata as $line) {
864                         list($key, $val) = explode(':', $line);
865                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
866                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
867                 }
868
869                 if (!isset($meminfo['MemAvailable']) || ! isset($meminfo['MemFree'])) {
870                         return false;
871                 }
872
873                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
874
875                 $reached = ($free < $min_memory);
876
877                 if ($reached) {
878                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
879                 }
880
881                 return $reached;
882         }
883
884         /**
885          * @brief Checks if the maximum load is reached
886          *
887          * @return bool Is the load reached?
888          */
889         function maxload_reached() {
890
891                 if ($this->is_backend()) {
892                         $process = 'backend';
893                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
894                         if ($maxsysload < 1) {
895                                 $maxsysload = 50;
896                         }
897                 } else {
898                         $process = 'frontend';
899                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
900                         if ($maxsysload < 1) {
901                                 $maxsysload = 50;
902                         }
903                 }
904
905                 $load = current_load();
906                 if ($load) {
907                         if (intval($load) > $maxsysload) {
908                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
909                                 return true;
910                         }
911                 }
912                 return false;
913         }
914
915         function proc_run($args) {
916
917                 if (!function_exists('proc_open')) {
918                         return;
919                 }
920
921                 // If the last worker fork was less than 2 seconds before then don't fork another one.
922                 // This should prevent the forking of masses of workers.
923                 $cachekey = 'app:proc_run:started';
924                 $result = Cache::get($cachekey);
925
926                 if (!is_null($result) && ( time() - $result) < 2) {
927                         return;
928                 }
929
930                 // Set the timestamp of the last proc_run
931                 Cache::set($cachekey, time(), CACHE_MINUTE);
932
933                 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
934
935                 // add baseurl to args. cli scripts can't construct it
936                 $args[] = $this->get_baseurl();
937
938                 for ($x = 0; $x < count($args); $x ++) {
939                         $args[$x] = escapeshellarg($args[$x]);
940                 }
941
942                 $cmdline = implode($args, ' ');
943
944                 if ($this->min_memory_reached()) {
945                         return;
946                 }
947
948                 if (Config::get('system', 'proc_windows')) {
949                         $resource = proc_open('cmd /c start /b ' . $cmdline, array(), $foo, $this->get_basepath());
950                 } else {
951                         $resource = proc_open($cmdline . ' &', array(), $foo, $this->get_basepath());
952                 }
953                 if (!is_resource($resource)) {
954                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
955                         return;
956                 }
957                 proc_close($resource);
958         }
959
960         /**
961          * @brief Returns the system user that is executing the script
962          *
963          * This mostly returns something like "www-data".
964          *
965          * @return string system username
966          */
967         static function systemuser() {
968                 if (!function_exists('posix_getpwuid') || ! function_exists('posix_geteuid')) {
969                         return '';
970                 }
971
972                 $processUser = posix_getpwuid(posix_geteuid());
973                 return $processUser['name'];
974         }
975
976         /**
977          * @brief Checks if a given directory is usable for the system
978          *
979          * @return boolean the directory is usable
980          */
981         static function directory_usable($directory, $check_writable = true) {
982                 if ($directory == '') {
983                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
984                         return false;
985                 }
986
987                 if (!file_exists($directory)) {
988                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
989                         return false;
990                 }
991                 if (is_file($directory)) {
992                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
993                         return false;
994                 }
995                 if (!is_dir($directory)) {
996                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
997                         return false;
998                 }
999                 if ($check_writable && !is_writable($directory)) {
1000                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1001                         return false;
1002                 }
1003                 return true;
1004         }
1005 }