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