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