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