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