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