3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Core;
24 use Friendica\Core\Config\Capability\IManageConfigValues;
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;
35 * Contains the class with system relevant stuff
40 * @var LoggerInterface
45 * @var IManageConfigValues
54 public function __construct(LoggerInterface $logger, IManageConfigValues $config, string $basepath)
56 $this->logger = $logger;
57 $this->config = $config;
58 $this->basePath = $basepath;
62 * Checks if the maximum number of database processes is reached
64 * @return bool Is the limit reached?
66 public function isMaxProcessesReached(): bool
68 // Deactivated, needs more investigating if this check really makes sense
72 * Commented out to suppress static analyzer issues
74 if ($this->mode->isBackend()) {
76 $max_processes = $this->config->get('system', 'max_processes_backend');
77 if (intval($max_processes) == 0) {
81 $process = 'frontend';
82 $max_processes = $this->config->get('system', 'max_processes_frontend');
83 if (intval($max_processes) == 0) {
88 $processlist = DBA::processlist();
89 if ($processlist['list'] != '') {
90 $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
92 if ($processlist['amount'] > $max_processes) {
93 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
102 * Checks if the minimal memory is reached
104 * @return bool Is the memory limit reached?
106 public function isMinMemoryReached(): bool
108 // Deactivated, needs more investigating if this check really makes sense
112 * Commented out to suppress static analyzer issues
114 $min_memory = $this->config->get('system', 'min_memory', 0);
115 if ($min_memory == 0) {
119 if (!is_readable('/proc/meminfo')) {
123 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
126 foreach ($memdata as $line) {
127 $data = explode(':', $line);
128 if (count($data) != 2) {
131 [$key, $val] = $data;
132 $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
133 $meminfo[$key] = (int)($meminfo[$key] / 1024);
136 if (!isset($meminfo['MemFree'])) {
140 $free = $meminfo['MemFree'];
142 $reached = ($free < $min_memory);
145 $this->logger->warning('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
153 * Checks if the maximum load is reached
155 * @return bool Is the load reached?
157 public function isMaxLoadReached(): bool
159 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
160 if ($maxsysload < 1) {
164 $load = System::currentLoad();
166 if (intval($load) > $maxsysload) {
167 $this->logger->warning('system load for process too high.', ['load' => $load, 'process' => 'backend', 'maxsysload' => $maxsysload]);
175 * Executes a child process with 'proc_open'
177 * @param string $command The command to execute
178 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
180 public function run(string $command, array $args)
182 if (!function_exists('proc_open')) {
183 $this->logger->warning('"proc_open" not available - quitting');
187 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
189 foreach ($args as $key => $value) {
190 if (!is_null($value) && is_bool($value) && !$value) {
194 $cmdline .= ' --' . $key;
195 if (!is_null($value) && !is_bool($value)) {
196 $cmdline .= ' ' . $value;
200 if ($this->isMinMemoryReached()) {
201 $this->logger->warning('Memory limit reached - quitting');
205 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
206 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
208 $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
211 if (!is_resource($resource)) {
212 $this->logger->warning('We got no resource for command.', ['command' => $cmdline]);
216 proc_close($resource);
218 $this->logger->info('Executed "proc_open"', ['command' => $cmdline, 'callstack' => System::callstack(10)]);
222 * Returns a string with a callstack. Can be used for logging.
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
229 public static function callstack(int $depth = 4, int $offset = 0): string
231 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
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);
237 $previous = ['class' => '', 'function' => '', 'database' => false];
239 // The ignore list contains all functions that are only wrapper functions
240 $ignore = ['call_user_func_array'];
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')) {
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'];
257 } elseif (!in_array($func['function'], $ignore)) {
258 $func['database'] = ($func['function'] == 'q');
259 $callstack[] = $func['function'];
266 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
267 $callstack2[] = array_pop($callstack);
270 return implode(', ', $callstack2);
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.
279 * @param string $message
282 public static function xmlExit($st, $message = '')
284 $result = ['status' => $st];
286 if ($message != '') {
287 $result['message'] = $message;
291 Logger::notice('xml_status returning non_zero: ' . $st . " message=" . $message);
294 DI::apiResponse()->setType(Response::TYPE_XML);
295 DI::apiResponse()->addContent(XML::fromArray(["result" => $result], $xml));
296 DI::page()->exit(DI::apiResponse()->generate());
302 * Send HTTP status header and exit.
304 * @param integer $val HTTP status result value
305 * @param string $message Error message. Optional.
306 * @param string $content Response body. Optional.
309 public static function httpError($httpCode, $message = '', $content = '')
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'] ?? '']);
314 DI::apiResponse()->setStatus($httpCode, $message);
315 DI::apiResponse()->addContent($content);
316 DI::page()->exit(DI::apiResponse()->generate());
322 * This function adds the content and a content-teype HTTP header to the output.
323 * After finishing the process is getting killed.
325 * @param string $content
326 * @param string $type
327 * @param string|null $content_type
330 public static function httpExit(string $content, string $type = Response::TYPE_HTML, ?string $content_type = null) {
331 DI::apiResponse()->setType($type, $content_type);
332 DI::apiResponse()->addContent($content);
333 DI::page()->exit(DI::apiResponse()->generate());
338 public static function jsonError($httpCode, $content, $content_type = 'application/json')
340 if ($httpCode >= 400) {
341 Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'callstack' => System::callstack(20), 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
343 DI::apiResponse()->setStatus($httpCode);
344 self::jsonExit($content, $content_type);
348 * Encodes content to json.
350 * This function encodes an array to json format
351 * and adds an application/json HTTP header to the output.
352 * After finishing the process is getting killed.
354 * @param mixed $content The input content
355 * @param string $content_type Type of the input (Default: 'application/json')
356 * @param integer $options JSON options
357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
359 public static function jsonExit($content, $content_type = 'application/json', int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) {
360 DI::apiResponse()->setType(Response::TYPE_JSON, $content_type);
361 DI::apiResponse()->addContent(json_encode($content, $options));
362 DI::page()->exit(DI::apiResponse()->generate());
368 * Exit the program execution.
370 public static function exit()
372 DI::page()->logRuntime(DI::config(), 'exit');
377 * Generates a random string in the UUID format
379 * @param bool|string $prefix A given prefix (default is empty)
380 * @return string a generated UUID
383 public static function createUUID($prefix = '')
385 $guid = System::createGUID(32, $prefix);
386 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
390 * Generates a GUID with the given parameters
392 * @param int $size The size of the GUID (default is 16)
393 * @param bool|string $prefix A given prefix (default is empty)
394 * @return string a generated GUID
397 public static function createGUID($size = 16, $prefix = '')
399 if (is_bool($prefix) && !$prefix) {
401 } elseif (empty($prefix)) {
402 $prefix = hash('crc32', DI::baseUrl()->getHostname());
405 while (strlen($prefix) < ($size - 13)) {
406 $prefix .= mt_rand();
410 $prefix = substr($prefix, 0, $size - 22);
411 return str_replace('.', '', uniqid($prefix, true));
413 $prefix = substr($prefix, 0, max($size - 13, 0));
414 return uniqid($prefix);
419 * Returns the current Load of the System
423 public static function currentLoad()
425 if (!function_exists('sys_getloadavg')) {
429 $load_arr = sys_getloadavg();
431 if (!is_array($load_arr)) {
435 return max($load_arr[0], $load_arr[1]);
439 * Fetch the load and number of processes
443 public static function getLoadAvg(): array
445 $content = @file_get_contents('/proc/loadavg');
446 if (empty($content)) {
447 $content = shell_exec('cat /proc/loadavg');
449 if (empty($content) || !preg_match("#([.\d]+)\s([.\d]+)\s([.\d]+)\s(\d+)/(\d+)#", $content, $matches)) {
450 $load_arr = sys_getloadavg();
451 if (empty($load_arr)) {
455 'average1' => $load_arr[0],
456 'average5' => $load_arr[1],
457 'average15' => $load_arr[2],
464 'average1' => (float)$matches[1],
465 'average5' => (float)$matches[2],
466 'average15' => (float)$matches[3],
467 'runnable' => (float)$matches[4],
468 'scheduled' => (float)$matches[5]
473 * Redirects to an external URL (fully qualified URL)
474 * If you want to route relative to the current Friendica base, use App->internalRedirect()
476 * @param string $url The new Location to redirect
477 * @param int $code The redirection code, which is used (Default is 302)
479 * @throws FoundException
480 * @throws MovedPermanentlyException
481 * @throws TemporaryRedirectException
483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
485 public static function externalRedirect($url, $code = 302)
487 if (empty(parse_url($url, PHP_URL_SCHEME))) {
488 Logger::warning('No fully qualified URL provided', ['url' => $url, 'callstack' => self::callstack(20)]);
489 DI::baseUrl()->redirect($url);
492 header("Location: $url");
496 throw new FoundException();
498 throw new MovedPermanentlyException();
500 throw new TemporaryRedirectException();
506 * Returns the system user that is executing the script
508 * This mostly returns something like "www-data".
510 * @return string system username
512 public static function getUser()
514 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
518 $processUser = posix_getpwuid(posix_geteuid());
519 return $processUser['name'];
523 * Checks if a given directory is usable for the system
526 * @param bool $check_writable
528 * @return boolean the directory is usable
530 private static function isDirectoryUsable($directory, $check_writable = true)
532 if ($directory == '') {
533 Logger::warning('Directory is empty. This shouldn\'t happen.');
537 if (!file_exists($directory)) {
538 Logger::warning('Path does not exist', ['directory' => $directory, 'user' => static::getUser()]);
542 if (is_file($directory)) {
543 Logger::warning('Path is a file', ['directory' => $directory, 'user' => static::getUser()]);
547 if (!is_dir($directory)) {
548 Logger::warning('Path is not a directory', ['directory' => $directory, 'user' => static::getUser()]);
552 if ($check_writable && !is_writable($directory)) {
553 Logger::warning('Path is not writable', ['directory' => $directory, 'user' => static::getUser()]);
561 * Exit method used by asynchronous update modules
565 public static function htmlUpdateExit($o)
567 DI::apiResponse()->setType(Response::TYPE_HTML);
568 echo "<!DOCTYPE html><html><body>\r\n";
569 // We can remove this hack once Internet Explorer recognises HTML5 natively
571 // reportedly some versions of MSIE don't handle tabs in XMLHttpRequest documents very well
572 echo str_replace("\t", " ", $o);
574 echo "</body></html>\r\n";
579 * Fetch the temp path of the system
581 * @return string Path for temp files
583 public static function getTempPath()
585 $temppath = DI::config()->get("system", "temppath");
587 if (($temppath != "") && self::isDirectoryUsable($temppath)) {
588 // We have a temp path and it is usable
589 return BasePath::getRealPath($temppath);
592 // We don't have a working preconfigured temp path, so we take the system path.
593 $temppath = sys_get_temp_dir();
595 // Check if it is usable
596 if (($temppath != "") && self::isDirectoryUsable($temppath)) {
597 // Always store the real path, not the path through symlinks
598 $temppath = BasePath::getRealPath($temppath);
600 // To avoid any interferences with other systems we create our own directory
601 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
602 if (!is_dir($new_temppath)) {
603 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
604 mkdir($new_temppath);
607 if (self::isDirectoryUsable($new_temppath)) {
608 // The new path is usable, we are happy
609 DI::config()->set("system", "temppath", $new_temppath);
610 return $new_temppath;
612 // We can't create a subdirectory, strange.
613 // But the directory seems to work, so we use it but don't store it.
618 // Reaching this point means that the operating system is configured badly.
623 * Returns the path where spool files are stored
625 * @return string Spool path
627 public static function getSpoolPath()
629 $spoolpath = DI::config()->get('system', 'spoolpath');
630 if (($spoolpath != "") && self::isDirectoryUsable($spoolpath)) {
631 // We have a spool path and it is usable
635 // We don't have a working preconfigured spool path, so we take the temp path.
636 $temppath = self::getTempPath();
638 if ($temppath != "") {
639 // To avoid any interferences with other systems we create our own directory
640 $spoolpath = $temppath . "/spool";
641 if (!is_dir($spoolpath)) {
645 if (self::isDirectoryUsable($spoolpath)) {
646 // The new path is usable, we are happy
647 DI::config()->set("system", "spoolpath", $spoolpath);
650 // We can't create a subdirectory, strange.
651 // But the directory seems to work, so we use it but don't store it.
656 // Reaching this point means that the operating system is configured badly.