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