3 * @copyright Copyright (C) 2010-2021, 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;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
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;
36 * Contains the class with system relevant stuff
41 * @var LoggerInterface
51 * @var IManageConfigValues
60 public function __construct(LoggerInterface $logger, App\Mode $mode, IManageConfigValues $config, string $basepath)
62 $this->logger = $logger;
64 $this->config = $config;
65 $this->basePath = $basepath;
69 * Checks if the maximum number of database processes is reached
71 * @return bool Is the limit reached?
73 public function isMaxProcessesReached(): bool
75 // Deactivated, needs more investigating if this check really makes sense
79 * Commented out to suppress static analyzer issues
81 if ($this->mode->isBackend()) {
83 $max_processes = $this->config->get('system', 'max_processes_backend');
84 if (intval($max_processes) == 0) {
88 $process = 'frontend';
89 $max_processes = $this->config->get('system', 'max_processes_frontend');
90 if (intval($max_processes) == 0) {
95 $processlist = DBA::processlist();
96 if ($processlist['list'] != '') {
97 $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
99 if ($processlist['amount'] > $max_processes) {
100 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
109 * Checks if the minimal memory is reached
111 * @return bool Is the memory limit reached?
113 public function isMinMemoryReached(): bool
115 $min_memory = $this->config->get('system', 'min_memory', 0);
116 if ($min_memory == 0) {
120 if (!is_readable('/proc/meminfo')) {
124 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
127 foreach ($memdata as $line) {
128 $data = explode(':', $line);
129 if (count($data) != 2) {
132 [$key, $val] = $data;
133 $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
134 $meminfo[$key] = (int)($meminfo[$key] / 1024);
137 if (!isset($meminfo['MemFree'])) {
141 $free = $meminfo['MemFree'];
143 $reached = ($free < $min_memory);
146 $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 if ($this->mode->isBackend()) {
160 $process = 'backend';
161 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
162 if ($maxsysload < 1) {
166 $process = 'frontend';
167 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
168 if ($maxsysload < 1) {
173 $load = System::currentLoad();
175 if (intval($load) > $maxsysload) {
176 $this->logger->warning('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]);
184 * Executes a child process with 'proc_open'
186 * @param string $command The command to execute
187 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
189 public function run(string $command, array $args)
191 if (!function_exists('proc_open')) {
192 $this->logger->warning('"proc_open" not available - quitting');
196 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
198 foreach ($args as $key => $value) {
199 if (!is_null($value) && is_bool($value) && !$value) {
203 $cmdline .= ' --' . $key;
204 if (!is_null($value) && !is_bool($value)) {
205 $cmdline .= ' ' . $value;
209 if ($this->isMinMemoryReached()) {
210 $this->logger->warning('Memory limit reached - quitting');
214 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
215 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
217 $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
219 if (!is_resource($resource)) {
220 $this->logger->warning('We got no resource for command.', ['command' => $cmdline]);
223 proc_close($resource);
225 $this->logger->info('Executed "proc_open"', ['command' => $cmdline, 'callstack' => System::callstack(10)]);
229 * Returns a string with a callstack. Can be used for logging.
231 * @param integer $depth How many calls to include in the stacks after filtering
232 * @param int $offset How many calls to shave off the top of the stack, for example if
233 * this is called from a centralized method that isn't relevant to the callstack
236 public static function callstack(int $depth = 4, int $offset = 0): 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($previous['function'], ['insert', 'fetch', 'toArray', 'exists', 'count', 'selectFirst', 'selectToArray',
252 'select', 'update', 'delete', 'selectFirstForUser', 'selectForUser'])
253 && (substr($previous['class'], 0, 15) === 'Friendica\Model')) {
257 // Don't show multiple calls from the Database classes to show the essential parts of the callstack
258 $func['database'] = in_array($func['class'], ['Friendica\Database\DBA', 'Friendica\Database\Database']);
259 if (!$previous['database'] || !$func['database']) {
260 $classparts = explode("\\", $func['class']);
261 $callstack[] = array_pop($classparts).'::'.$func['function'];
264 } elseif (!in_array($func['function'], $ignore)) {
265 $func['database'] = ($func['function'] == 'q');
266 $callstack[] = $func['function'];
273 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
274 $callstack2[] = array_pop($callstack);
277 return implode(', ', $callstack2);
282 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
283 * of $st and an optional text <message> of $message and terminates the current process.
286 * @param string $message
289 public static function xmlExit($st, $message = '')
291 $result = ['status' => $st];
293 if ($message != '') {
294 $result['message'] = $message;
298 Logger::notice('xml_status returning non_zero: ' . $st . " message=" . $message);
301 header("Content-type: text/xml");
303 $xmldata = ["result" => $result];
305 echo XML::fromArray($xmldata, $xml);
311 * Send HTTP status header and exit.
313 * @param integer $val HTTP status result value
314 * @param string $message Error message. Optional.
315 * @param string $content Response body. Optional.
318 public static function httpExit($val, $message = '', $content = '')
321 Logger::debug('Exit with error', ['code' => $val, 'message' => $message, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
323 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
330 public static function jsonError($httpCode, $data, $content_type = 'application/json')
332 if ($httpCode >= 400) {
333 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 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
336 self::jsonExit($data, $content_type);
340 * Encodes content to json.
342 * This function encodes an array to json format
343 * and adds an application/json HTTP header to the output.
344 * After finishing the process is getting killed.
346 * @param mixed $x The input content.
347 * @param string $content_type Type of the input (Default: 'application/json').
348 * @param integer $options JSON options
350 public static function jsonExit($x, $content_type = 'application/json', int $options = 0) {
351 header("Content-type: $content_type");
352 echo json_encode($x, $options);
357 * Generates a random string in the UUID format
359 * @param bool|string $prefix A given prefix (default is empty)
360 * @return string a generated UUID
363 public static function createUUID($prefix = '')
365 $guid = System::createGUID(32, $prefix);
366 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
370 * Generates a GUID with the given parameters
372 * @param int $size The size of the GUID (default is 16)
373 * @param bool|string $prefix A given prefix (default is empty)
374 * @return string a generated GUID
377 public static function createGUID($size = 16, $prefix = '')
379 if (is_bool($prefix) && !$prefix) {
381 } elseif (empty($prefix)) {
382 $prefix = hash('crc32', DI::baseUrl()->getHostname());
385 while (strlen($prefix) < ($size - 13)) {
386 $prefix .= mt_rand();
390 $prefix = substr($prefix, 0, $size - 22);
391 return str_replace('.', '', uniqid($prefix, true));
393 $prefix = substr($prefix, 0, max($size - 13, 0));
394 return uniqid($prefix);
399 * Returns the current Load of the System
403 public static function currentLoad()
405 if (!function_exists('sys_getloadavg')) {
409 $load_arr = sys_getloadavg();
411 if (!is_array($load_arr)) {
415 return max($load_arr[0], $load_arr[1]);
419 * Redirects to an external URL (fully qualified URL)
420 * If you want to route relative to the current Friendica base, use App->internalRedirect()
422 * @param string $url The new Location to redirect
423 * @param int $code The redirection code, which is used (Default is 302)
425 public static function externalRedirect($url, $code = 302)
427 if (empty(parse_url($url, PHP_URL_SCHEME))) {
428 Logger::warning('No fully qualified URL provided', ['url' => $url, 'callstack' => self::callstack(20)]);
429 DI::baseUrl()->redirect($url);
432 header("Location: $url");
436 throw new FoundException();
438 throw new MovedPermanentlyException();
440 throw new TemporaryRedirectException();
447 * Returns the system user that is executing the script
449 * This mostly returns something like "www-data".
451 * @return string system username
453 public static function getUser()
455 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
459 $processUser = posix_getpwuid(posix_geteuid());
460 return $processUser['name'];
464 * Checks if a given directory is usable for the system
467 * @param bool $check_writable
469 * @return boolean the directory is usable
471 public static function isDirectoryUsable($directory, $check_writable = true)
473 if ($directory == '') {
474 Logger::info('Directory is empty. This shouldn\'t happen.');
478 if (!file_exists($directory)) {
479 Logger::info('Path "' . $directory . '" does not exist for user ' . static::getUser());
483 if (is_file($directory)) {
484 Logger::info('Path "' . $directory . '" is a file for user ' . static::getUser());
488 if (!is_dir($directory)) {
489 Logger::info('Path "' . $directory . '" is not a directory for user ' . static::getUser());
493 if ($check_writable && !is_writable($directory)) {
494 Logger::info('Path "' . $directory . '" is not writable for user ' . static::getUser());
502 * Exit method used by asynchronous update modules
506 public static function htmlUpdateExit($o)
508 header("Content-type: text/html");
509 echo "<!DOCTYPE html><html><body>\r\n";
510 // We can remove this hack once Internet Explorer recognises HTML5 natively
512 // reportedly some versions of MSIE don't handle tabs in XMLHttpRequest documents very well
513 echo str_replace("\t", " ", $o);
515 echo "</body></html>\r\n";
520 * Fetch the temp path of the system
522 * @return string Path for temp files
524 public static function getTempPath()
526 $temppath = DI::config()->get("system", "temppath");
528 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
529 // We have a temp path and it is usable
530 return BasePath::getRealPath($temppath);
533 // We don't have a working preconfigured temp path, so we take the system path.
534 $temppath = sys_get_temp_dir();
536 // Check if it is usable
537 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
538 // Always store the real path, not the path through symlinks
539 $temppath = BasePath::getRealPath($temppath);
541 // To avoid any interferences with other systems we create our own directory
542 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
543 if (!is_dir($new_temppath)) {
544 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
545 mkdir($new_temppath);
548 if (System::isDirectoryUsable($new_temppath)) {
549 // The new path is usable, we are happy
550 DI::config()->set("system", "temppath", $new_temppath);
551 return $new_temppath;
553 // We can't create a subdirectory, strange.
554 // But the directory seems to work, so we use it but don't store it.
559 // Reaching this point means that the operating system is configured badly.
564 * Returns the path where spool files are stored
566 * @return string Spool path
568 public static function getSpoolPath()
570 $spoolpath = DI::config()->get('system', 'spoolpath');
571 if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
572 // We have a spool path and it is usable
576 // We don't have a working preconfigured spool path, so we take the temp path.
577 $temppath = self::getTempPath();
579 if ($temppath != "") {
580 // To avoid any interferences with other systems we create our own directory
581 $spoolpath = $temppath . "/spool";
582 if (!is_dir($spoolpath)) {
586 if (System::isDirectoryUsable($spoolpath)) {
587 // The new path is usable, we are happy
588 DI::config()->set("system", "spoolpath", $spoolpath);
591 // We can't create a subdirectory, strange.
592 // But the directory seems to work, so we use it but don't store it.
597 // Reaching this point means that the operating system is configured badly.