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