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