3 * @copyright Copyright (C) 2010-2023, 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\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
28 use Friendica\Model\User;
29 use Friendica\Module\Response;
30 use Friendica\Network\HTTPException\FoundException;
31 use Friendica\Network\HTTPException\InternalServerErrorException;
32 use Friendica\Network\HTTPException\MovedPermanentlyException;
33 use Friendica\Network\HTTPException\TemporaryRedirectException;
34 use Friendica\Util\BasePath;
35 use Friendica\Util\XML;
36 use Psr\Http\Message\ResponseInterface;
37 use Psr\Log\LoggerInterface;
40 * Contains the class with system relevant stuff
45 * @var LoggerInterface
50 * @var IManageConfigValues
59 public function __construct(LoggerInterface $logger, IManageConfigValues $config, string $basepath)
61 $this->logger = $logger;
62 $this->config = $config;
63 $this->basePath = $basepath;
67 * Checks if the maximum number of database processes is reached
69 * @return bool Is the limit reached?
71 public function isMaxProcessesReached(): bool
73 // Deactivated, needs more investigating if this check really makes sense
77 * Commented out to suppress static analyzer issues
79 if ($this->mode->isBackend()) {
81 $max_processes = $this->config->get('system', 'max_processes_backend');
82 if (intval($max_processes) == 0) {
86 $process = 'frontend';
87 $max_processes = $this->config->get('system', 'max_processes_frontend');
88 if (intval($max_processes) == 0) {
93 $processlist = DBA::processlist();
94 if ($processlist['list'] != '') {
95 $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
97 if ($processlist['amount'] > $max_processes) {
98 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
107 * Checks if the minimal memory is reached
109 * @return bool Is the memory limit reached?
111 public function isMinMemoryReached(): bool
113 // Deactivated, needs more investigating if this check really makes sense
117 * Commented out to suppress static analyzer issues
119 $min_memory = $this->config->get('system', 'min_memory', 0);
120 if ($min_memory == 0) {
124 if (!is_readable('/proc/meminfo')) {
128 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
131 foreach ($memdata as $line) {
132 $data = explode(':', $line);
133 if (count($data) != 2) {
136 [$key, $val] = $data;
137 $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
138 $meminfo[$key] = (int)($meminfo[$key] / 1024);
141 if (!isset($meminfo['MemFree'])) {
145 $free = $meminfo['MemFree'];
147 $reached = ($free < $min_memory);
150 $this->logger->warning('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
158 * Checks if the maximum load is reached
160 * @return bool Is the load reached?
162 public function isMaxLoadReached(): bool
164 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
165 if ($maxsysload < 1) {
169 $load = System::currentLoad();
171 if (intval($load) > $maxsysload) {
172 $this->logger->notice('system load for process too high.', ['load' => $load, 'process' => 'backend', 'maxsysload' => $maxsysload]);
180 * Executes a child process with 'proc_open'
182 * @param string $command The command to execute
183 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
185 public function run(string $command, array $args)
187 if (!function_exists('proc_open')) {
188 $this->logger->warning('"proc_open" not available - quitting');
192 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
194 foreach ($args as $key => $value) {
195 if (!is_null($value) && is_bool($value) && !$value) {
199 $cmdline .= ' --' . $key;
200 if (!is_null($value) && !is_bool($value)) {
201 $cmdline .= ' ' . $value;
205 if ($this->isMinMemoryReached()) {
206 $this->logger->warning('Memory limit reached - quitting');
210 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
211 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
213 $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
216 if (!is_resource($resource)) {
217 $this->logger->warning('We got no resource for command.', ['command' => $cmdline]);
221 proc_close($resource);
223 $this->logger->info('Executed "proc_open"', ['command' => $cmdline]);
227 * Returns a string with a callstack. Can be used for logging.
229 * @param integer $depth How many calls to include in the stacks after filtering
230 * @param int $offset How many calls to shave off the top of the stack, for example if
231 * this is called from a centralized method that isn't relevant to the callstack
232 * @param bool $full If enabled, the callstack is not compacted
233 * @param array $exclude
236 public static function callstack(int $depth = 4, int $offset = 0, bool $full = false, array $exclude = []): string
238 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
240 // We remove at least the first two items from the list since they contain data that we don't need.
241 $trace = array_slice($trace, 2 + $offset);
244 $previous = ['class' => '', 'function' => '', 'database' => false];
246 // The ignore list contains all functions that are only wrapper functions
247 $ignore = ['call_user_func_array'];
249 while ($func = array_pop($trace)) {
250 if (!empty($func['class'])) {
251 if (in_array($func['class'], $exclude)) {
255 if (!$full && in_array($previous['function'], ['insert', 'fetch', 'toArray', 'exists', 'count', 'selectFirst', 'selectToArray',
256 'select', 'update', 'delete', 'selectFirstForUser', 'selectForUser'])
257 && (substr($previous['class'], 0, 15) === 'Friendica\Model')) {
261 // Don't show multiple calls from the Database classes to show the essential parts of the callstack
262 $func['database'] = in_array($func['class'], ['Friendica\Database\DBA', 'Friendica\Database\Database']);
263 if ($full || !$previous['database'] || !$func['database']) {
264 $classparts = explode("\\", $func['class']);
265 $callstack[] = array_pop($classparts).'::'.$func['function'] . (isset($func['line']) ? ' (' . $func['line'] . ')' : '');
268 } elseif (!in_array($func['function'], $ignore)) {
269 $func['database'] = ($func['function'] == 'q');
270 $callstack[] = $func['function'] . (isset($func['line']) ? ' (' . $func['line'] . ')' : '');
277 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
278 $callstack2[] = array_pop($callstack);
281 return implode(', ', $callstack2);
285 * Display current response, including setting all headers
287 * @param ResponseInterface $response
289 public static function echoResponse(ResponseInterface $response)
291 header(sprintf("HTTP/%s %s %s",
292 $response->getProtocolVersion(),
293 $response->getStatusCode(),
294 $response->getReasonPhrase())
297 foreach ($response->getHeaders() as $key => $header) {
298 if (is_array($header)) {
299 $header_str = implode(',', $header);
301 $header_str = $header;
307 header("$key: $header_str");
311 echo $response->getBody();
316 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
317 * of $st and an optional text <message> of $message and terminates the current process.
319 * @param mixed $status
320 * @param string $message
322 * @deprecated since 2023.09 Use BaseModule->httpExit() instead
324 public static function xmlExit($status, string $message = '')
326 $result = ['status' => $status];
328 if ($message != '') {
329 $result['message'] = $message;
333 Logger::notice('xml_status returning non_zero: ' . $status . " message=" . $message);
336 self::httpExit(XML::fromArray(['result' => $result]), Response::TYPE_XML);
340 * Send HTTP status header and exit.
342 * @param integer $val HTTP status result value
343 * @param string $message Error message. Optional.
344 * @param string $content Response body. Optional.
346 * @deprecated since 2023.09 Use BaseModule->httpError instead
348 public static function httpError($httpCode, $message = '', $content = '')
350 if ($httpCode >= 400) {
351 Logger::debug('Exit with error', ['code' => $httpCode, 'message' => $message, 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
353 DI::apiResponse()->setStatus($httpCode, $message);
355 self::httpExit($content);
359 * This function adds the content and a content-type HTTP header to the output.
360 * After finishing the process is getting killed.
362 * @param string $content
363 * @param string $type
364 * @param string|null $content_type
366 * @throws InternalServerErrorException
367 * @deprecated since 2023.09 Use BaseModule->httpExit() instead
369 public static function httpExit(string $content, string $type = Response::TYPE_HTML, ?string $content_type = null)
371 DI::apiResponse()->setType($type, $content_type);
372 DI::apiResponse()->addContent($content);
373 self::echoResponse(DI::apiResponse()->generate());
379 * @deprecated since 2023.09 Use BaseModule->jsonError instead
381 public static function jsonError($httpCode, $content, $content_type = 'application/json')
383 if ($httpCode >= 400) {
384 Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
386 DI::apiResponse()->setStatus($httpCode);
387 self::jsonExit($content, $content_type);
391 * Encodes content to json.
393 * This function encodes an array to json format
394 * and adds an application/json HTTP header to the output.
395 * After finishing the process is getting killed.
397 * @param mixed $content The input content
398 * @param string $content_type Type of the input (Default: 'application/json')
399 * @param integer $options JSON options
400 * @throws InternalServerErrorException
401 * @deprecated since 2023.09 Use BaseModule->jsonExit instead
403 public static function jsonExit($content, string $content_type = 'application/json', int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
405 self::httpExit(json_encode($content, $options), Response::TYPE_JSON, $content_type);
409 * Exit the program execution.
411 public static function exit()
413 DI::page()->logRuntime(DI::config(), 'exit');
418 * Generates a random string in the UUID format
420 * @param bool|string $prefix A given prefix (default is empty)
421 * @return string a generated UUID
424 public static function createUUID($prefix = '')
426 $guid = System::createGUID(32, $prefix);
427 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
431 * Generates a GUID with the given parameters
433 * @param int $size The size of the GUID (default is 16)
434 * @param bool|string $prefix A given prefix (default is empty)
435 * @return string a generated GUID
438 public static function createGUID($size = 16, $prefix = '')
440 if (is_bool($prefix) && !$prefix) {
442 } elseif (empty($prefix)) {
443 $prefix = hash('crc32', DI::baseUrl()->getHost());
446 while (strlen($prefix) < ($size - 13)) {
447 $prefix .= mt_rand();
451 $prefix = substr($prefix, 0, $size - 22);
452 return str_replace('.', '', uniqid($prefix, true));
454 $prefix = substr($prefix, 0, max($size - 13, 0));
455 return uniqid($prefix);
460 * Returns the current Load of the System
464 public static function currentLoad()
466 if (!function_exists('sys_getloadavg')) {
470 $load_arr = sys_getloadavg();
472 if (!is_array($load_arr)) {
476 return max($load_arr[0], $load_arr[1]);
480 * Fetch the load and number of processes
482 * @param bool $get_processes
485 public static function getLoadAvg(bool $get_processes = true): array
487 $load_arr = sys_getloadavg();
488 if (empty($load_arr)) {
493 'average1' => $load_arr[0],
494 'average5' => $load_arr[1],
495 'average15' => $load_arr[2],
500 if ($get_processes && @is_readable('/proc/loadavg')) {
501 $content = @file_get_contents('/proc/loadavg');
502 if (!empty($content) && preg_match("#([.\d]+)\s([.\d]+)\s([.\d]+)\s(\d+)/(\d+)#", $content, $matches)) {
503 $load['runnable'] = (float)$matches[4];
504 $load['scheduled'] = (float)$matches[5];
512 * Redirects to an external URL (fully qualified URL)
513 * If you want to route relative to the current Friendica base, use App->internalRedirect()
515 * @param string $url The new Location to redirect
516 * @param int $code The redirection code, which is used (Default is 302)
518 * @throws FoundException
519 * @throws MovedPermanentlyException
520 * @throws TemporaryRedirectException
522 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
524 public static function externalRedirect($url, $code = 302)
526 if (empty(parse_url($url, PHP_URL_SCHEME))) {
527 Logger::warning('No fully qualified URL provided', ['url' => $url]);
528 DI::baseUrl()->redirect($url);
531 header("Location: $url");
535 throw new FoundException();
537 throw new MovedPermanentlyException();
539 throw new TemporaryRedirectException();
545 * Returns the system user that is executing the script
547 * This mostly returns something like "www-data".
549 * @return string system username
551 public static function getUser()
553 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
557 $processUser = posix_getpwuid(posix_geteuid());
558 return $processUser['name'];
562 * Checks if a given directory is usable for the system
566 * @return boolean the directory is usable
568 private static function isDirectoryUsable(string $directory): bool
570 if (empty($directory)) {
571 Logger::warning('Directory is empty. This shouldn\'t happen.');
575 if (!file_exists($directory)) {
576 Logger::info('Path does not exist', ['directory' => $directory, 'user' => static::getUser()]);
580 if (is_file($directory)) {
581 Logger::warning('Path is a file', ['directory' => $directory, 'user' => static::getUser()]);
585 if (!is_dir($directory)) {
586 Logger::warning('Path is not a directory', ['directory' => $directory, 'user' => static::getUser()]);
590 if (!is_writable($directory)) {
591 Logger::warning('Path is not writable', ['directory' => $directory, 'user' => static::getUser()]);
599 * Exit method used by asynchronous update modules
603 public static function htmlUpdateExit($o)
605 DI::apiResponse()->setType(Response::TYPE_HTML);
606 echo "<!DOCTYPE html><html><body>\r\n";
607 // We can remove this hack once Internet Explorer recognises HTML5 natively
609 // reportedly some versions of MSIE don't handle tabs in XMLHttpRequest documents very well
610 echo str_replace("\t", " ", $o);
612 echo "</body></html>\r\n";
617 * Fetch the temp path of the system
619 * @return string Path for temp files
621 public static function getTempPath()
623 $temppath = DI::config()->get("system", "temppath");
625 if (($temppath != "") && self::isDirectoryUsable($temppath)) {
626 // We have a temp path and it is usable
627 return BasePath::getRealPath($temppath);
630 // We don't have a working preconfigured temp path, so we take the system path.
631 $temppath = sys_get_temp_dir();
633 // Check if it is usable
634 if (($temppath != "") && self::isDirectoryUsable($temppath)) {
635 // Always store the real path, not the path through symlinks
636 $temppath = BasePath::getRealPath($temppath);
638 // To avoid any interferences with other systems we create our own directory
639 $new_temppath = $temppath . "/" . DI::baseUrl()->getHost();
640 if (!is_dir($new_temppath)) {
641 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
642 @mkdir($new_temppath);
645 if (self::isDirectoryUsable($new_temppath)) {
646 // The new path is usable, we are happy
647 DI::config()->set("system", "temppath", $new_temppath);
648 return $new_temppath;
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.
661 * Returns the path where spool files are stored
663 * @return string Spool path
665 public static function getSpoolPath()
667 $spoolpath = DI::config()->get('system', 'spoolpath');
668 if (($spoolpath != "") && self::isDirectoryUsable($spoolpath)) {
669 // We have a spool path and it is usable
673 // We don't have a working preconfigured spool path, so we take the temp path.
674 $temppath = self::getTempPath();
676 if ($temppath != "") {
677 // To avoid any interferences with other systems we create our own directory
678 $spoolpath = $temppath . "/spool";
679 if (!is_dir($spoolpath)) {
683 if (self::isDirectoryUsable($spoolpath)) {
684 // The new path is usable, we are happy
685 DI::config()->set("system", "spoolpath", $spoolpath);
688 // We can't create a subdirectory, strange.
689 // But the directory seems to work, so we use it but don't store it.
694 // Reaching this point means that the operating system is configured badly.
699 * Fetch the system rules
700 * @param bool $numeric_id If set to "true", the rules are returned with a numeric id as key.
704 public static function getRules(bool $numeric_id = false): array
709 if (DI::config()->get('system', 'tosdisplay')) {
710 $rulelist = DI::config()->get('system', 'tosrules') ?: DI::config()->get('system', 'tostext');
711 $msg = BBCode::toPlaintext($rulelist, false);
712 foreach (explode("\n", trim($msg)) as $line) {
716 $rules[++$id] = $line;
718 $rules[] = ['id' => (string)++$id, 'text' => $line];