]> git.mxchange.org Git - friendica.git/blob - src/App.php
Merge pull request #5370 from MrPetovan/develop
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use dba;
14
15 use Detection\MobileDetect;
16
17 use Exception;
18
19 require_once 'boot.php';
20 require_once 'include/text.php';
21
22 /**
23  *
24  * class: App
25  *
26  * @brief Our main application structure for the life of this page.
27  *
28  * Primarily deals with the URL that got us here
29  * and tries to make some sense of it, and
30  * stores our page contents and config storage
31  * and anything else that might need to be passed around
32  * before we spit the page out.
33  *
34  */
35 class App
36 {
37         const MODE_NORMAL = 0;
38         const MODE_INSTALL = 1;
39         const MODE_MAINTENANCE = 2;
40
41         public $module_loaded = false;
42         public $module_class = null;
43         public $query_string;
44         public $config;
45         public $page;
46         public $page_offset;
47         public $profile;
48         public $profile_uid;
49         public $user;
50         public $cid;
51         public $contact;
52         public $contacts;
53         public $page_contact;
54         public $content;
55         public $data = [];
56         public $error = false;
57         public $cmd;
58         public $argv;
59         public $argc;
60         public $module;
61         public $mode = App::MODE_NORMAL;
62         public $pager;
63         public $strings;
64         public $basepath;
65         public $path;
66         public $hooks;
67         public $timezone;
68         public $interactive = true;
69         public $addons;
70         public $addons_admin = [];
71         public $apps = [];
72         public $identities;
73         public $is_mobile = false;
74         public $is_tablet = false;
75         public $is_friendica_app;
76         public $performance = [];
77         public $callstack = [];
78         public $theme_info = [];
79         public $backend = true;
80         public $nav_sel;
81         public $category;
82         // Allow themes to control internal parameters
83         // by changing App values in theme.php
84
85         public $sourcename = '';
86         public $videowidth = 425;
87         public $videoheight = 350;
88         public $force_max_items = 0;
89         public $theme_events_in_profile = true;
90
91         /**
92          * @brief An array for all theme-controllable parameters
93          *
94          * Mostly unimplemented yet. Only options 'template_engine' and
95          * beyond are used.
96          */
97         public $theme = [
98                 'sourcename' => '',
99                 'videowidth' => 425,
100                 'videoheight' => 350,
101                 'force_max_items' => 0,
102                 'stylesheet' => '',
103                 'template_engine' => 'smarty3',
104         ];
105
106         /**
107          * @brief An array of registered template engines ('name'=>'class name')
108          */
109         public $template_engines = [];
110
111         /**
112          * @brief An array of instanced template engines ('name'=>'instance')
113          */
114         public $template_engine_instance = [];
115         public $process_id;
116         public $queue;
117         private $ldelim = [
118                 'internal' => '',
119                 'smarty3' => '{{'
120         ];
121         private $rdelim = [
122                 'internal' => '',
123                 'smarty3' => '}}'
124         ];
125         private $scheme;
126         private $hostname;
127         private $curl_code;
128         private $curl_content_type;
129         private $curl_headers;
130         private static $a;
131
132         /**
133          * @brief App constructor.
134          *
135          * @param string $basepath Path to the app base folder
136          */
137         public function __construct($basepath)
138         {
139                 global $default_timezone;
140
141                 if (!static::directory_usable($basepath, false)) {
142                         throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
143                 }
144
145                 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
146
147                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
148                         include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
149                 }
150
151                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
152
153                 date_default_timezone_set($this->timezone);
154
155                 $this->performance['start'] = microtime(true);
156                 $this->performance['database'] = 0;
157                 $this->performance['database_write'] = 0;
158                 $this->performance['cache'] = 0;
159                 $this->performance['cache_write'] = 0;
160                 $this->performance['network'] = 0;
161                 $this->performance['file'] = 0;
162                 $this->performance['rendering'] = 0;
163                 $this->performance['parser'] = 0;
164                 $this->performance['marktime'] = 0;
165                 $this->performance['markstart'] = microtime(true);
166
167                 $this->callstack['database'] = [];
168                 $this->callstack['database_write'] = [];
169                 $this->callstack['cache'] = [];
170                 $this->callstack['cache_write'] = [];
171                 $this->callstack['network'] = [];
172                 $this->callstack['file'] = [];
173                 $this->callstack['rendering'] = [];
174                 $this->callstack['parser'] = [];
175
176                 $this->config = [];
177
178                 $this->page = [
179                         'aside' => '',
180                         'bottom' => '',
181                         'content' => '',
182                         'end' => '',
183                         'footer' => '',
184                         'htmlhead' => '',
185                         'nav' => '',
186                         'page_title' => '',
187                         'right_aside' => '',
188                         'template' => '',
189                         'title' => ''
190                 ];
191
192                 $this->pager = [];
193
194                 $this->query_string = '';
195
196                 $this->process_id = System::processID('log');
197
198                 set_time_limit(0);
199
200                 // This has to be quite large to deal with embedded private photos
201                 ini_set('pcre.backtrack_limit', 500000);
202
203                 $this->scheme = 'http';
204
205                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
206                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
207                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
208                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
209                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
210                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
211                 ) {
212                         $this->scheme = 'https';
213                 }
214
215                 if (x($_SERVER, 'SERVER_NAME')) {
216                         $this->hostname = $_SERVER['SERVER_NAME'];
217
218                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
219                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
220                         }
221                         /*
222                          * Figure out if we are running at the top of a domain
223                          * or in a sub-directory and adjust accordingly
224                          */
225
226                         /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
227                         $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
228                         if (isset($path) && strlen($path) && ($path != $this->path)) {
229                                 $this->path = $path;
230                         }
231                 }
232
233                 set_include_path(
234                         get_include_path() . PATH_SEPARATOR
235                         . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
236                         . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
237                         . $this->basepath);
238
239                 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
240                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
241
242                         // removing trailing / - maybe a nginx problem
243                         $this->query_string = ltrim($this->query_string, '/');
244                 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
245                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
246
247                         // removing trailing / - maybe a nginx problem
248                         $this->query_string = ltrim($this->query_string, '/');
249                 }
250
251                 if (x($_GET, 'pagename')) {
252                         $this->cmd = trim($_GET['pagename'], '/\\');
253                 } elseif (x($_GET, 'q')) {
254                         $this->cmd = trim($_GET['q'], '/\\');
255                 }
256
257                 // fix query_string
258                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
259
260                 // unix style "homedir"
261                 if (substr($this->cmd, 0, 1) === '~') {
262                         $this->cmd = 'profile/' . substr($this->cmd, 1);
263                 }
264
265                 // Diaspora style profile url
266                 if (substr($this->cmd, 0, 2) === 'u/') {
267                         $this->cmd = 'profile/' . substr($this->cmd, 2);
268                 }
269
270                 /*
271                  * Break the URL path into C style argc/argv style arguments for our
272                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
273                  * will be 3 (integer) and $this->argv will contain:
274                  *   [0] => 'module'
275                  *   [1] => 'arg1'
276                  *   [2] => 'arg2'
277                  *
278                  *
279                  * There will always be one argument. If provided a naked domain
280                  * URL, $this->argv[0] is set to "home".
281                  */
282
283                 $this->argv = explode('/', $this->cmd);
284                 $this->argc = count($this->argv);
285                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
286                         $this->module = str_replace('.', '_', $this->argv[0]);
287                         $this->module = str_replace('-', '_', $this->module);
288                 } else {
289                         $this->argc = 1;
290                         $this->argv = ['home'];
291                         $this->module = 'home';
292                 }
293
294                 // See if there is any page number information, and initialise pagination
295                 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
296                 $this->pager['itemspage'] = 50;
297                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
298
299                 if ($this->pager['start'] < 0) {
300                         $this->pager['start'] = 0;
301                 }
302                 $this->pager['total'] = 0;
303
304                 // Detect mobile devices
305                 $mobile_detect = new MobileDetect();
306                 $this->is_mobile = $mobile_detect->isMobile();
307                 $this->is_tablet = $mobile_detect->isTablet();
308
309                 // Friendica-Client
310                 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
311
312                 // Register template engines
313                 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
314
315                 /**
316                  * Load the configuration file which contains our DB credentials.
317                  * Ignore errors. If the file doesn't exist or is empty, we are running in
318                  * installation mode.    *
319                  */
320                 $this->mode = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? App::MODE_NORMAL : App::MODE_INSTALL);
321
322
323                 self::$a = $this;
324         }
325
326         /**
327          * @brief Returns the base filesystem path of the App
328          *
329          * It first checks for the internal variable, then for DOCUMENT_ROOT and
330          * finally for PWD
331          *
332          * @return string
333          */
334         public function get_basepath()
335         {
336                 $basepath = $this->basepath;
337
338                 if (!$basepath) {
339                         $basepath = Config::get('system', 'basepath');
340                 }
341
342                 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
343                         $basepath = $_SERVER['DOCUMENT_ROOT'];
344                 }
345
346                 if (!$basepath && x($_SERVER, 'PWD')) {
347                         $basepath = $_SERVER['PWD'];
348                 }
349
350                 return self::realpath($basepath);
351         }
352
353         /**
354          * @brief Returns a normalized file path
355          *
356          * This is a wrapper for the "realpath" function.
357          * That function cannot detect the real path when some folders aren't readable.
358          * Since this could happen with some hosters we need to handle this.
359          *
360          * @param string $path The path that is about to be normalized
361          * @return string normalized path - when possible
362          */
363         public static function realpath($path)
364         {
365                 $normalized = realpath($path);
366
367                 if (!is_bool($normalized)) {
368                         return $normalized;
369                 } else {
370                         return $path;
371                 }
372         }
373
374         public function get_scheme()
375         {
376                 return $this->scheme;
377         }
378
379         /**
380          * @brief Retrieves the Friendica instance base URL
381          *
382          * This function assembles the base URL from multiple parts:
383          * - Protocol is determined either by the request or a combination of
384          * system.ssl_policy and the $ssl parameter.
385          * - Host name is determined either by system.hostname or inferred from request
386          * - Path is inferred from SCRIPT_NAME
387          *
388          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
389          *
390          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
391          * @return string Friendica server base URL
392          */
393         public function get_baseurl($ssl = false)
394         {
395                 $scheme = $this->scheme;
396
397                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
398                         $scheme = 'https';
399                 }
400
401                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
402                 //      (and also the login link). Anything seen by an outsider will have it turned off.
403
404                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
405                         if ($ssl) {
406                                 $scheme = 'https';
407                         } else {
408                                 $scheme = 'http';
409                         }
410                 }
411
412                 if (Config::get('config', 'hostname') != '') {
413                         $this->hostname = Config::get('config', 'hostname');
414                 }
415
416                 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
417         }
418
419         /**
420          * @brief Initializes the baseurl components
421          *
422          * Clears the baseurl cache to prevent inconsistencies
423          *
424          * @param string $url
425          */
426         public function set_baseurl($url)
427         {
428                 $parsed = @parse_url($url);
429                 $hostname = '';
430
431                 if (x($parsed)) {
432                         if (!empty($parsed['scheme'])) {
433                                 $this->scheme = $parsed['scheme'];
434                         }
435
436                         if (!empty($parsed['host'])) {
437                                 $hostname = $parsed['host'];
438                         }
439
440                         if (x($parsed, 'port')) {
441                                 $hostname .= ':' . $parsed['port'];
442                         }
443                         if (x($parsed, 'path')) {
444                                 $this->path = trim($parsed['path'], '\\/');
445                         }
446
447                         if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
448                                 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
449                         }
450
451                         if (Config::get('config', 'hostname') != '') {
452                                 $this->hostname = Config::get('config', 'hostname');
453                         }
454
455                         if (!isset($this->hostname) || ($this->hostname == '')) {
456                                 $this->hostname = $hostname;
457                         }
458                 }
459         }
460
461         public function get_hostname()
462         {
463                 if (Config::get('config', 'hostname') != '') {
464                         $this->hostname = Config::get('config', 'hostname');
465                 }
466
467                 return $this->hostname;
468         }
469
470         public function get_path()
471         {
472                 return $this->path;
473         }
474
475         public function set_pager_total($n)
476         {
477                 $this->pager['total'] = intval($n);
478         }
479
480         public function set_pager_itemspage($n)
481         {
482                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
483                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
484         }
485
486         public function set_pager_page($n)
487         {
488                 $this->pager['page'] = $n;
489                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
490         }
491
492         public function init_pagehead()
493         {
494                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
495
496                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
497                 if ($interval < 0) {
498                         $interval = 2147483647;
499                 }
500
501                 if ($interval < 10000) {
502                         $interval = 40000;
503                 }
504
505                 // compose the page title from the sitename and the
506                 // current module called
507                 if (!$this->module == '') {
508                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
509                 } else {
510                         $this->page['title'] = $this->config['sitename'];
511                 }
512
513                 /* put the head template at the beginning of page['htmlhead']
514                  * since the code added by the modules frequently depends on it
515                  * being first
516                  */
517                 if (!isset($this->page['htmlhead'])) {
518                         $this->page['htmlhead'] = '';
519                 }
520
521                 // If we're using Smarty, then doing replace_macros() will replace
522                 // any unrecognized variables with a blank string. Since we delay
523                 // replacing $stylesheet until later, we need to replace it now
524                 // with another variable name
525                 if ($this->theme['template_engine'] === 'smarty3') {
526                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
527                 } else {
528                         $stylesheet = '$stylesheet';
529                 }
530
531                 $shortcut_icon = Config::get('system', 'shortcut_icon');
532                 if ($shortcut_icon == '') {
533                         $shortcut_icon = 'images/friendica-32.png';
534                 }
535
536                 $touch_icon = Config::get('system', 'touch_icon');
537                 if ($touch_icon == '') {
538                         $touch_icon = 'images/friendica-128.png';
539                 }
540
541                 // get data wich is needed for infinite scroll on the network page
542                 $invinite_scroll = infinite_scroll_data($this->module);
543
544                 $tpl = get_markup_template('head.tpl');
545                 $this->page['htmlhead'] = replace_macros($tpl, [
546                         '$baseurl'         => $this->get_baseurl(),
547                         '$local_user'      => local_user(),
548                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
549                         '$delitem'         => L10n::t('Delete this item?'),
550                         '$showmore'        => L10n::t('show more'),
551                         '$showfewer'       => L10n::t('show fewer'),
552                         '$update_interval' => $interval,
553                         '$shortcut_icon'   => $shortcut_icon,
554                         '$touch_icon'      => $touch_icon,
555                         '$stylesheet'      => $stylesheet,
556                         '$infinite_scroll' => $invinite_scroll,
557                         '$block_public'    => intval(Config::get('system', 'block_public')),
558                 ]) . $this->page['htmlhead'];
559         }
560
561         public function init_page_end()
562         {
563                 if (!isset($this->page['end'])) {
564                         $this->page['end'] = '';
565                 }
566                 $tpl = get_markup_template('end.tpl');
567                 $this->page['end'] = replace_macros($tpl, [
568                         '$baseurl' => $this->get_baseurl()
569                 ]) . $this->page['end'];
570         }
571
572         public function set_curl_code($code)
573         {
574                 $this->curl_code = $code;
575         }
576
577         public function get_curl_code()
578         {
579                 return $this->curl_code;
580         }
581
582         public function set_curl_content_type($content_type)
583         {
584                 $this->curl_content_type = $content_type;
585         }
586
587         public function get_curl_content_type()
588         {
589                 return $this->curl_content_type;
590         }
591
592         public function set_curl_headers($headers)
593         {
594                 $this->curl_headers = $headers;
595         }
596
597         public function get_curl_headers()
598         {
599                 return $this->curl_headers;
600         }
601
602         /**
603          * @brief Removes the base url from an url. This avoids some mixed content problems.
604          *
605          * @param string $orig_url
606          *
607          * @return string The cleaned url
608          */
609         public function remove_baseurl($orig_url)
610         {
611                 // Remove the hostname from the url if it is an internal link
612                 $nurl = normalise_link($orig_url);
613                 $base = normalise_link($this->get_baseurl());
614                 $url = str_replace($base . '/', '', $nurl);
615
616                 // if it is an external link return the orignal value
617                 if ($url == normalise_link($orig_url)) {
618                         return $orig_url;
619                 } else {
620                         return $url;
621                 }
622         }
623
624         /**
625          * @brief Register template engine class
626          *
627          * @param string $class
628          */
629         private function register_template_engine($class)
630         {
631                 $v = get_class_vars($class);
632                 if (x($v, 'name')) {
633                         $name = $v['name'];
634                         $this->template_engines[$name] = $class;
635                 } else {
636                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
637                         die();
638                 }
639         }
640
641         /**
642          * @brief Return template engine instance.
643          *
644          * If $name is not defined, return engine defined by theme,
645          * or default
646          *
647          * @return object Template Engine instance
648          */
649         public function template_engine()
650         {
651                 $template_engine = 'smarty3';
652                 if (x($this->theme, 'template_engine')) {
653                         $template_engine = $this->theme['template_engine'];
654                 }
655
656                 if (isset($this->template_engines[$template_engine])) {
657                         if (isset($this->template_engine_instance[$template_engine])) {
658                                 return $this->template_engine_instance[$template_engine];
659                         } else {
660                                 $class = $this->template_engines[$template_engine];
661                                 $obj = new $class;
662                                 $this->template_engine_instance[$template_engine] = $obj;
663                                 return $obj;
664                         }
665                 }
666
667                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
668                 killme();
669         }
670
671         /**
672          * @brief Returns the active template engine.
673          *
674          * @return string
675          */
676         public function get_template_engine()
677         {
678                 return $this->theme['template_engine'];
679         }
680
681         public function set_template_engine($engine = 'smarty3')
682         {
683                 $this->theme['template_engine'] = $engine;
684         }
685
686         public function get_template_ldelim($engine = 'smarty3')
687         {
688                 return $this->ldelim[$engine];
689         }
690
691         public function get_template_rdelim($engine = 'smarty3')
692         {
693                 return $this->rdelim[$engine];
694         }
695
696         public function save_timestamp($stamp, $value)
697         {
698                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
699                         return;
700                 }
701
702                 $duration = (float) (microtime(true) - $stamp);
703
704                 if (!isset($this->performance[$value])) {
705                         // Prevent ugly E_NOTICE
706                         $this->performance[$value] = 0;
707                 }
708
709                 $this->performance[$value] += (float) $duration;
710                 $this->performance['marktime'] += (float) $duration;
711
712                 $callstack = System::callstack();
713
714                 if (!isset($this->callstack[$value][$callstack])) {
715                         // Prevent ugly E_NOTICE
716                         $this->callstack[$value][$callstack] = 0;
717                 }
718
719                 $this->callstack[$value][$callstack] += (float) $duration;
720         }
721
722         public function get_useragent()
723         {
724                 return
725                         FRIENDICA_PLATFORM . " '" .
726                         FRIENDICA_CODENAME . "' " .
727                         FRIENDICA_VERSION . '-' .
728                         DB_UPDATE_VERSION . '; ' .
729                         $this->get_baseurl();
730         }
731
732         public function is_friendica_app()
733         {
734                 return $this->is_friendica_app;
735         }
736
737         /**
738          * @brief Checks if the site is called via a backend process
739          *
740          * This isn't a perfect solution. But we need this check very early.
741          * So we cannot wait until the modules are loaded.
742          *
743          * @return bool Is it a known backend?
744          */
745         public function is_backend()
746         {
747                 static $backends = [
748                         '_well_known',
749                         'api',
750                         'dfrn_notify',
751                         'fetch',
752                         'hcard',
753                         'hostxrd',
754                         'nodeinfo',
755                         'noscrape',
756                         'p',
757                         'poco',
758                         'post',
759                         'proxy',
760                         'pubsub',
761                         'pubsubhubbub',
762                         'receive',
763                         'rsd_xml',
764                         'salmon',
765                         'statistics_json',
766                         'xrd',
767                 ];
768
769                 // Check if current module is in backend or backend flag is set
770                 return (in_array($this->module, $backends) || $this->backend);
771         }
772
773         /**
774          * @brief Checks if the maximum number of database processes is reached
775          *
776          * @return bool Is the limit reached?
777          */
778         public function max_processes_reached()
779         {
780                 // Deactivated, needs more investigating if this check really makes sense
781                 return false;
782
783                 /*
784                  * Commented out to suppress static analyzer issues
785                  *
786                 if ($this->is_backend()) {
787                         $process = 'backend';
788                         $max_processes = Config::get('system', 'max_processes_backend');
789                         if (intval($max_processes) == 0) {
790                                 $max_processes = 5;
791                         }
792                 } else {
793                         $process = 'frontend';
794                         $max_processes = Config::get('system', 'max_processes_frontend');
795                         if (intval($max_processes) == 0) {
796                                 $max_processes = 20;
797                         }
798                 }
799
800                 $processlist = DBM::processlist();
801                 if ($processlist['list'] != '') {
802                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
803
804                         if ($processlist['amount'] > $max_processes) {
805                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
806                                 return true;
807                         }
808                 }
809                 return false;
810                  */
811         }
812
813         /**
814          * @brief Checks if the minimal memory is reached
815          *
816          * @return bool Is the memory limit reached?
817          */
818         public function min_memory_reached()
819         {
820                 $min_memory = Config::get('system', 'min_memory', 0);
821                 if ($min_memory == 0) {
822                         return false;
823                 }
824
825                 if (!is_readable('/proc/meminfo')) {
826                         return false;
827                 }
828
829                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
830
831                 $meminfo = [];
832                 foreach ($memdata as $line) {
833                         list($key, $val) = explode(':', $line);
834                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
835                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
836                 }
837
838                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
839                         return false;
840                 }
841
842                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
843
844                 $reached = ($free < $min_memory);
845
846                 if ($reached) {
847                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
848                 }
849
850                 return $reached;
851         }
852
853         /**
854          * @brief Checks if the maximum load is reached
855          *
856          * @return bool Is the load reached?
857          */
858         public function maxload_reached()
859         {
860                 if ($this->is_backend()) {
861                         $process = 'backend';
862                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
863                         if ($maxsysload < 1) {
864                                 $maxsysload = 50;
865                         }
866                 } else {
867                         $process = 'frontend';
868                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
869                         if ($maxsysload < 1) {
870                                 $maxsysload = 50;
871                         }
872                 }
873
874                 $load = current_load();
875                 if ($load) {
876                         if (intval($load) > $maxsysload) {
877                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
878                                 return true;
879                         }
880                 }
881                 return false;
882         }
883
884         public function proc_run($args)
885         {
886                 if (!function_exists('proc_open')) {
887                         return;
888                 }
889
890                 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
891
892                 for ($x = 0; $x < count($args); $x ++) {
893                         $args[$x] = escapeshellarg($args[$x]);
894                 }
895
896                 $cmdline = implode(' ', $args);
897
898                 if ($this->min_memory_reached()) {
899                         return;
900                 }
901
902                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
903                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
904                 } else {
905                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
906                 }
907                 if (!is_resource($resource)) {
908                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
909                         return;
910                 }
911                 proc_close($resource);
912         }
913
914         /**
915          * @brief Returns the system user that is executing the script
916          *
917          * This mostly returns something like "www-data".
918          *
919          * @return string system username
920          */
921         private static function systemuser()
922         {
923                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
924                         return '';
925                 }
926
927                 $processUser = posix_getpwuid(posix_geteuid());
928                 return $processUser['name'];
929         }
930
931         /**
932          * @brief Checks if a given directory is usable for the system
933          *
934          * @return boolean the directory is usable
935          */
936         public static function directory_usable($directory, $check_writable = true)
937         {
938                 if ($directory == '') {
939                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
940                         return false;
941                 }
942
943                 if (!file_exists($directory)) {
944                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
945                         return false;
946                 }
947
948                 if (is_file($directory)) {
949                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
950                         return false;
951                 }
952
953                 if (!is_dir($directory)) {
954                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
955                         return false;
956                 }
957
958                 if ($check_writable && !is_writable($directory)) {
959                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
960                         return false;
961                 }
962
963                 return true;
964         }
965
966         /**
967          * @param string $cat     Config category
968          * @param string $k       Config key
969          * @param mixed  $default Default value if it isn't set
970          */
971         public function getConfigValue($cat, $k, $default = null)
972         {
973                 $return = $default;
974
975                 if ($cat === 'config') {
976                         if (isset($this->config[$k])) {
977                                 $return = $this->config[$k];
978                         }
979                 } else {
980                         if (isset($this->config[$cat][$k])) {
981                                 $return = $this->config[$cat][$k];
982                         }
983                 }
984
985                 return $return;
986         }
987
988         /**
989          * Sets a value in the config cache. Accepts raw output from the config table
990          *
991          * @param string $cat Config category
992          * @param string $k   Config key
993          * @param mixed  $v   Value to set
994          */
995         public function setConfigValue($cat, $k, $v)
996         {
997                 // Only arrays are serialized in database, so we have to unserialize sparingly
998                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
999
1000                 if ($cat === 'config') {
1001                         $this->config[$k] = $value;
1002                 } else {
1003                         if (!isset($this->config[$cat])) {
1004                                 $this->config[$cat] = [];
1005                         }
1006
1007                         $this->config[$cat][$k] = $value;
1008                 }
1009         }
1010
1011         /**
1012          * Deletes a value from the config cache
1013          *
1014          * @param string $cat Config category
1015          * @param string $k   Config key
1016          */
1017         public function deleteConfigValue($cat, $k)
1018         {
1019                 if ($cat === 'config') {
1020                         if (isset($this->config[$k])) {
1021                                 unset($this->config[$k]);
1022                         }
1023                 } else {
1024                         if (isset($this->config[$cat][$k])) {
1025                                 unset($this->config[$cat][$k]);
1026                         }
1027                 }
1028         }
1029
1030
1031         /**
1032          * Retrieves a value from the user config cache
1033          *
1034          * @param int    $uid     User Id
1035          * @param string $cat     Config category
1036          * @param string $k       Config key
1037          * @param mixed  $default Default value if key isn't set
1038          */
1039         public function getPConfigValue($uid, $cat, $k, $default = null)
1040         {
1041                 $return = $default;
1042
1043                 if (isset($this->config[$uid][$cat][$k])) {
1044                         $return = $this->config[$uid][$cat][$k];
1045                 }
1046
1047                 return $return;
1048         }
1049
1050         /**
1051          * Sets a value in the user config cache
1052          *
1053          * Accepts raw output from the pconfig table
1054          *
1055          * @param int    $uid User Id
1056          * @param string $cat Config category
1057          * @param string $k   Config key
1058          * @param mixed  $v   Value to set
1059          */
1060         public function setPConfigValue($uid, $cat, $k, $v)
1061         {
1062                 // Only arrays are serialized in database, so we have to unserialize sparingly
1063                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1064
1065                 if (!isset($this->config[$uid])) {
1066                         $this->config[$uid] = [];
1067                 }
1068
1069                 if (!isset($this->config[$uid][$cat])) {
1070                         $this->config[$uid][$cat] = [];
1071                 }
1072
1073                 $this->config[$uid][$cat][$k] = $value;
1074         }
1075
1076         /**
1077          * Deletes a value from the user config cache
1078          *
1079          * @param int    $uid User Id
1080          * @param string $cat Config category
1081          * @param string $k   Config key
1082          */
1083         public function deletePConfigValue($uid, $cat, $k)
1084         {
1085                 if (isset($this->config[$uid][$cat][$k])) {
1086                         unset($this->config[$uid][$cat][$k]);
1087                 }
1088         }
1089
1090         /**
1091          * Generates the site's default sender email address
1092          *
1093          * @return string
1094          */
1095         public function getSenderEmailAddress()
1096         {
1097                 $sender_email = Config::get('config', 'sender_email');
1098                 if (empty($sender_email)) {
1099                         $hostname = $this->get_hostname();
1100                         if (strpos($hostname, ':')) {
1101                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1102                         }
1103
1104                         $sender_email = 'noreply@' . $hostname;
1105                 }
1106
1107                 return $sender_email;
1108         }
1109
1110         /**
1111          * @note Checks, if the App is in the Maintenance-Mode
1112          *
1113          * @return boolean
1114          */
1115         public function checkMaintenanceMode()
1116         {
1117                 if (Config::get('system', 'maintenance')) {
1118                         $this->mode = App::MODE_MAINTENANCE;
1119                         return true;
1120                 }
1121
1122                 return false;
1123         }
1124
1125         /**
1126          * Returns the current theme name.
1127          *
1128          * @return string
1129          */
1130         public function getCurrentTheme()
1131         {
1132                 if ($this->mode == App::MODE_INSTALL) {
1133                         return '';
1134                 }
1135
1136                 //// @TODO Compute the current theme only once (this behavior has
1137                 /// already been implemented, but it didn't work well -
1138                 /// https://github.com/friendica/friendica/issues/5092)
1139                 $this->computeCurrentTheme();
1140
1141                 return $this->current_theme;
1142         }
1143
1144         /**
1145          * Computes the current theme name based on the node settings, the user settings and the device type
1146          *
1147          * @throws Exception
1148          */
1149         private function computeCurrentTheme()
1150         {
1151                 $system_theme = Config::get('system', 'theme');
1152                 if (!$system_theme) {
1153                         throw new Exception(L10n::t('No system theme config value set.'));
1154                 }
1155
1156                 // Sane default
1157                 $this->current_theme = $system_theme;
1158
1159                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1160
1161                 $page_theme = null;
1162                 // Find the theme that belongs to the user whose stuff we are looking at
1163                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1164                         // Allow folks to override user themes and always use their own on their own site.
1165                         // This works only if the user is on the same server
1166                         $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1167                         if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1168                                 $page_theme = $user['theme'];
1169                         }
1170                 }
1171
1172                 if (!empty($_SESSION)) {
1173                         $user_theme = defaults($_SESSION, 'theme', $system_theme);
1174                 } else {
1175                         $user_theme = $system_theme;
1176                 }
1177
1178                 // Specific mobile theme override
1179                 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1180                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1181                         $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1182
1183                         // --- means same mobile theme as desktop
1184                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1185                                 $user_theme = $user_mobile_theme;
1186                         }
1187                 }
1188
1189                 if ($page_theme) {
1190                         $theme_name = $page_theme;
1191                 } else {
1192                         $theme_name = $user_theme;
1193                 }
1194
1195                 if ($theme_name
1196                         && in_array($theme_name, $allowed_themes)
1197                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1198                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1199                 ) {
1200                         $this->current_theme = $theme_name;
1201                 }
1202         }
1203
1204         /**
1205          * @brief Return full URL to theme which is currently in effect.
1206          *
1207          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1208          *
1209          * @return string
1210          */
1211         public function getCurrentThemeStylesheetPath()
1212         {
1213                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1214         }
1215 }