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