]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
44249175a72341540ace92e1bb6294dacc70779e
[friendica.git] / src / Core / System.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Exception;
25 use Friendica\App;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
27 use Friendica\DI;
28 use Friendica\Network\HTTPException\FoundException;
29 use Friendica\Network\HTTPException\MovedPermanentlyException;
30 use Friendica\Network\HTTPException\TemporaryRedirectException;
31 use Friendica\Util\BasePath;
32 use Friendica\Util\XML;
33 use Psr\Log\LoggerInterface;
34
35 /**
36  * Contains the class with system relevant stuff
37  */
38 class System
39 {
40         /**
41          * @var LoggerInterface
42          */
43         private $logger;
44
45         /**
46          * @var App\Mode
47          */
48         private $mode;
49
50         /**
51          * @var IManageConfigValues
52          */
53         private $config;
54
55         /**
56          * @var string
57          */
58         private $basePath;
59
60         public function __construct(LoggerInterface $logger, App\Mode $mode, IManageConfigValues $config, string $basepath)
61         {
62                 $this->logger   = $logger;
63                 $this->mode     = $mode;
64                 $this->config   = $config;
65                 $this->basePath = $basepath;
66         }
67
68         /**
69          * Checks if the maximum number of database processes is reached
70          *
71          * @return bool Is the limit reached?
72          */
73         public function isMaxProcessesReached(): bool
74         {
75                 // Deactivated, needs more investigating if this check really makes sense
76                 return false;
77
78                 /*
79                  * Commented out to suppress static analyzer issues
80                  *
81                 if ($this->mode->isBackend()) {
82                         $process = 'backend';
83                         $max_processes = $this->config->get('system', 'max_processes_backend');
84                         if (intval($max_processes) == 0) {
85                                 $max_processes = 5;
86                         }
87                 } else {
88                         $process = 'frontend';
89                         $max_processes = $this->config->get('system', 'max_processes_frontend');
90                         if (intval($max_processes) == 0) {
91                                 $max_processes = 20;
92                         }
93                 }
94
95                 $processlist = DBA::processlist();
96                 if ($processlist['list'] != '') {
97                         $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
98
99                         if ($processlist['amount'] > $max_processes) {
100                                 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
101                                 return true;
102                         }
103                 }
104                 return false;
105                  */
106         }
107
108         /**
109          * Checks if the minimal memory is reached
110          *
111          * @return bool Is the memory limit reached?
112          */
113         public function isMinMemoryReached(): bool
114         {
115                 $min_memory = $this->config->get('system', 'min_memory', 0);
116                 if ($min_memory == 0) {
117                         return false;
118                 }
119
120                 if (!is_readable('/proc/meminfo')) {
121                         return false;
122                 }
123
124                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
125
126                 $meminfo = [];
127                 foreach ($memdata as $line) {
128                         $data = explode(':', $line);
129                         if (count($data) != 2) {
130                                 continue;
131                         }
132                         [$key, $val]     = $data;
133                         $meminfo[$key]   = (int)trim(str_replace('kB', '', $val));
134                         $meminfo[$key]   = (int)($meminfo[$key] / 1024);
135                 }
136
137                 if (!isset($meminfo['MemFree'])) {
138                         return false;
139                 }
140
141                 $free = $meminfo['MemFree'];
142
143                 $reached = ($free < $min_memory);
144
145                 if ($reached) {
146                         $this->logger->warning('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
147                 }
148
149                 return $reached;
150         }
151
152         /**
153          * Checks if the maximum load is reached
154          *
155          * @return bool Is the load reached?
156          */
157         public function isMaxLoadReached(): bool
158         {
159                 if ($this->mode->isBackend()) {
160                         $process    = 'backend';
161                         $maxsysload = intval($this->config->get('system', 'maxloadavg'));
162                         if ($maxsysload < 1) {
163                                 $maxsysload = 50;
164                         }
165                 } else {
166                         $process    = 'frontend';
167                         $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
168                         if ($maxsysload < 1) {
169                                 $maxsysload = 50;
170                         }
171                 }
172
173                 $load = System::currentLoad();
174                 if ($load) {
175                         if (intval($load) > $maxsysload) {
176                                 $this->logger->warning('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]);
177                                 return true;
178                         }
179                 }
180                 return false;
181         }
182
183         /**
184          * Executes a child process with 'proc_open'
185          *
186          * @param string $command The command to execute
187          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
188          */
189         public function run(string $command, array $args)
190         {
191                 if (!function_exists('proc_open')) {
192                         $this->logger->warning('"proc_open" not available - quitting');
193                         return;
194                 }
195
196                 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
197
198                 foreach ($args as $key => $value) {
199                         if (!is_null($value) && is_bool($value) && !$value) {
200                                 continue;
201                         }
202
203                         $cmdline .= ' --' . $key;
204                         if (!is_null($value) && !is_bool($value)) {
205                                 $cmdline .= ' ' . $value;
206                         }
207                 }
208
209                 if ($this->isMinMemoryReached()) {
210                         $this->logger->warning('Memory limit reached - quitting');
211                         return;
212                 }
213
214                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
215                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
216                 } else {
217                         $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
218                 }
219
220                 if (!is_resource($resource)) {
221                         $this->logger->warning('We got no resource for command.', ['command' => $cmdline]);
222                         return;
223                 }
224
225                 proc_close($resource);
226
227                 $this->logger->info('Executed "proc_open"', ['command' => $cmdline, 'callstack' => System::callstack(10)]);
228         }
229
230         /**
231          * Returns a string with a callstack. Can be used for logging.
232          *
233          * @param integer $depth  How many calls to include in the stacks after filtering
234          * @param int     $offset How many calls to shave off the top of the stack, for example if
235          *                        this is called from a centralized method that isn't relevant to the callstack
236          * @return string
237          */
238         public static function callstack(int $depth = 4, int $offset = 0): string
239         {
240                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
241
242                 // We remove at least the first two items from the list since they contain data that we don't need.
243                 $trace = array_slice($trace, 2 + $offset);
244
245                 $callstack = [];
246                 $previous = ['class' => '', 'function' => '', 'database' => false];
247
248                 // The ignore list contains all functions that are only wrapper functions
249                 $ignore = ['call_user_func_array'];
250
251                 while ($func = array_pop($trace)) {
252                         if (!empty($func['class'])) {
253                                 if (in_array($previous['function'], ['insert', 'fetch', 'toArray', 'exists', 'count', 'selectFirst', 'selectToArray',
254                                         'select', 'update', 'delete', 'selectFirstForUser', 'selectForUser'])
255                                         && (substr($previous['class'], 0, 15) === 'Friendica\Model')) {
256                                         continue;
257                                 }
258
259                                 // Don't show multiple calls from the Database classes to show the essential parts of the callstack
260                                 $func['database'] = in_array($func['class'], ['Friendica\Database\DBA', 'Friendica\Database\Database']);
261                                 if (!$previous['database'] || !$func['database']) {     
262                                         $classparts = explode("\\", $func['class']);
263                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
264                                         $previous = $func;
265                                 }
266                         } elseif (!in_array($func['function'], $ignore)) {
267                                 $func['database'] = ($func['function'] == 'q');
268                                 $callstack[] = $func['function'];
269                                 $func['class'] = '';
270                                 $previous = $func;
271                         }
272                 }
273
274                 $callstack2 = [];
275                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
276                         $callstack2[] = array_pop($callstack);
277                 }
278
279                 return implode(', ', $callstack2);
280         }
281
282         /**
283          * Generic XML return
284          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
285          * of $st and an optional text <message> of $message and terminates the current process.
286          *
287          * @param        $st
288          * @param string $message
289          * @throws \Exception
290          */
291         public static function xmlExit($st, $message = '')
292         {
293                 $result = ['status' => $st];
294
295                 if ($message != '') {
296                         $result['message'] = $message;
297                 }
298
299                 if ($st) {
300                         Logger::notice('xml_status returning non_zero: ' . $st . " message=" . $message);
301                 }
302
303                 header("Content-type: text/xml");
304
305                 $xmldata = ["result" => $result];
306
307                 echo XML::fromArray($xmldata, $xml);
308
309                 exit();
310         }
311
312         /**
313          * Send HTTP status header and exit.
314          *
315          * @param integer $val     HTTP status result value
316          * @param string  $message Error message. Optional.
317          * @param string  $content Response body. Optional.
318          * @throws \Exception
319          */
320         public static function httpExit($val, $message = '', $content = '')
321         {
322                 if ($val >= 400) {
323                         Logger::debug('Exit with error', ['code' => $val, 'message' => $message, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
324                 }
325                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
326
327                 echo $content;
328
329                 exit();
330         }
331
332         public static function jsonError($httpCode, $data, $content_type = 'application/json')
333         {
334                 if ($httpCode >= 400) {
335                         Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
336                 }
337                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
338                 self::jsonExit($data, $content_type);
339         }
340
341         /**
342          * Encodes content to json.
343          *
344          * This function encodes an array to json format
345          * and adds an application/json HTTP header to the output.
346          * After finishing the process is getting killed.
347          *
348          * @param mixed   $x The input content.
349          * @param string  $content_type Type of the input (Default: 'application/json').
350          * @param integer $options JSON options
351          */
352         public static function jsonExit($x, $content_type = 'application/json', int $options = 0) {
353                 header("Content-type: $content_type");
354                 echo json_encode($x, $options);
355                 exit();
356         }
357
358         /**
359          * Generates a random string in the UUID format
360          *
361          * @param bool|string $prefix A given prefix (default is empty)
362          * @return string a generated UUID
363          * @throws \Exception
364          */
365         public static function createUUID($prefix = '')
366         {
367                 $guid = System::createGUID(32, $prefix);
368                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
369         }
370
371         /**
372          * Generates a GUID with the given parameters
373          *
374          * @param int         $size   The size of the GUID (default is 16)
375          * @param bool|string $prefix A given prefix (default is empty)
376          * @return string a generated GUID
377          * @throws \Exception
378          */
379         public static function createGUID($size = 16, $prefix = '')
380         {
381                 if (is_bool($prefix) && !$prefix) {
382                         $prefix = '';
383                 } elseif (empty($prefix)) {
384                         $prefix = hash('crc32', DI::baseUrl()->getHostname());
385                 }
386
387                 while (strlen($prefix) < ($size - 13)) {
388                         $prefix .= mt_rand();
389                 }
390
391                 if ($size >= 24) {
392                         $prefix = substr($prefix, 0, $size - 22);
393                         return str_replace('.', '', uniqid($prefix, true));
394                 } else {
395                         $prefix = substr($prefix, 0, max($size - 13, 0));
396                         return uniqid($prefix);
397                 }
398         }
399
400         /**
401          * Returns the current Load of the System
402          *
403          * @return integer
404          */
405         public static function currentLoad()
406         {
407                 if (!function_exists('sys_getloadavg')) {
408                         return false;
409                 }
410
411                 $load_arr = sys_getloadavg();
412
413                 if (!is_array($load_arr)) {
414                         return false;
415                 }
416
417                 return max($load_arr[0], $load_arr[1]);
418         }
419
420         /**
421          * Redirects to an external URL (fully qualified URL)
422          * If you want to route relative to the current Friendica base, use App->internalRedirect()
423          *
424          * @param string $url  The new Location to redirect
425          * @param int    $code The redirection code, which is used (Default is 302)
426          */
427         public static function externalRedirect($url, $code = 302)
428         {
429                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
430                         Logger::warning('No fully qualified URL provided', ['url' => $url, 'callstack' => self::callstack(20)]);
431                         DI::baseUrl()->redirect($url);
432                 }
433
434                 header("Location: $url");
435
436                 switch ($code) {
437                         case 302:
438                                 throw new FoundException();
439                         case 301:
440                                 throw new MovedPermanentlyException();
441                         case 307:
442                                 throw new TemporaryRedirectException();
443                 }
444
445                 exit();
446         }
447
448         /**
449          * Returns the system user that is executing the script
450          *
451          * This mostly returns something like "www-data".
452          *
453          * @return string system username
454          */
455         public static function getUser()
456         {
457                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
458                         return '';
459                 }
460
461                 $processUser = posix_getpwuid(posix_geteuid());
462                 return $processUser['name'];
463         }
464
465         /**
466          * Checks if a given directory is usable for the system
467          *
468          * @param      $directory
469          * @param bool $check_writable
470          *
471          * @return boolean the directory is usable
472          */
473         public static function isDirectoryUsable($directory, $check_writable = true)
474         {
475                 if ($directory == '') {
476                         Logger::info('Directory is empty. This shouldn\'t happen.');
477                         return false;
478                 }
479
480                 if (!file_exists($directory)) {
481                         Logger::info('Path "' . $directory . '" does not exist for user ' . static::getUser());
482                         return false;
483                 }
484
485                 if (is_file($directory)) {
486                         Logger::info('Path "' . $directory . '" is a file for user ' . static::getUser());
487                         return false;
488                 }
489
490                 if (!is_dir($directory)) {
491                         Logger::info('Path "' . $directory . '" is not a directory for user ' . static::getUser());
492                         return false;
493                 }
494
495                 if ($check_writable && !is_writable($directory)) {
496                         Logger::info('Path "' . $directory . '" is not writable for user ' . static::getUser());
497                         return false;
498                 }
499
500                 return true;
501         }
502
503         /**
504          * Exit method used by asynchronous update modules
505          *
506          * @param string $o
507          */
508         public static function htmlUpdateExit($o)
509         {
510                 header("Content-type: text/html");
511                 echo "<!DOCTYPE html><html><body>\r\n";
512                 // We can remove this hack once Internet Explorer recognises HTML5 natively
513                 echo "<section>";
514                 // reportedly some versions of MSIE don't handle tabs in XMLHttpRequest documents very well
515                 echo str_replace("\t", "       ", $o);
516                 echo "</section>";
517                 echo "</body></html>\r\n";
518                 exit();
519         }
520
521         /**
522          * Fetch the temp path of the system
523          *
524          * @return string Path for temp files
525          */
526         public static function getTempPath()
527         {
528                 $temppath = DI::config()->get("system", "temppath");
529
530                 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
531                         // We have a temp path and it is usable
532                         return BasePath::getRealPath($temppath);
533                 }
534
535                 // We don't have a working preconfigured temp path, so we take the system path.
536                 $temppath = sys_get_temp_dir();
537
538                 // Check if it is usable
539                 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
540                         // Always store the real path, not the path through symlinks
541                         $temppath = BasePath::getRealPath($temppath);
542
543                         // To avoid any interferences with other systems we create our own directory
544                         $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
545                         if (!is_dir($new_temppath)) {
546                                 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
547                                 mkdir($new_temppath);
548                         }
549
550                         if (System::isDirectoryUsable($new_temppath)) {
551                                 // The new path is usable, we are happy
552                                 DI::config()->set("system", "temppath", $new_temppath);
553                                 return $new_temppath;
554                         } else {
555                                 // We can't create a subdirectory, strange.
556                                 // But the directory seems to work, so we use it but don't store it.
557                                 return $temppath;
558                         }
559                 }
560
561                 // Reaching this point means that the operating system is configured badly.
562                 return '';
563         }
564
565         /**
566          * Returns the path where spool files are stored
567          *
568          * @return string Spool path
569          */
570         public static function getSpoolPath()
571         {
572                 $spoolpath = DI::config()->get('system', 'spoolpath');
573                 if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
574                         // We have a spool path and it is usable
575                         return $spoolpath;
576                 }
577
578                 // We don't have a working preconfigured spool path, so we take the temp path.
579                 $temppath = self::getTempPath();
580
581                 if ($temppath != "") {
582                         // To avoid any interferences with other systems we create our own directory
583                         $spoolpath = $temppath . "/spool";
584                         if (!is_dir($spoolpath)) {
585                                 mkdir($spoolpath);
586                         }
587
588                         if (System::isDirectoryUsable($spoolpath)) {
589                                 // The new path is usable, we are happy
590                                 DI::config()->set("system", "spoolpath", $spoolpath);
591                                 return $spoolpath;
592                         } else {
593                                 // We can't create a subdirectory, strange.
594                                 // But the directory seems to work, so we use it but don't store it.
595                                 return $temppath;
596                         }
597                 }
598
599                 // Reaching this point means that the operating system is configured badly.
600                 return "";
601         }
602 }