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