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