]> git.mxchange.org Git - friendica.git/blob - src/App.php
Merge pull request #4091 from MrPetovan/task/4090-add-module-class-routing
[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 $module_class = null;
34         public $query_string;
35         public $config;
36         public $page;
37         public $profile;
38         public $profile_uid;
39         public $user;
40         public $cid;
41         public $contact;
42         public $contacts;
43         public $page_contact;
44         public $content;
45         public $data = array();
46         public $error = false;
47         public $cmd;
48         public $argv;
49         public $argc;
50         public $module;
51         public $pager;
52         public $strings;
53         public $basepath;
54         public $path;
55         public $hooks;
56         public $timezone;
57         public $interactive = true;
58         public $plugins;
59         public $apps = array();
60         public $identities;
61         public $is_mobile = false;
62         public $is_tablet = false;
63         public $is_friendica_app;
64         public $performance = array();
65         public $callstack = array();
66         public $theme_info = array();
67         public $backend = true;
68         public $nav_sel;
69         public $category;
70         // Allow themes to control internal parameters
71         // by changing App values in theme.php
72
73         public $sourcename = '';
74         public $videowidth = 425;
75         public $videoheight = 350;
76         public $force_max_items = 0;
77         public $theme_events_in_profile = true;
78
79         /**
80          * @brief An array for all theme-controllable parameters
81          *
82          * Mostly unimplemented yet. Only options 'template_engine' and
83          * beyond are used.
84          */
85         public $theme = array(
86                 'sourcename' => '',
87                 'videowidth' => 425,
88                 'videoheight' => 350,
89                 'force_max_items' => 0,
90                 'stylesheet' => '',
91                 'template_engine' => 'smarty3',
92         );
93
94         /**
95          * @brief An array of registered template engines ('name'=>'class name')
96          */
97         public $template_engines = array();
98
99         /**
100          * @brief An array of instanced template engines ('name'=>'instance')
101          */
102         public $template_engine_instance = array();
103         public $process_id;
104         public $queue;
105         private $ldelim = array(
106                 'internal' => '',
107                 'smarty3' => '{{'
108         );
109         private $rdelim = array(
110                 'internal' => '',
111                 'smarty3' => '}}'
112         );
113         private $scheme;
114         private $hostname;
115         private $db;
116         private $curl_code;
117         private $curl_content_type;
118         private $curl_headers;
119         private $cached_profile_image;
120         private $cached_profile_picdate;
121         private static $a;
122
123         /**
124          * @brief App constructor.
125          *
126          * @param string $basepath Path to the app base folder
127          */
128         function __construct($basepath) {
129
130                 global $default_timezone;
131
132                 $hostname = '';
133
134                 if (! static::directory_usable($basepath, false)) {
135                         throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
136                 }
137
138                 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
139
140                 if (file_exists($this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php')) {
141                         include $this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php';
142                 }
143
144                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
145
146                 date_default_timezone_set($this->timezone);
147
148                 $this->performance['start'] = microtime(true);
149                 $this->performance['database'] = 0;
150                 $this->performance['database_write'] = 0;
151                 $this->performance['network'] = 0;
152                 $this->performance['file'] = 0;
153                 $this->performance['rendering'] = 0;
154                 $this->performance['parser'] = 0;
155                 $this->performance['marktime'] = 0;
156                 $this->performance['markstart'] = microtime(true);
157
158                 $this->callstack['database'] = array();
159                 $this->callstack['database_write'] = array();
160                 $this->callstack['network'] = array();
161                 $this->callstack['file'] = array();
162                 $this->callstack['rendering'] = array();
163                 $this->callstack['parser'] = array();
164
165                 $this->config = array();
166                 $this->page = array();
167                 $this->pager = array();
168
169                 $this->query_string = '';
170
171                 $this->process_id = uniqid('log', true);
172
173                 startup();
174
175                 $this->scheme = 'http';
176
177                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
178                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
179                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
180                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
181                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
182                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
183                 ) {
184                         $this->scheme = 'https';
185                 }
186
187                 if (x($_SERVER, 'SERVER_NAME')) {
188                         $this->hostname = $_SERVER['SERVER_NAME'];
189
190                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
191                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
192                         }
193                         /*
194                          * Figure out if we are running at the top of a domain
195                          * or in a sub-directory and adjust accordingly
196                          */
197
198                         /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
199                         $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
200                         if (isset($path) && strlen($path) && ($path != $this->path)) {
201                                 $this->path = $path;
202                         }
203                 }
204
205                 if ($hostname != '') {
206                         $this->hostname = $hostname;
207                 }
208
209                 set_include_path(
210                         get_include_path() . PATH_SEPARATOR
211                         . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
212                         . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
213                         . $this->basepath);
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('Friendica\Render\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                 $scheme = $this->scheme;
373
374                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
375                         $scheme = 'https';
376                 }
377
378                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
379                 //      (and also the login link). Anything seen by an outsider will have it turned off.
380
381                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
382                         if ($ssl) {
383                                 $scheme = 'https';
384                         } else {
385                                 $scheme = 'http';
386                         }
387                 }
388
389                 if (Config::get('config', 'hostname') != '') {
390                         $this->hostname = Config::get('config', 'hostname');
391                 }
392
393                 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
394         }
395
396         /**
397          * @brief Initializes the baseurl components
398          *
399          * Clears the baseurl cache to prevent inconstistencies
400          *
401          * @param string $url
402          */
403         function set_baseurl($url) {
404                 $parsed = @parse_url($url);
405
406                 if ($parsed) {
407                         $this->scheme = $parsed['scheme'];
408
409                         $hostname = $parsed['host'];
410                         if (x($parsed, 'port')) {
411                                 $hostname .= ':' . $parsed['port'];
412                         }
413                         if (x($parsed, 'path')) {
414                                 $this->path = trim($parsed['path'], '\\/');
415                         }
416
417                         if (file_exists($this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php')) {
418                                 include $this->basepath.DIRECTORY_SEPARATOR.'.htpreconfig.php';
419                         }
420
421                         if (Config::get('config', 'hostname') != '') {
422                                 $this->hostname = Config::get('config', 'hostname');
423                         }
424
425                         if (!isset($this->hostname) || ( $this->hostname == '')) {
426                                 $this->hostname = $hostname;
427                         }
428                 }
429         }
430
431         function get_hostname() {
432                 if (Config::get('config', 'hostname') != '') {
433                         $this->hostname = Config::get('config', 'hostname');
434                 }
435
436                 return $this->hostname;
437         }
438
439         function set_hostname($h) {
440                 $this->hostname = $h;
441         }
442
443         function set_path($p) {
444                 $this->path = trim(trim($p), '/');
445         }
446
447         function get_path() {
448                 return $this->path;
449         }
450
451         function set_pager_total($n) {
452                 $this->pager['total'] = intval($n);
453         }
454
455         function set_pager_itemspage($n) {
456                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
457                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
458         }
459
460         function set_pager_page($n) {
461                 $this->pager['page'] = $n;
462                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
463         }
464
465         function init_pagehead() {
466                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
467
468                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
469                 if ($interval < 0) {
470                         $interval = 2147483647;
471                 }
472
473                 if ($interval < 10000) {
474                         $interval = 40000;
475                 }
476
477                 // compose the page title from the sitename and the
478                 // current module called
479                 if (!$this->module == '') {
480                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
481                 } else {
482                         $this->page['title'] = $this->config['sitename'];
483                 }
484
485                 /* put the head template at the beginning of page['htmlhead']
486                  * since the code added by the modules frequently depends on it
487                  * being first
488                  */
489                 if (!isset($this->page['htmlhead'])) {
490                         $this->page['htmlhead'] = '';
491                 }
492
493                 // If we're using Smarty, then doing replace_macros() will replace
494                 // any unrecognized variables with a blank string. Since we delay
495                 // replacing $stylesheet until later, we need to replace it now
496                 // with another variable name
497                 if ($this->theme['template_engine'] === 'smarty3') {
498                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
499                 } else {
500                         $stylesheet = '$stylesheet';
501                 }
502
503                 $shortcut_icon = Config::get('system', 'shortcut_icon');
504                 if ($shortcut_icon == '') {
505                         $shortcut_icon = 'images/friendica-32.png';
506                 }
507
508                 $touch_icon = Config::get('system', 'touch_icon');
509                 if ($touch_icon == '') {
510                         $touch_icon = 'images/friendica-128.png';
511                 }
512
513                 // get data wich is needed for infinite scroll on the network page
514                 $invinite_scroll = infinite_scroll_data($this->module);
515
516                 $tpl = get_markup_template('head.tpl');
517                 $this->page['htmlhead'] = replace_macros($tpl, array(
518                                 '$baseurl' => $this->get_baseurl(),
519                                 '$local_user' => local_user(),
520                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
521                                 '$delitem' => t('Delete this item?'),
522                                 '$showmore' => t('show more'),
523                                 '$showfewer' => t('show fewer'),
524                                 '$update_interval' => $interval,
525                                 '$shortcut_icon' => $shortcut_icon,
526                                 '$touch_icon' => $touch_icon,
527                                 '$stylesheet' => $stylesheet,
528                                 '$infinite_scroll' => $invinite_scroll,
529                         )) . $this->page['htmlhead'];
530         }
531
532         function init_page_end() {
533                 if (!isset($this->page['end'])) {
534                         $this->page['end'] = '';
535                 }
536                 $tpl = get_markup_template('end.tpl');
537                 $this->page['end'] = replace_macros($tpl, array(
538                                 '$baseurl' => $this->get_baseurl()
539                         )) . $this->page['end'];
540         }
541
542         function set_curl_code($code) {
543                 $this->curl_code = $code;
544         }
545
546         function get_curl_code() {
547                 return $this->curl_code;
548         }
549
550         function set_curl_content_type($content_type) {
551                 $this->curl_content_type = $content_type;
552         }
553
554         function get_curl_content_type() {
555                 return $this->curl_content_type;
556         }
557
558         function set_curl_headers($headers) {
559                 $this->curl_headers = $headers;
560         }
561
562         function get_curl_headers() {
563                 return $this->curl_headers;
564         }
565
566         function get_cached_avatar_image($avatar_image) {
567                 return $avatar_image;
568         }
569
570         /**
571          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
572          *
573          * @param string $orig_url
574          *
575          * @return string The cleaned url
576          */
577         function remove_baseurl($orig_url) {
578
579                 // Remove the hostname from the url if it is an internal link
580                 $nurl = normalise_link($orig_url);
581                 $base = normalise_link($this->get_baseurl());
582                 $url = str_replace($base . '/', '', $nurl);
583
584                 // if it is an external link return the orignal value
585                 if ($url == normalise_link($orig_url)) {
586                         return $orig_url;
587                 } else {
588                         return $url;
589                 }
590         }
591
592         /**
593          * @brief Register template engine class
594          *
595          * If $name is '', is used class static property $class::$name
596          *
597          * @param string $class
598          * @param string $name
599          */
600         function register_template_engine($class, $name = '') {
601                 /// @TODO Really === and not just == ?
602                 if ($name === '') {
603                         $v = get_class_vars($class);
604                         if (x($v, 'name'))
605                                 $name = $v['name'];
606                 }
607                 if ($name === '') {
608                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
609                         killme();
610                 }
611                 $this->template_engines[$name] = $class;
612         }
613
614         /**
615          * @brief Return template engine instance.
616          *
617          * If $name is not defined, return engine defined by theme,
618          * or default
619          *
620          * @param strin $name Template engine name
621          * @return object Template Engine instance
622          */
623         function template_engine($name = '') {
624                 /// @TODO really type-check included?
625                 if ($name !== '') {
626                         $template_engine = $name;
627                 } else {
628                         $template_engine = 'smarty3';
629                         if (x($this->theme, 'template_engine')) {
630                                 $template_engine = $this->theme['template_engine'];
631                         }
632                 }
633
634                 if (isset($this->template_engines[$template_engine])) {
635                         if (isset($this->template_engine_instance[$template_engine])) {
636                                 return $this->template_engine_instance[$template_engine];
637                         } else {
638                                 $class = $this->template_engines[$template_engine];
639                                 $obj = new $class;
640                                 $this->template_engine_instance[$template_engine] = $obj;
641                                 return $obj;
642                         }
643                 }
644
645                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
646                 killme();
647         }
648
649         /**
650          * @brief Returns the active template engine.
651          *
652          * @return string
653          */
654         function get_template_engine() {
655                 return $this->theme['template_engine'];
656         }
657
658         function set_template_engine($engine = 'smarty3') {
659                 $this->theme['template_engine'] = $engine;
660         }
661
662         function get_template_ldelim($engine = 'smarty3') {
663                 return $this->ldelim[$engine];
664         }
665
666         function get_template_rdelim($engine = 'smarty3') {
667                 return $this->rdelim[$engine];
668         }
669
670         function save_timestamp($stamp, $value) {
671                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
672                         return;
673                 }
674
675                 $duration = (float) (microtime(true) - $stamp);
676
677                 if (!isset($this->performance[$value])) {
678                         // Prevent ugly E_NOTICE
679                         $this->performance[$value] = 0;
680                 }
681
682                 $this->performance[$value] += (float) $duration;
683                 $this->performance['marktime'] += (float) $duration;
684
685                 $callstack = System::callstack();
686
687                 if (!isset($this->callstack[$value][$callstack])) {
688                         // Prevent ugly E_NOTICE
689                         $this->callstack[$value][$callstack] = 0;
690                 }
691
692                 $this->callstack[$value][$callstack] += (float) $duration;
693         }
694
695         /**
696          * @brief Log active processes into the "process" table
697          */
698         function start_process() {
699                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
700
701                 $command = basename($trace[0]['file']);
702
703                 $this->remove_inactive_processes();
704
705                 dba::transaction();
706
707                 $r = q('SELECT `pid` FROM `process` WHERE `pid` = %d', intval(getmypid()));
708                 if (!DBM::is_result($r)) {
709                         dba::insert('process', array('pid' => getmypid(), 'command' => $command, 'created' => datetime_convert()));
710                 }
711                 dba::commit();
712         }
713
714         /**
715          * @brief Remove inactive processes
716          */
717         function remove_inactive_processes() {
718                 dba::transaction();
719
720                 $r = q('SELECT `pid` FROM `process`');
721                 if (DBM::is_result($r)) {
722                         foreach ($r AS $process) {
723                                 if (!posix_kill($process['pid'], 0)) {
724                                         dba::delete('process', array('pid' => $process['pid']));
725                                 }
726                         }
727                 }
728                 dba::commit();
729         }
730
731         /**
732          * @brief Remove the active process from the "process" table
733          */
734         function end_process() {
735                 dba::delete('process', array('pid' => getmypid()));
736         }
737
738         function get_useragent() {
739                 return
740                         FRIENDICA_PLATFORM . " '" .
741                         FRIENDICA_CODENAME . "' " .
742                         FRIENDICA_VERSION . '-' .
743                         DB_UPDATE_VERSION . '; ' .
744                         $this->get_baseurl();
745         }
746
747         function is_friendica_app() {
748                 return $this->is_friendica_app;
749         }
750
751         /**
752          * @brief Checks if the site is called via a backend process
753          *
754          * This isn't a perfect solution. But we need this check very early.
755          * So we cannot wait until the modules are loaded.
756          *
757          * @return bool Is it a known backend?
758          */
759         function is_backend() {
760                 static $backends = array();
761                 $backends[] = '_well_known';
762                 $backends[] = 'api';
763                 $backends[] = 'dfrn_notify';
764                 $backends[] = 'fetch';
765                 $backends[] = 'hcard';
766                 $backends[] = 'hostxrd';
767                 $backends[] = 'nodeinfo';
768                 $backends[] = 'noscrape';
769                 $backends[] = 'p';
770                 $backends[] = 'poco';
771                 $backends[] = 'post';
772                 $backends[] = 'proxy';
773                 $backends[] = 'pubsub';
774                 $backends[] = 'pubsubhubbub';
775                 $backends[] = 'receive';
776                 $backends[] = 'rsd_xml';
777                 $backends[] = 'salmon';
778                 $backends[] = 'statistics_json';
779                 $backends[] = 'xrd';
780
781                 // Check if current module is in backend or backend flag is set
782                 return (in_array($this->module, $backends) || $this->backend);
783         }
784
785         /**
786          * @brief Checks if the maximum number of database processes is reached
787          *
788          * @return bool Is the limit reached?
789          */
790         function max_processes_reached() {
791                 // Deactivated, needs more investigating if this check really makes sense
792                 return false;
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']) || ! 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 2 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) && ( time() - $result) < 2) {
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') || ! 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 && !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 }