small-package/luci-app-nekobox/htdocs/nekobox/fetch_logs.php

70 lines
2.0 KiB
PHP
Raw Normal View History

2024-10-26 10:38:22 +08:00
<?php
2024-11-23 09:27:24 +08:00
ini_set('memory_limit', '256M');
2024-10-26 10:38:22 +08:00
header('Content-Type: text/plain');
$allowed_files = [
'plugin_log' => '/etc/neko/tmp/log.txt',
'mihomo_log' => '/etc/neko/tmp/neko_log.txt',
'singbox_log' => '/var/log/singbox_log.txt',
];
$file = $_GET['file'] ?? '';
$max_lines = 100;
$max_chars = 1000000;
2024-11-19 09:38:06 +08:00
$max_line_length = 300;
2024-10-26 10:38:22 +08:00
2024-11-23 09:27:24 +08:00
function remove_ansi_colors($string) {
$pattern = '/\033\[[0-9;]*m/';
2024-11-23 12:23:39 +08:00
if (@preg_match($pattern, '') === false) {
error_log("Invalid regex pattern: $pattern");
return $string;
}
2024-11-23 09:27:24 +08:00
return preg_replace($pattern, '', $string);
}
function format_datetime($line) {
$pattern = '/^(\+?\d{4}\s)(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/';
2024-11-23 12:23:39 +08:00
if (@preg_match($pattern, '') === false) {
error_log("Invalid regex pattern: $pattern");
return $line;
}
2024-11-23 09:27:24 +08:00
return preg_replace($pattern, '[ \3 ]', $line);
}
2024-10-26 10:38:22 +08:00
if (array_key_exists($file, $allowed_files)) {
$file_path = $allowed_files[$file];
if (file_exists($file_path)) {
2024-11-23 09:27:24 +08:00
$lines = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_map('remove_ansi_colors', $lines);
$lines = array_map('format_datetime', $lines);
2024-11-19 09:38:06 +08:00
$lines = array_filter($lines, function($line) use ($max_line_length) {
return strlen($line) <= $max_line_length;
});
2024-10-26 10:38:22 +08:00
$content = implode(PHP_EOL, $lines);
if (strlen($content) > $max_chars) {
file_put_contents($file_path, '');
echo "Log file has been cleared, exceeding the character limit.";
return;
}
if (count($lines) > $max_lines) {
$lines = array_slice($lines, -$max_lines);
file_put_contents($file_path, implode(PHP_EOL, $lines));
}
echo htmlspecialchars(implode(PHP_EOL, $lines));
} else {
http_response_code(404);
echo "File not found.";
}
} else {
http_response_code(403);
echo "Forbidden.";
}
2024-11-23 09:27:24 +08:00
?>