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