repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zgabievi/pingcrm-svelte | https://github.com/zgabievi/pingcrm-svelte/blob/4bc6d9883123d1b1a2c9b59b4d315d4f1823bf8a/resources/lang/en/auth.php | resources/lang/en/auth.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];
| php | MIT | 4bc6d9883123d1b1a2c9b59b4d315d4f1823bf8a | 2026-01-05T04:42:55.697447Z | false |
zgabievi/pingcrm-svelte | https://github.com/zgabievi/pingcrm-svelte/blob/4bc6d9883123d1b1a2c9b59b4d315d4f1823bf8a/resources/views/app.blade.php | resources/views/app.blade.php | <!DOCTYPE html>
<html class="h-full bg-gray-200">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/app.js') }}" defer></script>
@routes
</head>
<body class="font-sans leading-none text-gray-800 antialiased">
@inertia
</body>
</html>
| php | MIT | 4bc6d9883123d1b1a2c9b59b4d315d4f1823bf8a | 2026-01-05T04:42:55.697447Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_php_config.php | luci-app-nekobox/htdocs/nekobox/update_php_config.php | <?php
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$configFile = "/etc/php.ini";
$configChanges = [
'upload_max_filesize' => '2048M',
'post_max_size' => '2048M',
'max_file_uploads' => '100',
'memory_limit' => '2048M',
'max_execution_time' => '3600',
'max_input_time' => '3600'
];
$configData = file_get_contents($configFile);
foreach ($configChanges as $key => $value) {
$configData = preg_replace("/^$key\s*=\s*.*/m", "$key = $value", $configData);
}
if (file_put_contents($configFile, $configData) !== false) {
shell_exec("/etc/init.d/uhttpd restart > /dev/null 2>&1 &");
shell_exec("/etc/init.d/nginx restart > /dev/null 2>&1 &");
echo json_encode(["status" => "success", "message" => "PHP configuration updated and restarted successfully"]);
} else {
echo json_encode(["status" => "error", "message" => "Update failed, please check permissions!"]);
}
} else {
echo json_encode(["status" => "error", "message" => "Invalid request"]);
}
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/check_update.php | luci-app-nekobox/htdocs/nekobox/check_update.php | <?php
$repo_owner = "Thaolga";
$repo_name = "openwrt-nekobox";
$package_name = "luci-app-nekobox";
$json_file = __DIR__ . "/version_debug.json";
function getCurrentVersion($package_name) {
$output = shell_exec("opkg list-installed | grep " . escapeshellarg($package_name) . " 2>&1");
if (!$output) return "Error";
foreach (explode("\n", $output) as $line) {
if (preg_match('/' . preg_quote($package_name, '/') . '\s*-\s*([^\s]+)/', $line, $m)) {
return $m[1];
}
}
return "Error";
}
function getLatestVersionFromAssets($repo_owner, $repo_name, $package_name) {
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
$json = shell_exec("curl -H 'User-Agent: PHP' -s " . escapeshellarg($api_url) . " 2>/dev/null");
if (!$json) return "Error";
$data = json_decode($json, true);
if (!isset($data['assets'])) return "Error";
foreach ($data['assets'] as $asset) {
$name = $asset['name'] ?? '';
if (strpos($name, $package_name) !== false) {
if (preg_match('/' . preg_quote($package_name, '/') . '[_-]v?(\d+\.\d+\.\d+(?:-(?:r|rc)\d+)?)/i', $name, $m)) {
return $m[1];
}
}
}
return "Error";
}
$current = getCurrentVersion($package_name);
$latest = getLatestVersionFromAssets($repo_owner, $repo_name, $package_name);
$result = [
'currentVersion' => $current,
'latestVersion' => $latest,
'timestamp' => time()
];
file_put_contents($json_file, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
header("Content-Type: application/json");
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_rule.php | luci-app-nekobox/htdocs/nekobox/update_rule.php | <?php
ini_set('memory_limit', '128M');
ini_set('max_execution_time', 300);
$logMessages = [];
function logMessage($filename, $message) {
global $logMessages;
$timestamp = date('H:i:s');
$logMessages[] = "[$timestamp] $filename: $message";
}
class MultiDownloader {
private $urls = [];
private $maxConcurrent;
private $running = false;
private $mh;
private $handles = [];
private $retries = [];
private $maxRetries = 3;
public function __construct($maxConcurrent = 8) {
$this->maxConcurrent = $maxConcurrent;
$this->mh = curl_multi_init();
}
public function addDownload($url, $destination) {
$this->urls[] = [
'url' => $url,
'destination' => $destination,
'attempts' => 0
];
}
private function createHandle($url, $destination) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
]);
$this->handles[(int)$ch] = [
'ch' => $ch,
'url' => $url,
'destination' => $destination
];
curl_multi_add_handle($this->mh, $ch);
return $ch;
}
public function start() {
$urlCount = count($this->urls);
$processed = 0;
$batch = 0;
while ($processed < $urlCount) {
while (count($this->handles) < $this->maxConcurrent && !empty($this->urls)) {
$download = array_shift($this->urls);
$dir = dirname($download['destination']);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
logMessage(basename($download['destination']), "Start downloadin");
$this->createHandle($download['url'], $download['destination']);
}
do {
$status = curl_multi_exec($this->mh, $running);
} while ($status === CURLM_CALL_MULTI_PERFORM);
if ($running) {
curl_multi_select($this->mh);
}
while ($completed = curl_multi_info_read($this->mh)) {
$ch = $completed['handle'];
$chId = (int)$ch;
$info = $this->handles[$chId];
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content = curl_multi_getcontent($ch);
if ($httpCode === 200 && $content !== false) {
if (file_put_contents($info['destination'], $content) !== false) {
logMessage(basename($info['destination']), "Download successful");
} else {
logMessage(basename($info['destination']), "Save failed");
if (!isset($this->retries[$info['url']]) || $this->retries[$info['url']] < $this->maxRetries) {
$this->retries[$info['url']] = isset($this->retries[$info['url']]) ? $this->retries[$info['url']] + 1 : 1;
$this->urls[] = [
'url' => $info['url'],
'destination' => $info['destination'],
'attempts' => $this->retries[$info['url']]
];
}
}
} else {
logMessage(basename($info['destination']), "Download failed (HTTP $httpCode)");
if (!isset($this->retries[$info['url']]) || $this->retries[$info['url']] < $this->maxRetries) {
$this->retries[$info['url']] = isset($this->retries[$info['url']]) ? $this->retries[$info['url']] + 1 : 1;
$this->urls[] = [
'url' => $info['url'],
'destination' => $info['destination'],
'attempts' => $this->retries[$info['url']]
];
}
}
curl_multi_remove_handle($this->mh, $ch);
curl_close($ch);
unset($this->handles[$chId]);
$processed++;
}
}
}
public function __destruct() {
curl_multi_close($this->mh);
}
}
echo "Start updating the rule set...\n";
$urls = [
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/ads.srs" => "/etc/neko/rules/ads.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/ai.srs" => "/etc/neko/rules/ai.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/apple-cn.srs" => "/etc/neko/rules/apple-cn.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/applications.srs" => "/etc/neko/rules/applications.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/cn.srs" => "/etc/neko/rules/cn.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/cnip.srs" => "/etc/neko/rules/cnip.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/disney.srs" => "/etc/neko/rules/disney.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/fakeip-filter.srs" => "/etc/neko/rules/fakeip-filter.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/games-cn.srs" => "/etc/neko/rules/games-cn.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/google-cn.srs" => "/etc/neko/rules/google-cn.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/microsoft-cn.srs" => "/etc/neko/rules/microsoft-cn.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/netflix.srs" => "/etc/neko/rules/netflix.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/networktest.srs" => "/etc/neko/rules/networktest.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/private.srs" => "/etc/neko/rules/private.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/privateip.srs" => "/etc/neko/rules/privateip.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/proxy.srs" => "/etc/neko/rules/proxy.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/telegramip.srs" => "/etc/neko/rules/telegramip.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/tiktok.srs" => "/etc/neko/rules/tiktok.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/youtube.srs" => "/etc/neko/rules/youtube.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/geosite/tiktok.srs" => "/etc/neko/rules/geosite/tiktok.srs",
"https://raw.githubusercontent.com/Thaolga/neko/luci-app-neko/nekobox/rules/geosite/netflix.srs" => "/etc/neko/rules/geosite/netflix.srs"
];
$downloader = new MultiDownloader(8);
foreach ($urls as $url => $destination) {
$downloader->addDownload($url, $destination);
}
$downloader->start();
echo "\nRule set update completed!\n\n";
foreach ($logMessages as $message) {
echo $message . "\n";
}
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_dashboard.php | luci-app-nekobox/htdocs/nekobox/update_dashboard.php | <?php
ini_set('memory_limit', '128M');
$fixed_version = "v0.3.0";
function getUiVersion() {
$versionFile = '/etc/neko/ui/dashboard/version.txt';
if (file_exists($versionFile)) {
return trim(file_get_contents($versionFile));
} else {
return null;
}
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/ui/dashboard/version.txt';
file_put_contents($versionFile, $version);
}
$download_url = "https://github.com/Thaolga/neko/releases/download/$fixed_version/dashboard.tar";
$install_path = '/etc/neko/ui/dashboard';
$temp_file = '/tmp/dashboard-dist.tar';
if (!is_dir($install_path)) {
mkdir($install_path, 0755, true);
}
$current_version = getUiVersion();
if (isset($_GET['check_version'])) {
echo "Latest version: $fixed_version\n";
exit;
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed");
}
if (!file_exists($temp_file)) {
die("The downloaded file does not exist");
}
echo "Start extracting the file...\n";
exec("tar -xf '$temp_file' -C '$install_path'", $output, $return_var);
if ($return_var !== 0) {
echo "Decompression failed, error message: " . implode("\n", $output);
die("Decompression failed");
}
echo "Extraction successful \n";
exec("chown -R root:root '$install_path' 2>&1", $output, $return_var);
if ($return_var !== 0) {
echo "Failed to change file owner, error message: " . implode("\n", $output) . "\n";
die();
}
echo "The file owner has been changed to root.\n";
writeVersionToFile($fixed_version);
echo "Update complete! Current version: $fixed_version";
unlink($temp_file);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_metacubexd.php | luci-app-nekobox/htdocs/nekobox/update_metacubexd.php | <?php
ini_set('memory_limit', '128M');
function getUiVersion() {
$versionFile = '/etc/neko/ui/metacubexd/version.txt';
if (file_exists($versionFile)) {
return trim(file_get_contents($versionFile));
} else {
return "Version file does not exist";
}
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/ui/metacubexd/version.txt';
file_put_contents($versionFile, $version);
}
$repo_owner = "MetaCubeX";
$repo_name = "metacubexd";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
$curl_command = "curl -s -H 'User-Agent: PHP' --connect-timeout 10 " . escapeshellarg($api_url);
$response = shell_exec($curl_command);
if ($response === false || empty($response)) {
die("GitHub API request failed. Please check your network connection or try again later.");
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die("Error parsing GitHub API response: " . json_last_error_msg());
}
$latest_version = $data['tag_name'] ?? '';
$install_path = '/etc/neko/ui/metacubexd';
$temp_file = '/tmp/compressed-dist.tgz';
if (!is_dir($install_path)) {
mkdir($install_path, 0755, true);
}
$current_version = getUiVersion();
if (isset($_GET['check_version'])) {
echo "Latest version: $latest_version";
exit;
}
$download_url = $data['assets'][0]['browser_download_url'] ?? '';
if (empty($download_url)) {
die("Download link not found. Please check the resources for the release version.");
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed!");
}
exec("tar -xzf '$temp_file' -C '$install_path'", $output, $return_var);
if ($return_var !== 0) {
die("Extraction failed!");
}
writeVersionToFile($latest_version);
echo "Update complete! Current version: $latest_version";
unlink($temp_file);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/singbox.php | luci-app-nekobox/htdocs/nekobox/singbox.php | <?php
ob_start();
include './cfg.php';
$dataFilePath = '/etc/neko/proxy_provider/subscription_data.txt';
$lastSubscribeUrl = '';
if (file_exists($dataFilePath)) {
$fileContent = file_get_contents($dataFilePath);
$subscriptionLinkAddress = $translations['subscription_link_address'] ?? 'Subscription Link Address:';
$lastPos = strrpos($fileContent, $subscriptionLinkAddress);
if ($lastPos !== false) {
$urlSection = substr($fileContent, $lastPos);
$httpPos = strpos($urlSection, 'http');
if ($httpPos !== false) {
$endPos = strpos($urlSection, 'Custom Template URL:', $httpPos);
if ($endPos !== false) {
$lastSubscribeUrl = trim(substr($urlSection, $httpPos, $endPos - $httpPos));
} else {
$lastSubscribeUrl = trim(substr($urlSection, $httpPos));
}
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['setCron'])) {
$cronExpression = trim($_POST['cronExpression']);
$shellScriptPath = '/etc/neko/core/update_subscription.sh';
$logFile = '/etc/neko/tmp/log.txt';
if (preg_match('/^(\*|\d+)( (\*|\d+)){4}$/', $cronExpression)) {
$cronJob = "$cronExpression $shellScriptPath";
$currentCrons = shell_exec('crontab -l 2>/dev/null');
$updatedCrons = preg_replace(
"/^.*" . preg_quote($shellScriptPath, '/') . ".*$/m",
'',
$currentCrons
);
$updatedCrons = trim($updatedCrons) . "\n" . $cronJob . "\n";
$tempCronFile = tempnam(sys_get_temp_dir(), 'cron');
file_put_contents($tempCronFile, $updatedCrons);
exec("crontab $tempCronFile");
unlink($tempCronFile);
$timestamp = date('[ H:i:s ]');
file_put_contents($logFile, "$timestamp Cron job successfully set. Sing-box will update at $cronExpression.\n", FILE_APPEND);
echo "<div class='log-message alert alert-success' data-translate='cron_job_set' data-dynamic-content='$cronExpression'></div>";
} else {
$timestamp = date('[ H:i:s ]');
file_put_contents($logFile, "$timestamp Invalid Cron expression: $cronExpression\n", FILE_APPEND);
echo "<div class='log-message alert alert-danger' data-translate='cron_job_added_failed'></div>";
}
}
?>
<?php
$subscriptionFilePath = '/etc/neko/proxy_provider/subscription_data.txt';
$latestLink = '';
if (file_exists($subscriptionFilePath)) {
$fileContent = trim(file_get_contents($subscriptionFilePath));
if (!empty($fileContent)) {
$lines = explode("\n", $fileContent);
$latestTimestamp = '';
foreach ($lines as $line) {
if (preg_match('/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \| .*: (.*)$/', $line, $matches)) {
$timestamp = $matches[1];
$linkCandidate = $matches[2];
if ($timestamp > $latestTimestamp) {
$latestTimestamp = $timestamp;
$latestLink = $linkCandidate;
}
}
}
}
}
?>
<?php
$shellScriptPath = '/etc/neko/core/update_subscription.sh';
$LOG_FILE = '/etc/neko/tmp/log.txt';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['subscribeUrl'])) {
$SUBSCRIBE_URL = trim($_POST['subscribeUrl']);
if (empty($SUBSCRIBE_URL)) {
echo "<div class='log-message alert alert-warning'><span data-translate='subscribe_url_empty'></span></div>";
exit;
}
//echo '<div class="log-message alert alert-success" data-translate="subscribe_url_saved" data-dynamic-content="' . $SUBSCRIBE_URL . '"></div>';
}
if (isset($_POST['createShellScript'])) {
$shellScriptContent = <<<EOL
#!/bin/sh
LOG_FILE="$LOG_FILE"
SUBSCRIBE_URL=\$(cat /etc/neko/proxy_provider/subscription.txt | tr -d '\\n\\r')
if [ -z "\$SUBSCRIBE_URL" ]; then
echo "\$(date '+[ %H:%M:%S ]') Subscription URL is empty or extraction failed." >> "\$LOG_FILE"
exit 1
fi
echo "\$(date '+[ %H:%M:%S ]') Using subscription URL: \$SUBSCRIBE_URL" >> "\$LOG_FILE"
CONFIG_DIR="/etc/neko/config"
if [ ! -d "\$CONFIG_DIR" ]; then
mkdir -p "\$CONFIG_DIR"
if [ \$? -ne 0 ]; then
echo "\$(date '+[ %H:%M:%S ]') Failed to create config directory: \$CONFIG_DIR" >> "\$LOG_FILE"
exit 1
fi
fi
CONFIG_FILE="\$CONFIG_DIR/sing-box.json"
wget -q -O "\$CONFIG_FILE" "\$SUBSCRIBE_URL" >/dev/null 2>&1
if [ \$? -eq 0 ]; then
echo "\$(date '+[ %H:%M:%S ]') Sing-box configuration file updated successfully. Saved to: \$CONFIG_FILE" >> "\$LOG_FILE"
sed -i 's/"Proxy"/"DIRECT"/g' "\$CONFIG_FILE"
if [ \$? -eq 0 ]; then
echo "\$(date '+[ %H:%M:%S ]') Successfully replaced 'Proxy' with 'DIRECT' in the configuration file." >> "\$LOG_FILE"
else
echo "\$(date '+[ %H:%M:%S ]') Failed to replace 'Proxy' with 'DIRECT'. Please check the configuration file." >> "\$LOG_FILE"
exit 1
fi
else
echo "\$(date '+[ %H:%M:%S ]') Configuration file update failed. Please check the URL or network." >> "\$LOG_FILE"
exit 1
fi
EOL;
if (file_put_contents($shellScriptPath, $shellScriptContent) !== false) {
chmod($shellScriptPath, 0755);
echo "<div class='log-message alert alert-success'><span data-translate='shell_script_created' data-dynamic-content='$shellScriptPath'></span></div>";
} else {
echo "<div class='log-message alert alert-danger'><span data-translate='shell_script_failed'></span></div>";
}
}
}
?>
<?php
$dataFilePath = '/etc/neko/proxy_provider/subscription_data.txt';
$lastUpdateTime = null;
$validUrls = [];
if (file_exists($dataFilePath)) {
$lines = file($dataFilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') continue;
$parts = explode('|', $line);
foreach ($parts as $part) {
$part = trim($part);
if ($part !== '' && preg_match('/^https?:\/\//i', $part)) {
$validUrls[] = $part;
}
}
}
}
$libDir = __DIR__ . '/lib';
$cacheFile = $libDir . '/sub_info.json';
if (empty($validUrls) && file_exists($cacheFile)) {
unlink($cacheFile);
}
function formatBytes($bytes, $precision = 2) {
if ($bytes === INF || $bytes === "∞") return "∞";
if ($bytes <= 0) return "0 B";
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$pow = floor(log($bytes, 1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
function getSubInfo($subUrl, $userAgent = "Clash") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $subUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code !== 200 || !$response) {
return ["http_code"=>$http_code,"sub_info"=>"Request Failed","get_time"=>time()];
}
if (!preg_match("/subscription-userinfo: (.*)/i", $response, $matches)) {
return ["http_code"=>$http_code,"sub_info"=>"No Sub Info Found","get_time"=>time()];
}
$info = $matches[1];
preg_match("/upload=(\d+)/",$info,$m); $upload = isset($m[1]) ? (int)$m[1] : 0;
preg_match("/download=(\d+)/",$info,$m); $download = isset($m[1]) ? (int)$m[1] : 0;
preg_match("/total=(\d+)/",$info,$m); $total = isset($m[1]) ? (int)$m[1] : 0;
preg_match("/expire=(\d+)/",$info,$m); $expire = isset($m[1]) ? (int)$m[1] : 0;
$used = $upload + $download;
$percent = ($total > 0) ? ($used / $total) * 100 : 100;
$expireDate = "null";
$day_left = "null";
if ($expire > 0) {
$expireDate = date("Y-m-d H:i:s",$expire);
$day_left = $expire > time() ? ceil(($expire-time())/(3600*24)) : 0;
} elseif ($expire === 0) {
$expireDate = "Long-term";
$day_left = "∞";
}
return [
"http_code"=>$http_code,
"sub_info"=>"Successful",
"upload"=>$upload,
"download"=>$download,
"used"=>$used,
"total"=>$total > 0 ? $total : "∞",
"percent"=>round($percent,1),
"day_left"=>$day_left,
"expire"=>$expireDate,
"get_time"=>time(),
"url"=>$subUrl
];
}
function saveAllSubInfos($results) {
$libDir = __DIR__ . '/lib';
if (!is_dir($libDir)) mkdir($libDir, 0755, true);
$filePath = $libDir . '/sub_info.json';
file_put_contents($filePath, json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
return $filePath;
}
function loadAllSubInfosFromFile(&$lastUpdateTime = null) {
$libDir = __DIR__ . '/lib';
$filePath = $libDir . '/sub_info.json';
$results = [];
if (file_exists($filePath)) {
$results = json_decode(file_get_contents($filePath), true);
if ($results) {
$times = array_column($results, 'get_time');
if (!empty($times)) $lastUpdateTime = max($times);
}
}
return $results;
}
function clearSubFile() {
$libDir = __DIR__ . '/lib';
$filePath = $libDir . '/sub_info.json';
if (file_exists($filePath)) unlink($filePath);
}
function fetchAllSubInfos($urls) {
$results = [];
foreach ($urls as $url) {
if (empty(trim($url))) continue;
$userAgents = ["Clash","clash","ClashVerge","Stash","NekoBox","Quantumult%20X","Surge","Shadowrocket","V2rayU","Sub-Store","Mozilla/5.0"];
$subInfo = null;
foreach ($userAgents as $ua) {
$subInfo = getSubInfo($url,$ua);
if ($subInfo['sub_info']==="Successful") break;
}
$results[$url] = $subInfo;
}
saveAllSubInfos($results);
return $results;
}
if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['clearSubscriptions'])) {
clearSubFile();
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
$lastUpdateTime = null;
if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['generateConfig'])) {
$subscribeUrls = preg_split('/[\r\n,|]+/', trim($_POST['subscribeUrl'] ?? ''));
$subscribeUrls = array_filter($subscribeUrls);
$customFileName = basename(trim($_POST['customFileName'] ?? ''));
if (empty($customFileName)) $customFileName = 'sing-box';
if (substr($customFileName,-5) !== '.json') $customFileName .= '.json';
$configFilePath = '/etc/neko/config/'.$customFileName;
$allSubInfos = fetchAllSubInfos($subscribeUrls);
$lastUpdateTime = time();
} else {
$allSubInfos = loadAllSubInfosFromFile($lastUpdateTime);
}
?>
<meta charset="utf-8">
<title>singbox - Nekobox</title>
<link rel="icon" href="./assets/img/nekobox.png">
<script src="./assets/bootstrap/jquery.min.js"></script>
<?php include './ping.php'; ?>
<div class="container-sm container-bg px-0 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span style="color: var(--accent-color); letter-spacing: 1px;"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: var(--accent-color); font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php"><i class="bi bi-house-door"></i> <span data-translate="home">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo_manager.php' ? 'active' : '' ?>" href="./mihomo_manager.php"><i class="bi bi-folder"></i> <span data-translate="manager">Manager</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php"><i class="bi bi-shop"></i> <span data-translate="template_i">Template I</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'subscription.php' ? 'active' : '' ?>" href="./subscription.php"><i class="bi bi-bank"></i> <span data-translate="template_ii">Template II</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo.php' ? 'active' : '' ?>" href="./mihomo.php"><i class="bi bi-building"></i> <span data-translate="template_iii">Template III</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'netmon.php' ? 'active' : '' ?>" href="./netmon.php"><i class="bi bi-activity"></i> <span data-translate="traffic_monitor">Traffic Monitor</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'filekit.php' ? 'active' : '' ?>" href="./filekit.php"><i class="bi bi-bank"></i> <span data-translate="pageTitle">File Assistant</span></a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-3 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-translate-title="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-translate-title="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-translate-title="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" id="toggleIpStatusBtn" class="btn btn-warning icon-btn me-2" onclick="toggleIpStatusBar()" data-translate-title="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2" data-bs-toggle="modal" data-bs-target="#portModal" data-translate-title="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn-refresh-page btn btn-orange icon-btn me-2 d-none d-sm-inline"><i class="fas fa-sync-alt"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-translate-title="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<div class="outer-container px-3">
<div class="container-fluid">
<h2 class="title text-center mt-3 mb-3" data-translate="title">Sing-box Conversion Template One</h2>
<div class="card">
<div class="card-body">
<h4 class="card-title" data-translate="helpInfoHeading">Help Information</h4>
<ul class="list-unstyled ps-3">
<li data-translate="template1"><strong>Template 1</strong>: No Region, No Groups.</li>
<li data-translate="template2"><strong>Template 2</strong>: No Region, With Routing Rules.</li>
<li data-translate="template3"><strong>Template 3</strong>: Hong Kong, Taiwan, Singapore, Japan, USA, South Korea, With Routing Rules.</li>
<li data-translate="template4"><strong>Template 4</strong>: Same As Above, Multiple Rules.</li>
</ul>
</div>
</div>
<form method="post" action="">
<div class="mb-3 mt-3">
<label for="subscribeUrl" class="form-label" data-translate="subscribeUrlLabel">Subscription URL</label>
<input type="text" class="form-control" id="subscribeUrl" name="subscribeUrl" value="<?php echo htmlspecialchars($latestLink); ?>" placeholder="Enter subscription URL, multiple URLs separated by |" data-translate-placeholder="subscribeUrlPlaceholder" required>
</div>
<div class="mb-3">
<label for="customFileName" class="form-label" data-translate="customFileNameLabel">Custom Filename (Default: sing-box.json)</label>
<input type="text" class="form-control" id="customFileName" name="customFileName" placeholder="sing-box.json">
</div>
<fieldset class="mb-3">
<legend class="form-label" data-translate="chooseTemplateLabel">Choose Template</legend>
<div class="row">
<div class="col d-flex align-items-center">
<input type="radio" class="form-check-input" id="useDefaultTemplate0" name="defaultTemplate" value="0">
<label class="form-check-label ms-2" for="useDefaultTemplate0" data-translate="defaultTemplateLabel">Default Template</label>
</div>
<div class="col d-flex align-items-center">
<input type="radio" class="form-check-input" id="useDefaultTemplate1" name="defaultTemplate" value="1">
<label class="form-check-label ms-2" for="useDefaultTemplate1" data-translate="template1Label">Template 1</label>
</div>
<div class="col d-flex align-items-center">
<input type="radio" class="form-check-input" id="useDefaultTemplate2" name="defaultTemplate" value="2">
<label class="form-check-label ms-2" for="useDefaultTemplate2" data-translate="template2Label">Template 2</label>
</div>
<div class="col d-flex align-items-center">
<input type="radio" class="form-check-input" id="useDefaultTemplate3" name="defaultTemplate" value="3" checked>
<label class="form-check-label ms-2" for="useDefaultTemplate3" data-translate="template3Label">Template 3</label>
</div>
<div class="col d-flex align-items-center">
<input type="radio" class="form-check-input" id="useDefaultTemplate4" name="defaultTemplate" value="4">
<label class="form-check-label ms-2" for="useDefaultTemplate4" data-translate="template4Label">Template 4</label>
</div>
</div>
<div class="mt-3">
<div class="d-flex align-items-center">
<input type="radio" class="form-check-input" id="useCustomTemplate" name="templateOption" value="custom">
<label class="form-check-label ms-2 mb-0" for="useCustomTemplate" data-translate="useCustomTemplateLabel">Use Custom Template URL</label>
</div>
<input type="text" class="form-control mt-2" id="customTemplateUrl" name="customTemplateUrl" placeholder="Enter custom template URL" data-translate-placeholder="customTemplateUrlPlaceholder">
</div>
</fieldset>
<div class="d-flex flex-wrap gap-2 mb-4">
<div class="col-auto">
<form method="post" action="">
<button type="submit" name="generateConfig" class="btn btn-info">
<i class="bi bi-file-earmark-text"></i> <span data-translate="generateConfigLabel">Generate Configuration File</span>
</button>
</form>
</div>
<div class="col-auto">
<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#cronModal">
<i class="bi bi-clock"></i> <span data-translate="setCronLabel">Set Cron Job</span>
</button>
</div>
<div class="col-auto">
<form method="post" action="">
<button type="submit" name="createShellScript" class="btn btn-primary">
<i class="bi bi-terminal"></i> <span data-translate="generateShellLabel">Generate Update Script</span>
</button>
</form>
</div>
</div>
</div>
<div class="modal fade" id="cronModal" tabindex="-1" aria-labelledby="cronModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<form method="post" action="">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="cronModalLabel" data-translate="setCronModalTitle">Set Cron Job</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="cronExpression" class="form-label" data-translate="cronExpressionLabel">Cron Expression</label>
<input type="text" class="form-control" id="cronExpression" name="cronExpression" value="0 2 * * *" required>
</div>
<div class="alert alert-info mb-0">
<div class="fw-bold" data-translate="cron_hint"></div>
<div class="mt-2" data-translate="cron_expression_format"></div>
<ul class="mt-2 mb-0">
<li><span data-translate="cron_format_help"></span></li>
<li>
<span data-translate="cron_example"></span>
<code>0 2 * * *</code>
</li>
</ul>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="cancelButton">Cancel</button>
<button type="submit" name="setCron" class="btn btn-primary" data-translate="saveButton">Save</button>
</div>
</div>
</form>
</div>
</div>
<?php if (!empty($allSubInfos)): ?>
<div class="container-sm py-1">
<div class="card">
<div class="card-body p-2">
<h5 class="py-1 ps-3">
<i class="bi bi-bar-chart"></i>
<span data-translate="subscriptionInfo"></span>
</h5>
<div class="rounded-3 p-2 border mx-3">
<?php foreach ($allSubInfos as $url => $subInfo): ?>
<?php
$total = formatBytes($subInfo['total'] ?? 0);
$used = formatBytes($subInfo['used'] ?? 0);
$percent = $subInfo['percent'] ?? 0;
$dayLeft = $subInfo['day_left'] ?? '∞';
$expire = $subInfo['expire'] ?? 'expire';
$remainingLabel = $translations['resetDaysLeftLabel'] ?? 'Remaining';
$daysUnit = $translations['daysUnit'] ?? 'days';
$expireLabel = $translations['expireDateLabel'] ?? 'Expires';
?>
<div class="mb-1">
<?= htmlspecialchars($url) ?>:
<?php if ($subInfo['sub_info'] === "Successful"): ?>
<span class="text-success">
<?= "{$used} / {$total} ({$percent}%) • {$remainingLabel} {$dayLeft} {$daysUnit} • {$expireLabel}: {$expire}" ?>
</span>
<?php else: ?>
<span class="text-danger">
<?= htmlspecialchars($translations['subscriptionFetchFailed'] ?? 'Failed to obtain') ?>
</span>
<?php endif; ?>
</div>
<?php endforeach; ?>
<?php if (!empty($lastUpdateTime)): ?>
<div class="mt-2 text-end" style="font-size: 0.9em; color: var(--accent-color);">
<?= ($translations['lastModified'] ?? 'Last Updated') ?>: <?= date('Y-m-d H:i:s', $lastUpdateTime) ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?php endif; ?>
<?php
function displayLogData($dataFilePath, $translations) {
if (isset($_POST['clearData'])) {
if (file_exists($dataFilePath)) {
file_put_contents($dataFilePath, '');
}
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
if (file_exists($dataFilePath)) {
$savedData = file_get_contents($dataFilePath);
?>
<div class="container-sm py-2">
<div class="card">
<div class="card-body p-2">
<div class="d-flex justify-content-between align-items-center mb-2 mt-2">
<h4 class="py-2 ps-3"><?= htmlspecialchars($translations['data_saved']) ?></h4>
</div>
<div class="rounded-3 p-2 border mx-3" style="height: 300px; overflow-y: auto; overflow-x: hidden;">
<pre class="p-1 m-0 ms-2" style="white-space: pre-wrap; word-wrap: break-word; overflow: hidden;"><?= htmlspecialchars($savedData) ?></pre>
</div>
<div class="text-center mt-3">
<form method="post" action="">
<button class="btn btn-sm btn-danger" type="submit" name="clearData">
<i class="bi bi-trash"></i> <?= htmlspecialchars($translations['clear_data']) ?>
</button>
</form>
</div>
</div>
</div>
</div>
<?php
}
}
displayLogData('/etc/neko/proxy_provider/subscription_data.txt', $translations);
?>
<?php
ini_set('memory_limit', '512M');
$dataFilePath = '/etc/neko/proxy_provider/subscription_data.txt';
$configFilePath = '/etc/neko/config/sing-box.json';
$downloadedContent = '';
$fixedFileName = 'subscription.txt';
function isValidSubscriptionContent($content) {
$patterns = ['shadowsocks', 'vmess', 'vless', 'trojan', 'hysteria2', 'socks5', 'http'];
foreach ($patterns as $p) {
if (stripos($content, $p) !== false) {
return true;
}
}
return false;
}
function url_decode_fields(&$node) {
$fields_to_decode = ['password', 'uuid', 'public_key', 'psk', 'id', 'alterId', 'short_id'];
foreach ($fields_to_decode as $field) {
if (isset($node[$field]) && is_string($node[$field])) {
$node[$field] = urldecode($node[$field]);
if (in_array($field, ['password', 'public_key', 'psk'])) {
$node[$field] = trim($node[$field]);
}
}
}
if (isset($node['tls']['reality'])) {
url_decode_fields($node['tls']['reality']);
}
if (isset($node['transport']['path']) && is_string($node['transport']['path'])) {
$node['transport']['path'] = urldecode($node['transport']['path']);
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['generateConfig'])) {
$subscribeUrl = trim($_POST['subscribeUrl'] ?? '');
$customTemplateUrl = trim($_POST['customTemplateUrl'] ?? '');
$templateOption = $_POST['templateOption'] ?? 'default';
$currentTime = date('Y-m-d H:i:s');
$lang = $_GET['lang'] ?? 'en';
$lang = isset($translations[$lang]) ? $lang : 'en';
$subscribeLinkText = $langData[$currentLang]['subscriptionLink'] ?? 'Subscription Link Address';
$dataContent = $currentTime . " | " . $subscribeLinkText . ": " . $subscribeUrl . "\n";
$customFileName = basename(trim($_POST['customFileName'] ?? ''));
if (empty($customFileName)) {
$customFileName = 'sing-box';
}
if (substr($customFileName, -5) !== '.json') {
$customFileName .= '.json';
}
$currentData = file_exists($dataFilePath) ? file_get_contents($dataFilePath) : '';
$logEntries = array_filter(explode("\n\n", trim($currentData)));
if (!in_array(trim($dataContent), $logEntries)) {
$logEntries[] = trim($dataContent);
}
while (count($logEntries) > 100) {
array_shift($logEntries);
}
file_put_contents($dataFilePath, implode("\n\n", $logEntries) . "\n\n");
$subscribeUrlEncoded = urlencode($subscribeUrl);
if (isset($_POST['defaultTemplate']) && $_POST['defaultTemplate'] == '0') {
$templateUrlEncoded = '';
} elseif ($templateOption === 'custom' && !empty($customTemplateUrl)) {
$templateUrlEncoded = urlencode($customTemplateUrl);
} else {
$defaultTemplates = [
'1' => "https://raw.githubusercontent.com/Thaolga/Rules/main/sing-box/config_1.json",
'2' => "https://raw.githubusercontent.com/Thaolga/Rules/main/sing-box/config_2.json",
'3' => "https://raw.githubusercontent.com/Thaolga/Rules/main/sing-box/config_3.json",
'4' => "https://raw.githubusercontent.com/Thaolga/Rules/main/sing-box/config_4.json"
];
$templateUrlEncoded = urlencode($defaultTemplates[$_POST['defaultTemplate']] ?? '');
}
if (empty($templateUrlEncoded)) {
$completeSubscribeUrl = "https://sing-box-subscribe-doraemon.vercel.app/config/{$subscribeUrlEncoded}";
} else {
$completeSubscribeUrl = "https://sing-box-subscribe-doraemon.vercel.app/config/{$subscribeUrlEncoded}&file={$templateUrlEncoded}";
}
$tempFilePath = '/etc/neko/' . $customFileName;
$logMessages = [];
$command = "wget -O " . escapeshellarg($tempFilePath) . " " . escapeshellarg($completeSubscribeUrl);
exec($command, $output, $returnVar);
if ($returnVar !== 0) {
$command = "curl -s -L -o " . escapeshellarg($tempFilePath) . " " . escapeshellarg($completeSubscribeUrl);
exec($command, $output, $returnVar);
if ($returnVar !== 0) {
$logMessages[] = "Unable to download content: " . htmlspecialchars($completeSubscribeUrl);
}
}
if ($returnVar === 0) {
$downloadedContent = file_get_contents($tempFilePath);
if ($downloadedContent === false) {
$logMessages[] = "Unable to read the downloaded file content";
} else {
$data = json_decode($downloadedContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$logMessages[] = "Invalid JSON format in downloaded file: " . json_last_error_msg();
} else {
$removedTags = [];
if (isset($data['outbounds']) && is_array($data['outbounds'])) {
foreach ($data['outbounds'] as &$node) {
url_decode_fields($node);
}
unset($node);
}
if (isset($data['outbounds']) && is_array($data['outbounds'])) {
$data['outbounds'] = array_values(array_filter($data['outbounds'], function ($node) use (&$removedTags) {
if (
(isset($node['method']) && strtolower($node['method']) === 'chacha20') ||
(isset($node['plugin']) && stripos($node['plugin'], 'v2ray-plugin') !== false)
) {
if (isset($node['tag'])) {
$removedTags[] = $node['tag'];
}
return false;
}
return true;
}));
}
if (isset($data['outbounds']) && is_array($data['outbounds'])) {
foreach ($data['outbounds'] as &$node) {
if (
isset($node['type']) && in_array($node['type'], ['selector', 'urltest'], true) &&
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/ping.php | luci-app-nekobox/htdocs/nekobox/ping.php | <?php
$timezone = trim(shell_exec("uci get system.@system[0].zonename 2>/dev/null"));
date_default_timezone_set($timezone ?: 'UTC');
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'clearNekoTmpDir') {
$nekoDir = '/tmp/neko';
$response = [
'success' => false,
'message' => ''
];
if (is_dir($nekoDir)) {
if (deleteNekoTmpDirectory($nekoDir)) {
$response['success'] = true;
$response['message'] = 'Directory cleared successfully.';
} else {
$response['message'] = 'Failed to delete the directory.';
}
} else {
$response['message'] = 'The directory does not exist.';
}
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
function deleteNekoTmpDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item === '.' || $item === '..') {
continue;
}
if (!deleteNekoTmpDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
?>
<?php
$singbox_autostart = exec("uci -q get neko.cfg.singbox_autostart") ?: '0';
if (isset($_POST['save_autostart'])) {
$autostart = isset($_POST['autostart']) ? '1' : '0';
shell_exec("uci set neko.cfg.singbox_autostart='$autostart'");
shell_exec("uci commit neko");
writeToLog("Autostart setting changed to: $autostart");
echo "<div class='log-message alert alert-danger'><span data-translate='settingSaved'></span></div>";
$singbox_autostart = $autostart;
}
?>
<style>
.modal {
opacity: 0;
visibility: hidden;
}
.modal.show {
opacity: 1;
visibility: visible;
}
#theme-loader {
position: fixed;
inset: 0;
background: linear-gradient(
135deg,
var(--accent-color),
color-mix(in oklch, var(--accent-color), white 30%),
color-mix(in oklch, var(--accent-color), black 30%)
);
background-size: 300% 300%;
animation: animated-gradient 6s ease infinite;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
transition: opacity 0.6s ease;
color: var(--text-primary);
font-family: "Segoe UI", sans-serif;
}
.theme-loader-content {
text-align: center;
backdrop-filter: var(--glass-blur);
padding: 2rem 3rem;
border-radius: var(--radius);
background: color-mix(in oklch, var(--bg-container), white 10%);
box-shadow: 0 0 20px oklch(0 0 0 / 0.2);
}
.loader-icon {
font-size: 3.5rem;
animation: bounceIn 1s ease-in-out infinite alternate;
}
.loader-title {
font-size: 1.25rem;
margin-top: 1rem;
opacity: 0.85;
}
@keyframes animated-gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
@keyframes bounceIn {
0% {
transform: scale(1) translateY(0);
}
100% {
transform: scale(1.1) translateY(-10px);
}
}
.navbar {
backdrop-filter: none;
-webkit-backdrop-filter: none;
border: none;
padding: 0.8rem 1.2rem;
border-radius: 0;
box-shadow: none;
color: var(--text-primary);
transition: var(--transition);
}
.navbar-brand {
font-size: 1.5rem !important;
font-weight: 900 !important;
color: var(--accent-color) !important;
text-decoration: none;
transition: var(--transition);
}
.nav-link::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 0;
height: 2px;
background: var(--accent-color);
transition: width var(--transition-speed) ease;
}
.nav-link:hover::after {
width: 70%;
}
.navbar-brand:hover {
color: var(--accent-color) !important;
}
.navbar .nav-link {
color: var(--text-primary) !important;
padding: 0.5rem 1rem;
border-radius: var(--radius);
transition: var(--transition);
display: flex;
align-items: center;
gap: 0.4rem;
font-weight: 500;
position: relative;
}
.navbar .nav-link.active:hover,
.navbar .nav-link:hover {
color: var(--accent-color) !important;
}
.navbar .nav-link.active {
color: var(--accent-color) !important;
font-weight: 600;
}
.navbar-toggler {
color: var(--accent-color) !important;
border: none;
background: transparent;
outline: none;
}
.navbar-toggler i {
color: var(--accent-color) !important;
font-size: 1.8rem;
transition: var(--transition);
}
.icon-btn-group {
display: flex;
flex-wrap: wrap;
gap: 0.7rem !important;
justify-content: flex-start;
}
.icon-btn {
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
width: 2rem !important;
height: 2rem !important;
padding: 0 !important;
border-radius: 1rem !important;
font-size: 1rem !important;
line-height: 1 !important;
flex-shrink: 0;
}
.log-message.alert {
position: fixed;
left: 20px;
padding: 12px 16px;
background: rgb(45, 125, 55) !important;
color: #fff !important;
color: white;
border-radius: 8px;
z-index: 9999;
max-width: 370px;
font-size: 15px;
word-wrap: break-word;
line-height: 1.5;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.15);
border: 1px solid rgba(255, 255, 255, 0.15);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
backdrop-filter: blur(2px);
transform: translateY(0);
opacity: 0;
animation: scrollUp 12s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
display: inline-block;
margin-bottom: 10px;
transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
@keyframes scrollUp {
0% {
top: 90%;
opacity: 0;
}
20% {
opacity: 1;
}
80% {
top: 50%;
opacity: 1;
}
100% {
top: 45%;
opacity: 0;
}
}
.white-text-table,
.white-text-table td,
.white-text-table input {
color: var(--text-primary) !important;
}
.custom-tooltip {
position: fixed;
background: var(--accent-color);
color: #fff;
padding: 8px 12px;
border-radius: var(--radius);
font-size: 0.85rem;
pointer-events: none;
z-index: 10000;
white-space: nowrap;
max-width: 300px;
line-height: 1.4;
backdrop-filter: var(--glass-blur);
border: var(--glass-border);
box-shadow: 0 4px 20px color-mix(in oklch, var(--bg-container), black 85%),
inset 0 0 0 1px rgba(255, 255, 255, 0.1);
opacity: 0;
transform: translateY(10px);
transition: opacity 0.2s ease-out,
transform 0.2s ease-out;
}
.custom-tooltip.show {
opacity: var(--glass-opacity);
transform: translateY(0);
}
.custom-tooltip::after {
content: '';
position: absolute;
top: -5px;
left: 50%;
transform: translateX(-50%) rotate(45deg);
width: 10px;
height: 10px;
background: inherit;
border-top: var(--glass-border);
border-left: var(--glass-border);
z-index: -1;
}
.custom-tooltip[data-position="top"]::after {
top: auto;
bottom: -5px;
border: none;
border-right: var(--glass-border);
border-bottom: var(--glass-border);
}
@media (max-width: 768px) {
.custom-tooltip {
max-width: 200px;
white-space: normal;
font-size: 0.8rem;
}
}
.modal-body .alert.alert-warning .note-text {
color: #ff0000 !important;
}
@media (max-width: 600px) {
.navbar-brand {
flex-shrink: 1;
min-width: 0;
white-space: nowrap;
}
#dynamicTitle {
white-space: nowrap;
}
.navbar-toggler i {
font-size: 1.2rem !important;
}
.navbar-toggler {
padding: 0.15rem 0.35rem;
}
}
@media (max-width: 768px) {
.row > .col {
flex: 0 0 50%;
max-width: 50%;
}
.row > .col:nth-child(n+3) {
flex: 0 0 33.3333%;
max-width: 33.3333%;
}
.row {
row-gap: 13px;
}
.d-flex.flex-wrap.mb-4 {
flex-wrap: nowrap !important;
}
}
.centered-img {
transition: transform 0.6s ease-in-out;
transform-style: preserve-3d;
transform: rotateY(0deg);
}
</style>
<div id="theme-loader" style="display: none;">
<div class="theme-loader-content">
<div class="loader-icon">🚀</div>
<div class="loader-title">Updating...</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
const loader = document.getElementById("theme-loader");
const MAX_WAIT_TIME = 15000;
document.querySelectorAll("form").forEach(form => {
form.addEventListener("submit", (e) => {
if (e.submitter?.classList.contains('cancel-btn')) {
e.preventDefault();
return;
}
if (form.classList.contains('no-loader')) {
return;
}
if (loader) {
loader.style.display = "flex";
setTimeout(() => {
loader.style.opacity = "0";
setTimeout(() => {
loader.style.display = "none";
loader.style.opacity = "1";
}, 600);
}, MAX_WAIT_TIME);
}
});
});
});
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const tooltip = document.createElement('div');
tooltip.className = 'custom-tooltip';
document.body.appendChild(tooltip);
document.querySelectorAll('[data-tooltip]').forEach(el => {
el.addEventListener('mouseenter', e => {
tooltip.textContent = el.getAttribute('data-tooltip');
tooltip.classList.add('show');
requestAnimationFrame(() => {
positionTooltip(e);
});
});
el.addEventListener('mousemove', e => {
positionTooltip(e);
});
el.addEventListener('mouseleave', () => {
tooltip.classList.remove('show');
});
});
function positionTooltip(e) {
const spacing = 20;
const tooltipRect = tooltip.getBoundingClientRect();
const targetRect = e.target.getBoundingClientRect();
const top = targetRect.bottom + spacing;
const left = targetRect.left + (targetRect.width - tooltipRect.width) / 2;
tooltip.style.top = `${top}px`;
tooltip.style.left = `${left}px`;
tooltip.dataset.position = 'bottom';
}
});
document.addEventListener('click', e => {
if (e.target.closest('.btn-refresh-page')) {
location.reload();
}
});
</script>
<div class="modal fade" id="autostartModal" tabindex="-1" aria-labelledby="autostartModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<form method="post" class="no-loader">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="autostartModalLabel" data-translate="singboxAutostartTitle">
Sing-box Auto Start
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" name="autostart" id="autostart"
<?php echo ($singbox_autostart === '1') ? 'checked' : ''; ?>>
<label class="form-check-label" for="autostart">
<strong data-translate="enableAutostart">Enable Auto Start</strong>
</label>
</div>
<div class="mt-3">
<small class="text-muted" data-translate="autostartTip">
When checked, Sing-box will start automatically on router reboot (if Mihomo is not running)
</small>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="cancel">Cancel</button>
<button type="submit" name="save_autostart" class="btn btn-primary" data-translate="saveButton">Save</button>
</div>
</div>
</form>
</div>
</div>
<div class="modal fade" id="portModal" tabindex="-1" aria-labelledby="portModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl">
<form id="portForm" method="POST" action="./save_ports.php" class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="portModalLabel" data-translate="portInfoTitle">Port Information</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<table class="table table-light table-striped text-center align-middle w-100 mb-0 white-text-table">
<thead class="table-light">
<tr>
<th style="width: 20%;" class="text-center" data-translate="componentName">Component Name</th>
<th style="width: 16%;" class="text-center">socks-port</th>
<th style="width: 16%;" class="text-center">mixed-port</th>
<th style="width: 16%;" class="text-center">redir-port</th>
<th style="width: 16%;" class="text-center">port</th>
<th style="width: 16%;" class="text-center">tproxy-port</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mihomo</td>
<td><input type="number" class="form-control text-center" name="mihomo_socks" value="<?= htmlspecialchars($neko_cfg['socks']) ?>"></td>
<td><input type="number" class="form-control text-center" name="mihomo_mixed" value="<?= htmlspecialchars($neko_cfg['mixed']) ?>"></td>
<td><input type="number" class="form-control text-center" name="mihomo_redir" value="<?= htmlspecialchars($neko_cfg['redir']) ?>"></td>
<td><input type="number" class="form-control text-center" name="mihomo_port" value="<?= htmlspecialchars($neko_cfg['port']) ?>"></td>
<td><input type="number" class="form-control text-center" name="mihomo_tproxy" value="<?= htmlspecialchars($neko_cfg['tproxy']) ?>"></td>
</tr>
<tr>
<td>Sing-box</td>
<td><input type="number" class="form-control text-center" name="singbox_http" value="<?= htmlspecialchars($http_port) ?>"></td>
<td><input type="number" class="form-control text-center" name="singbox_mixed" value="<?= htmlspecialchars($mixed_port) ?>"></td>
<td><input type="text" class="form-control text-center" name="singbox_mixed" value="—" disabled></td>
<td><input type="text" class="form-control text-center" name="singbox_mixed" value="—" disabled></td>
<td><input type="text" class="form-control text-center" name="singbox_mixed" value="—" disabled></td>
</tr>
</tbody>
</table>
<div class="text-danger text-center fw-bold mt-3 mb-1" data-translate="portChangeNotice">
Port changes will take effect after restarting the service.
</div>
</div>
<div class="modal-footer justify-content-end">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="closeButton">Close</button>
<button type="submit" class="btn btn-primary" data-translate="save">Save</button>
</div>
</form>
</div>
</div>
<?php include './language.php'; include './cfg.php'; $current = basename($_SERVER['PHP_SELF']); ?>
<html lang="<?php echo $currentLang; ?>">
<div class="modal fade" id="langModal" tabindex="-1" aria-labelledby="langModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="langModalLabel" data-translate="select_language">Select Language</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<select id="langSelect" class="form-select" onchange="changeLanguage(this.value)">
<option value="zh" data-translate="simplified_chinese">Simplified Chinese</option>
<option value="hk" data-translate="traditional_chinese">Traditional Chinese</option>
<option value="en" data-translate="english">English</option>
<option value="ko" data-translate="korean">Korean</option>
<option value="vi" data-translate="vietnamese">Vietnamese</option>
<option value="ja" data-translate="japanese"></option>
<option value="ru" data-translate="russian"></option>
<option value="de" data-translate="germany">Germany</option>
<option value="fr" data-translate="france">France</option>
<option value="ar" data-translate="arabic"></option>
<option value="es" data-translate="spanish">spanish</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="close">Close</button>
</div>
</div>
</div>
</div>
<?php
$default_url = 'https://raw.githubusercontent.com/Thaolga/Rules/main/music/songs.txt';
$file_path = __DIR__ . '/lib/url_config.txt';
$message = '';
if (!file_exists($file_path)) {
if (file_put_contents($file_path, $default_url) !== false) {
chmod($file_path, 0644);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['new_url'])) {
$new_url = $_POST['new_url'];
if (file_put_contents($file_path, $new_url) !== false) {
chmod($file_path, 0644);
$message = 'Update successful!';
} else {
$message = 'Update failed, please check permissions.';
}
}
if (isset($_POST['reset_default'])) {
if (file_put_contents($file_path, $default_url) !== false) {
chmod($file_path, 0644);
$message = 'Default URL restored!';
} else {
$message = 'Restore failed, please check permissions.';
}
}
} else {
$new_url = file_exists($file_path) ? file_get_contents($file_path) : $default_url;
}
?>
<div class="modal fade" id="colorModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-xl modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" data-translate="advanced_color_control">Advanced Color Control</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="card h-100">
<div class="card-header bg-primary text-white">
<i class="bi bi-sliders"></i> <span data-translate="color_control">Color Control</span>
</div>
<div class="card-body">
<div class="mb-3">
<label class="form-label" data-translate="primary_hue">Primary Hue</label>
<div class="d-flex align-items-center">
<input type="range" class="form-range flex-grow-1" id="hueSlider" min="0" max="360" step="1">
<span class="ms-2" style="min-width: 50px;" id="hueValue">0°</span>
</div>
</div>
<div class="mb-3">
<label class="form-label" data-translate="chroma">Chroma</label>
<div class="d-flex align-items-center">
<input type="range" class="form-range flex-grow-1" id="chromaSlider" min="0" max="0.3" step="0.01">
<span class="ms-2" style="min-width: 50px;" id="chromaValue">0.10</span>
</div>
</div>
<div class="mb-3">
<label class="form-label" data-translate="lightness">Lightness</label>
<div class="d-flex align-items-center">
<input type="range" class="form-range flex-grow-1" id="lightnessSlider" min="0" max="100" step="1">
<span class="ms-2" style="min-width: 50px;" id="lightnessValue">30%</span>
</div>
</div>
<div class="mb-3">
<label class="form-label" data-translate="or_use_palette">Or use palette:</label>
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#4d79ff" data-h="240" data-c="0.2" data-l="30"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#ff4d94" data-h="340" data-c="0.25" data-l="35"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#4dff88" data-h="150" data-c="0.18" data-l="40"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#ffb84d" data-h="40" data-c="0.22" data-l="45"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#bf4dff" data-h="280" data-c="0.23" data-l="50"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#ff6b6b" data-h="10" data-c="0.24" data-l="55"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#4eca9e" data-h="160" data-c="0.19" data-l="60"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#ff9ff3" data-h="310" data-c="0.21" data-l="65"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#6c757d" data-h="200" data-c="0.05" data-l="50"></button>
<button class="btn btn-sm p-3 rounded-circle" style="background-color:#ffc107" data-h="50" data-c="0.26" data-l="70"></button>
</div>
</div>
<div class="mt-3">
<button class="btn btn-secondary w-100" id="resetColorBtn">
<i class="bi bi-arrow-counterclockwise"></i> <span data-translate="reset_to_default">Reset to Default</span>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card h-100">
<div class="card-header bg-primary text-white">
<i class="bi bi-eye"></i> <span data-translate="color_preview">Color Preview</span>
</div>
<div class="card-body">
<div id="colorPreview" style="height: 100px; border-radius: 5px; margin-bottom: 15px;"></div>
<div class="mb-3">
<label class="form-label" data-translate="oklch_values">OKLCH Values:</label>
<div id="oklchValue" class="text-monospace">OKLCH(30%, 0.10, 260°)</div>
</div>
<div class="mb-3">
<label class="form-label" data-translate="contrast_ratio">Contrast Ratio:</label>
<div id="contrastRatio">21.00:1</div>
<div id="contrastRating" class="mt-1 text-success fw-bold"><i class="bi bi-check-circle-fill"></i> Excellent (AAA)</div>
</div>
<div class="mb-3">
<label class="form-label" data-translate="recent_colors">Recent Colors:</label>
<div id="recentColors" class="d-flex flex-wrap gap-2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
<i class="bi bi-x"></i> <span data-translate="cancel">Cancel</span>
</button>
<button type="button" class="btn btn-danger" id="removeAppColorBtn">
<i class="bi bi-eraser"></i> <span data-translate="reset">Reset</span>
</button>
<button type="button" class="btn btn-primary" id="applyColorBtn">
<i class="bi bi-check"></i> <span data-translate="apply_color">Apply Color</span>
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="colorPickerModal" tabindex="-1" aria-labelledby="colorPickerModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-xl modal-dialog-centered">
<div class="modal-content bg-dark text-white border border-secondary rounded">
<div class="modal-header">
<h5 class="modal-title" id="colorPickerModalLabel" data-translate="color_width_panel">Color & Width Panel</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row mb-3">
<div class="col-md-6">
<label for="containerWidth" class="form-label" data-translate="page_width">Page Width</label>
<input type="range" class="form-range" name="containerWidth" id="containerWidth" min="800" max="5400" step="50" value="1800" style="width: 100%;">
<div id="widthValue" class="mt-2" style="color: #FF00FF;" data-translate="current_width">Current Width: 1800px</div>
</div>
<div class="col-md-6">
<label for="modalMaxWidth" class="form-label" data-translate="settings.modal.maxWidth">Modal Max Width</label>
<input type="range" class="form-range" name="modalMaxWidth" id="modalMaxWidth" min="500" max="5400" step="50" value="800" style="width: 100%;">
<div id="modalWidthValue" class="mt-2" style="color: #00FF00;" data-translate="current_max_width">Current Max Width: 800px</div>
</div>
</div>
<div id="color-preview" class="rounded border mb-3" style="height: 100px; background: #333;"></div>
<div class="d-flex align-items-center gap-2 mb-3">
<div class="d-flex align-items-center justify-content-center rounded"
style="width: 80px; height: 50px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.3);">
<input type="color" id="color-selector"
class="form-control form-control-color p-0"
value="#0f3460"
data-tooltip="choose_color"
style="width: 36px; height: 36px; cursor: pointer;">
</div>
<div id="current-color-block"
class="rounded d-flex align-items-center justify-content-center text-white position-relative"
style="height: 50px; flex: 1; cursor: pointer; background: #333; border: 2px solid white; transition: all 0.3s ease;">
<input type="text"
id="color-input"
class="form-control text-center border-0 bg-transparent text-white p-0 m-0"
value=" "
style="width: 100%; font-size: 0.9rem;">
<span class="fake-cursor">|</span>
</div>
</div>
<div class="d-flex gap-2 mb-3">
<button id="apply-color" class="btn btn-success flex-fill"><i class="fa fa-paint-brush"></i> <span data-translate="apply_color">Apply</span> </button>
<button id="reset-color" class="btn btn-danger flex-fill"><i class="fa fa-undo"></i> <span data-translate="reset">Reset</span></button>
</div>
<div id="preset-colors" class="d-grid gap-2"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fa fa-times"></i> <span data-translate="close">Close</span></button>
</div>
</div>
</div>
</div>
<div class="control-panel-overlay" id="controlPanelOverlay" style="display:none;">
<div class="control-panel">
<div class="panel-header">
<h3><i class="bi bi-gear"></i> <span data-translate="control_panel_title">Control Panel</span></h3>
<button class="close-icon" onclick="toggleControlPanel()" data-tooltip="close">
<i class="bi bi-x-lg"></i>
</button>
</div>
<div class="buttons-grid">
<button class="panel-btn" data-bs-toggle="modal" data-bs-target="#musicModal" data-tooltip="music_player">
<div class="btn-icon">
<i class="bi bi-music-note-beamed"></i>
</div>
<div>
<div data-translate="music_player">Music Player</div>
<small class="opacity-75" data-translate="music_desc">Control background music settings</small>
</div>
</button>
<button class="panel-btn" id="color-panel-btn" data-bs-toggle="modal" data-bs-target="#colorPickerModal">
<div class="btn-icon">
<i class="bi bi-palette"></i>
</div>
<div>
<div data-translate="color_panel">Color Panel</div>
<small class="opacity-75" data-translate="color_desc">Customize interface colors</small>
</div>
</button>
<button class="panel-btn" id="advancedColorBtn" data-tooltip="advanced_color_settings">
<div class="btn-icon">
<i class="bi bi-palette2"></i>
</div>
<div>
<div data-translate="advanced_color">Advanced Color Settings</div>
<small class="opacity-75" data-translate="advanced_color_desc">Professional color adjustments</small>
</div>
</button>
<button class="panel-btn" id="clear-cache-btn" data-tooltip="clear_cache">
<div class="btn-icon">
<i class="bi bi-trash"></i>
</div>
<div>
<div data-translate="clear_cache">Clear Cache</div>
<small class="opacity-75" data-translate="cache_desc">Free up system resources</small>
</div>
</button>
<button class="panel-btn" id="startCheckBtn" data-tooltip="start_check">
<div class="btn-icon">
<i class="bi bi-globe2"></i>
</div>
<div>
<div data-translate="start_check">Start Website Check</div>
<small class="opacity-75" data-translate="check_desc">Diagnose website status</small>
</div>
<i class="bi bi-toggle-off" id="autoCheckIcon" style="cursor: pointer; margin-left: 10px;"></i>
</button>
<button class="panel-btn" id="openModalBtn" data-tooltip="open_animation">
<div class="btn-icon">
<i class="bi bi-sliders"></i>
</div>
<div>
<div data-translate="open_animation">Animation Control</div>
<small class="opacity-75" data-translate="animation_desc">Adjust animation effects</small>
</div>
</button>
<button class="panel-btn" data-bs-toggle="modal" data-bs-target="#langModal">
<div class="btn-icon">
<i class="bi bi-translate"></i>
</div>
<div class="language-container">
<div>
<div data-translate="set_language">Set Language</div>
<small class="opacity-75" data-translate="language_desc">Choose interface language</small>
</div>
<img id="flagIcon" src="https://flagcdn.com/w20/cn.png" class="flag-icon" alt="Country Flag">
</div>
</button>
<button class="panel-btn" onclick="window.open('./monaco.php', '_blank')">
<div class="btn-icon">
<i class="bi bi-file-earmark"></i>
</div>
<div>
<div data-translate="fileHelper">File Helper</div>
<small class="opacity-75" data-translate="file_desc">Manage your files</small>
</div>
</button>
<button class="panel-btn" id="translationToggleBtn" data-tooltip="enable">
<div class="btn-icon" id="translationToggleIcon">
<i class="bi bi-toggle-off"></i>
</div>
<div>
<div data-translate="ip_info">IP Info</div>
<div class="opacity-75" id="translationToggleText" style="font-size: 0.85rem;">enable</div>
</div>
</button>
</div>
<div class="action-row">
<div class="color-picker">
<button class="btn btn-info ms-2" id="fontSwitchBtn" data-tooltip="toggle_font">
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/fetch_logs.php | luci-app-nekobox/htdocs/nekobox/fetch_logs.php | <?php
ini_set('memory_limit', '256M');
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_chars = 1000000;
$max_line_length = 160;
function remove_ansi_colors($string) {
$pattern = '/\033\[[0-9;]*m/';
if (@preg_match($pattern, '') === false) {
error_log("Invalid regex pattern: $pattern");
return $string;
}
return preg_replace($pattern, '', $string);
}
function format_datetime($line) {
$pattern = '/^\[\w{3} \w{3}\s+\d{1,2} (\d{2}:\d{2}:\d{2}) [A-Z]+ \d{4}\] (.*)$/';
if (preg_match($pattern, $line, $matches)) {
return sprintf('[ %s ] %s', $matches[1], $matches[2]);
}
$pattern_standard = '/^(\+?\d{4}\s)(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/';
if (preg_match($pattern_standard, $line, $matches)) {
return preg_replace($pattern_standard, '[ \3 ]', $line);
}
return $line;
}
function is_bang_line($line) {
return preg_match('/^\[\!\]/', $line);
}
function filter_unwanted_lines($lines) {
return array_filter($lines, function($line) {
return !preg_match('/^(Environment|Tags|CGO):/', $line);
});
}
if (array_key_exists($file, $allowed_files)) {
$file_path = $allowed_files[$file];
if (file_exists($file_path)) {
$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);
$lines = filter_unwanted_lines($lines);
$lines = array_filter($lines, function($line) use ($max_line_length) {
return strlen($line) <= $max_line_length && !is_bang_line($line);
});
$lines = array_values($lines);
$lines_with_numbers = array_map(function($line, $index) {
return sprintf("%d %s", $index + 1, $line);
}, $lines, array_keys($lines));
$content = implode(PHP_EOL, $lines_with_numbers);
if (strlen($content) > $max_chars) {
file_put_contents($file_path, '');
echo "Log file has been cleared, exceeding the character limit.";
return;
}
echo htmlspecialchars($content);
} else {
http_response_code(404);
echo "File not found.";
}
} else {
http_response_code(403);
echo "Forbidden.";
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/cfg.php | luci-app-nekobox/htdocs/nekobox/cfg.php | <?php
$neko_dir="/etc/neko";
$neko_www="/www/nekobox";
$neko_bin="/usr/bin/mihomo";
$neko_status=exec("uci -q get neko.cfg.enabled");
$current = basename($_SERVER['PHP_SELF']);
$selected_config= exec("cat $neko_www/lib/selected_config.txt");
$neko_cfg = array();
$neko_cfg['redir']=exec("cat $selected_config | grep redir-port | awk '{print $2}'");
$neko_cfg['port'] = trim(exec("grep '^port:' $selected_config | awk '{print $2}'"));
$neko_cfg['socks']=exec("cat $selected_config | grep socks-port | awk '{print $2}'");
$neko_cfg['mixed']=exec("cat $selected_config | grep mixed-port | awk '{print $2}'");
$neko_cfg['tproxy']=exec("cat $selected_config | grep tproxy-port | awk '{print $2}'");
$neko_cfg['mode']=strtoupper(exec("cat $selected_config | grep mode | head -1 | awk '{print $2}'"));
$neko_cfg['echanced']=strtoupper(exec("cat $selected_config | grep enhanced-mode | awk '{print $2}'"));
$neko_cfg['secret'] = trim(exec("grep '^secret:' $selected_config | awk -F': ' '{print $2}'"));
$neko_cfg['ext_controller']=shell_exec("cat $selected_config | grep external-ui | awk '{print $2}'");
$singbox_path_file = "$neko_www/lib/singbox.txt";
$singbox_config_path = trim(exec("cat $singbox_path_file"));
$http_port = "Not obtained";
$mixed_port = "Not obtained";
if (file_exists($singbox_config_path)) {
$json_content = file_get_contents($singbox_config_path);
$config = json_decode($json_content, true);
if (is_array($config) && isset($config['inbounds'])) {
foreach ($config['inbounds'] as $inbound) {
if (
isset($inbound['type']) && $inbound['type'] === 'mixed' &&
isset($inbound['tag']) && $inbound['tag'] === 'mixed' &&
isset($inbound['listen_port'])
) {
$mixed_port = $inbound['listen_port'];
}
if (
isset($inbound['type']) && $inbound['type'] === 'http' &&
isset($inbound['listen_port'])
) {
$http_port = $inbound['listen_port'];
}
}
}
} else {
$http_port = "Config file not found";
$mixed_port = "Config file not found";
}
$title = "Nekobox";
$titleLink = "#";
$configFile = '/etc/config/neko';
$enabled = null;
$singbox_enabled = null;
$iconHtml = '';
if (file_exists($configFile)) {
$lines = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
if (strpos($line, '#') === 0 || strpos($line, '//') === 0) {
continue;
}
if (preg_match("/option\s+enabled\s+'(\d+)'/", $line, $matches)) {
$enabled = intval($matches[1]);
}
if (preg_match("/option\s+singbox_enabled\s+'(\d+)'/", $line, $matches)) {
$singbox_enabled = intval($matches[1]);
}
}
}
if ($singbox_enabled === 1) {
$title .= " - Singbox";
$titleLink = "https://github.com/SagerNet/sing-box";
$iconHtml = '<img src="./assets/img/singbox.svg" alt="Singbox" class="me-2" style="width: 1.8rem; height: 1.8rem;">';
} elseif ($enabled === 1) {
$title .= " - Mihomo";
$titleLink = "https://github.com/MetaCubeX/mihomo";
$iconHtml = '<img src="./assets/img/mihomo.png" alt="Mihomo" class="me-1" style="width: 2.8rem; height: 2.8rem;">';
} else {
$iconHtml = '<i class="bi bi-palette-fill me-2" style="color: var(--accent-color); font-size: 1.8rem;"></i>';
}
$footer = '<span class="footer-text">©2025 <b>Thaolga</b></span>';
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/filekit.php | luci-app-nekobox/htdocs/nekobox/filekit.php | <?php
ini_set('memory_limit', '256M');
ob_start();
include './cfg.php';
$root_dir = "/";
$current_dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$current_dir = '/' . trim($current_dir, '/') . '/';
if ($current_dir == '//') $current_dir = '/';
$current_path = $root_dir . ltrim($current_dir, '/');
if (strpos(realpath($current_path), realpath($root_dir)) !== 0) {
$current_dir = '/';
$current_path = $root_dir;
}
if (isset($_GET['preview']) && isset($_GET['path'])) {
$preview_path = realpath($root_dir . '/' . $_GET['path']);
if ($preview_path && strpos($preview_path, realpath($root_dir)) === 0) {
$mime_type = mime_content_type($preview_path);
header('Content-Type: ' . $mime_type);
readfile($preview_path);
exit;
}
header('HTTP/1.0 404 Not Found');
exit;
}
if (isset($_GET['action']) && $_GET['action'] === 'refresh') {
$contents = getDirectoryContents($current_path);
echo json_encode($contents);
exit;
}
if (isset($_POST['action']) && $_POST['action'] === 'delete_selected') {
if (isset($_POST['selected_paths']) && is_array($_POST['selected_paths'])) {
foreach ($_POST['selected_paths'] as $path) {
deleteItem($current_path . $path);
}
header("Location: ?dir=" . urlencode($current_dir));
exit;
}
}
if (isset($_GET['action']) && $_GET['action'] === 'get_content' && isset($_GET['path'])) {
$file_path = $current_path . $_GET['path'];
if (file_exists($file_path) && is_readable($file_path)) {
$content = file_get_contents($file_path);
header('Content-Type: text/plain; charset=utf-8');
echo $content;
exit;
} else {
http_response_code(404);
echo 'File does not exist or is not readable.';
exit;
}
}
if (isset($_GET['download'])) {
downloadFile($current_path . $_GET['download']);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'rename':
$new_name = basename($_POST['new_path']);
$old_path = $current_path . $_POST['old_path'];
$new_path = dirname($old_path) . '/' . $new_name;
renameItem($old_path, $new_path);
break;
case 'edit':
$content = $_POST['content'];
$encoding = $_POST['encoding'];
$result = editFile($current_path . $_POST['path'], $content, $encoding);
if (!$result) {
echo "<script>alert('Error: Unable to save the file.');</script>";
}
break;
case 'delete':
deleteItem($current_path . $_POST['path']);
break;
case 'chmod':
chmodItem($current_path . $_POST['path'], $_POST['permissions']);
break;
case 'create_folder':
$new_folder_name = $_POST['new_folder_name'];
$new_folder_path = $current_path . '/' . $new_folder_name;
if (!file_exists($new_folder_path)) {
mkdir($new_folder_path);
}
break;
case 'create_file':
$new_file_name = $_POST['new_file_name'];
$new_file_path = $current_path . '/' . $new_file_name;
if (!file_exists($new_file_path)) {
file_put_contents($new_file_path, '');
chmod($new_file_path, 0644);
}
break;
}
} elseif (isset($_FILES['upload'])) {
uploadFile($current_path);
}
}
function deleteItem($path) {
$path = rtrim(str_replace('//', '/', $path), '/');
if (!file_exists($path)) {
error_log("Attempted to delete non-existent item: $path");
return false;
}
if (is_dir($path)) {
return deleteDirectory($path);
} else {
if (@unlink($path)) {
return true;
} else {
error_log("Failed to delete file: $path");
return false;
}
}
}
function deleteDirectory($dir) {
if (!is_dir($dir)) {
return false;
}
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
$path = $dir . '/' . $file;
is_dir($path) ? deleteDirectory($path) : @unlink($path);
}
return @rmdir($dir);
}
function readFileWithEncoding($path) {
$content = file_get_contents($path);
$encoding = mb_detect_encoding($content, ['UTF-8', 'ASCII', 'ISO-8859-1', 'Windows-1252', 'GBK', 'Big5', 'Shift_JIS', 'EUC-KR'], true);
return json_encode([
'content' => mb_convert_encoding($content, 'UTF-8', $encoding),
'encoding' => $encoding
]);
}
function renameItem($old_path, $new_path) {
$old_path = rtrim(str_replace('//', '/', $old_path), '/');
$new_path = rtrim(str_replace('//', '/', $new_path), '/');
$new_name = basename($new_path);
$dir = dirname($old_path);
$new_full_path = $dir . '/' . $new_name;
if (!file_exists($old_path)) {
error_log("Source file does not exist before rename: $old_path");
if (file_exists($new_full_path)) {
error_log("But new file already exists: $new_full_path. Rename might have succeeded.");
return true;
}
return false;
}
$result = rename($old_path, $new_full_path);
if (!$result) {
error_log("Rename function returned false for: $old_path to $new_full_path");
if (file_exists($new_full_path) && !file_exists($old_path)) {
error_log("However, new file exists and old file doesn't. Consider rename successful.");
return true;
}
}
if (file_exists($new_full_path)) {
error_log("New file exists after rename: $new_full_path");
} else {
error_log("New file does not exist after rename attempt: $new_full_path");
}
if (file_exists($old_path)) {
error_log("Old file still exists after rename attempt: $old_path");
} else {
error_log("Old file no longer exists after rename attempt: $old_path");
}
return $result;
}
function editFile($path, $content, $encoding) {
if (file_exists($path) && is_writable($path)) {
return file_put_contents($path, $content) !== false;
}
return false;
}
function chmodItem($path, $permissions) {
chmod($path, octdec($permissions));
}
function uploadFile($destination) {
$uploaded_files = [];
$errors = [];
if (!is_dir($destination)) {
@mkdir($destination, 0755, true);
}
foreach ($_FILES["upload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["upload"]["tmp_name"][$key];
$name = basename($_FILES["upload"]["name"][$key]);
$target_file = rtrim($destination, '/') . '/' . $name;
if (file_exists($target_file)) {
$errors[] = "The file $name already exists.";
continue;
}
if (move_uploaded_file($tmp_name, $target_file)) {
$uploaded_files[] = $name;
chmod($target_file, 0644);
} else {
$errors[] = "Failed to upload $name.";
}
} else {
$errors[] = "Upload error for file $key: " . getUploadError($error);
}
}
$result = [];
if (!empty($errors)) {
$result['error'] = implode("\n", $errors);
}
if (!empty($uploaded_files)) {
$result['success'] = implode(", ", $uploaded_files);
}
return $result;
}
if (!function_exists('deleteDirectory')) {
function deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) return false;
}
return rmdir($dir);
}
}
function downloadFile($file) {
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
function getDirectoryContents($dir) {
$contents = array();
foreach (scandir($dir) as $item) {
if ($item != "." && $item != "..") {
$path = $dir . DIRECTORY_SEPARATOR . $item;
$perms = '----';
$size = '-';
$mtime = '-';
$owner = '-';
if (file_exists($path) && is_readable($path)) {
$perms = substr(sprintf('%o', fileperms($path)), -4);
if (!is_dir($path)) {
$size = formatSize(filesize($path));
}
$mtime = date("Y-m-d H:i:s", filemtime($path));
$owner = function_exists('posix_getpwuid') ? posix_getpwuid(fileowner($path))['name'] : fileowner($path);
}
$contents[] = array(
'name' => $item,
'path' => str_replace($dir, '', $path),
'is_dir' => is_dir($path),
'permissions' => $perms,
'size' => $size,
'mtime' => $mtime,
'owner' => $owner,
'extension' => pathinfo($path, PATHINFO_EXTENSION)
);
}
}
return $contents;
}
function formatSize($bytes) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2) . ' ' . $units[$pow];
}
$contents = getDirectoryContents($current_path);
$breadcrumbs = array();
$path_parts = explode('/', trim($current_dir, '/'));
$cumulative_path = '';
foreach ($path_parts as $part) {
$cumulative_path .= $part . '/';
$breadcrumbs[] = array('name' => $part, 'path' => $cumulative_path);
}
if (isset($_GET['action']) && $_GET['action'] === 'search' && isset($_GET['term'])) {
$searchTerm = $_GET['term'];
$searchResults = searchFiles($current_path, $searchTerm);
echo json_encode($searchResults);
exit;
}
function searchFiles($dir, $term) {
$results = array();
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::SELF_FIRST
);
$webRoot = $_SERVER['DOCUMENT_ROOT'];
$tmpDir = sys_get_temp_dir();
foreach ($files as $file) {
if ($file->isDir()) continue;
if (stripos($file->getFilename(), $term) !== false) {
$fullPath = $file->getPathname();
if (strpos($fullPath, $webRoot) === 0) {
$relativePath = substr($fullPath, strlen($webRoot));
} elseif (strpos($fullPath, $tmpDir) === 0) {
$relativePath = 'tmp' . substr($fullPath, strlen($tmpDir));
} else {
$relativePath = $fullPath;
}
$relativePath = ltrim($relativePath, '/');
$results[] = array(
'path' => $relativePath,
'dir' => dirname($relativePath) === '.' ? '' : dirname($relativePath),
'name' => $file->getFilename()
);
}
}
return $results;
}
?>
<title>Filekit - Nekobox</title>
<?php include './ping.php'; ?>
<link rel="icon" href="./assets/img/nekobox.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.32.6/ace.js"></script>
<script src="./assets/js/js-yaml.min.js"></script>
<script src="./assets/js/ext-language_tools.js"></script>
<script src="./assets/js/mode-json.min.js"></script>
<script src="./assets/js/mode-yaml.min.js"></script>
<script src="./assets/js/beautify.min.js"></script>
<script src="./assets/js/beautify-css.min.js"></script>
<script src="./assets/js/beautify-html.min.js"></script>
<script src="./assets/js/beautify.min.js"></script>
<script src="./assets/js/ext-beautify.min.js"></script>
<script src="./assets/js/ext-spellcheck.min.js"></script>
<style>
.folder-icon::before{content:"📁";}.file-icon::before{content:"📄";}.file-icon.file-pdf::before{content:"📕";}.file-icon.file-doc::before,.file-icon.file-docx::before{content:"📘";}.file-icon.file-xls::before,.file-icon.file-xlsx::before{content:"📗";}.file-icon.file-ppt::before,.file-icon.file-pptx::before{content:"📙";}.file-icon.file-zip::before,.file-icon.file-rar::before,.file-icon.file-7z::before{content:"🗜️";}.file-icon.file-mp3::before,.file-icon.file-wav::before,.file-icon.file-ogg::before,.file-icon.file-flac::before{content:"🎵";}.file-icon.file-mp4::before,.file-icon.file-avi::before,.file-icon.file-mov::before,.file-icon.file-wmv::before,.file-icon.file-flv::before{content:"🎞️";}.file-icon.file-jpg::before,.file-icon.file-jpeg::before,.file-icon.file-png::before,.file-icon.file-gif::before,.file-icon.file-bmp::before,.file-icon.file-tiff::before{content:"🖼️";}.file-icon.file-txt::before{content:"📝";}.file-icon.file-rtf::before{content:"📄";}.file-icon.file-md::before,.file-icon.file-markdown::before{content:"📑";}.file-icon.file-exe::before,.file-icon.file-msi::before{content:"⚙️";}.file-icon.file-bat::before,.file-icon.file-sh::before,.file-icon.file-command::before{content:"📜";}.file-icon.file-iso::before,.file-icon.file-img::before{content:"💿";}.file-icon.file-sql::before,.file-icon.file-db::before,.file-icon.file-dbf::before{content:"🗃️";}.file-icon.file-font::before,.file-icon.file-ttf::before,.file-icon.file-otf::before,.file-icon.file-woff::before,.file-icon.file-woff2::before{content:"🔤";}.file-icon.file-cfg::before,.file-icon.file-conf::before,.file-icon.file-ini::before{content:"🔧";}.file-icon.file-psd::before,.file-icon.file-ai::before,.file-icon.file-eps::before,.file-icon.file-svg::before{content:"🎨";}.file-icon.file-dll::before,.file-icon.file-so::before{content:"🧩";}.file-icon.file-css::before{content:"🎨";}.file-icon.file-js::before{content:"🟨";}.file-icon.file-php::before{content:"🐘";}.file-icon.file-json::before{content:"📊";}.file-icon.file-html::before,.file-icon.file-htm::before{content:"🌐";}.file-icon.file-bin::before{content:"👾";}
#aceEditor {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
flex-direction: column;
box-sizing: border-box;
background-color: var(--card-bg);
z-index: 1100;
}
#aceEditorContainer {
flex: 1;
width: 90%;
margin: 0 auto;
min-height: 0;
border-radius: 4px;
overflow: hidden;
margin-top: 40px;
z-index: 1100;
}
#editorControls {
display: flex;
align-items: center;
padding: 8px 16px;
background-color: var(--card-bg);
width: 100%;
position: fixed;
top: 0;
z-index: 1101;
box-sizing: border-box;
border-bottom: 1px solid #ccc;
}
#encoding, #editorTheme, #fontSize {
background-color: var(--header-bg) !important;
color: #ffffff !important;
border: 1px solid #ccc !important;
padding: 5px !important;
border-radius: 4px !important;
appearance: none !important;
}
#encoding option,
#editorTheme option,
#fontSize option {
background-color: #ffffff !important;
color: #000000 !important
}
#encoding option:checked,
#editorTheme option:checked,
#fontSize option:checked {
background-color: #cce5ff !important;
}
button.editor-btn {
background-color: var(--header-bg) !important;
color: #ffffff !important;
border: 1px solid var(--header-bg) !important;
border-radius: 4px !important;
}
button.editor-btn:hover {
background-color: var(--header-bg) !important;
}
#leftControls {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
overflow-x: auto;
white-space: nowrap;
}
#statusInfo {
display: flex;
align-items: center;
gap: 12px;
font-size: 16px;
color: var(--text-primary);
margin-left: auto;
padding-left: 20px;
font-weight: bold;
}
#currentLine,
#currentColumn,
#charCount {
font-size: 17px;
color: var(--text-primary);
font-weight: bolder;
}
#editorControls select,
#editorControls button {
padding: 5px 10px;
font-size: 13px;
height: 30px;
border: 1px solid #ccc;
border-radius: 4px;
background-color: #fff;
cursor: pointer;
flex-shrink: 0;
}
#editorControls button:hover {
background-color: #e8e8e8;
}
#editorControls select:hover {
background-color: #f2f2f2;
}
.ace_editor {
width: 100% !important;
height: 100% !important;
}
@media (max-width: 768px) {
#fontSize,
#editorTheme {
display: none !important;
}
#statusInfo {
position: fixed !important;
bottom: 10% !important;
left: 0;
width: 100%;
background-color: var(--header-bg);
border-top: 1px solid #ddd;
padding: 5px 10px;
text-align: center;
z-index: 1050;
}
}
.action-grid {
display: grid;
grid-template-columns: repeat(5, 36px);
column-gap: 15px;
overflow: visible;
justify-content: start;
}
.action-btn {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: none;
border-radius: 6px;
transition: background-color 0.2s ease, box-shadow 0.2s ease;
}
.placeholder {
width: 36px;
height: 0;
}
.ace_error_line {
background-color: rgba(255, 0, 0, 0.2) !important;
position: absolute;
z-index: 1;
}
.upload-container {
margin-bottom: 20px;
}
.upload-area {
margin-top: 10px;
}
.upload-drop-zone {
border: 2px dashed #ccc !important;
border-radius: 8px;
padding: 25px;
text-align: center;
background: #f8f9fa;
transition: all 0.3s ease;
cursor: pointer;
min-height: 150px;
display: flex;
align-items: center;
justify-content: center;
}
.upload-drop-zone.drag-over {
background: #e9ecef;
border-color: #0d6efd;
}
.upload-icon {
font-size: 50px;
color: #6c757d;
transition: all 0.3s ease;
}
.upload-drop-zone:hover .upload-icon {
color: #0d6efd;
transform: scale(1.1);
}
.table td:nth-child(3),
.table td:nth-child(4),
.table td:nth-child(5),
.table td:nth-child(6),
.table td:nth-child(7) {
color: var(--text-primary);
}
.btn-toolbar .btn-group .btn.btn-outline-secondary {
color: var(--text-primary);
border-color: var(--text-primary);
}
.btn-toolbar .btn-group .btn.btn-outline-secondary i {
color: var(--text-primary) !important;
}
.upload-instructions,
.form-text[data-translate],
label.form-label[data-translate] {
color: var(--text-primary) !important;
}
.table th, .table td {
text-align: center !important;
}
.container-sm {
max-width: 100%;
margin: 0 auto;
}
table.table tbody tr:nth-child(odd) td {
color: var(--text-primary) !important;
}
.table tbody tr {
transition: all 0.2s ease;
position: relative;
cursor: pointer;
}
.table tbody tr:hover {
transform: translateY(-2px);
box-shadow: 0 3px 10px rgba(0,0,0,0.1);
z-index: 2;
background-color: rgba(0, 123, 255, 0.05);
}
.table tbody tr:hover td {
color: #007bff;
}
.ace_search {
background: var(--bg-container) !important;
border: 1px solid var(--border-color) !important;
border-radius: var(--radius);
box-shadow: var(--item-hover-shadow);
padding: 8px 12px !important;
color: var(--text-primary);
backdrop-filter: var(--glass-blur);
transition: var(--transition);
}
.ace_search_form, .ace_replace_form {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.ace_search_field {
background: var(--card-bg) !important;
border: 1px solid var(--border-color) !important;
color: var(--text-primary) !important;
padding: 6px 12px !important;
border-radius: calc(var(--radius) - 4px) !important;
font-size: 14px !important;
min-width: 200px;
transition: var(--transition);
}
.ace_search_field:focus {
border-color: var(--accent-color) !important;
outline: none;
box-shadow: 0 0 0 2px color-mix(in oklch, var(--accent-color), transparent 70%);
}
.ace_searchbtn {
background: var(--btn-primary-bg) !important;
color: white !important;
border: none !important;
border-radius: calc(var(--radius) - 4px) !important;
background-image: none !important;
padding: 6px 12px !important;
font-size: 13px !important;
cursor: pointer;
transition: var(--transition);
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 60px;
filter: contrast(1.2) brightness(1.1);
}
.ace_searchbtn:hover {
background: var(--btn-primary-hover) !important;
color: white !important;
}
.ace_searchbtn.prev,
.ace_searchbtn.next {
position: relative;
}
.ace_searchbtn.prev::before,
.ace_searchbtn.next::before {
content: "";
font-size: 14px;
color: white !important;
filter: contrast(1.3);
display: inline-block;
line-height: 1;
}
.ace_searchbtn.prev::before {
content: "↑";
}
.ace_searchbtn.next::before {
content: "↓";
}
.ace_searchbtn .ace_icon,
.ace_searchbtn::after {
display: none !important;
opacity: 0 !important;
}
.ace_searchbtn_close {
background: transparent !important;
color: var(--text-secondary) !important;
position: absolute;
right: 12px;
top: 12px;
cursor: pointer;
font-size: 16px;
transition: var(--transition);
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 3px;
}
.ace_searchbtn_close:hover {
color: white !important;
background: var(--btn-primary-bg) !important;
}
.ace_searchbtn_close::before {
content: "×";
}
.ace_search_options {
display: flex;
align-items: center;
gap: 8px;
margin-top: 8px;
}
.ace_button {
background: var(--btn-primary-bg) !important;
color: white !important;
border: none !important;
border-radius: calc(var(--radius) - 4px) !important;
padding: 4px 8px !important;
font-size: 12px !important;
cursor: pointer;
transition: var(--transition);
filter: contrast(1.2);
}
.ace_button:hover {
background: var(--btn-primary-hover) !important;
color: white !important;
}
.ace_search_counter {
color: var(--text-secondary);
font-size: 12px;
margin-right: auto;
}
[action="toggleRegexpMode"] {
background: var(--btn-info-bg) !important;
color: white !important;
}
[action="toggleCaseSensitive"] {
background: var(--btn-warning-bg) !important;
color: white !important;
}
[action="toggleWholeWords"] {
background: var(--btn-success-bg) !important;
color: white !important;
}
[action="searchInSelection"] {
background: var(--ocean-bg) !important;
color: white !important;
}
[action="toggleReplace"] {
background: var(--lavender-bg) !important;
color: white !important;
}
.ace_searchbtn,
.ace_button,
.ace_searchbtn_close:hover {
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
}
#statusInfo {
display: flex;
align-items: center;
gap: 1.5rem;
}
#lineColumnDisplay,
#charCountDisplay {
color: var(--text-primary);
font-size: 1.1rem;
}
#lineColumnDisplay::before,
#charCountDisplay::before {
font-size: 1.3rem;
}
#lineColumnDisplay .number,
#charCountDisplay .number {
font-size: 1.3rem;
}
table.table tbody tr td.folder-icon,
table.table tbody tr td.file-icon {
text-align: left !important;
}
.section-wrapper {
padding-left: 1rem;
padding-right: 1rem;
}
#siteLogo {
max-height: 50px;
height: auto;
margin-top: -25px;
}
@media (max-width: 768px) {
#siteLogo {
display: none;
}
.row.mb-3.px-2.mt-5 {
margin-top: 1.5rem !important;
}
.btn i.fas,
.btn i.bi {
font-size: 1.2rem;
}
}
</style>
<div class="container-sm container-bg px-1 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span style="color: var(--accent-color); letter-spacing: 1px;"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: var(--accent-color); font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php"><i class="bi bi-house-door"></i> <span data-translate="home">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo_manager.php' ? 'active' : '' ?>" href="./mihomo_manager.php"><i class="bi bi-folder"></i> <span data-translate="manager">Manager</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php"><i class="bi bi-shop"></i> <span data-translate="template_i">Template I</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'subscription.php' ? 'active' : '' ?>" href="./subscription.php"><i class="bi bi-bank"></i> <span data-translate="template_ii">Template II</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo.php' ? 'active' : '' ?>" href="./mihomo.php"><i class="bi bi-building"></i> <span data-translate="template_iii">Template III</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'netmon.php' ? 'active' : '' ?>" href="./netmon.php"><i class="bi bi-activity"></i> <span data-translate="traffic_monitor">Traffic Monitor</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'filekit.php' ? 'active' : '' ?>" href="./filekit.php"><i class="bi bi-bank"></i> <span data-translate="pageTitle">File Assistant</span></a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-3 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-translate-title="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-translate-title="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-translate-title="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" id="toggleIpStatusBtn" class="btn btn-warning icon-btn me-2" onclick="toggleIpStatusBar()" data-translate-title="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2" data-bs-toggle="modal" data-bs-target="#portModal" data-translate-title="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-translate-title="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<div class="row align-items-center mb-4 p-3">
<div class="col-md-3 text-center text-md-start">
<img src="./assets/img/nekobox.png" id="siteLogo" alt="Neko Box" class="img-fluid" style="max-height: 100px;">
</div>
<div class="col-md-6 text-center">
<h2 class="mb-0" id="pageTitle" data-translate="pageTitle">File Assistant</h2>
</div>
<div class="col-md-3"></div>
</div>
<div class="row mb-3 px-2 mt-5">
<div class="col-12">
<div class="btn-toolbar justify-content-between">
<div class="btn-group">
<button type="button" class="btn btn-outline-secondary" onclick="goToParentDirectory()" title="Go Back" data-translate-title="goToParentDirectoryTitle">
<i class="fas fa-arrow-left"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="location.href='?dir=/'" title="Return to Root Directory" data-translate-title="rootDirectoryTitle">
<i class="fas fa-home"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="location.href='?dir=/root'" title="Return to Home Directory" data-translate-title="homeDirectoryTitle">
<i class="fas fa-user"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="location.reload()" title="Refresh Directory Content" data-translate-title="refreshDirectoryTitle">
<i class="fas fa-sync-alt"></i>
</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#searchModal" id="searchBtn" title="Search" data-translate-title="searchTitle">
<i class="fas fa-search"></i>
</button>
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#createModal" id="createBtn" title="Create New" data-translate-title="createTitle">
<i class="fas fa-plus"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="showUploadArea()" id="uploadBtn" title="Upload" data-translate-title="uploadTitle">
<i class="fas fa-upload"></i>
</button>
</div>
</div>
</div>
</div>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="?dir=">root</a></li>
<?php
$path = '';
$breadcrumbs = explode('/', trim($current_dir, '/'));
foreach ($breadcrumbs as $crumb) {
if (!empty($crumb)) {
$path .= '/' . $crumb;
echo '<li class="breadcrumb-item"><a href="?dir=' . urlencode($path) . '">' . htmlspecialchars($crumb) . '</a></li>';
}
}
?>
</ol>
</nav>
<div class="section-wrapper">
<div class="upload-container">
<div class="upload-area" id="uploadArea" style="display: none;">
<div class="d-flex justify-content-between align-items-center mb-2">
<p class="upload-instructions mb-0">
<span data-translate="dragHint">Drag files here or click to select files to upload</span>
</p>
<button type="button" class="btn btn-secondary btn-sm ms-2" onclick="hideUploadArea()" data-translate="cancel">Cancel</button>
</div>
<form action="" method="post" enctype="multipart/form-data" id="uploadForm">
<input type="file" name="upload[]" id="fileInput" style="display: none;" multiple required>
<div class="upload-drop-zone p-4 border rounded bg-light" id="dropZone">
<i class="fas fa-cloud-upload-alt upload-icon"></i>
</div>
</form>
</div>
</div>
</div>
<div class="section-wrapper">
<div class="alert alert-secondary d-none mb-3" id="toolbar">
<div class="d-flex justify-content-between flex-column flex-sm-row align-items-center">
<div class="mb-2 mb-sm-0">
<button class="btn btn-outline-primary btn-sm me-2" id="selectAllBtn" data-translate="select_all">Deselect All</button>
<span id="selectedInfo" class="text-muted small" data-translate="selected_info">{0} item(s) selected</span>
</div>
<button class="btn btn-danger btn-sm" id="batchDeleteBtn"><i class="fas fa-trash-alt me-1"></i><span data-translate="batch_delete">Batch Delete</span></button>
</div>
</div>
</div>
<form id="batchDeleteForm" method="post" action="?dir=<?php echo urlencode($current_dir); ?>" style="display: none;"></form>
<div class="container-fluid text-center">
<div class="table-responsive">
<table class="table table-striped table-bordered align-middle">
<thead class="table-light">
<tr>
<th scope="col">
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/panel.php | luci-app-nekobox/htdocs/nekobox/panel.php | <?php
include './cfg.php';
$neko_cfg['ctrl_host'] = $_SERVER['SERVER_NAME'];
$command = "cat $selected_config | grep external-c | awk '{print $2}' | cut -d: -f2";
$port_output = shell_exec($command);
if ($port_output === null) {
$neko_cfg['ctrl_port'] = 'default_port';
} else {
$neko_cfg['ctrl_port'] = trim($port_output);
}
$yacd_link = $neko_cfg['ctrl_host'] . ':' . $neko_cfg['ctrl_port'] . '/ui/meta?hostname=' . $neko_cfg['ctrl_host'] . '&port=' . $neko_cfg['ctrl_port'] . '&secret=' . $neko_cfg['secret'];
$zash_link = $neko_cfg['ctrl_host'] . ':' . $neko_cfg['ctrl_port'] . '/ui/zashboard?hostname=' . $neko_cfg['ctrl_host'] . '&port=' . $neko_cfg['ctrl_port'] . '&secret=' . $neko_cfg['secret'];
$meta_link = $neko_cfg['ctrl_host'] . ':' . $neko_cfg['ctrl_port'] . '/ui/metacubexd?hostname=' . $neko_cfg['ctrl_host'] . '&port=' . $neko_cfg['ctrl_port'] . '&secret=' . $neko_cfg['secret'];
$dash_link = $neko_cfg['ctrl_host'] . ':' . $neko_cfg['ctrl_port'] . '/ui/dashboard?hostname=' . $neko_cfg['ctrl_host'] . '&port=' . $neko_cfg['ctrl_port'] . '&secret=' . $neko_cfg['secret'];
?>
<title>Panel - Nekobox</title>
<link rel="icon" href="./assets/img/nekobox.png">
<?php include './ping.php'; ?>
<style>
#iframeMeta {
width: 100%;
height: 78vh;
transition: height 0.3s ease;
}
@media (max-width: 768px) {
#iframeMeta {
height: 68vh;
}
}
body, html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
}
main {
flex: 1;
}
footer {
margin-top: 8px !important;
padding: 8px 0;
}
</style>
<div id="mainNavbar" class="container-sm container-bg text-center mt-4">
<?php include 'navbar.php'; ?>
<main class="container-fluid text-left px-0 px-sm-3 px-md-4 p-3">
<iframe id="iframeMeta" class="w-100" src="http://<?=$zash_link?>" title="zash" allowfullscreen style="border-radius: 10px;"></iframe>
<div class="mt-3 mb-0">
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#panelModal" data-translate="panel_settings">Panel Settings</button>
</div>
</main>
<div class="modal fade" id="panelModal" tabindex="-1" aria-labelledby="panelModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="panelModalLabel" data-translate="select_panel">Select Panel</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="panelSelect" class="form-label" data-translate="select_panel">Select Panel</label>
<select id="panelSelect" class="form-select" onchange="changeIframe(this.value)">
<option value="http://<?=$zash_link?>" data-translate="zash_panel">Zash</option>
<option value="http://<?=$yacd_link?>" data-translate="yacd_panel">YACD</option>
<option value="http://<?=$dash_link?>" data-translate="dash_panel">Dash</option>
<option value="http://<?=$meta_link?>" data-translate="metacubexd_panel">MetaCubeXD</option>
</select>
</div>
<div class="d-flex justify-content-around flex-wrap gap-2">
<a class="btn btn-primary btn-sm text-white" target="_blank" href="http://<?=$yacd_link?>" data-translate="yacd_panel">YACD</a>
<a class="btn btn-success btn-sm text-white" target="_blank" href="http://<?=$dash_link?>" data-translate="dash_panel">Dash</a>
<a class="btn btn-warning btn-sm text-white" target="_blank" href="http://<?=$meta_link?>" data-translate="metacubexd_panel">MetaCubeXD</a>
<a class="btn btn-info btn-sm text-white" target="_blank" href="http://<?=$zash_link?>" data-translate="zash_panel">Zash</a>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="close">Close</button>
</div>
</div>
</div>
</div>
<script>
const panelSelect = document.getElementById('panelSelect');
const iframeMeta = document.getElementById('iframeMeta');
const savedPanel = localStorage.getItem('selectedPanel');
if (savedPanel) {
iframeMeta.src = savedPanel;
panelSelect.value = savedPanel;
}
panelSelect.addEventListener('change', function() {
iframeMeta.src = panelSelect.value;
localStorage.setItem('selectedPanel', panelSelect.value);
});
document.getElementById('confirmPanelSelection').addEventListener('click', function() {
var selectedPanel = panelSelect.value;
iframeMeta.src = selectedPanel;
var myModal = new bootstrap.Modal(document.getElementById('panelModal'));
myModal.hide();
localStorage.setItem('selectedPanel', selectedPanel);
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
const iframe = document.getElementById('iframeMeta');
const buttonContainer = document.querySelector('.mt-3.mb-0');
const footer = document.querySelector('footer');
function adjustIframeHeight() {
const viewportHeight = window.innerHeight;
const buttonHeight = buttonContainer ? buttonContainer.offsetHeight : 0;
const footerHeight = footer ? footer.offsetHeight : 0;
const extraMargin = 40;
const availableHeight = viewportHeight - buttonHeight - footerHeight - extraMargin;
const isSmallScreen = window.innerWidth <= 768;
const baseHeight = isSmallScreen ? viewportHeight * 0.68 : viewportHeight * 0.78;
const finalHeight = Math.min(baseHeight, availableHeight);
iframe.style.height = finalHeight + 'px';
}
adjustIframeHeight();
window.addEventListener('resize', adjustIframeHeight);
});
</script> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/navbar.php | luci-app-nekobox/htdocs/nekobox/navbar.php | <nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-1 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span id="dynamicTitle" style="color: var(--accent-color); letter-spacing: 1px; cursor: pointer;" onclick="window.open('<?= $titleLink ?>', '_blank')"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: var(--accent-color); font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php">
<i class="bi bi-house-door"></i>
<span data-translate="home">Home</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'panel.php' ? 'active' : '' ?>" href="./panel.php">
<i class="bi bi-bar-chart"></i>
<span data-translate="panel">Panel</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php">
<i class="bi bi-box"></i>
<span data-translate="document">Document</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'settings.php' ? 'active' : '' ?>" href="./settings.php">
<i class="bi bi-gear"></i>
<span data-translate="settings">Settings</span>
</a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-0 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-tooltip="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-deepskyblue icon-btn me-2" data-bs-toggle="modal" data-bs-target="#autostartModal" data-tooltip="autostartTooltip"><i class="fas fa-power-off"></i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-tooltip="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-tooltip="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" class="btn btn-warning icon-btn me-2" id="toggleIpStatusBtn" onclick="toggleIpStatusBar()" data-tooltip="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2 d-none d-sm-inline" data-bs-toggle="modal" data-bs-target="#portModal" data-tooltip="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" id="updatePhpConfig" data-tooltip="unlock_php_upload_limit"><i class="bi bi-unlock"></i></button>
<button type="button" class="btn-refresh-page btn btn-orange icon-btn me-2 d-none d-sm-inline"><i class="fas fa-sync-alt"></i></button>
<button type="button" class="btn btn-fuchsia icon-btn me-2 d-none d-sm-inline" onclick="handleIPClick()" data-tooltip="show_ip"><i class="fas fa-globe"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-tooltip="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<script>
document.getElementById("updatePhpConfig").addEventListener("click", function() {
const confirmText = translations['confirm_update_php'] || "Are you sure you want to update PHP configuration?";
speakMessage(confirmText);
showConfirmation(confirmText, () => {
fetch("update_php_config.php", {
method: "POST",
headers: { "Content-Type": "application/json" }
})
.then(response => response.json())
.then(data => {
const msg = data.message || "Configuration updated successfully.";
showLogMessage(msg);
speakMessage(msg);
})
.catch(error => {
const errMsg = translations['request_failed'] || ("Request failed: " + error.message);
showLogMessage(errMsg);
speakMessage(errMsg);
});
});
});
</script>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/mihomo.php | luci-app-nekobox/htdocs/nekobox/mihomo.php | <?php
ob_start();
include './cfg.php';
ini_set('memory_limit', '256M');
$subscription_file = '/etc/neko/subscription.txt';
$download_path = '/etc/neko/config/';
$sh_script_path = '/etc/neko/core/update_config.sh';
$log_file = '/var/log/neko_update.log';
$current_subscription_url = '';
if (isset($_POST['subscription_url'])) {
$current_subscription_url = $_POST['subscription_url'];
}
function logMessage($message) {
global $log_file;
$timestamp = date('Y-m-d H:i:s');
file_put_contents($log_file, "[$timestamp] $message\n", FILE_APPEND);
}
function buildFinalUrl($subscription_url, $config_url, $include, $exclude, $backend_url, $emoji, $udp, $xudp, $tfo, $tls13, $fdn, $sort, $rename) {
$encoded_subscription_url = urlencode($subscription_url);
$encoded_config_url = urlencode($config_url);
$encoded_include = urlencode($include);
$encoded_exclude = urlencode($exclude);
$encoded_rename = urlencode($rename);
$final_url = "{$backend_url}target=clash&url={$encoded_subscription_url}&insert=false&config={$encoded_config_url}";
if (!empty($include)) {
$final_url .= "&include={$encoded_include}";
}
if (!empty($exclude)) {
$final_url .= "&exclude={$encoded_exclude}";
}
$final_url .= "&emoji=" . (isset($_POST['emoji']) && $_POST['emoji'] === 'true' ? "true" : "false");
$final_url .= "&xudp=" . (isset($_POST['xudp']) && $_POST['xudp'] === 'true' ? "true" : "false");
$final_url .= "&udp=" . (isset($_POST['udp']) && $_POST['udp'] === 'true' ? "true" : "false");
$final_url .= "&tfo=" . (isset($_POST['tfo']) && $_POST['tfo'] === 'true' ? "true" : "false");
$final_url .= "&fdn=" . (isset($_POST['fdn']) && $_POST['fdn'] === 'true' ? "true" : "false");
$final_url .= "&tls13=" . (isset($_POST['tls13']) && $_POST['tls13'] === 'true' ? "true" : "false");
$final_url .= "&sort=" . (isset($_POST['sort']) && $_POST['sort'] === 'true' ? "true" : "false");
$final_url .= "&list=false&expand=true&scv=false&new_name=true";
return $final_url;
}
function saveSubscriptionUrlToFile($url, $file) {
$success = file_put_contents($file, $url) !== false;
logMessage($success ? "Subscription link has been saved to $file" : "Failed to save subscription link to $file");
return $success;
}
function transformContent($content) {
$new_config_start = "redir-port: 7892
port: 7890
socks-port: 7891
mixed-port: 7893
mode: rule
log-level: info
allow-lan: true
unified-delay: true
external-controller: 0.0.0.0:9090
secret: Akun
bind-address: 0.0.0.0
external-ui: ui
tproxy-port: 7895
tcp-concurrent: true
enable-process: true
find-process-mode: always
ipv6: true
experimental:
ignore-resolve-fail: true
sniff-tls-sni: true
tracing: true
hosts:
\"localhost\": 127.0.0.1
profile:
store-selected: true
store-fake-ip: true
sniffer:
enable: true
sniff:
http: { ports: [1-442, 444-8442, 8444-65535], override-destination: true }
tls: { ports: [1-79, 81-8079, 8081-65535], override-destination: true }
force-domain:
- \"+.v2ex.com\"
- www.google.com
- google.com
skip-domain:
- Mijia Cloud
- dlg.io.mi.com
sniffing:
- tls
- http
port-whitelist:
- \"80\"
- \"443\"
tun:
enable: true
prefer-h3: true
listen: 0.0.0.0:53
stack: gvisor
dns-hijack:
- \"any:53\"
- \"tcp://any:53\"
auto-redir: true
auto-route: true
auto-detect-interface: true
dns:
enable: true
ipv6: true
default-nameserver:
- '1.1.1.1'
- '8.8.8.8'
enhanced-mode: fake-ip
fake-ip-range: 198.18.0.1/16
fake-ip-filter:
- 'stun.*.*'
- 'stun.*.*.*'
- '+.stun.*.*'
- '+.stun.*.*.*'
- '+.stun.*.*.*.*'
- '+.stun.*.*.*.*.*'
- '*.lan'
- '+.msftncsi.com'
- msftconnecttest.com
- 'time?.*.com'
- 'time.*.com'
- 'time.*.gov'
- 'time.*.apple.com'
- time-ios.apple.com
- 'time1.*.com'
- 'time2.*.com'
- 'time3.*.com'
- 'time4.*.com'
- 'time5.*.com'
- 'time6.*.com'
- 'time7.*.com'
- 'ntp?.*.com'
- 'ntp.*.com'
- 'ntp1.*.com'
- 'ntp2.*.com'
- 'ntp3.*.com'
- 'ntp4.*.com'
- 'ntp5.*.com'
- 'ntp6.*.com'
- 'ntp7.*.com'
- '+.pool.ntp.org'
- '+.ipv6.microsoft.com'
- speedtest.cros.wr.pvp.net
- network-test.debian.org
- detectportal.firefox.com
- cable.auth.com
- miwifi.com
- routerlogin.com
- routerlogin.net
- tendawifi.com
- tendawifi.net
- tplinklogin.net
- tplinkwifi.net
- '*.xiami.com'
- tplinkrepeater.net
- router.asus.com
- '*.*.*.srv.nintendo.net'
- '*.*.stun.playstation.net'
- '*.openwrt.pool.ntp.org'
- resolver1.opendns.com
- 'GC._msDCS.*.*'
- 'DC._msDCS.*.*'
- 'PDC._msDCS.*.*'
use-hosts: true
nameserver:
- '8.8.4.4'
- '1.0.0.1'
- \"https://1.0.0.1/dns-query\"
- \"https://8.8.4.4/dns-query\"
";
$parts = explode('proxies:', $content, 2);
if (count($parts) == 2) {
return $new_config_start . "\nproxies:" . $parts[1];
} else {
return $content;
}
}
function saveSubscriptionContentToYaml($url, $filename) {
global $download_path;
if (pathinfo($filename, PATHINFO_EXTENSION) !== 'yaml') {
$filename .= '.yaml';
}
if (strpbrk($filename, "!@#$%^&*()+=[]\\\';,/{}|\":<>?") !== false) {
$message = "Filename contains illegal characters. Please use letters, numbers, dots, underscores, or hyphens.";
logMessage($message);
return $message;
}
if (!is_dir($download_path)) {
if (!mkdir($download_path, 0755, true)) {
$message = "Unable to create directory: $download_path";
logMessage($message);
return $message;
}
}
$output_file = escapeshellarg($download_path . $filename);
$command = "wget -q --no-check-certificate -O $output_file " . escapeshellarg($url);
exec($command, $output, $return_var);
if ($return_var !== 0) {
$message = "wget Error,Unable to retrieve subscription content. Please check if the link is correct.";
logMessage($message);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$subscription_data = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
curl_close($ch);
$message = "cURL Error: $error_msg";
logMessage($message);
return $message;
}
curl_close($ch);
if (empty($subscription_data)) {
$message = "Unable to retrieve subscription content. Please check if the link is correct.";
logMessage($message);
return $message;
}
$decoded_data = (base64_decode($subscription_data, true) !== false) ? base64_decode($subscription_data) : $subscription_data;
$transformed_data = transformContent($decoded_data);
$file_path = $download_path . $filename;
$success = file_put_contents($file_path, $transformed_data) !== false;
$message = $success ? "Content successfully saved to: $file_path" : "File save failed.";
logMessage($message);
return $message;
}
function generateShellScript() {
global $subscription_file, $download_path, $sh_script_path;
$sh_script_content = <<<EOD
#!/bin/bash
SUBSCRIPTION_FILE='$subscription_file'
DOWNLOAD_PATH='$download_path'
DEST_PATH='/etc/neko/config/config.yaml'
if [ ! -f "\$SUBSCRIPTION_FILE" ]; then
echo "Subscription file not found: \$SUBSCRIPTION_FILEE"
exit 1
fi
SUBSCRIPTION_URL=\$(cat "\$SUBSCRIPTION_FILE")
subscription_data=\$(wget -qO- "\$SUBSCRIPTION_URL")
if [ -z "\$subscription_data" ]; then
echo "Unable to retrieve subscription content, please check the subscription link."
exit 1
fi
subscription_data=\$(echo "\$subscription_data" | sed '/port: 7890/d')
subscription_data=\$(echo "\$subscription_data" | sed '/socks-port: 7891/d')
subscription_data=\$(echo "\$subscription_data" | sed '/allow-lan: true/d')
subscription_data=\$(echo "\$subscription_data" | sed '/mode: Rule/d')
subscription_data=\$(echo "\$subscription_data" | sed '/log-level: info/d')
subscription_data=\$(echo "\$subscription_data" | sed '/external-controller: :9090/d')
subscription_data=\$(echo "\$subscription_data" | sed '/dns:/d')
subscription_data=\$(echo "\$subscription_data" | sed '/enabled: true/d')
subscription_data=\$(echo "\$subscription_data" | sed '/nameserver:/d')
subscription_data=\$(echo "\$subscription_data" | sed '/119.29.29.29/d')
subscription_data=\$(echo "\$subscription_data" | sed '/223.5.5.5/d')
subscription_data=\$(echo "\$subscription_data" | sed '/fallback:/d')
subscription_data=\$(echo "\$subscription_data" | sed '/8.8.8.8/d')
subscription_data=\$(echo "\$subscription_data" | sed '/8.8.4.4/d')
subscription_data=\$(echo "\$subscription_data" | sed '/tls:\/\/1.0.0.1:853/d')
subscription_data=\$(echo "\$subscription_data" | sed '/- tls:\/\/dns.google:853/d')
new_config_start="redir-port: 7892
port: 7890
socks-port: 7891
mixed-port: 7893
mode: rule
log-level: info
allow-lan: true
unified-delay: true
external-controller: 0.0.0.0:9090
secret: Akun
bind-address: 0.0.0.0
external-ui: ui
tproxy-port: 7895
tcp-concurrent: true
enable-process: true
find-process-mode: always
ipv6: true
experimental:
ignore-resolve-fail: true
sniff-tls-sni: true
tracing: true
hosts:
\"localhost\": 127.0.0.1
profile:
store-selected: true
store-fake-ip: true
sniffer:
enable: true
sniff:
http: { ports: [1-442, 444-8442, 8444-65535], override-destination: true }
tls: { ports: [1-79, 81-8079, 8081-65535], override-destination: true }
force-domain:
- \"+.v2ex.com\"
- www.google.com
- google.com
skip-domain:
- Mijia Cloud
- dlg.io.mi.com
sniffing:
- tls
- http
port-whitelist:
- \"80\"
- \"443\"
tun:
enable: true
prefer-h3: true
listen: 0.0.0.0:53
stack: gvisor
dns-hijack:
- \"any:53\"
- \"tcp://any:53\"
auto-redir: true
auto-route: true
auto-detect-interface: true
dns:
enable: true
ipv6: true
default-nameserver:
- '1.1.1.1'
- '8.8.8.8'
enhanced-mode: fake-ip
fake-ip-range: 198.18.0.1/16
fake-ip-filter:
- 'stun.*.*'
- 'stun.*.*.*'
- '+.stun.*.*'
- '+.stun.*.*.*'
- '+.stun.*.*.*.*'
- '+.stun.*.*.*.*.*'
- '*.lan'
- '+.msftncsi.com'
- msftconnecttest.com
- 'time?.*.com'
- 'time.*.com'
- 'time.*.gov'
- 'time.*.apple.com'
- time-ios.apple.com
- 'time1.*.com'
- 'time2.*.com'
- 'time3.*.com'
- 'time4.*.com'
- 'time5.*.com'
- 'time6.*.com'
- 'time7.*.com'
- 'ntp?.*.com'
- 'ntp.*.com'
- 'ntp1.*.com'
- 'ntp2.*.com'
- 'ntp3.*.com'
- 'ntp4.*.com'
- 'ntp5.*.com'
- 'ntp6.*.com'
- 'ntp7.*.com'
- '+.pool.ntp.org'
- '+.ipv6.microsoft.com'
- speedtest.cros.wr.pvp.net
- network-test.debian.org
- detectportal.firefox.com
- cable.auth.com
- miwifi.com
- routerlogin.com
- routerlogin.net
- tendawifi.com
- tendawifi.net
- tplinklogin.net
- tplinkwifi.net
- '*.xiami.com'
- tplinkrepeater.net
- router.asus.com
- '*.*.*.srv.nintendo.net'
- '*.*.stun.playstation.net'
- '*.openwrt.pool.ntp.org'
- resolver1.opendns.com
- 'GC._msDCS.*.*'
- 'DC._msDCS.*.*'
- 'PDC._msDCS.*.*'
use-hosts: true
nameserver:
- '8.8.4.4'
- '1.0.0.1'
- \"https://1.0.0.1/dns-query\"
- \"https://8.8.4.4/dns-query\"
"
echo -e "\$new_config_start\$subscription_data" > "\$DOWNLOAD_PATH/config.yaml"
mv "\$DOWNLOAD_PATH/config.yaml" "\$DEST_PATH"
if [ \$? -eq 0 ]; then
echo "Configuration file has been successfully updated and moved to \$DEST_PATH"
else
echo "Configuration file move failed"
exit 1
fi
EOD;
$success = file_put_contents($sh_script_path, $sh_script_content) !== false;
logMessage($success ? "Shell script has been successfully created and granted execution permissions." : "Unable to create the Shell script file.");
if ($success) {
shell_exec("chmod +x $sh_script_path");
}
return $success ? "Shell script has been successfully created and granted execution permissions." : "Unable to create the Shell script file.";
}
function setupCronJob($cron_time) {
global $sh_script_path;
$cron_entry = "$cron_time $sh_script_path\n";
$current_cron = shell_exec('crontab -l 2>/dev/null');
if (empty($current_cron)) {
$updated_cron = $cron_entry;
} else {
$updated_cron = preg_replace('/.*' . preg_quote($sh_script_path, '/') . '/m', $cron_entry, $current_cron);
if ($updated_cron == $current_cron) {
$updated_cron .= $cron_entry;
}
}
$success = file_put_contents('/tmp/cron.txt', $updated_cron) !== false;
if ($success) {
shell_exec('crontab /tmp/cron.txt');
logMessage("Cron job has been successfully set to run at $cron_time.");
return "Cron job has been successfully set to run at $cron_time.";
} else {
logMessage("Unable to write to the temporary Cron file.");
return "Unable to write to the temporary Cron file.";
}
}
$result = '';
$cron_result = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$templates = [
'1' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_NoAuto.ini?',
'2' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_AdblockPlus.ini?',
'3' => 'https://raw.githubusercontent.com/youshandefeiyang/webcdn/main/SONY.ini',
'4' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/default_with_clash_adg.yml?',
'5' => 'https://raw.githubusercontent.com/WC-Dream/ACL4SSR/WD/Clash/config/ACL4SSR_Online_Full_Dream.ini?',
'6' => 'https://raw.githubusercontent.com/WC-Dream/ACL4SSR/WD/Clash/config/ACL4SSR_Mini_Dream.ini?',
'7' => 'https://raw.githubusercontent.com/justdoiting/ClashRule/main/GeneralClashRule.ini?',
'8' => 'https://raw.githubusercontent.com/cutethotw/ClashRule/main/GeneralClashRule.ini?',
'9' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini?',
'10' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoAuto.ini?',
'11' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_AdblockPlus.ini?',
'12' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_MultiCountry.ini?',
'13' => 'ttps://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoReject.ini?',
'14' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_NoAuto.ini?',
'15' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full.ini?',
'16' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Google.ini?',
'17' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_MultiMode.ini?',
'18' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Netflix.ini?',
'19' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini.ini?',
'20' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_AdblockPlus.ini?',
'21' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_Fallback.ini?',
'22' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiCountry.ini?',
'23' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiMode.ini?',
'24' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG.ini?',
'25' => 'https://raw.githubusercontent.com/xiaoshenxian233/cool/rule/complex.ini?',
'26' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/special/phaors.ini?',
'27' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG_Area_Fallback.ini?',
'28' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG_Area_Urltest.ini?',
'29' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG_Area_NoAuto.ini?',
'30' => 'https://raw.githubusercontent.com/OoHHHHHHH/ini/master/config.ini?',
'31' => 'https://raw.githubusercontent.com/OoHHHHHHH/ini/master/cfw-tap.ini?',
'32' => 'https://raw.githubusercontent.com/lhl77/sub-ini/main/tsutsu-full.ini?',
'33' => 'https://raw.githubusercontent.com/lhl77/sub-ini/main/tsutsu-mini-gfw.ini?',
'34' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/connershua_new.ini?',
'35' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/connershua_backtocn.ini?',
'36' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/lhie1_clash.ini?',
'37' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/lhie1_dler.ini?',
'38' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/ehpo1_main.ini?',
'39' => 'https://raw.nameless13.com/api/public/dl/ROzQqi2S/white.ini?',
'40' => 'https://raw.nameless13.com/api/public/dl/ptLeiO3S/mayinggfw.ini?',
'41' => 'https://raw.nameless13.com/api/public/dl/FWSh3dXz/easy3.ini?',
'42' => 'https://raw.nameless13.com/api/public/dl/L_-vxO7I/youtube.ini?',
'43' => 'https://raw.nameless13.com/api/public/dl/zKF9vFbb/easy.ini?',
'44' => 'https://raw.nameless13.com/api/public/dl/E69bzCaE/easy2.ini?',
'45' => 'https://raw.nameless13.com/api/public/dl/XHr0miMg/ipip.ini?',
'46' => 'https://raw.nameless13.com/api/public/dl/BBnfb5lD/MAYINGVIP.ini?',
'47' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Examine.ini?',
'48' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Examine_Full.ini?',
'49' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/nzw9314_custom.ini?',
'50' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/maicoo-l_custom.ini?',
'51' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/dlercloud_lige_platinum.ini?',
'52' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/dlercloud_lige_gold.ini?',
'53' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/dlercloud_lige_silver.ini?',
'54' => 'https://unpkg.com/proxy-script/config/Clash/clash.ini?',
'55' => 'https://github.com/UlinoyaPed/ShellClash/raw/master/rules/ShellClash.ini?',
'56' => 'https://gist.github.com/jklolixxs/16964c46bad1821c70fa97109fd6faa2/raw/EXFLUX.ini?',
'57' => 'https://gist.github.com/jklolixxs/32d4e9a1a5d18a92beccf3be434f7966/raw/NaNoport.ini?',
'58' => 'https://gist.github.com/jklolixxs/dfbe0cf71ffc547557395c772836d9a8/raw/CordCloud.ini?',
'59' => 'https://gist.github.com/jklolixxs/e2b0105c8be6023f3941816509a4c453/raw/BigAirport.ini?',
'60' => 'https://gist.github.com/jklolixxs/9f6989137a2cfcc138c6da4bd4e4cbfc/raw/PaoLuCloud.ini?',
'61' => 'https://gist.github.com/jklolixxs/fccb74b6c0018b3ad7b9ed6d327035b3/raw/WaveCloud.ini?',
'62' => 'https://gist.github.com/jklolixxs/bfd5061dceeef85e84401482f5c92e42/raw/JiJi.ini?',
'63' => 'https://gist.github.com/jklolixxs/6ff6e7658033e9b535e24ade072cf374/raw/SJ.ini?',
'64' => 'https://gist.github.com/jklolixxs/24f4f58bb646ee2c625803eb916fe36d/raw/ImmTelecom.ini?',
'65' => 'https://gist.github.com/jklolixxs/b53d315cd1cede23af83322c26ce34ec/raw/AmyTelecom.ini?',
'66' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/convenience.ini?',
'67' => 'https://gist.github.com/jklolixxs/ff8ddbf2526cafa568d064006a7008e7/raw/Miaona.ini?',
'68' => 'https://gist.github.com/jklolixxs/df8fda1aa225db44e70c8ac0978a3da4/raw/Foo&Friends.ini?',
'69' => 'https://gist.github.com/jklolixxs/b1f91606165b1df82e5481b08fd02e00/raw/ABCloud.ini?',
'70' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/xianyu.ini?',
'71' => 'https://subweb.oss-cn-hongkong.aliyuncs.com/RemoteConfig/customized/convenience.ini?',
'72' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/SSRcloud.ini?',
'73' => 'https://raw.githubusercontent.com/Mazetsz/ACL4SSR/master/Clash/config/V2rayPro.ini?',
'74' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/V2Pro.ini?',
'75' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Stitch.ini?',
'76' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Stitch-Balance.ini?',
'77' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/maying.ini?',
'78' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/ytoo.ini?',
'79' => 'https://raw.nameless13.com/api/public/dl/M-We_Fn7/w8ves.ini?',
'80' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/nyancat.ini?',
'81' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/nexitally.ini?',
'82' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/socloud.ini?',
'83' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/ark.ini?',
'84' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/n3ro_optimized.ini?',
'85' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/scholar_optimized.ini?',
'86' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/flower.ini?',
'88' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/special/netease.ini?',
'89' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/special/basic.ini?'
];
$emoji = isset($_POST['emoji']) ? $_POST['emoji'] === 'true' : true;
$udp = isset($_POST['udp']) ? $_POST['udp'] === 'true' : true;
$xudp = isset($_POST['xudp']) ? $_POST['xudp'] === 'true' : true;
$tfo = isset($_POST['tfo']) ? $_POST['tfo'] === 'true' : true;
$fdn = isset($_POST['fdn']) ? $_POST['fdn'] === 'true' : true;
$sort = isset($_POST['sort']) ? $_POST['sort'] === 'true' : true;
$tls13 = isset($_POST['tls13']) ? $_POST['tls13'] === 'true' : true;
$filename = isset($_POST['filename']) && $_POST['filename'] !== '' ? $_POST['filename'] : 'config.yaml';
$subscription_url = isset($_POST['subscription_url']) ? $_POST['subscription_url'] : '';
$backend_url = isset($_POST['backend_url']) && $_POST['backend_url'] === 'custom' && !empty($_POST['custom_backend_url'])
? rtrim($_POST['custom_backend_url'], '?') . '?'
: ($_POST['backend_url'] ?? 'https://url.v1.mk/sub?');
$template_key = $_POST['template'] ?? '';
$include = $_POST['include'] ?? '';
$exclude = $_POST['exclude'] ?? '';
$template = $templates[$template_key] ?? '';
$rename = isset($_POST['rename']) ? $_POST['rename'] : '';
if (isset($_POST['action'])) {
if ($_POST['action'] === 'generate_subscription') {
$final_url = buildFinalUrl($subscription_url, $template, $include, $exclude, $backend_url, $emoji, $udp, $xudp, $tfo, $rename, $tls13, $fdn, $sort);
if (saveSubscriptionUrlToFile($final_url, $subscription_file)) {
$result = saveSubscriptionContentToYaml($final_url, $filename);
$result .= generateShellScript() . "<br>";
if (isset($_POST['cron_time'])) {
$cron_time = $_POST['cron_time'];
$cron_result = setupCronJob($cron_time) . "<br>";
}
} else {
echo "Failed to save subscription link to file.";
}
} elseif ($_POST['action'] === 'update_cron') {
if (isset($_POST['cron_time']) && $_POST['cron_time']) {
$cron_time = $_POST['cron_time'];
$cron_result = setupCronJob($cron_time);
}
}
}
}
function getSubscriptionUrlFromFile($file) {
if (file_exists($file)) {
return file_get_contents($file);
}
return '';
}
?>
<meta charset="utf-8">
<title>Mihomo - Nekobox</title>
<link rel="icon" href="./assets/img/nekobox.png">
<script src="./assets/bootstrap/jquery.min.js"></script>
<?php include './ping.php'; ?>
<div class="container-sm container-bg px-0 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span style="color: var(--accent-color); letter-spacing: 1px;"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: var(--accent-color); font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php"><i class="bi bi-house-door"></i> <span data-translate="home">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo_manager.php' ? 'active' : '' ?>" href="./mihomo_manager.php"><i class="bi bi-folder"></i> <span data-translate="manager">Manager</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php"><i class="bi bi-shop"></i> <span data-translate="template_i">Template I</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'subscription.php' ? 'active' : '' ?>" href="./subscription.php"><i class="bi bi-bank"></i> <span data-translate="template_ii">Template II</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo.php' ? 'active' : '' ?>" href="./mihomo.php"><i class="bi bi-building"></i> <span data-translate="template_iii">Template III</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'netmon.php' ? 'active' : '' ?>" href="./netmon.php"><i class="bi bi-activity"></i> <span data-translate="traffic_monitor">Traffic Monitor</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'filekit.php' ? 'active' : '' ?>" href="./filekit.php"><i class="bi bi-bank"></i> <span data-translate="pageTitle">File Assistant</span></a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-3 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-translate-title="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-translate-title="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-translate-title="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" id="toggleIpStatusBtn" class="btn btn-warning icon-btn me-2" onclick="toggleIpStatusBar()" data-translate-title="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2" data-bs-toggle="modal" data-bs-target="#portModal" data-translate-title="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn-refresh-page btn btn-orange icon-btn me-2 d-none d-sm-inline"><i class="fas fa-sync-alt"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-translate-title="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<h2 class="text-center p-2 mt-3 mb-2" data-translate="mihomo_conversion_template"></h2>
<div class="col-12 px-4">
<div class="form-section">
<form method="post">
<div class="mb-3">
<label for="subscription_url" class="form-label" data-translate="subscription_url_label"></label>
<input type="text" class="form-control" id="subscription_url" name="subscription_url"
value="<?php echo htmlspecialchars($current_subscription_url); ?>" placeholder="" data-translate-placeholder="subscription_url_placeholder" required>
</div>
<div class="mb-3">
<label for="filename" class="form-label" data-translate="filename"></label>
<input type="text" class="form-control" id="filename" name="filename"
value="<?php echo htmlspecialchars(isset($_POST['filename']) ? $_POST['filename'] : ''); ?>"
placeholder="config.yaml">
</div>
<div class="mb-3">
<label for="backend_url" class="form-label" data-translate="backend_url_label"></label>
<select class="form-select" id="backend_url" name="backend_url" required>
<option value="https://url.v1.mk/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://url.v1.mk/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_1"></option>
<option value="https://sub.d1.mk/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.d1.mk/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_2"></option>
<option value="https://sub.xeton.dev/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.xeton.dev/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_3"></option>
<option value="https://www.tline.website/sub/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://www.tline.website/sub/sub?' ? 'selected' : ''; ?>>
tline.website
</option>
<option value="https://api.dler.io/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://api.dler.io/sub?' ? 'selected' : ''; ?>>
api.dler.io
</option>
<option value="https://v.id9.cc/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://v.id9.cc/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_6"></option>
<option value="https://sub.id9.cc/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.id9.cc/sub?' ? 'selected' : ''; ?>>
sub.id9.cc
</option>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_singbox_core.php | luci-app-nekobox/htdocs/nekobox/update_singbox_core.php | <?php
$repo_owner = "Thaolga";
$repo_name = "luci-app-nekoclash";
$package_name = "sing-box";
$new_version = isset($_GET['version']) ? $_GET['version'] : "v1.11.0-alpha.10";
$new_version_cleaned = str_replace('v', '', $new_version);
if (isset($_GET['check_version'])) {
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
$curl_command = "curl -s -H 'User-Agent: PHP' --connect-timeout 10 " . escapeshellarg($api_url);
$latest_version_data = shell_exec($curl_command);
$latest_version_info = json_decode($latest_version_data, true);
if (isset($latest_version_info['tag_name'])) {
$latest_version = $latest_version_info['tag_name'];
echo "Latest version: v$latest_version";
} else {
echo "Unable to retrieve the latest version information";
}
exit;
}
$arch = shell_exec("opkg info " . escapeshellarg($package_name) . " | grep 'Architecture'");
if (strpos($arch, 'aarch64') !== false || strpos($arch, 'arm') !== false) {
$arch = "aarch64_generic";
$download_url = "https://github.com/$repo_owner/$repo_name/releases/download/$new_version_cleaned/{$package_name}_{$new_version_cleaned}-1_aarch64_generic.ipk";
} elseif (strpos($arch, 'x86_64') !== false) {
$arch = "x86_64";
$download_url = "https://github.com/$repo_owner/$repo_name/releases/download/$new_version_cleaned/{$package_name}_{$new_version_cleaned}-1_x86_64.ipk";
} elseif (strpos($arch, 'mips') !== false) {
$arch = "mips";
$download_url = "https://github.com/$repo_owner/$repo_name/releases/download/$new_version_cleaned/{$package_name}_{$new_version_cleaned}-1_mips.ipk";
} else {
die("The current device architecture is not supported");
}
$local_file = "/tmp/{$package_name}_{$new_version_cleaned}_{$arch}.ipk";
echo "<pre>Latest version: $new_version_cleaned</pre>";
echo "<pre>Download URL: $download_url</pre>";
echo "<pre id='logOutput'></pre>";
echo "<script>
function appendLog(message) {
document.getElementById('logOutput').innerHTML += message + '\\n';
}
</script>";
echo "<script>appendLog('Start downloading...');</script>";
$curl_command = "curl -sL " . escapeshellarg($download_url) . " -o " . escapeshellarg($local_file);
exec($curl_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_file)) {
echo "<pre>Download failed. Output: " . implode("\n", $output) . "</pre>";
die("Download failed. File not found");
}
echo "<script>appendLog('Download completed。');</script>";
echo "<script>appendLog('Updating package list...');</script>";
$output = shell_exec("opkg update");
echo "<pre>$output</pre>";
echo "<script>appendLog('Starting installation...');</script>";
$output = shell_exec("opkg install --force-reinstall " . escapeshellarg($local_file));
echo "<pre>$output</pre>";
echo "<script>appendLog('Installation completed。');</script>";
unlink($local_file);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_preview.php | luci-app-nekobox/htdocs/nekobox/update_preview.php | <?php
$repo_owner = "Thaolga";
$repo_name = "neko";
$package_name = "luci-app-nekobox";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
$local_api_response = "/tmp/api_response.json";
$curl_command = "curl -H 'User-Agent: PHP' -s " . escapeshellarg($api_url) . " -o " . escapeshellarg($local_api_response);
exec($curl_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_api_response)) {
echo "<script>appendLog('curl failed to fetch version information, attempting to use wget...');</script>";
$wget_command = "wget -q --no-check-certificate " . escapeshellarg($api_url) . " -O " . escapeshellarg($local_api_response);
exec($wget_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_api_response)) {
die("Unable to access GitHub API. Please check the URL or network connection. Output: " . implode("\n", $output));
}
echo "<script>appendLog('wget has completed fetching version information');</script>";
}
$response = file_get_contents($local_api_response);
$data = json_decode($response, true);
unlink($local_api_response);
$new_version = $data['tag_name'] ?? '';
if (empty($new_version)) {
die("No latest version found or version information is empty");
}
$installed_lang = isset($_GET['lang']) ? $_GET['lang'] : 'en';
if ($installed_lang !== 'cn' && $installed_lang !== 'en') {
die("Invalid language selection. Please choose 'cn' or 'en'");
}
if (isset($_GET['check_version'])) {
echo "Latest version: V" . $new_version . "-beta";
exit;
}
$download_url = "https://github.com/$repo_owner/$repo_name/releases/download/$new_version/{$package_name}_{$new_version}-{$installed_lang}_all.ipk";
echo "<pre>Latest version: $new_version</pre>";
echo "<pre>Download URL: $download_url</pre>";
echo "<pre id='logOutput'></pre>";
echo "<script>
function appendLog(message) {
document.getElementById('logOutput').innerHTML += message + '\\n';
}
</script>";
echo "<script>appendLog('Start downloading updates...');</script>";
$local_file = "/tmp/{$package_name}_{$new_version}-{$installed_lang}_all.ipk";
$curl_command = "curl -sL " . escapeshellarg($download_url) . " -o " . escapeshellarg($local_file);
exec($curl_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_file)) {
echo "<script>appendLog('curl download failed, trying to use wget...');</script>";
$wget_command = "wget -q --show-progress --no-check-certificate " . escapeshellarg($download_url) . " -O " . escapeshellarg($local_file);
exec($wget_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_file)) {
echo "<pre>Download failed. Command output: " . implode("\n", $output) . "</pre>";
die("Download failed. The downloaded file was not found");
}
echo "<script>appendLog('wget download complete');</script>";
} else {
echo "<script>appendLog('curl download complete');</script>";
}
echo "<script>appendLog('Update the list of software packages...');</script>";
$output = shell_exec("opkg update");
echo "<pre>$output</pre>";
echo "<script>appendLog('Start installation...');</script>";
$output = shell_exec("opkg install --force-reinstall " . escapeshellarg($local_file));
echo "<pre>$output</pre>";
echo "<script>appendLog('Installation complete。');</script>";
unlink($local_file);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/language.php | luci-app-nekobox/htdocs/nekobox/language.php | <?php
$langData = [
'de' => [
'home' => 'Startseite',
'panel' => 'Panel',
'document' => 'Abonnement',
'settings' => 'Einstellungen',
'manager' => 'Verwalten',
'template_i' => 'Vorlage Eins',
'template_ii' => 'Vorlage Zwei',
'template_iii' => 'Vorlage Drei',
'panel_settings' => 'Panel-Einstellungen',
'select_panel' => 'Panel auswählen',
'close' => 'Schließen',
'file_type_proxy' => 'Proxy-Datei',
'file_type_config' => 'Konfigurationsdatei',
'chooseThemeColor' => 'Wählen Sie die Themenfarbe',
'zash_panel' => 'ZASHBOARD Panel',
'yacd_panel' => 'YACD-META Panel',
'dash_panel' => 'DASHBOARD Panel',
'metacubexd_panel' => 'METACUBEXD Panel',
'select_language' => 'Sprache wählen',
'simplified_chinese' => 'Vereinfacht Chinesisch',
'traditional_chinese' => 'Traditionelles Chinesisch',
'english' => 'Englisch',
'vietnamese' => 'Vietnamesisch',
'korean' => 'Koreanisch',
'japanese' => 'Japanisch',
'russian' => 'Russisch',
'arabic' => 'Arabisch',
'spanish' => 'Spanisch',
'germany' => 'Deutsch',
'france' => 'Französisch',
'viewPortInfoButton' => 'Portinformationen anzeigen',
'autoCheckEnabled' => 'Automatische Prüfung aktiviert',
'autoCheckDisabled' => 'Automatische Prüfung deaktiviert',
'portInfoTitle' => 'Portinformationen',
'add_ace' => 'Ace-Komponente hinzufügen',
'remove_ace' => 'Ace-Komponente entfernen',
'portChangeNotice' => 'Der Dienst muss nach einer Portänderung neu gestartet werden, damit sie wirksam wird',
'update_success' => 'URL erfolgreich aktualisiert!',
'update_fail' => 'URL-Aktualisierung fehlgeschlagen!',
'reset_success' => 'Zurücksetzen des Standard-Links erfolgreich!',
'reset_fail' => 'Zurücksetzen des Standard-Links fehlgeschlagen!',
'refresh_ip' => 'Klicken Sie, um die IP-Adresse zu aktualisieren',
'checking' => 'Überprüfen...',
'test_latency' => 'Latenz testen',
'testing_latency' => 'Verbindungslatenz von %s wird getestet',
'latency_result' => 'Verbindungslatenz von %s: %d ms',
'connection_timeout' => 'Verbindungszeitüberschreitung für %s',
'show_ip' => 'Klicken, um IP-Details anzuzeigen',
'hide_ip' => 'Klicken, um IP zu verbergen/anzeigen',
'control_panel' => 'Kontrollpanel öffnen',
'location' => 'Standort',
'isp' => 'ISP',
'flag' => 'Flagge',
'ip_info' => 'IP-Details',
'ip_support' => 'IP-Unterstützung',
'ip_address' => 'IP-Adresse',
'location' => 'Region',
'isp' => 'Anbieter',
'asn' => 'ASN',
'timezone' => 'Zeitzone',
'latitude_longitude' => 'Breiten- und Längengrad',
'latency_info' => 'Latenz-Informationen',
'close' => 'Schließen',
'current_location' => 'Aktueller Standort',
'checking' => 'Überprüfen',
'ip_info_fail' => 'Fehler beim Abrufen der IP-Informationen',
'checking' => 'Überprüfen...',
'ip_info_fail' => 'Fehler beim Abrufen der IP-Informationen',
'music_player' => 'Musik-Player',
'clear_cache' => 'Cache leeren',
'start_check' => 'Webseitenüberprüfung starten',
'open_animation' => 'Animationseinstellungen öffnen',
'set_language' => 'Sprache festlegen',
'video_control_panel' => 'Video-Steuerpanel',
'volume_control' => 'Lautstärkeregler',
'progress_control' => 'Fortschrittsregler',
'clear_video_settings' => 'Video-Einstellungen zurücksetzen',
'control_panel_title' => 'Steuerpanel',
'start_cube_animation' => '🖥️ Würfeln-Animation starten',
'start_snow_animation' => '❄️ Schneefall-Animation starten',
'start_light_animation' => '💡 Licht-Animation starten',
'start_light_effect_animation' => '✨ Lichteffekt-Animation starten',
'close' => 'Schließen',
'cache_cleared_notification' => 'Cache gelöscht',
'cache_cleared_speech' => 'Cache gelöscht',
'no_song' => 'Kein Lied',
'toggle_playlist' => 'Playlist ein/aus',
'customize_playlist' => ' Playlist anpassen',
'clear_playback_settings' => 'Wiedergabeeinstellungen löschen',
'pin_lyrics' => 'Lyrics anheften',
'playlist' => 'Playlist',
'rewind_10_seconds' => '10 Sekunden zurückspulen',
'fast_forward_10_seconds' => '10 Sekunden vorspulen',
'reset_to_first_song' => 'Zur ersten Lied zurücksetzen',
'pause_play' => 'Pause der Wiedergabe',
'start_play' => 'Wiedergabe starten',
'loop_play' => 'Wiedergabe in Schleife',
'sequential' => 'Sequentielle Wiedergabe',
'sequential_play' => 'Sequentielle Wiedergabe',
'player_state_expired' => 'Player-Status abgelaufen, zurückgesetzt',
'clear_player_state' => 'Player-Status gelöscht!',
'restore_play_error' => 'Fehler beim Wiederherstellen der Wiedergabe',
'clear_storage' => 'Player-Status löschen und Playlist zurücksetzen',
'restore_play_error' => 'Fehler beim Wiederherstellen der Wiedergabe',
'start_playing' => 'Wiedergabe starten',
'paused' => 'Wiedergabe pausiert',
'unknown_song' => 'Unbekanntes Lied',
'no_songs' => 'Keine Lieder',
'auto_switch' => 'Automatisch wechseln zu',
'looping' => 'In Schleife abspielen',
'sequential_playing' => 'Sequentielle Wiedergabe',
'load_playlist_error' => 'Fehler beim Laden der Playlist',
'no_valid_songs_in_playlist' => 'Keine gültigen Lieder in der Playlist',
'playlist_loaded' => 'Playlist geladen',
'playlist_click_log' => 'Playlist-Klick-Protokoll: Index',
'play' => 'Abspielen',
'pause' => 'Pause',
'startAnimation' => '▶ Würfeln-Animation starten',
'stopAnimation' => '⏸️ Würfeln-Animation stoppen',
'animationStarted' => 'Würfeln-Animation gestartet',
'animationStopped' => 'Würfeln-Animation gestoppt',
'startNotification' => '▶ Würfeln-Animation gestartet',
'stopNotification' => '⏸️ Würfeln-Animation gestoppt',
'urlModalLabel' => 'Playlist aktualisieren',
'customUrlLabel' => 'Benutzerdefinierte Playlist-URL',
'saveButton' => 'Speichern',
'resetButton' => 'Zurücksetzen',
'cancelButton' => 'Abbrechen',
'restoreSuccess' => 'URL erfolgreich wiederhergestellt!',
'restoreError' => 'Fehler beim Wiederherstellen der URL',
'openCustomPlaylist' => 'Benutzerdefinierte Playlist öffnen',
'keyHelpModalLabel' => 'Tastenkürzel Hilfe',
'f9Key' => 'F9-Taste: Wiedergabe/Pause umschalten',
'arrowUpDown' => 'Pfeiltasten hoch/runter: Vorheriges/Nächstes Lied',
'arrowLeftRight' => 'Pfeiltasten links/rechts: 10 Sekunden vor/zurück',
'escKey' => 'ESC-Taste: Zur ersten Song der Playlist zurückkehren',
'f2Key' => 'F2-Taste: Wechseln zwischen Schleifen- und sequentieller Wiedergabe',
'f8Key' => 'F8-Taste: Verbindungsprüfung aktivieren',
'f4Key' => 'F4-Taste: Wetter anzeigen',
'ctrlF6' => 'Strg + F6: Starten/Stoppen der Schneefall-Animation',
'ctrlF7' => 'Strg + F7: Starten/Stoppen der Licht-Animation',
'ctrlF10' => 'Strg + F10: Starten/Stoppen der Würfeln-Animation',
'ctrlF11' => 'Strg + F11: Starten/Stoppen der Lichteffekt-Animation',
'ctrlShiftQ' => 'Strg + Shift + Q: Steuerpanel öffnen',
'ctrlShiftC' => 'Strg + Shift + C: Cache leeren',
'ctrlShiftV' => 'Strg + Shift + V: Playlist anpassen',
'ctrlShiftX' => 'Strg + Shift + X: Stadt einstellen',
'singBoxStartupTips' => 'Sing-Box Starttipps',
'startupFailure' => 'Im Falle eines Startfehlers gehen Sie zu Dateimanager ⇨ Datenbank aktualisieren ⇨ Cache.db herunterladen',
'startupNetworkIssue' => 'Wenn keine Verbindung möglich ist, gehen Sie zu Firewall-Einstellungen ⇨ Ein/Aus-Übertragungen ⇨ Zulassen ⇨ Änderungen speichern',
'cityModalLabel' => 'Stadt einstellen',
'cityInputLabel' => 'Bitte geben Sie den Städtenamen ein:',
'saveCityButton' => 'Stadt speichern',
'websiteCheckStarted' => 'Überprüfung der Website läuft...',
'websiteCheckCompleted' => 'Website-Überprüfung abgeschlossen, danke für die Nutzung.',
'websiteAccessible' => 'Website ist zugänglich.',
'websiteInaccessible' => 'Website ist nicht zugänglich, bitte überprüfen Sie Ihre Verbindung.',
'startCheckMessage' => 'Website-Überprüfung gestartet, bitte warten...',
'adjust_container_width' => 'Container-Breite anpassen',
'warning_message' => 'Wenn Änderungen nicht angewendet wurden, leeren Sie bitte den Browser-Cache und aktualisieren Sie die Seite!',
'page_width' => 'Seitenbreite',
"current_width" => "Aktuelle Breite",
"modal_max_width" => "Aktuelle maximale Breite: %spx",
"page_width_updated" => "Seitenbreite aktualisiert! Aktuelle Breite: %spx",
"modal_width_updated" => "Modale Fensterbreite aktualisiert! Aktuelle maximale Breite: %spx",
"enable_transparent_dropdown" => "Transparente Dropdowns, Formulardropdowns und Informationshintergrund aktiviert",
"disable_transparent_dropdown" => "Transparente Dropdowns, Formulardropdowns und Informationshintergrund deaktiviert",
"enable_transparent_body" => "Transparenter Hintergrund aktiviert",
"disable_transparent_body" => "Transparenter Hintergrund deaktiviert",
"notificationMessage" => "Cache geleert",
'select_theme_color' => 'Themenfarbe auswählen',
'navbar_text_color' => 'Textfarbe der Navigationsleiste',
'navbar_hover_text_color' => 'Textfarbe im Hover der Navigationsleiste',
'body_background_color' => 'Hintergrundfarbe des Körpers',
'info_background_color' => 'Hintergrundfarbe der Informationen',
'table_background_color' => 'Tabelle Hintergrundfarbe',
'table_text_color' => 'Textfarbe der Tabelle',
'main_title_text_color_1' => 'Textfarbe des Haupttitels 1',
'main_title_text_color_2' => 'Textfarbe des Haupttitels 2',
'row_text_color' => 'Textfarbe der Zeile',
'input_text_color_1' => 'Textfarbe des Eingabefeldes 1',
'input_text_color_2' => 'Textfarbe des Eingabefeldes 2',
'disabled_box_background_color' => 'Hintergrundfarbe des deaktivierten Feldes',
'log_text_color' => 'Textfarbe des Logs',
'main_border_background_color' => 'Hintergrundfarbe der Hauptgrenze',
'main_border_text_color' => 'Textfarbe der Hauptgrenze',
'table_text_color_1' => 'Textfarbe der Tabelle 1',
'table_text_color_2' => 'Textfarbe der Tabelle 2',
'table_text_color_3' => 'Textfarbe der Tabelle 3',
'ip_text_color' => 'Textfarbe der IP-Adresse',
'isp_text_color' => 'Textfarbe des ISP',
'ip_detail_text_color' => 'Textfarbe der IP-Details',
'button_color_cyan' => 'Buttonfarbe (cyan)',
'button_color_green' => 'Buttonfarbe (grün)',
'button_color_blue' => 'Buttonfarbe (blau)',
'button_color_yellow' => 'Buttonfarbe (gelb)',
'button_color_pink' => 'Buttonfarbe (pink)',
'button_color_red' => 'Buttonfarbe (rot)',
'heading_color_1' => 'Farbe der Überschrift 1',
'heading_color_2' => 'Farbe der Überschrift 2',
'heading_color_3' => 'Farbe der Überschrift 3',
'heading_color_4' => 'Farbe der Überschrift 4',
'heading_color_5' => 'Farbe der Überschrift 5',
'heading_color_6' => 'Farbe der Überschrift 6',
'custom_theme_name' => 'Benutzerdefinierter Themenname',
'save_theme' => 'Thema speichern',
'restore_default' => 'Auf Standard zurücksetzen',
'backup_now' => 'Jetzt sichern',
'restore_backup' => 'Sicherung wiederherstellen',
'cancel' => 'Abbrechen',
'media_player' => 'Medienplayer',
'play_media' => 'Medien abspielen',
'playlist' => 'Wiedergabeliste',
'toggle_fullscreen' => 'Vollbild umschalten',
'clear_playlist' => 'Wiedergabeliste löschen',
'close' => 'Schließen',
'add_drive_file' => 'Laufwerksdatei hinzufügen',
'drive_file_link' => 'Laufwerksdatei-Link',
'add' => 'Hinzufügen',
'rename_file' => 'Datei umbenennen',
'new_file_name' => 'Neuer Dateiname',
'save' => 'Speichern',
'upload_file' => 'Datei hochladen',
'upload_image_video_audio' => 'Bild/Video/Audio hochladen',
'drag_and_drop_or_click' => 'Ziehen Sie die Datei in diesen Bereich oder klicken Sie auf das Symbol, um eine Datei auszuwählen.',
'php_upload_limit_notice' => 'Es gibt eine PHP-Upload-Dateigrößenbeschränkung. Bei fehlgeschlagenen Uploads können Sie die Datei manuell in das Verzeichnis /nekobox/assets/Pictures hochladen.',
'upload_image_video' => 'Bild/Video hochladen',
'update_php_config' => 'PHP Upload-Größe konfigurieren',
'confirm_update' => 'Möchten Sie die PHP Upload-Limits wirklich ändern?',
'request_failed' => 'Anforderung fehlgeschlagen',
'select_all' => 'Alle auswählen',
'deselect_all' => 'Alle abwählen',
'selected_files' => '{count} Datei(en) ausgewählt, insgesamt {size}',
'toggle_fullscreen' => 'Vollbild umschalten',
'exit_fullscreen' => 'Vollbild verlassen',
"selectFiles" => "Bitte wählen Sie die zu löschenden Dateien aus.",
"confirmDelete" => "Möchten Sie die ausgewählten Dateien wirklich löschen?",
"deleteFailed" => "Dateilöschung fehlgeschlagen",
"uploadManageTitle" => "Hochladen und Verwalten von Hintergrundbildern/Videos/Audio",
"selectAll" => "Alle auswählen",
"batchDelete" => "Stapelweise löschen",
"playVideo" => "Video abspielen",
"uploadFile" => "Datei hochladen",
"addDriveFile" => "Laufwerksdatei hinzufügen",
"removeBackground" => "Hintergrund entfernen",
"selectedCount" => "0 Dateien ausgewählt, insgesamt 0 MB",
"localFiles" => "Lokale Dateien",
"driveFiles" => "Laufwerksdateien",
"unknownFileType" => "Unbekannter Dateityp",
"delete" => "🗑️ Löschen",
"rename" => "✏️ Umbenennen",
"download" => "📥 Herunterladen",
"name" => "Name",
"size" => "Größe",
"setBackgroundImage" => "Hintergrundbild festlegen",
"setBackgroundVideo" => "Hintergrundvideo festlegen",
"setBackgroundMusic" => "Hintergrundmusik festlegen",
"fileHelper" => "Dateihilfe",
"status" => "Status",
"mihomoControl" => "Mihomo",
"singboxControl" => "Singbox",
"runningMode" => "Betriebsmodus",
"enableMihomo" => "Mihomo aktivieren",
"disableMihomo" => "Mihomo deaktivieren",
"restartMihomo" => "Mihomo neu starten",
"enableSingbox" => "Singbox aktivieren",
"disableSingbox" => "Singbox deaktivieren",
"restartSingbox" => "Singbox neu starten",
"selectConfig" => "Konfigurationsdatei auswählen",
"pleaseSelectConfig" => "Bitte Konfigurationsdatei auswählen",
"mihomoRunning" => "Mihomo {index} läuft",
"mihomoNotRunning" => "Mihomo läuft nicht",
"singboxRunning" => "Singbox {index} läuft",
"singboxNotRunning" => "Singbox läuft nicht",
'log' => 'Protokoll',
'nekoBoxLog' => 'Nekobox-Protokoll',
'mihomoLog' => 'Mihomo-Protokoll',
'singboxLog' => 'Singbox-Protokoll',
'clearLog' => 'Protokoll löschen',
'autoRefresh' => 'Automatische Aktualisierung',
'scheduledRestart' => 'Geplantes Neustarten',
'systemInfo' => 'Systeminformationen',
'systemMemory' => 'Systemspeicher',
'avgLoad' => 'Durchschnittliche Last',
'playback_speed' => 'Wiedergabegeschwindigkeit',
'systemTimezone' => 'Systemzeitzone',
'currentTime' => 'Aktuelle Zeit',
'uptime' => 'Betriebszeit',
'days' => 'Tage',
'hours' => 'Stunden',
'minutes' => 'Minuten',
'seconds' => 'Sekunden',
'confirm_update_php' => 'Möchten Sie die PHP-Konfiguration wirklich aktualisieren?',
'unlock_php_upload_limit'=> 'PHP Upload-Limit entsperren',
'trafficStats' => 'Verkehrsstatistik',
'setCronTitle' => 'Cron-Aufgabenzeit einstellen',
'setRestartTime' => 'Singbox-Neustartzeit einstellen',
'tip' => 'Tipp',
'cronFormat' => 'Cron-Ausdrucksformat',
'example1' => 'Beispiel: Jeden Tag um 2 Uhr',
'example2' => 'Beispiel: Jeden Montag um 3 Uhr',
'example3' => 'Beispiel: Wochentage (Montag bis Freitag) um 9 Uhr',
'cancel' => 'Abbrechen',
'save' => 'Speichern',
'nginxWarning' => 'Warnung! Es wurde festgestellt, dass Sie Nginx verwenden. Dieses Plugin unterstützt Nginx nicht, bitte verwenden Sie Uhttpd für die Firmware.',
'nginxWarningStrong' => 'Warnung!',
'config_file_missing' => 'Konfigurationsdatei fehlt, Standardkonfigurationsdatei wurde erstellt.',
'config_file_incomplete' => 'Die Konfigurationsdatei fehlt einige Optionen, fehlende Konfigurationen wurden automatisch hinzugefügt.',
'invalid_config_file' => 'Ungültige Konfigurationsdatei.',
'cron_time_empty' => 'Bitte geben Sie ein gültiges Cron-Zeitformat an!',
'cron_task_success' => 'Geplante Aufgabe erfolgreich eingerichtet, Singbox wird automatisch um $cronTime neu gestartet.',
'invalid_cron_format' => 'Ungültiges Cron-Zeitformat!',
'cron_task_failed' => 'Die geplante Aufgabe konnte nicht eingerichtet werden, bitte versuchen Sie es erneut!',
'cron_script_created_successfully' => 'Cron-Skript erfolgreich erstellt und ausgeführt. Log-Cleanup-Aufgaben wurden hinzugefügt oder aktualisiert, um $log_file und $tmp_log_file-Logs zu löschen.',
'theme_settings' => 'Themen-Einstellungen',
'change_theme' => 'Thema ändern (%s)',
'change_theme_button' => 'Thema ändern',
'software_information_title' => 'Softwareinformationen',
'client_version_title' => 'Client-Version',
'ui_panel_title' => 'Steuerpanel',
'singbox_core_version_title' => 'Singbox-Core-Version',
'mihomo_core_version_title' => 'Mihomo-Core-Version',
'enable_button' => 'Aktivieren',
'disable_button' => 'Deaktivieren',
'detect_button' => 'Erkennen',
'update_button' => 'Aktualisieren',
'updateCompleted' => 'Aktualisierung abgeschlossen!',
'errorOccurred' => 'Ein Fehler ist aufgetreten:',
'networkError' => 'Netzwerkfehler, bitte versuchen Sie es später noch einmal.',
'checkingVersion' => 'Überprüfe auf neue Version...',
'requestFailed' => 'Anforderung fehlgeschlagen',
'cannotParseVersion' => 'Version konnte nicht geparst werden',
'networkError' => 'Netzwerkfehler',
'componentName' => 'Komponentenname',
'currentVersion' => 'Aktuelle Version',
'latestVersion' => 'Neueste Version',
'unknown' => 'Unbekannt',
"mihomo_version_modal_title" => "Mihomo-Core-Version auswählen",
"mihomo_version_stable" => "Stabile Version",
"mihomo_version_preview" => "Vorschau-Version",
"options_modal_title" => "Optionen auswählen",
"options_modal_note" => "Remarque : Cliquez manuellement sur Vérifier. Le système génère dynamiquement le numéro de version le plus récent pour le téléchargement. Pour la première installation, utilisez le canal 1 pour mettre à jour les dépendances, puis utilisez le canal 2 pour les mises à jour officielles.",
"singbox_channel_one" => "Singbox-Core aktualisieren (Kanal eins)",
"singbox_channel_two" => "Singbox-Core aktualisieren (Kanal zwei)",
"other_operations" => "Weitere Operationen",
"operation_modal_title" => "Operation auswählen",
"operation_modal_note" => "Hinweis: Bitte wählen Sie die gewünschte Operation aus",
"switch_to_puernya" => "Auf Puernya-Core wechseln",
"update_pcore_rule" => "P-core-Regelsatz aktualisieren",
"update_config_backup" => "Konfigurationsdatei (Backup) aktualisieren",
"close_button" => "Schließen",
"versionModalLabel" => "Versionsergebnisse",
"loadingMessage" => "Wird geladen...",
"closeButton" => "Schließen",
"updateModalLabel" => "Aktualisierungsstatus",
"updateDescription" => "Der Aktualisierungsprozess wird bald beginnen.",
"waitingMessage" => "Warten auf die Aktion...",
"versionSelectionModalTitle" => "Singbox-Core-Version auswählen",
"helpMessage" => "Hilfe: Bitte wählen Sie eine vorhandene Version oder geben Sie manuell eine Version ein und klicken Sie auf \"Version hinzufügen\", um sie zur Dropdown-Liste hinzuzufügen.",
"addVersionButton" => "Version hinzufügen",
"cancelButton" => "Abbrechen",
"confirmButton" => "Bestätigen",
"singboxVersionModalTitle" => "Singbox-Core-Version auswählen (Kanal 2)",
"panelSelectionModalTitle" => "Panel auswählen",
"selectPanelLabel" => "Panel auswählen",
"zashboardPanel" => "Zashboard Panel",
"metacubexdPanel" => "Metacubexd Panel",
"yacdMeatPanel" => "Yacd-Meat Panel",
"dashboardPanel" => "Dashboard Panel",
'singbox_message' => 'Beginne mit dem Download der Singbox-Core-Update...',
'singbox_description' => 'Singbox-Core auf die neueste Version aktualisieren',
'sing-box_message' => 'Beginne mit dem Download der Singbox-Core-Update...',
'sing-box_description' => 'Singbox-Core auf ' ,
'puernya_message' => 'Beginne mit dem Wechsel zu Puernya-Core...',
'puernya_description' => 'Wechsel zu Puernya-Core, diese Operation ersetzt den aktuellen Singbox-Core',
'rule_message' => 'Beginne mit dem Download des Singbox-Regelsatzes...',
'rule_description' => 'Singbox-Regelsatz aktualisieren',
'config_message' => 'Beginne mit dem Download der Mihomo-Konfigurationsdatei...',
'config_description' => 'Mihomo-Konfigurationsdatei auf die neueste Version aktualisieren',
'mihomo_message' => 'Beginne mit dem Download des Mihomo-Core-Updates...',
'mihomo_description' => 'Mihomo-Core auf die neueste Version aktualisieren',
'settings.modal.maxWidth' => 'Maximale Breite des Modals',
"transparent_dropdown" => "Transparentes Dropdown, Formularauswahl und Informationshintergrund aktivieren",
"transparent_body" => "Transparenten Körperhintergrund aktivieren",
'remaining Space' => 'Verbleibender Speicherplatz in OpenWRT:',
'client_message' => 'Beginne mit dem Herunterladen von Client-Updates...',
'client_description' => 'Aktualisiere den Client auf die neueste offizielle Version',
'panel_zashboard_message' => 'Beginne mit dem Herunterladen des Zashboard-Panel-Updates (dist-cdn-fonts.zip)...',
'panel_Zashboard_message' => 'Beginne mit dem Herunterladen des Zashboard-Panel-Updates (dist.zip)...',
'panel_zashboard_description' => 'Aktualisiere das Zashboard-Panel auf die neueste Version (dist-cdn-fonts.zip)',
'panel_Zashboard_description' => 'Aktualisiere das Zashboard-Panel auf die neueste Version (dist.zip)',
'panel_zashboard_option' => 'Zashboard-Panel [Niedriger Speicher]',
'panel_Zashboard_option' => 'Zashboard-Panel [Hoher Speicher]',
'panel_yacd-meat_message' => 'Beginne mit dem Download des Yacd-Meat-Panel-Updates...',
'panel_yacd-meat_description' => 'Yacd-Meat-Panel auf die neueste Version aktualisieren',
'panel_metacubexd_message' => 'Beginne mit dem Download des Metacubexd-Panel-Updates...',
'panel_metacubexd_description' => 'Metacubexd-Panel auf die neueste Version aktualisieren',
'panel_dashboard_message' => 'Beginne mit dem Download des Dashboard-Panel-Updates...',
'panel_dashboard_description' => 'Dashboard-Panel auf die neueste Version aktualisieren',
'panel_unknown_message' => 'Unbekannter Panel-Update-Typ...',
'panel_unknown_description' => 'Paneltyp konnte nicht erkannt werden, Update fehlgeschlagen.',
'client' => 'Client',
'stable' => 'Stabile Version',
'preview' => 'Vorschau-Version',
'notInstalled' => 'Nicht installiert',
'compiled' => 'Kompilierte Version',
"notInstalled" => "Nicht installiert",
"notInstalledMessage" => "Sing-box-Installation nicht gefunden, bitte die Systemkonfiguration überprüfen.",
"versionWarning" => "Version-Warnung",
"versionTooLowMessage" => "Ihre Sing-box-Version",
"recommendedMinVersion" => "liegt unter der empfohlenen Mindestversion",
"upgradeSuggestion" => "Bitte erwägen Sie ein Upgrade auf eine höhere Version für die beste Leistung.",
'aboutTitle' => 'Über NekoBox',
'nekoBoxTitle' => 'NekoBox',
'nekoBoxDescription' => 'NekoBox ist ein sorgfältig gestaltetes Sing-box Proxy-Tool, das speziell für Haushaltsbenutzer entwickelt wurde, um eine einfache und leistungsstarke Proxy-Lösung bereitzustellen. Basierend auf PHP und BASH-Technologie vereinfacht NekoBox komplexe Proxy-Konfigurationen in eine benutzerfreundliche Erfahrung, damit jeder Benutzer eine effiziente und sichere Netzwerkomgebung genießen kann.',
'coreFeatures' => 'Kernmerkmale',
'simplifiedConfiguration' => 'Vereinfachte Konfiguration',
'simplifiedConfigurationDescription' => 'Einfache Einrichtung und Verwaltung von Sing-box Proxy durch benutzerfreundliche Oberflächen.',
'powerfulProxyFeatures' => 'Leistungsstarke Proxy-Funktionen',
'powerfulProxyFeaturesDescription' => 'NekoBox bietet umfangreiche Proxy-Funktionen wie Bandbreitenlimitierung, benutzerdefinierte Regeln, detaillierte Netzwerkstatistiken und vieles mehr.',
'efficientDataHandling' => 'Effiziente Datenverarbeitung',
'efficientDataHandlingDescription' => 'Verarbeitet Daten effizient und gewährleistet hohe Geschwindigkeit und Stabilität.',
'userFriendlyDesign' => 'Benutzerfreundliches Design',
'userFriendlyDesignDescription' => 'Das Design ist einfach und intuitiv, so dass die Benutzer ohne Probleme alle Funktionen nutzen können.',
'dependencies' => 'Abhängigkeiten',
'phpVersion' => 'PHP-Version',
'installSingBox' => 'SingBox installieren',
'installSingBoxDescription' => 'Installiere Singbox auf deinem System, um mit der Arbeit zu beginnen.',
'upgradeSingBox' => 'SingBox aktualisieren',
'upgradeSingBoxDescription' => 'Aktualisiere Singbox auf die neueste Version für verbesserte Funktionen und Sicherheit.',
'clientPanel' => 'Client-Panel',
'clientPanelDescription' => 'Zugriff auf Ihr Client-Panel für die Verwaltung und Konfiguration.',
'updateClient' => 'Client aktualisieren',
'checkForUpdates' => 'Auf Updates überprüfen',
'saveChanges' => 'Änderungen speichern',
'configPanel' => 'Konfigurationspanel',
'advancedEditorTitle' => 'Erweiterter Editor - Vollbildmodus',
'formatIndentation' => 'Einrückung formatieren',
'formatYaml' => 'YAML formatieren',
'validateJson' => 'JSON-Syntax überprüfen',
'validateYaml' => 'YAML-Syntax überprüfen',
'saveAndClose' => 'Speichern und schließen',
'search' => 'Suchen',
'cancel' => 'Abbrechen',
'toggleFullscreen' => 'Vollbild',
"lineColumnDisplay" => "Zeile: {line}, Spalte: {column}",
"charCountDisplay" => "Zeichenanzahl: {charCount}",
'validateJson' => 'JSON-Syntax überprüfen',
'jsonSyntaxCorrect' => 'Syntax korrekt',
'jsonSyntaxError' => 'Syntaxfehler',
'validateYaml' => 'YAML-Syntax überprüfen',
'yamlSyntaxCorrect' => 'YAML-Syntax korrekt',
'yamlSyntaxError' => 'YAML-Syntaxfehler',
'formatIndentation' => 'Einrückung formatieren',
'jsonFormatSuccess' => 'JSON-Formatierung erfolgreich',
'jsFormatSuccess' => 'JavaScript-Formatierung erfolgreich',
'unsupportedMode' => 'Der aktuelle Modus unterstützt keine Einrückungsformatierung',
'formatError' => 'Formatierungsfehler',
"yamlFormatSuccess" => "YAML-Formatierung erfolgreich",
'subscriptionManagement' => 'Mihomo-Abonnementverwaltung',
'subscriptionLink' => 'Abonnement-Link',
'enterSubscriptionUrl' => 'Bitte geben Sie den Abonnement-Link ein',
'customFileName' => 'Benutzerdefinierter Dateiname',
'updateSubscription' => 'Abonnement aktualisieren',
'upload_success' => 'Datei erfolgreich hochgeladen:',
'upload_failure' => 'Datei-Upload fehlgeschlagen!',
'upload_error' => 'Upload-Fehler:',
'config_upload_success' => 'Konfigurationsdatei erfolgreich hochgeladen:',
'config_upload_failure' => 'Konfigurationsdatei-Upload fehlgeschlagen!',
'file_deleted_success' => 'Datei erfolgreich gelöscht:',
'file_deleted_failure' => 'Datei-Löschung fehlgeschlagen!',
'config_file_deleted_success' => 'Konfigurationsdatei erfolgreich gelöscht:',
'config_file_deleted_failure' => 'Konfigurationsdatei-Löschung fehlgeschlagen!',
'file_rename_success' => 'Datei erfolgreich umbenannt:',
'file_rename_failure' => 'Datei-Umbenennung fehlgeschlagen!',
'file_not_exists' => 'Datei existiert nicht',
'invalid_file_type' => 'Ungültiger Dateityp',
'file_content_updated' => 'Dateiinhalt aktualisiert:',
"auto_update_title" => "Automatische Aktualisierung",
"set_cron_job" => "Cron-Job einrichten",
"generate_update_script" => "Update-Skript generieren",
"update_database" => "Datenbank aktualisieren",
"open_file_helper" => "Datei-Helfer öffnen",
"select_database_download" => "Datenbank zum Download auswählen",
"select_file" => "Datei auswählen",
"geoip_file" => "geoip.metadb",
"geosite_file" => "geosite.dat",
"cache_file" => "cache.db",
"download_button" => "Herunterladen",
"cancel_button" => "Abbrechen",
"cron_task_title" => "Cron-Job einrichten",
"cron_expression_label" => "Cron-Ausdruck",
"cron_hint" => "Hinweis:",
"cron_expression_format" => "Cron-Ausdruck-Format:",
"cron_example" => "Beispiel: Täglich um 2 Uhr morgens: ",
"save_button" => "Speichern",
'form_title' => 'Sing-box Konvertierungsvorlage 2',
'subscription_url_label' => 'Abonnement-Link eingeben',
'subscription_url_placeholder' => 'Unterstützt verschiedene Abonnement-Links oder Einzelknoten-Links, mehrere Links mit | trennen',
'filename_label' => 'Benutzerdefinierter Dateiname (Standard: config.json)',
'filename' => 'Benutzerdefinierter Dateiname (Standard: config.yaml)',
'filename_placeholder' => 'config.json',
'backend_url_label' => 'Backend-URL auswählen',
'custom_backend_url_label' => 'Benutzerdefinierte Backend-URL eingeben',
'submit_button' => 'Absenden',
'backend_url_option_1' => 'Feiyang erweitertes Backend【vless reality+hy1+hy2】',
'backend_url_option_2' => 'Feiyang Backup-Backend【vless reality+hy1+hy2】',
'backend_url_option_3' => 'Bereitgestellt von subconverter-Autor',
'backend_url_option_6' => 'v.id9.cc (bereitgestellt von Pincloud)',
'backend_url_option_10' => 'sub.maoxiongnet.com (bereitgestellt von Maoxiong)',
'backend_url_option_11' => 'localhost:25500 Lokale Version',
'backend_url_option_custom' => 'Benutzerdefinierte Backend-URL',
"choose_additional_options" => "Zusätzliche Konfigurationsoptionen auswählen",
"enable_emoji" => "Emoji aktivieren",
"enable_udp" => "UDP aktivieren",
"enable_xudp" => "XUDP aktivieren",
"enable_tfo" => "TFO aktivieren",
"enable_fdn" => "FDN aktivieren",
"enable_sort" => "SORT aktivieren",
"enable_tls13" => "TLS_1.3 aktivieren",
"enable_ipv6" => "IPv6 aktivieren",
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/puernya.php | luci-app-nekobox/htdocs/nekobox/puernya.php | <?php
ini_set('memory_limit', '128M');
function logMessage($message) {
$logFile = '/var/log/sing-box_update.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/core/version.txt';
file_put_contents($versionFile, $version);
}
$repo_owner = "Thaolga";
$repo_name = "luci-app-nekoclash";
$latest_version = "1.10.0-alpha.29-067c81a7";
$current_version = '';
$install_path = '/usr/bin/sing-box';
$temp_file = '/tmp/sing-box.tar.gz';
$temp_dir = '/tmp/singbox_temp';
if (file_exists($install_path)) {
$current_version = trim(shell_exec("{$install_path} --version"));
}
if (isset($_GET['check_version'])) {
echo "Latest version: $latest_version\n";
exit;
}
$current_arch = trim(shell_exec("uname -m"));
$download_url = '';
switch ($current_arch) {
case 'aarch64':
$download_url = "https://github.com/Thaolga/luci-app-nekoclash/releases/download/sing-box/sing-box-puernya-linux-armv8.tar.gz";
break;
case 'x86_64':
$download_url = "https://github.com/Thaolga/luci-app-nekoclash/releases/download/sing-box/sing-box-puernya-linux-amd64.tar.gz";
break;
default:
die("No suitable download link found for architecture: $current_arch");
}
if (trim($current_version) === trim($latest_version)) {
die("You are already on the latest version.");
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed!");
}
if (!is_dir($temp_dir)) {
mkdir($temp_dir, 0755, true);
}
exec("tar -xzf '$temp_file' -C '$temp_dir'", $output, $return_var);
if ($return_var !== 0) {
die("Extraction failed!");
}
$extracted_file = glob("$temp_dir/CrashCore")[0] ?? '';
if ($extracted_file && file_exists($extracted_file)) {
exec("cp -f '$extracted_file' '$install_path'");
exec("chmod 0755 '$install_path'");
writeVersionToFile($latest_version);
echo "Update complete! Current version: $latest_version";
} else {
die("The extracted file 'CrashCore' does not exist.");
}
unlink($temp_file);
exec("rm -r '$temp_dir'");
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_mihomo_stable.php | luci-app-nekobox/htdocs/nekobox/update_mihomo_stable.php | <?php
function logMessage($message) {
$logFile = '/var/log/mihomo_update.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/core/mihomo_version.txt';
$result = file_put_contents($versionFile, $version);
if ($result === false) {
logMessage("Unable to write version file: $versionFile");
}
}
$repo_owner = "MetaCubeX";
$repo_name = "mihomo";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
if (isset($_GET['check_version'])) {
$curl_command = "curl -s -H 'User-Agent: PHP' " . escapeshellarg($api_url);
$response = shell_exec($curl_command);
if ($response === false || empty($response)) {
echo "GitHub API request failed.";
exit;
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Error parsing GitHub API response: " . json_last_error_msg();
exit;
}
$latest_version = $data['tag_name'] ?? '';
if (empty($latest_version)) {
echo "Latest version information not found.";
exit;
}
echo "Latest version: " . htmlspecialchars($latest_version);
exit;
}
$curl_command = "curl -s -H 'User-Agent: PHP' " . escapeshellarg($api_url);
$response = shell_exec($curl_command);
if ($response === false || empty($response)) {
die("GitHub API request failed. Please check your network connection or try again later.");
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die("Error parsing GitHub API response: " . json_last_error_msg());
}
$latest_version = $data['tag_name'] ?? '';
$current_version = '';
$install_path = '/usr/bin/mihomo';
$temp_file = '/tmp/mihomo.gz';
if (file_exists($install_path)) {
$current_version = trim(shell_exec("{$install_path} --version"));
}
$current_arch = trim(shell_exec("uname -m"));
$download_url = '';
$base_version = ltrim($latest_version, 'v');
switch ($current_arch) {
case 'aarch64':
$download_url = "https://github.com/MetaCubeX/mihomo/releases/download/$latest_version/mihomo-linux-arm64-v$base_version.gz";
break;
case 'armv7l':
$download_url = "https://github.com/MetaCubeX/mihomo/releases/download/$latest_version/mihomo-linux-armv7l-v$base_version.gz";
break;
case 'x86_64':
$download_url = "https://github.com/MetaCubeX/mihomo/releases/download/$latest_version/mihomo-linux-amd64-v$base_version.gz";
break;
default:
echo "Download link for architecture not found: $current_arch";
exit;
}
if (trim($current_version) === trim($latest_version)) {
echo "Current version is up to date. No update needed.";
exit;
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var === 0) {
exec("gzip -d -c '$temp_file' > '/tmp/mihomo-linux-arm64'", $output, $return_var);
if ($return_var === 0) {
exec("mv '/tmp/mihomo-linux-arm64' '$install_path'", $output, $return_var);
if ($return_var === 0) {
exec("chmod 0755 '$install_path'", $output, $return_var);
if ($return_var === 0) {
writeVersionToFile($latest_version);
echo "Update completed! Current version: $latest_version";
} else {
echo "Failed to set permissions!";
}
} else {
echo "Failed to move file!";
}
} else {
echo "Extraction failed!";
}
} else {
echo "Download failed!";
}
if (file_exists($temp_file)) {
unlink($temp_file);
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/index.php | luci-app-nekobox/htdocs/nekobox/index.php | <?php
include './cfg.php';
$needRefresh = false;
$str_cfg = substr($selected_config, strlen("$neko_dir/config") + 1);
$_IMG = '/luci-static/ssr/';
$singbox_bin = '/usr/bin/sing-box';
$singbox_log = '/var/log/singbox_log.txt';
$singbox_config_dir = '/etc/neko/config';
$log = '/etc/neko/tmp/log.txt';
$start_script_path = '/etc/neko/core/start.sh';
$neko_enabled = exec("uci -q get neko.cfg.enabled");
$singbox_enabled = exec("uci -q get neko.cfg.singbox_enabled");
$neko_status = ($neko_enabled == '1') ? '1' : '0';
$singbox_status = ($singbox_enabled == '1') ? '1' : '0';
$log_dir = dirname($log);
if (!file_exists($log_dir)) {
mkdir($log_dir, 0755, true);
}
$start_script_template = <<<'EOF'
#!/bin/bash
SINGBOX_LOG="%s"
CONFIG_FILE="%s"
SINGBOX_BIN="%s"
FIREWALL_LOG="%s"
mkdir -p "$(dirname "$SINGBOX_LOG")"
mkdir -p "$(dirname "$FIREWALL_LOG")"
touch "$SINGBOX_LOG"
touch "$FIREWALL_LOG"
chmod 644 "$SINGBOX_LOG"
chmod 644 "$FIREWALL_LOG"
exec >> "$SINGBOX_LOG" 2>&1
log() {
echo "[$(date)] $1" >> "$FIREWALL_LOG"
}
log "Starting Sing-box with config: $CONFIG_FILE"
log "Restarting firewall..."
/etc/init.d/firewall restart
sleep 2
if command -v fw4 > /dev/null; then
log "FW4 Detected. Starting nftables."
nft flush ruleset
nft -f - <<'NFTABLES'
flush ruleset
table inet singbox {
set local_ipv4 {
type ipv4_addr
flags interval
elements = {
10.0.0.0/8,
127.0.0.0/8,
169.254.0.0/16,
172.16.0.0/12,
192.168.0.0/16,
240.0.0.0/4
}
}
set local_ipv6 {
type ipv6_addr
flags interval
elements = {
::ffff:0.0.0.0/96,
64:ff9b::/96,
100::/64,
2001::/32,
2001:10::/28,
2001:20::/28,
2001:db8::/32,
2002::/16,
fc00::/7,
fe80::/10
}
}
chain common-exclude {
fib daddr type { unspec, local, anycast, multicast } return
meta nfproto ipv4 ip daddr @local_ipv4 return
meta nfproto ipv6 ip6 daddr @local_ipv6 return
udp dport { 123 } return
}
chain singbox-tproxy {
goto common-exclude
meta l4proto { tcp, udp } meta mark set 1 tproxy to :9888 accept
}
chain singbox-mark {
goto common-exclude
meta l4proto { tcp, udp } meta mark set 1
}
chain mangle-output {
type route hook output priority mangle; policy accept;
meta l4proto { tcp, udp } ct state new skgid != 1 goto singbox-mark
}
chain mangle-prerouting {
type filter hook prerouting priority mangle; policy accept;
iifname { eth0, wlan0 } meta l4proto { tcp, udp } ct state new goto singbox-tproxy
}
}
NFTABLES
elif command -v fw3 > /dev/null; then
log "FW3 Detected. Starting iptables."
iptables -t mangle -F
iptables -t mangle -X
ip6tables -t mangle -F
ip6tables -t mangle -X
iptables -t mangle -N singbox-mark
iptables -t mangle -A singbox-mark -m addrtype --dst-type UNSPEC,LOCAL,ANYCAST,MULTICAST -j RETURN
iptables -t mangle -A singbox-mark -d 10.0.0.0/8 -j RETURN
iptables -t mangle -A singbox-mark -d 127.0.0.0/8 -j RETURN
iptables -t mangle -A singbox-mark -d 169.254.0.0/16 -j RETURN
iptables -t mangle -A singbox-mark -d 172.16.0.0/12 -j RETURN
iptables -t mangle -A singbox-mark -d 192.168.0.0/16 -j RETURN
iptables -t mangle -A singbox-mark -d 240.0.0.0/4 -j RETURN
iptables -t mangle -A singbox-mark -p udp --dport 123 -j RETURN
iptables -t mangle -A singbox-mark -j MARK --set-mark 1
iptables -t mangle -N singbox-tproxy
iptables -t mangle -A singbox-tproxy -m addrtype --dst-type UNSPEC,LOCAL,ANYCAST,MULTICAST -j RETURN
iptables -t mangle -A singbox-tproxy -d 10.0.0.0/8 -j RETURN
iptables -t mangle -A singbox-tproxy -d 127.0.0.0/8 -j RETURN
iptables -t mangle -A singbox-tproxy -d 169.254.0.0/16 -j RETURN
iptables -t mangle -A singbox-tproxy -d 172.16.0.0/12 -j RETURN
iptables -t mangle -A singbox-tproxy -d 192.168.0.0/16 -j RETURN
iptables -t mangle -A singbox-tproxy -d 240.0.0.0/4 -j RETURN
iptables -t mangle -A singbox-tproxy -p udp --dport 123 -j RETURN
iptables -t mangle -A singbox-tproxy -p tcp -j TPROXY --tproxy-mark 0x1/0x1 --on-port 9888
iptables -t mangle -A singbox-tproxy -p udp -j TPROXY --tproxy-mark 0x1/0x1 --on-port 9888
iptables -t mangle -A OUTPUT -p tcp -m cgroup ! --cgroup 1 -j singbox-mark
iptables -t mangle -A OUTPUT -p udp -m cgroup ! --cgroup 1 -j singbox-mark
iptables -t mangle -A PREROUTING -i eth0 -p tcp -j singbox-tproxy
iptables -t mangle -A PREROUTING -i eth0 -p udp -j singbox-tproxy
iptables -t mangle -A PREROUTING -i wlan0 -p tcp -j singbox-tproxy
iptables -t mangle -A PREROUTING -i wlan0 -p udp -j singbox-tproxy
ip6tables -t mangle -N singbox-mark
ip6tables -t mangle -A singbox-mark -m addrtype --dst-type UNSPEC,LOCAL,ANYCAST,MULTICAST -j RETURN
ip6tables -t mangle -A singbox-mark -d ::ffff:0.0.0.0/96 -j RETURN
ip6tables -t mangle -A singbox-mark -d 64:ff9b::/96 -j RETURN
ip6tables -t mangle -A singbox-mark -d 100::/64 -j RETURN
ip6tables -t mangle -A singbox-mark -d 2001::/32 -j RETURN
ip6tables -t mangle -A singbox-mark -d 2001:10::/28 -j RETURN
ip6tables -t mangle -A singbox-mark -d 2001:20::/28 -j RETURN
ip6tables -t mangle -A singbox-mark -d 2001:db8::/32 -j RETURN
ip6tables -t mangle -A singbox-mark -d 2002::/16 -j RETURN
ip6tables -t mangle -A singbox-mark -d fc00::/7 -j RETURN
ip6tables -t mangle -A singbox-mark -d fe80::/10 -j RETURN
ip6tables -t mangle -A singbox-mark -p udp --dport 123 -j RETURN
ip6tables -t mangle -A singbox-mark -j MARK --set-mark 1
ip6tables -t mangle -N singbox-tproxy
ip6tables -t mangle -A singbox-tproxy -m addrtype --dst-type UNSPEC,LOCAL,ANYCAST,MULTICAST -j RETURN
ip6tables -t mangle -A singbox-tproxy -d ::ffff:0.0.0.0/96 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 64:ff9b::/96 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 100::/64 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 2001::/32 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 2001:10::/28 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 2001:20::/28 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 2001:db8::/32 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d 2002::/16 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d fc00::/7 -j RETURN
ip6tables -t mangle -A singbox-tproxy -d fe80::/10 -j RETURN
ip6tables -t mangle -A singbox-tproxy -p udp --dport 123 -j RETURN
ip6tables -t mangle -A singbox-tproxy -p tcp -j TPROXY --tproxy-mark 0x1/0x1 --on-port 9888
ip6tables -t mangle -A singbox-tproxy -p udp -j TPROXY --tproxy-mark 0x1/0x1 --on-port 9888
ip6tables -t mangle -A OUTPUT -p tcp -m cgroup ! --cgroup 1 -j singbox-mark
ip6tables -t mangle -A OUTPUT -p udp -m cgroup ! --cgroup 1 -j singbox-mark
ip6tables -t mangle -A PREROUTING -i lo -p tcp -j singbox-tproxy
ip6tables -t mangle -A PREROUTING -i lo -p udp -j singbox-tproxy
ip6tables -t mangle -A PREROUTING -i eth0 -p tcp -j singbox-tproxy
ip6tables -t mangle -A PREROUTING -i eth0 -p udp -j singbox-tproxy
else
log "Neither fw3 nor fw4 detected, unable to configure firewall rules."
exit 1
fi
log "Firewall rules applied successfully"
log "Starting sing-box with config: $CONFIG_FILE"
ENABLE_DEPRECATED_SPECIAL_OUTBOUNDS=true "$SINGBOX_BIN" run -c "$CONFIG_FILE"
EOF;
function createStartScript($configFile) {
global $start_script_template, $singbox_bin, $singbox_log, $log;
$script = sprintf($start_script_template, $singbox_log, $configFile, $singbox_bin, $log);
$dir = dirname('/etc/neko/core/start.sh');
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents('/etc/neko/core/start.sh', $script);
chmod('/etc/neko/core/start.sh', 0755);
//writeToLog("Created start script with config: $configFile");
//writeToLog("Singbox binary: $singbox_bin");
//writeToLog("Log file: $singbox_log");
//writeToLog("Firewall log file: $log");
}
function writeToLog($message) {
global $log;
$dateTime = new DateTime();
$time = $dateTime->format('H:i:s');
$logMessage = "[ $time ] $message\n";
if (file_put_contents($log, $logMessage, FILE_APPEND) === false) {
error_log("Failed to write to log file: $log");
}
}
function createCronScript() {
$log_file = '/var/log/singbox_log.txt';
$tmp_log_file = '/etc/neko/tmp/neko_log.txt';
$additional_log_file = '/etc/neko/tmp/log.txt';
$max_size = 1048576;
$cron_schedule = "0 */4 * * * /bin/bash /etc/neko/core/set_cron.sh";
$cronScriptContent = <<<EOL
#!/bin/bash
LOG_FILES=("$log_file" "$tmp_log_file" "$additional_log_file")
LOG_NAMES=("Sing-box" "Mihomo" "NeKoBox")
MAX_SIZE=$max_size
LOG_PATH="/etc/neko/tmp/log.txt"
timestamp() {
date "+[ %H:%M:%S ]"
}
check_and_clear_log() {
local file="\$1"
local name="\$2"
if [ -f "\$file" ]; then
if [ ! -r "\$file" ]; then
echo "\$(timestamp) \$name log file (\$file) exists but is not readable. Check permissions." >> \$LOG_PATH
return 1
fi
size=\$(ls -l "\$file" 2>/dev/null | awk '{print \$5}')
if [ -z "\$size" ] || ! echo "\$size" | grep -q '^[0-9]\+$'; then
echo "\$(timestamp) \$name log file (\$file) size could not be determined. ls command failed or output invalid." >> \$LOG_PATH
return 1
fi
if [ \$size -gt \$MAX_SIZE ]; then
echo "\$(timestamp) \$name log file (\$file) exceeded \$MAX_SIZE bytes (\$size). Clearing log..." >> \$LOG_PATH
> "\$file"
echo "\$(timestamp) \$name log file (\$file) has been cleared." >> \$LOG_PATH
else
echo "\$(timestamp) \$name log file (\$file) is within the size limit (\$size bytes). No action needed." >> \$LOG_PATH
fi
else
echo "\$(timestamp) \$name log file (\$file) not found." >> \$LOG_PATH
fi
}
for i in \${!LOG_FILES[@]}; do
check_and_clear_log "\${LOG_FILES[\$i]}" "\${LOG_NAMES[\$i]}"
done
echo "\$(timestamp) Log rotation completed." >> \$LOG_PATH
(crontab -l 2>/dev/null | grep -v '/etc/neko/core/set_cron.sh'; echo "$cron_schedule") | sort -u | crontab -
EOL;
$cronScriptPath = '/etc/neko/core/set_cron.sh';
file_put_contents($cronScriptPath, $cronScriptContent);
chmod($cronScriptPath, 0755);
shell_exec("bash $cronScriptPath");
}
function rotateLogs($logFile, $maxSize = 1048576) {
if (file_exists($logFile) && filesize($logFile) > $maxSize) {
file_put_contents($logFile, '');
chmod($logFile, 0644);
}
}
function isSingboxRunning() {
global $singbox_bin;
$command = "pgrep -f " . escapeshellarg($singbox_bin);
exec($command, $output);
return !empty($output);
}
function isNekoBoxRunning() {
global $neko_dir;
$pid = trim(shell_exec("cat $neko_dir/tmp/neko.pid 2>/dev/null"));
return !empty($pid) && file_exists("/proc/$pid");
}
function getSingboxPID() {
global $singbox_bin;
$command = "pgrep -f " . escapeshellarg($singbox_bin);
exec($command, $output);
return isset($output[0]) ? $output[0] : null;
}
function getRunningConfigFile() {
global $singbox_bin;
$command = "ps w | grep '$singbox_bin' | grep -v grep";
exec($command, $output);
foreach ($output as $line) {
if (strpos($line, '-c') !== false) {
$parts = explode('-c', $line);
if (isset($parts[1])) {
$configPath = trim(explode(' ', trim($parts[1]))[0]);
return $configPath;
}
}
}
return null;
}
function getAvailableConfigFiles() {
global $singbox_config_dir;
return glob("$singbox_config_dir/*.json");
}
$availableConfigs = getAvailableConfigFiles();
//writeToLog("Script started");
if(isset($_POST['neko'])){
$dt = $_POST['neko'];
writeToLog("Received Mihomo action: $dt");
if ($dt == 'start') {
if (isSingboxRunning()) {
writeToLog("Cannot start NekoBox: Sing-box is running");
} else {
shell_exec("$neko_dir/core/neko -s");
writeToLog("Mihomo started successfully");
}
}
if ($dt == 'disable') {
shell_exec("$neko_dir/core/neko -k");
writeToLog("Mihomo stopped");
}
if ($dt == 'restart') {
if (isSingboxRunning()) {
writeToLog("Cannot restart NekoBox: Sing-box is running");
} else {
shell_exec("$neko_dir/core/neko -r");
writeToLog("Mihomo restarted successfully");
}
}
if ($dt == 'clear') {
shell_exec("echo \"Logs has been cleared...\" > $neko_dir/tmp/neko_log.txt");
writeToLog("Mihomo logs cleared");
}
writeToLog("Mihomo action completed: $dt");
}
if (isset($_POST['singbox'])) {
$action = $_POST['singbox'];
$config_file = isset($_POST['config_file']) ? $_POST['config_file'] : '';
writeToLog("Received singbox action: $action with config: $config_file");
switch ($action) {
case 'start':
if (isNekoBoxRunning()) {
writeToLog("Cannot start Sing-box: Sing-box is running");
} elseif (!file_exists($config_file)) {
writeToLog("Config file not found: $config_file");
} else {
writeToLog("Starting Sing-box");
$singbox_version = trim(preg_replace(['/^Revision:.*$/m', '/sing-box version\s*/i'], '', shell_exec("$singbox_bin version")));
writeToLog("Sing-box version: $singbox_version");
shell_exec("mkdir -p " . dirname($singbox_log));
shell_exec("touch $singbox_log && chmod 644 $singbox_log");
rotateLogs($singbox_log);
createStartScript($config_file);
createCronScript();
shell_exec("sh $start_script_path >> $singbox_log 2>&1 &");
sleep(3);
$pid = getSingboxPID();
if ($pid) {
writeToLog("Sing-box started successfully. PID: $pid");
$needRefresh = true;
} else {
writeToLog("Failed to start Sing-box");
}
}
break;
case 'disable':
writeToLog("Stopping Sing-box");
$pid = getSingboxPID();
if ($pid) {
writeToLog("Killing Sing-box PID: $pid");
shell_exec("kill $pid");
sleep(1);
if (isSingboxRunning()) {
writeToLog("Force killing Sing-box");
shell_exec("kill -9 $pid");
}
if (file_exists('/usr/sbin/fw4')) {
shell_exec("nft flush ruleset");
} else {
shell_exec("iptables -t mangle -F");
shell_exec("iptables -t mangle -X");
shell_exec("ip6tables -t mangle -F");
shell_exec("ip6tables -t mangle -X");
}
shell_exec("/etc/init.d/firewall restart");
writeToLog("Cleared firewall rules and restarted firewall");
if (!isSingboxRunning()) {
writeToLog("Sing-box stopped successfully");
$needRefresh = true;
}
} else {
writeToLog("Sing-box is not running");
}
break;
case 'restart':
if (isNekoBoxRunning()) {
writeToLog("Cannot restart Sing-box: Sing-box is running");
} elseif (!file_exists($config_file)) {
writeToLog("Config file not found: $config_file");
} else {
writeToLog("Restarting Sing-box");
$pid = getSingboxPID();
if ($pid) {
shell_exec("kill $pid");
sleep(1);
}
shell_exec("mkdir -p " . dirname($singbox_log));
shell_exec("touch $singbox_log && chmod 644 $singbox_log");
rotateLogs($singbox_log);
createStartScript($config_file);
shell_exec("sh $start_script_path >> $singbox_log 2>&1 &");
sleep(3);
$new_pid = getSingboxPID();
if ($new_pid) {
writeToLog("Sing-box restarted successfully. New PID: $new_pid");
$needRefresh = true;
} else {
writeToLog("Failed to restart Sing-box");
}
}
break;
}
sleep(2);
$singbox_status = isSingboxRunning() ? '1' : '0';
shell_exec("uci set neko.cfg.singbox_enabled='$singbox_status'");
shell_exec("uci commit neko");
//writeToLog("Singbox status set to: $singbox_status");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cronTime'])) {
$cronTime = $_POST['cronTime'];
if (empty($cronTime)) {
$logMessage = "Please provide a valid Cron time format!";
file_put_contents('/etc/neko/tmp/log.txt', date('Y-m-d H:i:s') . " - ERROR: $logMessage\n", FILE_APPEND);
echo $logMessage;
exit;
}
$startScriptPath = '/etc/neko/core/start.sh';
if (!file_exists('/etc/neko/tmp')) {
mkdir('/etc/neko/tmp', 0755, true);
}
$restartScriptContent = <<<EOL
#!/bin/bash
LOG_PATH="/etc/neko/tmp/log.txt"
timestamp() {
date "+%Y-%m-%d %H:%M:%S"
}
MAX_RETRIES=5
RETRY_INTERVAL=5
start_singbox() {
sh /etc/neko/core/start.sh
}
check_singbox() {
pgrep -x "singbox" > /dev/null
return $?
}
if pgrep -x "singbox" > /dev/null
then
echo "$(timestamp) Sing-box is already running, restarting..." >> \$LOG_PATH
kill $(pgrep -x "singbox")
sleep 2
start_singbox
RETRY_COUNT=0
while ! check_singbox && [ \$RETRY_COUNT -lt \$MAX_RETRIES ]; do
echo "$(timestamp) Sing-box restart failed, retrying... (\$((RETRY_COUNT + 1))/\$MAX_RETRIES)" >> \$LOG_PATH
sleep \$RETRY_INTERVAL
start_singbox
((RETRY_COUNT++))
done
if check_singbox; then
echo "$(timestamp) Sing-box restarted successfully!" >> \$LOG_PATH
else
echo "$(timestamp) Sing-box restart failed, max retries reached!" >> \$LOG_PATH
fi
else
echo "$(timestamp) Sing-box is not running, starting Sing-box..." >> \$LOG_PATH
start_singbox
RETRY_COUNT=0
while ! check_singbox && [ \$RETRY_COUNT -lt \$MAX_RETRIES ]; do
echo "$(timestamp) Sing-box start failed, retrying... (\$((RETRY_COUNT + 1))/\$MAX_RETRIES)" >> \$LOG_PATH
sleep \$RETRY_INTERVAL
start_singbox
((RETRY_COUNT++))
done
if check_singbox; then
echo "$(timestamp) Sing-box started successfully!" >> \$LOG_PATH
else
echo "$(timestamp) Sing-box start failed, max retries reached!" >> \$LOG_PATH
fi
fi
EOL;
$scriptPath = '/etc/neko/core/restart_singbox.sh';
file_put_contents($scriptPath, $restartScriptContent);
chmod($scriptPath, 0755);
$cronSchedule = $cronTime . " /bin/bash $scriptPath";
exec("crontab -l | grep -v '$scriptPath' | crontab -");
exec("(crontab -l 2>/dev/null; echo \"$cronSchedule\") | crontab -");
$logMessage = "Cron job successfully set. Sing-box will restart automatically at $cronTime.";
file_put_contents('/etc/neko/tmp/log.txt', date('[ H:i:s ] ') . "$logMessage\n", FILE_APPEND);
echo json_encode(['success' => true, 'message' => 'Cron job successfully set.']);
exit;
}
if (isset($_POST['clear_singbox_log'])) {
file_put_contents($singbox_log, '');
writeToLog("Singbox log cleared");
}
if (isset($_POST['clear_plugin_log'])) {
$plugin_log_file = "$neko_dir/tmp/log.txt";
file_put_contents($plugin_log_file, '');
writeToLog("Nekobox log cleared");
}
$neko_status = exec("uci -q get neko.cfg.enabled");
$singbox_status = isSingboxRunning() ? '1' : '0';
exec("uci set neko.cfg.singbox_enabled='$singbox_status'");
exec("uci commit neko");
//writeToLog("Final neko status: $neko_status");
//writeToLog("Final singbox status: $singbox_status");
if ($singbox_status == '1') {
$runningConfigFile = getRunningConfigFile();
if ($runningConfigFile) {
$str_cfg = htmlspecialchars(basename($runningConfigFile));
//writeToLog("Running config file: $str_cfg");
} else {
$str_cfg = 'Sing-box configuration file: No running configuration file found';
writeToLog("No running config file found");
}
}
function readRecentLogLines($filePath, $lines = 1000) {
if (!file_exists($filePath)) {
return "The log file does not exist: $filePath";
}
if (!is_readable($filePath)) {
return "Unable to read the log file: $filePath";
}
$command = "tail -n $lines " . escapeshellarg($filePath);
$output = shell_exec($command);
return $output ?: "The log is empty";
}
function readLogFile($filePath) {
if (file_exists($filePath)) {
return nl2br(htmlspecialchars(readRecentLogLines($filePath, 1000), ENT_NOQUOTES));
} else {
return 'The log file does not exist';
}
}
$neko_log_content = readLogFile("$neko_dir/tmp/neko_log.txt");
$singbox_log_content = readLogFile($singbox_log);
if ($needRefresh):
?>
<script>
window.addEventListener('load', function() {
if (!sessionStorage.getItem('refreshed')) {
sessionStorage.setItem('refreshed', 'true');
window.location.reload();
} else {
sessionStorage.removeItem('refreshed');
}
});
</script>
<?php endif; ?>
<?php
$confDirectory = '/etc/neko/config';
$storageFile = '/www/nekobox/lib/singbox.txt';
$storageDir = dirname($storageFile);
if (!is_dir($storageDir)) {
mkdir($storageDir, 0755, true);
}
$currentConfigPath = '';
if (file_exists($storageFile)) {
$rawPath = trim(file_get_contents($storageFile));
$currentConfigPath = realpath($rawPath) ?: $rawPath;
}
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['config_file'])) {
$submittedPath = trim($_POST['config_file']);
$normalizedPath = realpath($submittedPath);
if ($normalizedPath &&
strpos($normalizedPath, realpath($confDirectory)) === 0 &&
file_exists($normalizedPath)
) {
if (file_put_contents($storageFile, $normalizedPath) !== false) {
$currentConfigPath = $normalizedPath;
} else {
error_log("Write failed: $storageFile");
}
} else {
error_log("Invalid path: $submittedPath");
}
}
function fetchConfigFiles() {
global $confDirectory;
$baseDir = rtrim($confDirectory, '/') . '/';
return glob($baseDir . '*.json') ?: [];
}
$foundConfigs = fetchConfigFiles();
?>
<?php
$isNginx = false;
if (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
$isNginx = true;
}
?>
<?php
if (isset($_GET['ajax'])) {
$dt = json_decode(shell_exec("ubus call system board"), true);
$devices = $dt['model'];
$kernelv = exec("cat /proc/sys/kernel/ostype");
$osrelease = exec("cat /proc/sys/kernel/osrelease");
$OSVer = $dt['release']['distribution'] . ' ' . $dt['release']['version'];
$kernelParts = explode('.', $osrelease, 3);
$kernelv = 'Linux ' .
(isset($kernelParts[0]) ? $kernelParts[0] : '') . '.' .
(isset($kernelParts[1]) ? $kernelParts[1] : '') . '.' .
(isset($kernelParts[2]) ? $kernelParts[2] : '');
$kernelv = strstr($kernelv, '-', true) ?: $kernelv;
$fullOSInfo = $kernelv . ' ' . $OSVer;
$tmpramTotal = exec("cat /proc/meminfo | grep MemTotal | awk '{print $2}'");
$tmpramAvailable = exec("cat /proc/meminfo | grep MemAvailable | awk '{print $2}'");
$ramTotal = number_format(($tmpramTotal / 1000), 1);
$ramAvailable = number_format(($tmpramAvailable / 1000), 1);
$ramUsage = number_format((($tmpramTotal - $tmpramAvailable) / 1000), 1);
$raw_uptime = exec("cat /proc/uptime | awk '{print $1}'");
$days = floor($raw_uptime / 86400);
$hours = floor(($raw_uptime / 3600) % 24);
$minutes = floor(($raw_uptime / 60) % 60);
$seconds = $raw_uptime % 60;
$cpuLoad = shell_exec("cat /proc/loadavg");
$cpuLoad = explode(' ', $cpuLoad);
$cpuLoadAvg1Min = round($cpuLoad[0], 2);
$cpuLoadAvg5Min = round($cpuLoad[1], 2);
$cpuLoadAvg15Min = round($cpuLoad[2], 2);
$timezone = trim(shell_exec("uci get system.@system[0].zonename 2>/dev/null"));
if (!$timezone) {
$timezone = 'UTC';
}
date_default_timezone_set($timezone);
$currentTime = date("Y-m-d H:i:s");
echo json_encode([
'systemInfo' => "$devices - $fullOSInfo",
'ramUsage' => "$ramUsage/$ramTotal MB",
'cpuLoad' => "$cpuLoadAvg1Min $cpuLoadAvg5Min $cpuLoadAvg15Min",
'uptime' => "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds",
'cpuLoadAvg1Min' => $cpuLoadAvg1Min,
'ramTotal' => $ramTotal,
'ramUsageOnly' => $ramUsage,
'timezone' => $timezone,
'currentTime' => $currentTime,
]);
exit;
}
?>
<?php
$default_config = '/etc/neko/config/mihomo.yaml';
$current_config = file_exists('/www/nekobox/lib/selected_config.txt')
? trim(file_get_contents('/www/nekobox/lib/selected_config.txt'))
: $default_config;
if (!file_exists($current_config)) {
$default_config_content = "external-controller: 0.0.0.0:9090\n";
$default_config_content .= "secret: Akun\n";
$default_config_content .= "external-ui: ui\n";
$default_config_content .= "# Please edit this file as needed\n";
file_put_contents($current_config, $default_config_content);
file_put_contents('/www/nekobox/lib/selected_config.txt', $current_config);
$logMessage = "The configuration file is missing; a default configuration file has been created.";
} else {
$config_content = file_get_contents($current_config);
$missing_config = false;
$default_config_content = [
"external-controller" => "0.0.0.0:9090",
"secret" => "Akun",
"external-ui" => "ui"
];
foreach ($default_config_content as $key => $value) {
if (strpos($config_content, "$key:") === false) {
$config_content .= "$key: $value\n";
$missing_config = true;
}
}
if ($missing_config) {
file_put_contents($current_config, $config_content);
$logMessage = "The configuration file is missing some options; the missing configuration items have been added automatically";
}
}
if (isset($logMessage)) {
echo "<script>alert('$logMessage');</script>";
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['selected_config'])) {
$selected_file = $_POST['selected_config'];
$config_dir = '/etc/neko/config';
$selected_file_path = $config_dir . '/' . $selected_file;
if (file_exists($selected_file_path) && pathinfo($selected_file, PATHINFO_EXTENSION) == 'yaml') {
file_put_contents('/www/nekobox/lib/selected_config.txt', $selected_file_path);
} else {
echo "<script>alert('Invalid configuration file');</script>";
}
}
?>
<meta charset="utf-8">
<title>Home - Nekobox</title>
<link rel="icon" href="./assets/img/nekobox.png">
<?php include './ping.php'; ?>
<?php if ($isNginx): ?>
<div id="nginxWarning"
class="alert alert-warning alert-dismissible fade show"
role="alert"
style="position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 1050;">
<strong data-translate="nginxWarningStrong"></strong>
<span data-translate="nginxWarning"></span>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const lastWarningTime = localStorage.getItem('nginxWarningTime');
const currentTime = new Date().getTime();
const warningInterval = 12 * 60 * 60 * 1000;
if (!lastWarningTime || currentTime - lastWarningTime > warningInterval) {
localStorage.setItem('nginxWarningTime', currentTime);
const warningAlert = document.getElementById('nginxWarning');
if (warningAlert) {
warningAlert.style.display = 'block';
setTimeout(function () {
warningAlert.classList.remove('show');
setTimeout(function () {
warningAlert.remove();
}, 300);
}, 5000);
}
}
});
</script>
<?php endif; ?>
<div class="container-sm container-bg mt-0">
<?php include 'navbar.php'; ?>
<div class="container-sm text-center col-8">
<img src="./assets/img/nekobox.png" alt="Icon" class="centered-img">
<div id="version-info" class="d-flex align-items-center justify-content-center mt-1 gap-1">
<a id="version-link"
href="https://github.com/Thaolga/openwrt-nekobox/releases"
target="_blank">
<img id="current-version" src="./assets/img/curent.svg" alt="Current Version" class="img-fluid" style="height:23px;">
</a>
</div>
</div>
<h2 id="neko-title" class="neko-title-style m-2" style="cursor: pointer;" data-bs-toggle="modal" data-bs-target="#systemInfoModal">NekoBox</h2>
<?php
function getSingboxVersion() {
$singBoxPath = '/usr/bin/sing-box';
$command = "$singBoxPath version 2>&1";
exec($command, $output, $returnVar);
if ($returnVar === 0) {
foreach ($output as $line) {
if (strpos($line, 'version') !== false) {
$parts = explode(' ', $line);
return end($parts);
}
}
}
return 'Not installed';
}
function getMihomoVersion() {
$mihomoPath = '/usr/bin/mihomo';
if (!file_exists($mihomoPath)) {
return 'Not installed';
}
$command = "$mihomoPath -v 2>&1";
exec($command, $output, $returnVar);
if ($returnVar === 0 && !empty($output)) {
$line = trim($output[0]);
if (preg_match('/Mihomo Meta\s+([^\s]+)/i', $line, $matches)) {
return $matches[1];
}
return $line;
}
return 'Command failed: ' . $returnVar;
}
$singboxVersion = getSingboxVersion();
$mihomoVersion = getMihomoVersion();
?>
<div class="px-0 px-sm-4 mt-3 control-box">
<div class="card">
<div class="card-body">
<div class="mb-4">
<h6 class="mb-2"><i data-feather="activity"></i> <span data-translate="status">Status</span></h6>
<div class="btn-group w-100" role="group">
<?php if ($neko_status == '1'): ?>
<button type="button" class="btn btn-success">
<i class="bi bi-router"></i>
<span data-translate="mihomoRunning" data-index="(<?= htmlspecialchars($mihomoVersion) ?>)"></span>
</button>
<?php else: ?>
<button type="button" class="btn btn-outline-danger">
<i class="bi bi-router"></i>
<span data-translate="mihomoNotRunning">Mihomo Not Running</span>
</button>
<?php endif; ?>
<button type="button" class="btn btn-deepskyblue">
<i class="bi bi-file-earmark-text"></i> <?= $str_cfg ?>
</button>
<?php if ($singbox_status == '1'): ?>
<button type="button" class="btn btn-success">
<i class="bi bi-hdd-stack"></i>
<span data-translate="singboxRunning" data-index="(<?= htmlspecialchars($singboxVersion) ?>)"></span>
</button>
<?php else: ?>
<button type="button" class="btn btn-outline-danger">
<i class="bi bi-hdd-stack"></i>
<span data-translate="singboxNotRunning">Sing-box Not Running</span>
</button>
<?php endif; ?>
</div>
</div>
<div class="mb-4 control-box" id="mihomoControl">
<h6 class="mb-2"><i class="fas fa-box custom-icon"></i> <span data-translate="mihomoControl">Mihomo Control</span></h6>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_mihomo_preview.php | luci-app-nekobox/htdocs/nekobox/update_mihomo_preview.php | <?php
ini_set('memory_limit', '256M');
function logMessage($message) {
$logFile = '/tmp/mihomo_prerelease_update.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/core/mihomo_version.txt';
$result = file_put_contents($versionFile, $version);
if ($result === false) {
logMessage("Unable to write to version file: $versionFile");
}
}
$repo_owner = "MetaCubeX";
$repo_name = "mihomo";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases";
$curl_command = "curl -s -H 'User-Agent: PHP' " . escapeshellarg($api_url);
$response = shell_exec($curl_command);
if ($response === false || empty($response)) {
logMessage("curl request failed, try using wget...");
$wget_command = "wget -q --no-check-certificate --timeout=10 " . escapeshellarg($api_url) . " -O /tmp/api_response.json";
exec($wget_command, $output, $return_var);
if ($return_var !== 0 || !file_exists('/tmp/api_response.json')) {
logMessage("GitHub API request failed, both curl and wget failed");
die("GitHub API request failed. Please check your network connection or try again later");
}
$response = file_get_contents('/tmp/api_response.json');
unlink('/tmp/api_response.json');
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die("Error occurred while parsing GitHub API response: " . json_last_error_msg());
}
$latest_prerelease = null;
foreach ($data as $release) {
if (isset($release['prerelease']) && $release['prerelease'] == true) {
$latest_prerelease = $release;
break;
}
}
if ($latest_prerelease === null) {
die("No latest preview version found");
}
$latest_version = $latest_prerelease['tag_name'] ?? '';
$assets = $latest_prerelease['assets'] ?? [];
if (empty($latest_version)) {
die("No latest version information found");
}
$download_url = '';
$asset_found = false;
$current_arch = trim(shell_exec("uname -m"));
foreach ($assets as $asset) {
if ($current_arch === 'x86_64' && strpos($asset['name'], 'linux-amd64-alpha') !== false && strpos($asset['name'], '.gz') !== false) {
$download_url = $asset['browser_download_url'];
$asset_found = true;
break;
}
if ($current_arch === 'aarch64' && strpos($asset['name'], 'linux-arm64-alpha') !== false && strpos($asset['name'], '.gz') !== false) {
$download_url = $asset['browser_download_url'];
$asset_found = true;
break;
}
if ($current_arch === 'armv7l' && strpos($asset['name'], 'linux-armv7l-alpha') !== false && strpos($asset['name'], '.gz') !== false) {
$download_url = $asset['browser_download_url'];
$asset_found = true;
break;
}
}
if (!$asset_found) {
die("No suitable architecture preview download link found");
}
$filename = basename($download_url);
preg_match('/alpha-[\w-]+/', $filename, $matches);
$version_from_filename = $matches[0] ?? 'Unknown version';
$latest_version = $version_from_filename;
echo "Latest version: " . htmlspecialchars($latest_version) . "\n";
$temp_file = '/tmp/mihomo_prerelease.gz';
$curl_command = "curl -sL " . escapeshellarg($download_url) . " -o " . escapeshellarg($temp_file);
exec($curl_command, $output, $return_var);
if ($return_var !== 0 || !file_exists($temp_file)) {
logMessage("Download failed, try using wget...");
$wget_command = "wget -q --show-progress --no-check-certificate " . escapeshellarg($download_url) . " -O " . escapeshellarg($temp_file);
exec($wget_command, $output, $return_var);
if ($return_var !== 0 || !file_exists($temp_file)) {
logMessage("Download failed, both curl and wget have failed");
die("Download failed");
}
}
exec("gzip -d -c '$temp_file' > '/tmp/mihomo-linux-$current_arch'", $output, $return_var);
if ($return_var === 0) {
$install_path = '/usr/bin/mihomo';
exec("mv '/tmp/mihomo-linux-$current_arch' '$install_path'", $output, $return_var);
if ($return_var === 0) {
exec("chmod 0755 '$install_path'", $output, $return_var);
if ($return_var === 0) {
logMessage("Update complete! Current version: $latest_version");
echo "Update complete! Current version: $latest_version";
writeVersionToFile($latest_version);
} else {
logMessage("Failed to set permissions");
echo "Failed to set permissions";
}
} else {
logMessage("Failed to move the file");
echo "Failed to move the file";
}
} else {
logMessage("Failed to unzip");
echo "Failed to unzip";
}
if (file_exists($temp_file)) {
unlink($temp_file);
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_singbox_stable.php | luci-app-nekobox/htdocs/nekobox/update_singbox_stable.php | <?php
ini_set('memory_limit', '128M');
function logMessage($message) {
$logFile = '/var/log/sing-box_update.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/core/version.txt';
file_put_contents($versionFile, $version);
}
$repo_owner = "SagerNet";
$repo_name = "sing-box";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases";
$curl_command = "curl -s -H 'User-Agent: PHP' --connect-timeout 10 " . escapeshellarg($api_url);
$response = shell_exec($curl_command);
if ($response === false || empty($response)) {
logMessage("GitHub API request failed, possibly due to network issues or GitHub API restrictions.");
die("GitHub API request failed. Please check your network connection or try again later.");
}
logMessage("GitHub API response: " . substr($response, 0, 200) . "...");
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
logMessage("Error parsing GitHub API response: " . json_last_error_msg());
die("Error parsing GitHub API response: " . json_last_error_msg());
}
$latest_version = '';
if (is_array($data)) {
foreach ($data as $release) {
if (isset($release['tag_name']) && isset($release['prerelease']) && !$release['prerelease']) {
$latest_version = $release['tag_name'];
break;
}
}
}
if (empty($latest_version)) {
logMessage("No stable version found.");
die("No stable version found.");
}
$current_version = '';
$install_path = '/usr/bin/sing-box';
$temp_file = '/tmp/sing-box.tar.gz';
$temp_dir = '/tmp/singbox_temp';
if (file_exists($install_path)) {
$current_version = trim(shell_exec("{$install_path} --version"));
}
$current_arch = trim(shell_exec("uname -m"));
$base_version = ltrim($latest_version, 'v');
$download_url = '';
switch ($current_arch) {
case 'aarch64':
$download_url = "https://github.com/SagerNet/sing-box/releases/download/$latest_version/sing-box-$base_version-linux-arm64.tar.gz";
break;
case 'x86_64':
$download_url = "https://github.com/SagerNet/sing-box/releases/download/$latest_version/sing-box-$base_version-linux-amd64.tar.gz";
break;
default:
die("No download link found for architecture: $current_arch");
}
if (isset($_GET['check_version'])) {
if (trim($current_version) === trim($latest_version)) {
echo "Current version is already the latest: v$current_version";
} else {
echo "Latest version: $latest_version";
}
exit;
}
if (trim($current_version) === trim($latest_version)) {
die("Current version is already the latest.");
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed!");
}
if (!is_dir($temp_dir)) {
mkdir($temp_dir, 0755, true);
}
exec("tar -xzf '$temp_file' -C '$temp_dir'", $output, $return_var);
if ($return_var !== 0) {
die("Extraction failed!");
}
$extracted_file = glob("$temp_dir/sing-box-*/*sing-box")[0] ?? '';
if ($extracted_file && file_exists($extracted_file)) {
exec("cp -f '$extracted_file' '$install_path'");
exec("chmod 0755 '$install_path'");
writeVersionToFile($latest_version);
echo "Update completed! Current version: $latest_version";
} else {
die("Extracted file 'sing-box' does not exist.");
}
unlink($temp_file);
exec("rm -r '$temp_dir'");
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_zashboard.php | luci-app-nekobox/htdocs/nekobox/update_zashboard.php | <?php
ini_set('memory_limit', '128M');
function getUiVersion() {
$versionFile = '/etc/neko/ui/zashboard/version.txt';
return file_exists($versionFile) ? trim(file_get_contents($versionFile)) : "Version file not found";
}
function writeVersionToFile($version) {
file_put_contents('/etc/neko/ui/zashboard/version.txt', $version);
}
$repo_owner = "Zephyruso";
$repo_name = "zashboard";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
$response = shell_exec("curl -s -H 'User-Agent: PHP' --connect-timeout 10 " . escapeshellarg($api_url));
if ($response === false || empty($response)) {
die("GitHub API request failed");
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die("Failed to parse GitHub API response");
}
$latest_version = $data['tag_name'] ?? '';
$install_path = '/etc/neko/ui/zashboard';
$temp_file = '/tmp/dist.zip';
$dist_url = $data['assets'][0]['browser_download_url'] ?? '';
$fonts_url = $data['assets'][1]['browser_download_url'] ?? '';
if (empty($dist_url) || empty($fonts_url)) {
die("Download link not found");
}
if (!is_dir($install_path)) {
mkdir($install_path, 0755, true);
}
$current_version = getUiVersion();
if (isset($_GET['check_version'])) {
echo "Latest version: $latest_version";
exit;
}
$update_type = $_GET['update_type'] ?? 'dist';
$download_url = ($update_type === 'fonts') ? $fonts_url : $dist_url;
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed");
}
if (!file_exists($temp_file)) {
die("Downloaded file not found");
}
exec("rm -rf /tmp/dist_extract", $output, $return_var);
if ($return_var !== 0) {
die("Failed to clean temporary extraction directory");
}
exec("unzip -o '$temp_file' -d '/tmp/dist_extract'", $output, $return_var);
if ($return_var !== 0) {
die("Extraction failed");
}
$extracted_dist_dir = "/tmp/dist_extract/dist";
if (is_dir($extracted_dist_dir)) {
exec("rm -rf $install_path/*", $output, $return_var);
if ($return_var !== 0) {
die("Failed to delete old files");
}
exec("mv $extracted_dist_dir/* $install_path/", $output, $return_var);
if ($return_var !== 0) {
die("Failed to move extracted files");
}
exec("rm -rf /tmp/dist_extract", $output, $return_var);
if ($return_var !== 0) {
die("Failed to remove temporary extraction directory");
}
} else {
die("'dist' directory not found, extraction failed");
}
exec("chown -R root:root '$install_path' 2>&1", $output, $return_var);
if ($return_var !== 0) {
die("Failed to change file ownership");
}
writeVersionToFile($latest_version);
echo "Update complete! Current version: $latest_version";
unlink($temp_file);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_script.php | luci-app-nekobox/htdocs/nekobox/update_script.php | <?php
$repo_owner = "Thaolga";
$repo_name = "openwrt-nekobox";
$package_name = "luci-app-nekobox";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases/latest";
$local_api_response = "/tmp/api_response.json";
$curl_command = "curl -H 'User-Agent: PHP' -s " . escapeshellarg($api_url) . " -o " . escapeshellarg($local_api_response);
exec($curl_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_api_response)) {
echo "<script>appendLog('curl failed to fetch version information, attempting to use wget...');</script>";
$wget_command = "wget -q --no-check-certificate " . escapeshellarg($api_url) . " -O " . escapeshellarg($local_api_response);
exec($wget_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_api_response)) {
die("Unable to access GitHub API. Please check the URL or network connection. Output: " . implode("\n", $output));
}
echo "<script>appendLog('wget has completed fetching version information');</script>";
}
$response = file_get_contents($local_api_response);
$data = json_decode($response, true);
unlink($local_api_response);
$tag_name = $data['tag_name'] ?? '';
$new_version = '';
$asset_file_name = '';
if (isset($data['assets']) && is_array($data['assets'])) {
foreach ($data['assets'] as $asset) {
if (strpos($asset['name'], $package_name) !== false) {
preg_match('/' . preg_quote($package_name, '/') . '_(v?\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?)_all\.ipk$/', $asset['name'], $matches);
if (!empty($matches[1])) {
$new_version = $matches[1];
$asset_file_name = $asset['name'];
break;
}
}
}
}
if (empty($new_version)) {
die("No latest version found or version information is empty");
}
if (isset($_GET['check_version'])) {
echo "Latest version: v" . $new_version;
exit;
}
$download_url = "https://github.com/$repo_owner/$repo_name/releases/download/{$tag_name}/{$asset_file_name}";
echo "<pre>Latest version: $new_version</pre>";
echo "<pre>Tag name: $tag_name</pre>";
echo "<pre>Asset file: $asset_file_name</pre>";
echo "<pre>Download URL: $download_url</pre>";
echo "<pre id='logOutput'></pre>";
echo "<script>
function appendLog(message) {
document.getElementById('logOutput').innerHTML += message + '\\n';
}
</script>";
echo "<script>appendLog('Start downloading updates...');</script>";
$local_file = "/tmp/{$asset_file_name}";
$curl_command = "curl -sL " . escapeshellarg($download_url) . " -o " . escapeshellarg($local_file);
exec($curl_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_file)) {
echo "<script>appendLog('curl download failed, trying to use wget...');</script>";
$wget_command = "wget -q --show-progress --no-check-certificate " . escapeshellarg($download_url) . " -O " . escapeshellarg($local_file);
exec($wget_command . " 2>&1", $output, $return_var);
if ($return_var !== 0 || !file_exists($local_file)) {
echo "<pre>Download failed. Command output: " . implode("\n", $output) . "</pre>";
die("Download failed. The downloaded file was not found");
}
echo "<script>appendLog('wget download complete');</script>";
} else {
echo "<script>appendLog('curl download complete');</script>";
}
echo "<script>appendLog('Update the list of software packages...');</script>";
$output = shell_exec("opkg update");
echo "<pre>$output</pre>";
echo "<script>appendLog('Start installation...');</script>";
$output = shell_exec("opkg install --force-reinstall " . escapeshellarg($local_file));
echo "<pre>$output</pre>";
echo "<script>appendLog('Installation complete。');</script>";
unlink($local_file);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_config.php | luci-app-nekobox/htdocs/nekobox/update_config.php | <?php
ini_set('memory_limit', '128M');
ini_set('max_execution_time', 300);
$logMessages = [];
function logMessage($filename, $message) {
global $logMessages;
$timestamp = date('H:i:s');
$logMessages[] = "[$timestamp] $filename: $message";
}
function downloadFile($url, $destination, $retries = 3, $timeout = 30) {
$attempt = 1;
while ($attempt <= $retries) {
try {
$dir = dirname($destination);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$command = sprintf(
"wget -q --timeout=%d --tries=%d --header='Accept-Charset: utf-8' -O %s %s",
$timeout,
$retries,
escapeshellarg($destination),
escapeshellarg($url)
);
$output = [];
$return_var = null;
exec($command, $output, $return_var);
if ($return_var !== 0) {
throw new Exception("wget error message: " . implode("\n", $output));
}
logMessage(basename($destination), "Download and save successful");
return true;
} catch (Exception $e) {
logMessage(basename($destination), "Attempt $attempt failed: " . $e->getMessage());
if ($attempt === $retries) {
logMessage(basename($destination), "All download attempts failed");
return false;
}
$attempt++;
sleep(2);
}
}
return false;
}
echo "Start updating configuration file...\n";
$urls = [
"https://raw.githubusercontent.com/Thaolga/openwrt-nekobox/refs/heads/main/luci-app-nekobox/root/etc/neko/config/mihomo.yaml" => "/etc/neko/config/mihomo.yaml",
"https://raw.githubusercontent.com/Thaolga/openwrt-nekobox/nekobox/luci-app-nekobox/root/etc/neko/config/Puernya.json" => "/etc/neko/config/Puernya.json"
];
foreach ($urls as $url => $destination) {
logMessage(basename($destination), "Start downloading from $url");
if (downloadFile($url, $destination)) {
logMessage(basename($destination), "File update successful");
} else {
logMessage(basename($destination), "File update failed");
}
}
echo "\nConfiguration file update completed!\n\n";
foreach ($logMessages as $message) {
echo $message . "\n";
}
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_singbox_preview.php | luci-app-nekobox/htdocs/nekobox/update_singbox_preview.php | <?php
ini_set('memory_limit', '128M');
function logMessage($message) {
$logFile = '/var/log/sing-box_update.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/core/version.txt';
file_put_contents($versionFile, $version);
}
$repo_owner = "SagerNet";
$repo_name = "sing-box";
$api_url = "https://api.github.com/repos/$repo_owner/$repo_name/releases";
$curl_command = "curl -s -H 'User-Agent: PHP' --connect-timeout 10 " . escapeshellarg($api_url);
$response = shell_exec($curl_command);
if ($response === false || empty($response)) {
logMessage("GitHub API request failed, possibly due to network issues or GitHub API restrictions.");
die("GitHub API request failed. Please check your network connection or try again later.");
}
logMessage("GitHub API response: " . substr($response, 0, 200) . "...");
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
logMessage("Error parsing GitHub API response: " . json_last_error_msg());
die("Error parsing GitHub API response: " . json_last_error_msg());
}
$latest_version = '';
if (is_array($data)) {
foreach ($data as $release) {
if (isset($release['tag_name'])) {
$latest_version = $release['tag_name'];
break;
}
}
}
if (empty($latest_version)) {
logMessage("No version information found.");
die("No version information found.");
}
$current_version = '';
$install_path = '/usr/bin/sing-box';
$temp_file = '/tmp/sing-box.tar.gz';
$temp_dir = '/tmp/singbox_temp';
if (file_exists($install_path)) {
$current_version = trim(shell_exec("{$install_path} --version"));
}
$current_arch = trim(shell_exec("uname -m"));
$base_version = ltrim($latest_version, 'v');
$download_url = '';
switch ($current_arch) {
case 'aarch64':
$download_url = "https://github.com/SagerNet/sing-box/releases/download/$latest_version/sing-box-$base_version-linux-arm64.tar.gz";
break;
case 'x86_64':
$download_url = "https://github.com/SagerNet/sing-box/releases/download/$latest_version/sing-box-$base_version-linux-amd64.tar.gz";
break;
default:
die("No download link found for architecture: $current_arch");
}
if (isset($_GET['check_version'])) {
if (trim($current_version) === trim($latest_version)) {
echo "Current version is already the latest: v$current_version";
} else {
echo "Latest version: $latest_version";
}
exit;
}
if (trim($current_version) === trim($latest_version)) {
die("Current version is already the latest.");
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed!");
}
if (!is_dir($temp_dir)) {
mkdir($temp_dir, 0755, true);
}
exec("tar -xzf '$temp_file' -C '$temp_dir'", $output, $return_var);
if ($return_var !== 0) {
die("Extraction failed!");
}
$extracted_file = glob("$temp_dir/sing-box-*/*sing-box")[0] ?? '';
if ($extracted_file && file_exists($extracted_file)) {
exec("cp -f '$extracted_file' '$install_path'");
exec("chmod 0755 '$install_path'");
writeVersionToFile($latest_version);
echo "Update completed! Current version: $latest_version";
} else {
die("Extracted file 'sing-box' does not exist.");
}
unlink($temp_file);
exec("rm -r '$temp_dir'");
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/subscription.php | luci-app-nekobox/htdocs/nekobox/subscription.php | <?php
ob_start();
include './cfg.php';
ini_set('memory_limit', '256M');
$result = $result ?? '';
$subscription_file = '/etc/neko/tmp/singbox.txt';
$download_path = '/etc/neko/config/';
$log_file = '/var/log/neko_update.log';
$current_subscription_url = '';
if (isset($_POST['subscription_url'])) {
$current_subscription_url = $_POST['subscription_url'];
}
function logMessage($message) {
global $log_file;
$timestamp = date('Y-m-d H:i:s');
file_put_contents($log_file, "[$timestamp] $message\n", FILE_APPEND);
}
function buildFinalUrl($subscription_url, $config_url, $include, $exclude, $backend_url, $emoji, $udp, $xudp, $tfo, $ipv6, $tls13, $fdn, $sort, $rename) {
$encoded_subscription_url = urlencode($subscription_url);
$encoded_config_url = urlencode($config_url);
$encoded_include = urlencode($include);
$encoded_exclude = urlencode($exclude);
$encoded_rename = urlencode($rename);
$final_url = "{$backend_url}target=singbox&url={$encoded_subscription_url}&insert=false&config={$encoded_config_url}";
if (!empty($include)) {
$final_url .= "&include={$encoded_include}";
}
if (!empty($exclude)) {
$final_url .= "&exclude={$encoded_exclude}";
}
$final_url .= "&emoji=" . (isset($_POST['emoji']) && $_POST['emoji'] === 'true' ? "true" : "false");
$final_url .= "&xudp=" . (isset($_POST['xudp']) && $_POST['xudp'] === 'true' ? "true" : "false");
$final_url .= "&udp=" . (isset($_POST['udp']) && $_POST['udp'] === 'true' ? "true" : "false");
$final_url .= "&tfo=" . (isset($_POST['tfo']) && $_POST['tfo'] === 'true' ? "true" : "false");
$final_url .= "&fdn=" . (isset($_POST['fdn']) && $_POST['fdn'] === 'true' ? "true" : "false");
$final_url .= "&tls13=" . (isset($_POST['tls13']) && $_POST['tls13'] === 'true' ? "true" : "false");
$final_url .= "&sort=" . (isset($_POST['sort']) && $_POST['sort'] === 'true' ? "true" : "false");
$final_url .= "&list=false&expand=true&scv=false";
if (!empty($rename)) {
$final_url .= "&rename={$encoded_rename}";
}
if ($ipv6 === 'true') {
$final_url .= "&singbox.ipv6=1";
}
return $final_url;
}
function saveSubscriptionUrlToFile($url, $file) {
$success = file_put_contents($file, $url) !== false;
logMessage($success ? "Subscription link has been saved to $file" : "Failed to save subscription link to $file");
return $success;
}
function transformContent($content) {
$parsedData = json_decode($content, true);
if ($parsedData === null) {
logMessage("Unable to parse content into JSON format");
return "Unable to parse content as JSON";
}
if (isset($parsedData['inbounds'])) {
$newInbounds = [];
foreach ($parsedData['inbounds'] as $inbound) {
if (isset($inbound['type']) && $inbound['type'] === 'mixed' && $inbound['tag'] === 'mixed-in') {
if ($inbound['listen_port'] !== 2080) {
$newInbounds[] = $inbound;
}
} elseif (isset($inbound['type']) && $inbound['type'] === 'tun') {
continue;
}
}
$newInbounds[] = [
"domain_strategy" => "prefer_ipv4",
"listen" => "127.0.0.1",
"listen_port" => 2334,
"sniff" => true,
"sniff_override_destination" => true,
"tag" => "mixed-in",
"type" => "mixed",
"users" => []
];
$newInbounds[] = [
"tag" => "tun",
"type" => "tun",
"address" => [
"172.19.0.1/30",
"fdfe:dcba:9876::1/126"
],
"route_address" => [
"0.0.0.0/1",
"128.0.0.0/1",
"::/1",
"8000::/1"
],
"route_exclude_address" => [
"192.168.0.0/16",
"fc00::/7"
],
"stack" => "system",
"auto_route" => true,
"strict_route" => true,
"sniff" => true,
"platform" => [
"http_proxy" => [
"enabled" => true,
"server" => "0.0.0.0",
"server_port" => 1082
]
]
];
$newInbounds[] = [
"tag" => "mixed",
"type" => "mixed",
"listen" => "0.0.0.0",
"listen_port" => 1082,
"sniff" => true
];
$parsedData['inbounds'] = $newInbounds;
}
if (isset($parsedData['experimental']['clash_api'])) {
$parsedData['experimental']['clash_api'] = [
"external_ui" => "/etc/neko/ui/",
"external_controller" => "0.0.0.0:9090",
"secret" => "Akun"
];
}
$fileContent = json_encode($parsedData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return $fileContent;
}
function saveSubscriptionContentToYaml($url, $filename) {
global $download_path;
if (pathinfo($filename, PATHINFO_EXTENSION) !== 'json') {
$filename .= '.json';
}
if (strpbrk($filename, "!@#$%^&*()+=[]\\\';,/{}|\":<>?") !== false) {
$message = "Filename contains illegal characters. Please use letters, numbers, dots, underscores, or hyphens.";
logMessage($message);
return $message;
}
if (!is_dir($download_path)) {
if (!mkdir($download_path, 0755, true)) {
$message = "Unable to create directory: $download_path";
logMessage($message);
return $message;
}
}
$output_file = escapeshellarg($download_path . $filename);
$command = "wget -q --no-check-certificate -O $output_file " . escapeshellarg($url);
exec($command, $output, $return_var);
if ($return_var !== 0) {
$message = "wget Error,Unable to retrieve subscription content. Please check if the link is correct.";
logMessage($message);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$subscription_data = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
curl_close($ch);
$message = "cURL Error: $error_msg";
logMessage($message);
return $message;
}
curl_close($ch);
if (empty($subscription_data)) {
$message = "Unable to retrieve subscription content. Please check if the link is correct.";
logMessage($message);
return $message;
}
$transformed_data = transformContent($subscription_data);
$file_path = $download_path . $filename;
$success = file_put_contents($file_path, $transformed_data) !== false;
$message = $success ? "Content successfully saved to: $file_path" : "File save failed.";
logMessage($message);
return $message;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$templates = [
'1' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_NoAuto.ini?',
'2' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_AdblockPlus.ini?',
'3' => 'https://raw.githubusercontent.com/youshandefeiyang/webcdn/main/SONY.ini',
'4' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/default_with_clash_adg.yml?',
'5' => 'https://raw.githubusercontent.com/WC-Dream/ACL4SSR/WD/Clash/config/ACL4SSR_Online_Full_Dream.ini?',
'6' => 'https://raw.githubusercontent.com/WC-Dream/ACL4SSR/WD/Clash/config/ACL4SSR_Mini_Dream.ini?',
'7' => 'https://raw.githubusercontent.com/justdoiting/ClashRule/main/GeneralClashRule.ini?',
'8' => 'https://raw.githubusercontent.com/cutethotw/ClashRule/main/GeneralClashRule.ini?',
'9' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini?',
'10' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoAuto.ini?',
'11' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_AdblockPlus.ini?',
'12' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_MultiCountry.ini?',
'13' => 'ttps://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoReject.ini?',
'14' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_NoAuto.ini?',
'15' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full.ini?',
'16' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Google.ini?',
'17' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_MultiMode.ini?',
'18' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Netflix.ini?',
'19' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini.ini?',
'20' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_AdblockPlus.ini?',
'21' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_Fallback.ini?',
'22' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiCountry.ini?',
'23' => 'https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiMode.ini?',
'24' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG.ini?',
'25' => 'https://raw.githubusercontent.com/xiaoshenxian233/cool/rule/complex.ini?',
'26' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/special/phaors.ini?',
'27' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG_Area_Fallback.ini?',
'28' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG_Area_Urltest.ini?',
'29' => 'https://raw.githubusercontent.com/flyhigherpi/merlinclash_clash_related/master/Rule_config/ZHANG_Area_NoAuto.ini?',
'30' => 'https://raw.githubusercontent.com/OoHHHHHHH/ini/master/config.ini?',
'31' => 'https://raw.githubusercontent.com/OoHHHHHHH/ini/master/cfw-tap.ini?',
'32' => 'https://raw.githubusercontent.com/lhl77/sub-ini/main/tsutsu-full.ini?',
'33' => 'https://raw.githubusercontent.com/lhl77/sub-ini/main/tsutsu-mini-gfw.ini?',
'34' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/connershua_new.ini?',
'35' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/connershua_backtocn.ini?',
'36' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/lhie1_clash.ini?',
'37' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/lhie1_dler.ini?',
'38' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/ehpo1_main.ini?',
'39' => 'https://raw.nameless13.com/api/public/dl/ROzQqi2S/white.ini?',
'40' => 'https://raw.nameless13.com/api/public/dl/ptLeiO3S/mayinggfw.ini?',
'41' => 'https://raw.nameless13.com/api/public/dl/FWSh3dXz/easy3.ini?',
'42' => 'https://raw.nameless13.com/api/public/dl/L_-vxO7I/youtube.ini?',
'43' => 'https://raw.nameless13.com/api/public/dl/zKF9vFbb/easy.ini?',
'44' => 'https://raw.nameless13.com/api/public/dl/E69bzCaE/easy2.ini?',
'45' => 'https://raw.nameless13.com/api/public/dl/XHr0miMg/ipip.ini?',
'46' => 'https://raw.nameless13.com/api/public/dl/BBnfb5lD/MAYINGVIP.ini?',
'47' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Examine.ini?',
'48' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Examine_Full.ini?',
'49' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/nzw9314_custom.ini?',
'50' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/maicoo-l_custom.ini?',
'51' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/dlercloud_lige_platinum.ini?',
'52' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/dlercloud_lige_gold.ini?',
'53' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/dlercloud_lige_silver.ini?',
'54' => 'https://unpkg.com/proxy-script/config/Clash/clash.ini?',
'55' => 'https://github.com/UlinoyaPed/ShellClash/raw/master/rules/ShellClash.ini?',
'56' => 'https://gist.github.com/jklolixxs/16964c46bad1821c70fa97109fd6faa2/raw/EXFLUX.ini?',
'57' => 'https://gist.github.com/jklolixxs/32d4e9a1a5d18a92beccf3be434f7966/raw/NaNoport.ini?',
'58' => 'https://gist.github.com/jklolixxs/dfbe0cf71ffc547557395c772836d9a8/raw/CordCloud.ini?',
'59' => 'https://gist.github.com/jklolixxs/e2b0105c8be6023f3941816509a4c453/raw/BigAirport.ini?',
'60' => 'https://gist.github.com/jklolixxs/9f6989137a2cfcc138c6da4bd4e4cbfc/raw/PaoLuCloud.ini?',
'61' => 'https://gist.github.com/jklolixxs/fccb74b6c0018b3ad7b9ed6d327035b3/raw/WaveCloud.ini?',
'62' => 'https://gist.github.com/jklolixxs/bfd5061dceeef85e84401482f5c92e42/raw/JiJi.ini?',
'63' => 'https://gist.github.com/jklolixxs/6ff6e7658033e9b535e24ade072cf374/raw/SJ.ini?',
'64' => 'https://gist.github.com/jklolixxs/24f4f58bb646ee2c625803eb916fe36d/raw/ImmTelecom.ini?',
'65' => 'https://gist.github.com/jklolixxs/b53d315cd1cede23af83322c26ce34ec/raw/AmyTelecom.ini?',
'66' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/convenience.ini?',
'67' => 'https://gist.github.com/jklolixxs/ff8ddbf2526cafa568d064006a7008e7/raw/Miaona.ini?',
'68' => 'https://gist.github.com/jklolixxs/df8fda1aa225db44e70c8ac0978a3da4/raw/Foo&Friends.ini?',
'69' => 'https://gist.github.com/jklolixxs/b1f91606165b1df82e5481b08fd02e00/raw/ABCloud.ini?',
'70' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/xianyu.ini?',
'71' => 'https://subweb.oss-cn-hongkong.aliyuncs.com/RemoteConfig/customized/convenience.ini?',
'72' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/SSRcloud.ini?',
'73' => 'https://raw.githubusercontent.com/Mazetsz/ACL4SSR/master/Clash/config/V2rayPro.ini?',
'74' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/V2Pro.ini?',
'75' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Stitch.ini?',
'76' => 'https://raw.githubusercontent.com/Mazeorz/airports/master/Clash/Stitch-Balance.ini?',
'77' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/maying.ini?',
'78' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/ytoo.ini?',
'79' => 'https://raw.nameless13.com/api/public/dl/M-We_Fn7/w8ves.ini?',
'80' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/nyancat.ini?',
'81' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/nexitally.ini?',
'82' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/socloud.ini?',
'83' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/customized/ark.ini?',
'84' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/n3ro_optimized.ini?',
'85' => 'https://gist.githubusercontent.com/tindy2013/1fa08640a9088ac8652dbd40c5d2715b/raw/scholar_optimized.ini?',
'86' => 'https://subweb.s3.fr-par.scw.cloud/RemoteConfig/customized/flower.ini?',
'88' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/special/netease.ini?',
'89' => 'https://raw.githubusercontent.com/SleepyHeeead/subconverter-config/master/remote-config/special/basic.ini?'
];
$emoji = isset($_POST['emoji']) ? $_POST['emoji'] === 'true' : true;
$udp = isset($_POST['udp']) ? $_POST['udp'] === 'true' : true;
$xudp = isset($_POST['xudp']) ? $_POST['xudp'] === 'true' : true;
$tfo = isset($_POST['tfo']) ? $_POST['tfo'] === 'true' : true;
$fdn = isset($_POST['fdn']) ? $_POST['fdn'] === 'true' : true;
$sort = isset($_POST['sort']) ? $_POST['sort'] === 'true' : true;
$tls13 = isset($_POST['tls13']) ? $_POST['tls13'] === 'true' : true;
$ipv6 = isset($_POST['ipv6']) ? $_POST['ipv6'] : 'false';
$filename = isset($_POST['filename']) && $_POST['filename'] !== '' ? $_POST['filename'] : 'config.json';
$subscription_url = isset($_POST['subscription_url']) ? $_POST['subscription_url'] : '';
$backend_url = isset($_POST['backend_url']) && $_POST['backend_url'] === 'custom' && !empty($_POST['custom_backend_url'])
? rtrim($_POST['custom_backend_url'], '?') . '?'
: ($_POST['backend_url'] ?? 'https://url.v1.mk/sub?');
$template_key = $_POST['template'] ?? '';
$include = $_POST['include'] ?? '';
$exclude = $_POST['exclude'] ?? '';
$template = $templates[$template_key] ?? '';
$rename = isset($_POST['rename']) ? $_POST['rename'] : '';
if (isset($_POST['action']) && $_POST['action'] === 'generate_subscription') {
$final_url = buildFinalUrl($subscription_url, $template, $include, $exclude, $backend_url, $emoji, $udp, $xudp, $tfo, $ipv6, $rename, $tls13, $fdn, $sort);
if (saveSubscriptionUrlToFile($final_url, $subscription_file)) {
$result = saveSubscriptionContentToYaml($final_url, $filename);
} else {
$result = "Failed to save subscription link to file";
}
}
if (isset($result)) {
echo "<div class='log-message alert alert-success'>" . nl2br(htmlspecialchars($result)) . "</div>";
}
$download_option = $_POST['download_option'] ?? 'none';
if (isset($_POST['download_action']) && $_POST['download_action'] === 'download_files') {
if ($download_option === 'geoip') {
$geoip_url = "https://github.com/SagerNet/sing-geoip/releases/latest/download/geoip.db";
$geoip_path = '/www/nekobox/geoip.db';
echo downloadFileWithWget($geoip_url, $geoip_path);
} elseif ($download_option === 'geosite') {
$geosite_url = "https://github.com/SagerNet/sing-geosite/releases/latest/download/geosite.db";
$geosite_path = '/www/nekobox/geosite.db';
echo downloadFileWithWget($geosite_url, $geosite_path);
}
}
}
function downloadFileWithWget($url, $path) {
$command = "wget -q --no-check-certificate -O " . escapeshellarg($path) . " " . escapeshellarg($url);
exec($command, $output, $return_var);
if ($return_var === 0) {
return "File downloaded successfully: $path<br>";
} else {
return "File download failed: $path<br>";
}
}
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['createCronJob'])) {
$cronExpression = trim($_POST['cronExpression']);
if (empty($cronExpression)) {
echo "<div class='alert alert-warning'>The cron expression cannot be empty</div>";
exit;
}
$cronJob = "$cronExpression /etc/neko/core/update_singbox.sh > /dev/null 2>&1";
exec("crontab -l | grep -v '/etc/neko/core/update_singbox.sh' | crontab -");
exec("(crontab -l; echo '$cronJob') | crontab -");
echo "<div class='log-message alert alert-success'>The cron job has been successfully added or updated.</div>";
}
}
?>
<?php
$shellScriptPath = '/etc/neko/core/update_singbox.sh';
$LOG_FILE = '/etc/neko/tmp/log.txt';
$CONFIG_FILE = '/etc/neko/config/config.json';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['createShellScript'])) {
$shellScriptContent = <<<EOL
#!/bin/sh
LOG_FILE="/etc/neko/tmp/log.txt"
LINK_FILE="/etc/neko/tmp/singbox.txt"
CONFIG_FILE="/etc/neko/config/config.json"
log() {
echo "[ \$(date +'%H:%M:%S') ] \$1" >> "\$LOG_FILE"
}
log "Starting the update script..."
log "Attempting to read subscription link file: \$LINK_FILE"
if [ ! -f "\$LINK_FILE" ]; then
log "Error: File \$LINK_FILE does not exist."
exit 1
fi
SUBSCRIBE_URL=\$(awk 'NR==1 {print \$0}' "\$LINK_FILE" | tr -d '\\n\\r' | xargs)
if [ -z "\$SUBSCRIBE_URL" ]; then
log "Error: Subscription link is empty or extraction failed."
exit 1
fi
log "Using subscription link: \$SUBSCRIBE_URL"
log "Attempting to download and update the configuration file..."
wget -q -O "\$CONFIG_FILE" "\$SUBSCRIBE_URL" >> "\$LOG_FILE" 2>&1
if [ \$? -eq 0 ]; then
log "Configuration file updated successfully. Saved to: \$CONFIG_FILE"
else
log "Configuration file update failed. Please check the link or network."
exit 1
fi
jq '.inbounds = [
{
"domain_strategy": "prefer_ipv4",
"listen": "127.0.0.1",
"listen_port": 2334,
"sniff": true,
"sniff_override_destination": true,
"tag": "mixed-in",
"type": "mixed",
"users": []
},
{
"tag": "tun",
"type": "tun",
"address": [
"172.19.0.1/30",
"fdfe:dcba:9876::1/126"
],
"route_address": [
"0.0.0.0/1",
"128.0.0.0/1",
"::/1",
"8000::/1"
],
"route_exclude_address": [
"192.168.0.0/16",
"fc00::/7"
],
"stack": "system",
"auto_route": true,
"strict_route": true,
"sniff": true,
"platform": {
"http_proxy": {
"enabled": true,
"server": "0.0.0.0",
"server_port": 1082
}
}
},
{
"tag": "mixed",
"type": "mixed",
"listen": "0.0.0.0",
"listen_port": 1082,
"sniff": true
}
]' "\$CONFIG_FILE" > /tmp/config_temp.json && mv /tmp/config_temp.json "\$CONFIG_FILE"
jq '.experimental.clash_api = {
"external_ui": "/etc/neko/ui/",
"external_controller": "0.0.0.0:9090",
"secret": "Akun"
}' "\$CONFIG_FILE" > /tmp/config_temp.json && mv /tmp/config_temp.json "\$CONFIG_FILE"
if [ \$? -eq 0 ]; then
log "Configuration file modifications completed successfully."
else
log "Error: Configuration file modification failed."
exit 1
fi
EOL;
if (file_put_contents($shellScriptPath, $shellScriptContent) !== false) {
chmod($shellScriptPath, 0755);
echo "<div class='log-message alert alert-success' data-translate='shell_script_created' data-dynamic-content='$shellScriptPath'></div>";
} else {
echo "<div class='log-message alert alert-danger' data-translate='shell_script_failed'></div>";
}
}
}
?>
<meta charset="utf-8">
<title>singbox - Nekobox</title>
<script src="./assets/bootstrap/jquery.min.js"></script>
<link rel="icon" href="./assets/img/nekobox.png">
<?php include './ping.php'; ?>
<style>
@media (max-width: 767px) {
.row a {
font-size: 9px;
}
}
.table-responsive {
width: 100%;
}
</style>
<div class="container-sm container-bg px-0 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span style="color: var(--accent-color); letter-spacing: 1px;"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: var(--accent-color); font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php"><i class="bi bi-house-door"></i> <span data-translate="home">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo_manager.php' ? 'active' : '' ?>" href="./mihomo_manager.php"><i class="bi bi-folder"></i> <span data-translate="manager">Manager</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php"><i class="bi bi-shop"></i> <span data-translate="template_i">Template I</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'subscription.php' ? 'active' : '' ?>" href="./subscription.php"><i class="bi bi-bank"></i> <span data-translate="template_ii">Template II</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo.php' ? 'active' : '' ?>" href="./mihomo.php"><i class="bi bi-building"></i> <span data-translate="template_iii">Template III</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'netmon.php' ? 'active' : '' ?>" href="./netmon.php"><i class="bi bi-activity"></i> <span data-translate="traffic_monitor">Traffic Monitor</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'filekit.php' ? 'active' : '' ?>" href="./filekit.php"><i class="bi bi-bank"></i> <span data-translate="pageTitle">File Assistant</span></a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-3 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-translate-title="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-translate-title="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-translate-title="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" id="toggleIpStatusBtn" class="btn btn-warning icon-btn me-2" onclick="toggleIpStatusBar()" data-translate-title="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2" data-bs-toggle="modal" data-bs-target="#portModal" data-translate-title="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn-refresh-page btn btn-orange icon-btn me-2 d-none d-sm-inline"><i class="fas fa-sync-alt"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-translate-title="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<h2 class="text-center p-2 mt-3 mb-2" data-translate="form_title"></h2>
<div class="col-12 px-4">
<div class="form-section">
<form method="post">
<div class="mb-3">
<label for="subscription_url" class="form-label" data-translate="subscription_url_label"></label>
<input type="text" class="form-control" id="subscription_url" name="subscription_url"
value="<?php echo htmlspecialchars($current_subscription_url); ?>" placeholder="" data-translate-placeholder="subscription_url_placeholder" required>
</div>
<div class="mb-3">
<label for="filename" class="form-label" data-translate="filename_label"></label>
<input type="text" class="form-control" id="filename" name="filename"
value="<?php echo htmlspecialchars(isset($_POST['filename']) ? $_POST['filename'] : ''); ?>"
placeholder="config.json">
</div>
<div class="mb-3">
<label for="backend_url" class="form-label" data-translate="backend_url_label"></label>
<select class="form-select" id="backend_url" name="backend_url" required>
<option value="https://url.v1.mk/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://url.v1.mk/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_1"></option>
<option value="https://sub.d1.mk/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.d1.mk/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_2"></option>
<option value="https://sub.xeton.dev/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.xeton.dev/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_3"></option>
<option value="https://www.tline.website/sub/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://www.tline.website/sub/sub?' ? 'selected' : ''; ?>>
tline.website
</option>
<option value="https://api.dler.io/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://api.dler.io/sub?' ? 'selected' : ''; ?>>
api.dler.io
</option>
<option value="https://v.id9.cc/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://v.id9.cc/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_6"></option>
<option value="https://sub.id9.cc/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.id9.cc/sub?' ? 'selected' : ''; ?>>
sub.id9.cc
</option>
<option value="https://api.wcc.best/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://api.wcc.best/sub?' ? 'selected' : ''; ?>>
api.wcc.best
</option>
<option value="https://yun-api.subcloud.xyz/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://yun-api.subcloud.xyz/sub?' ? 'selected' : ''; ?>>
subcloud.xyz
</option>
<option value="https://sub.maoxiongnet.com/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'https://sub.maoxiongnet.com/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_10"></option>
<option value="http://localhost:25500/sub?" <?php echo ($_POST['backend_url'] ?? '') === 'http://localhost:25500/sub?' ? 'selected' : ''; ?> data-translate="backend_url_option_11"></option>
<option value="custom" <?php echo ($_POST['backend_url'] ?? '') === 'custom' ? 'selected' : ''; ?> data-translate="backend_url_option_custom"></option>
</select>
</div>
<div class="mb-3" id="custom_backend_url_input" style="display: none;">
<label for="custom_backend_url" class="form-label" data-translate="custom_backend_url_label"></label>
<input type="text" class="form-control" id="custom_backend_url" name="custom_backend_url" value="<?php echo htmlspecialchars($_POST['custom_backend_url'] ?? '') . (empty($_POST['custom_backend_url']) ? '' : '?'); ?>" />
</div>
<div class="mb-3">
<label for="template" class="form-label" data-translate="subscription"></label>
<select class="form-select" id="template" name="template" required>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/settings.php | luci-app-nekobox/htdocs/nekobox/settings.php |
<?php
include './cfg.php';
function getSingboxVersion() {
$singBoxPath = '/usr/bin/sing-box';
$command = "$singBoxPath version 2>&1";
exec($command, $output, $returnVar);
if ($returnVar === 0) {
foreach ($output as $line) {
if (strpos($line, 'version') !== false) {
$parts = explode(' ', $line);
$version = end($parts);
if (strpos($version, 'alpha') !== false || strpos($version, 'beta') !== false) {
if (strpos($version, '1.10.0-alpha.29-067c81a7') !== false) {
return ['version' => $version, 'type' => 'Puernya Preview'];
}
return ['version' => $version, 'type' => 'Singbox Preview'];
} else {
return ['version' => $version, 'type' => 'Singbox Stable'];
}
}
}
}
return ['version' => 'Not installed', 'type' => 'Unknown'];
}
function getMihomoVersion() {
$mihomoPath = '/usr/bin/mihomo';
$command = "$mihomoPath -v 2>&1";
exec($command, $output, $returnVar);
if ($returnVar === 0) {
foreach ($output as $line) {
if (strpos($line, 'Mihomo') !== false) {
preg_match('/alpha-[a-z0-9]+/', $line, $matches);
if (!empty($matches)) {
$version = $matches[0];
if (preg_match('/^\d/', $version)) {
$version = 'v' . $version;
}
return ['version' => $version, 'type' => 'Preview'];
}
preg_match('/([0-9]+(\.[0-9]+)+)/', $line, $matches);
if (!empty($matches)) {
$version = $matches[0];
return ['version' => $version, 'type' => 'Stable'];
}
}
}
}
return ['version' => 'Not installed', 'type' => 'Unknown'];
}
function getVersion($versionFile) {
if (file_exists($versionFile)) {
return trim(file_get_contents($versionFile));
} else {
return "Not installed";
}
}
function getUiVersion() {
return getVersion('/etc/neko/ui/zashboard/version.txt');
}
function getMetaCubexdVersion() {
return getVersion('/etc/neko/ui/metacubexd/version.txt');
}
function getMetaVersion() {
return getVersion('/etc/neko/ui/meta/version.txt');
}
function getRazordVersion() {
return getVersion('/etc/neko/ui/dashboard/version.txt');
}
function getCliverVersion() {
$output = shell_exec("opkg list-installed luci-app-nekobox 2>/dev/null");
if ($output) {
$lines = explode("\n", trim($output));
foreach ($lines as $line) {
if (preg_match('/luci-app-nekobox\s*-\s*([^\s]+)/', $line, $matches)) {
$version = 'v' . $matches[1];
return ['version' => $version, 'type' => 'Installed'];
}
}
}
return ['version' => 'Not installed', 'type' => 'Unknown'];
}
$cliverData = getCliverVersion();
$cliverVersion = $cliverData['version'];
$cliverType = $cliverData['type'];
$singBoxVersionInfo = getSingboxVersion();
$singBoxVersion = $singBoxVersionInfo['version'];
$singBoxType = $singBoxVersionInfo['type'];
$puernyaVersion = ($singBoxType === 'Puernya Preview') ? $singBoxVersion : 'Not installed';
$singboxPreviewVersion = ($singBoxType === 'Singbox Preview') ? $singBoxVersion : 'Not installed';
$singboxCompileVersion = ($singBoxType === 'Singbox Compiled') ? $singBoxVersion : 'Not installed';
$mihomoVersionInfo = getMihomoVersion();
$mihomoVersion = $mihomoVersionInfo['version'];
$mihomoType = $mihomoVersionInfo['type'];
$uiVersion = getUiVersion();
$metaCubexdVersion = getMetaCubexdVersion();
$metaVersion = getMetaVersion();
$razordVersion = getRazordVersion();
?>
<title>Settings - Nekobox</title>
<?php include './ping.php'; ?>
<div class="container-sm container-bg px-0 px-sm-4 mt-4">
<?php include 'navbar.php'; ?>
<div class="container-sm container px-4 theme-settings-container text-center">
<h2 class="text-center p-2 mb-2" data-translate="component_update">Component Update</h2>
<div class="row g-4">
<div class="col-md-6">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title" data-translate="client_version_title">Client Version</h5>
<p id="cliverVersion" class="card-text" style="font-family: monospace;"><?php echo htmlspecialchars($cliverVersion); ?></p>
<div class="d-flex justify-content-center gap-2 mt-3">
<button class="btn btn-pink" id="checkCliverButton">
<i class="bi bi-search"></i> <span data-translate="detect_button">Detect</span>
</button>
<button class="btn btn-info" id="updateButton" onclick="showUpdateVersionModal()">
<i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title" data-translate="ui_panel_title">Ui Panel</h5>
<p id="uiVersion" class="card-text"><?php echo htmlspecialchars($uiVersion); ?></p>
<div class="d-flex justify-content-center gap-2 mt-3">
<button class="btn btn-pink" id="checkUiButton">
<i class="bi bi-search"></i> <span data-translate="detect_button">Detect</span>
</button>
<button class="btn btn-info" id="updateUiButton" onclick="showPanelSelector()">
<i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title" data-translate="singbox_core_version_title">Sing-box Core Version</h5>
<p id="singBoxCorever" class="card-text"><?php echo htmlspecialchars($singBoxVersion); ?></p>
<div class="d-flex justify-content-center gap-2 mt-3">
<button class="btn btn-pink" id="checkSingboxButton">
<i class="bi bi-search"></i> <span data-translate="detect_button">Detect</span>
</button>
<button class="btn btn-info" id="singboxOptionsButton">
<i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title" data-translate="mihomo_core_version_title">Mihomo Core Version</h5>
<p id="mihomoVersion" class="card-text"><?php echo htmlspecialchars($mihomoVersion); ?></p>
<div class="d-flex justify-content-center gap-2 mt-3">
<button class="btn btn-pink" id="checkMihomoButton">
<i class="bi bi-search"></i> <span data-translate="detect_button">Detect</span>
</button>
<button class="btn btn-info" id="updateCoreButton" onclick="showMihomoVersionSelector()">
<i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container-sm container px-4 theme-settings-container">
<h2 class="text-center mb-4 mt-4" data-translate="aboutTitle"></h2>
<div class="card mb-5">
<div class="card-body text-center feature-box">
<h5 data-translate="nekoBoxTitle"></h5>
<p data-translate="nekoBoxDescription"></p>
</div>
</div>
<div class="row g-4 mb-5">
<div class="col-md-4 d-flex">
<div class="card flex-fill">
<div class="card-body text-center">
<h6 data-translate="simplifiedConfiguration"></h6>
<p data-translate="simplifiedConfigurationDescription"></p>
</div>
</div>
</div>
<div class="col-md-4 d-flex">
<div class="card flex-fill">
<div class="card-body text-center">
<h6 data-translate="optimizedPerformance"></h6>
<p data-translate="optimizedPerformanceDescription"></p>
</div>
</div>
</div>
<div class="col-md-4 d-flex">
<div class="card flex-fill">
<div class="card-body text-center">
<h6 data-translate="seamlessExperience"></h6>
<p data-translate="seamlessExperienceDescription"></p>
</div>
</div>
</div>
</div>
<div class="row g-4 mb-5">
<div class="col-md-6 d-flex flex-column">
<div class="card flex-fill">
<div class="card-body">
<h5 class="mb-4 text-center">
<i data-feather="tool"></i> <span data-translate="toolInfo"></span>
</h5>
<div class="card">
<div class="card-body p-3">
<div class="table-responsive">
<table class="table table-borderless text-center mb-0">
<tbody>
<tr>
<td>SagerNet</td>
<td>MetaCubeX</td>
</tr>
<tr>
<td>
<a href="https://github.com/SagerNet/sing-box" target="_blank" class="d-inline-flex align-items-center gap-2 link-primary">
<i data-feather="codesandbox"></i> Sing-box
</a>
</td>
<td>
<a href="https://github.com/MetaCubeX/mihomo" target="_blank" class="d-inline-flex align-items-center gap-2 link-primary">
<i data-feather="box"></i> Mihomo
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6 d-flex flex-column">
<div class="card flex-fill">
<div class="card-body">
<h5 class="mb-4 text-center">
<i data-feather="paperclip"></i> <span data-translate="externalLinks"></span>
</h5>
<div class="card">
<div class="card-body p-3">
<div class="table-responsive">
<table class="table table-borderless text-center mb-0">
<tbody>
<tr>
<td>Github</td>
<td>Thaolga</td>
</tr>
<tr>
<td>
<a href="https://github.com/Thaolga/openwrt-nekobox/issues" target="_blank" class="d-inline-flex align-items-center gap-2 link-primary">
<i data-feather="github"></i> Issues
</a>
</td>
<td>
<a href="https://github.com/Thaolga/openwrt-nekobox" target="_blank" class="d-inline-flex align-items-center gap-2 link-primary">
<i data-feather="github"></i> NEKOBOX
</a>
</td>
</tr>
<tr>
<td>Telegram</td>
<td>Zephyruso</td>
</tr>
<tr>
<td>
<a href="https://t.me/+J55MUupktxFmMDgx" target="_blank" class="d-inline-flex align-items-center gap-2 link-primary">
<i data-feather="send"></i> Telegram
</a>
</td>
<td>
<a href="https://github.com/Zephyruso/zashboard" target="_blank" class="d-inline-flex align-items-center gap-2 link-primary">
<i data-feather="package"></i> ZASHBOARD
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="updateVersionModal" tabindex="-1" aria-labelledby="updateVersionModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updateVersionModalLabel" data-translate="stable">Select the updated version of the language</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<select id="languageSelect" class="form-select">
<option value="cn" data-translate="stable">Stable</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" onclick="clearNekoTmpDir()" data-tooltip="delete_old_config"><i class="bi bi-trash"></i> <span data-translate="clear_config">Clear Config</span></button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="close_button">cancel</button>
<button type="button" class="btn btn-primary" onclick="confirmUpdateVersion()" data-translate="confirmButton">confirm</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="mihomoVersionSelectionModal" tabindex="-1" aria-labelledby="mihomoVersionSelectionModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="mihomoVersionSelectionModalLabel" data-translate="mihomo_version_modal_title">Select Mihomo Kernel Version</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<select id="mihomoVersionSelect" class="form-select">
<option value="preview" data-translate="mihomo_version_preview">Preview</option>
<option value="stable" data-translate="mihomo_version_stable">Stable</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="close_button">cancel</button>
<button type="button" class="btn btn-primary" onclick="confirmMihomoVersion()" data-translate="confirmButton">confirm</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="optionsModal" tabindex="-1" aria-labelledby="optionsModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-xl modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="optionsModalLabel" data-translate="options_modal_title">Select Operation</h5>
<button type="button" class="btn-close ms-auto" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row g-3">
<div class="col-md-4">
<div class="card h-100 text-center">
<div class="card-body d-flex flex-column">
<h5 class="card-title" data-translate="singbox_channel_one">Singbox Core (Channel One)</h5>
<p class="card-text flex-grow-1" data-translate="channel_one_desc">Backup channel</p>
<button class="btn btn-info mt-auto" onclick="showSingboxVersionSelector()"><i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span></button>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card h-100 text-center">
<div class="card-body d-flex flex-column">
<h5 class="card-title" data-translate="singbox_channel_two">Singbox Core (Channel Two)</h5>
<p class="card-text flex-grow-1" data-translate="channel_two_desc">Official preferred channel</p>
<button class="btn btn-info mt-auto" onclick="showSingboxVersionSelectorForChannelTwo()"><i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span></button>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card h-100 text-center">
<div class="card-body d-flex flex-column">
<h5 class="card-title" data-translate="other_operations">Other Operations</h5>
<p class="card-text flex-grow-1" data-translate="other_operations_desc">Additional management options</p>
<button class="btn btn-info mt-auto" id="operationOptionsButton"><i class="bi bi-arrow-repeat"></i> <span data-translate="update_button">Update</span></button>
</div>
</div>
</div>
</div>
<div class="d-flex justify-content-end mt-3">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="close_button">
Close
</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="operationModal" tabindex="-1" aria-labelledby="operationModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="operationModalLabel" data-translate="operation_modal_title">Select operation</h5>
<button type="button" class="btn-close ms-auto" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="alert alert-warning text-start" role="alert">
<strong data-translate="note_label"></strong>
<span data-translate="operation_modal_note" class="text-black">
Please select an operation based on your requirements
</span>
</div>
<div class="d-flex flex-wrap justify-content-end gap-2 mt-3">
<button class="btn btn-success btn-lg flex-fill" style="max-width: 240px;" onclick="selectOperation('puernya')" data-translate="switch_to_puernya">
Switch to Puernya kernel
</button>
<button class="btn btn-primary btn-lg flex-fill" style="max-width: 240px;" onclick="selectOperation('rule')" data-translate="update_pcore_rule">
Update P-core rule set
</button>
<button class="btn btn-primary btn-lg flex-fill" style="max-width: 240px;" onclick="selectOperation('config')" data-translate="update_config_backup">
Update config file (backup)
</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="close_button">
Close
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="versionSelectionModal" tabindex="-1" aria-labelledby="versionSelectionModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="versionSelectionModalLabel" data-translate="versionSelectionModalTitle">Select Singbox core version</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-info" data-translate="helpMessage">
<strong>Help:</strong> Please select an existing version or manually enter a version number, and click "Add Version" to add it to the dropdown list.
</div>
<select id="singboxVersionSelect" class="form-select">
<option value="v1.11.0-alpha.10">v1.11.0-alpha.10</option>
<option value="v1.11.0-alpha.15">v1.11.0-alpha.15</option>
<option value="v1.11.0-alpha.20">v1.11.0-alpha.20</option>
<option value="v1.11.0-beta.5">v1.11.0-beta.5</option>
<option value="v1.11.0-beta.10">v1.11.0-beta.10</option>
<option value="v1.11.0-beta.15">v1.11.0-beta.15</option>
<option value="v1.11.0-beta.20">v1.11.0-beta.20</option>
<option value="v1.12.0-rc.3">v1.12.0-rc.3</option>
<option value="v1.12.0-rc.4">v1.12.0-rc.4</option>
<option value="v1.13.0-alpha.1">v1.13.0-alpha.1</option>
</select>
<input type="text" id="manualVersionInput" class="form-control mt-2" placeholder="For example: v1.12.0-rc.3">
<button type="button" class="btn btn-secondary mt-2" onclick="addManualVersion()" data-translate="addVersionButton">Add Version</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="cancelButton">cancel</button>
<button type="button" class="btn btn-primary" onclick="confirmSingboxVersion()" data-translate="confirmButton">confirm</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="singboxVersionModal" tabindex="-1" aria-labelledby="singboxVersionModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="singboxVersionModalLabel" data-translate="singboxVersionModalTitle">Select Singbox core version (Channel 2)</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<select id="singboxVersionSelectForChannelTwo" class="form-select">
<option value="preview" data-translate="preview">Preview</option>
<option value="stable" data-translate="stable">Stable</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="cancelButton">cancel</button>
<button type="button" class="btn btn-primary" onclick="confirmSingboxVersionForChannelTwo()" data-translate="confirmButton">confirm</button>
</div>
</div>
</div>
</div>
<div id="panelSelectionModal" class="modal fade" tabindex="-1" aria-labelledby="panelSelectionModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="panelSelectionModalLabel" data-translate="panelSelectionModalTitle">Selection Panel</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="panelSelect" data-translate="selectPanelLabel">Select a Panel</label>
<select id="panelSelect" class="form-select">
<option value="zashboard" data-translate="panel_zashboard_option">Zashboard Panel [Low Memory]</option>
<option value="Zashboard" data-translate="panel_Zashboard_option">Zashboard Panel [High Memory]</option>
<option value="metacubexd" data-translate="metacubexdPanel">Metacubexd Panel</option>
<option value="yacd-meat" data-translate="yacdMeatPanel">Yacd-Meat Panel</option>
<option value="dashboard" data-translate="dashboardPanel">Dashboard Panel</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="cancelButton">cancel</button>
<button type="button" class="btn btn-primary" onclick="confirmPanelSelection()" data-translate="confirmButton">confirm</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="versionModal" tabindex="-1" aria-labelledby="versionModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="versionModalLabel" data-translate="versionModalLabel">Version check results</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="modalContent">
<p data-translate="loadingMessage">Loading...</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="closeButton">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updateModalLabel" data-translate="updateModalLabel">Update status</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-center">
<div id="updateDescription" class="alert alert-info mb-3" data-translate="updateDescription"></div>
<pre id="logOutput" style="white-space: pre-wrap; word-wrap: break-word; text-align: left; display: inline-block;" data-translate="waitingMessage">Waiting for the operation to begin...</pre>
</div>
</div>
</div>
</div>
<style>
.version-indicator {
position: absolute;
top: 15px;
right: 20px;
width: 12px;
height: 12px;
border-radius: 50%;
cursor: pointer;
display: inline-block;
}
.version-indicator.success {
background-color: #28a745;
animation: pulse-success 2s infinite;
box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7);
}
.version-indicator.warning {
background-color: #ffc107;
animation: pulse-warning 2s infinite;
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7);
}
.version-indicator.error {
background-color: #dc3545;
animation: pulse-error 2s infinite;
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7);
}
.version-indicator::after {
content: attr(data-text);
position: absolute;
bottom: -28px;
right: 100%;
margin-right: 6px;
background: rgba(0,0,0,0.75);
color: #fff;
padding: 2px 6px;
border-radius: 4px;
white-space: nowrap;
font-size: 0.75rem;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s ease;
z-index: 99999;
}
.version-indicator:hover::after {
opacity: 1;
}
@keyframes pulse-success {
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7); }
70% { transform: scale(1); box-shadow: 0 0 0 8px rgba(40, 167, 69, 0); }
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
}
@keyframes pulse-warning {
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); }
70% { transform: scale(1); box-shadow: 0 0 0 8px rgba(255, 193, 7, 0); }
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
}
@keyframes pulse-error {
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
70% { transform: scale(1); box-shadow: 0 0 0 8px rgba(220, 53, 69, 0); }
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
}
.card-body {
position: relative;
}
@media (max-width: 768px) {
.navbar-toggler {
margin-left: auto;
margin-right: 15px;
}
.navbar-brand {
margin-left: 15px !important;
}
.navbar .d-flex.align-items-center {
margin-left: 15px !important;
}
}
</style>
<script>
let selectedSingboxVersion = 'v1.11.0-alpha.10';
let selectedMihomoVersion = 'stable';
let selectedLanguage = 'cn';
let selectedSingboxVersionForChannelTwo = 'preview';
let selectedPanel = 'zashboard';
let selectedVersionType = 'stable';
function showPanelSelector() {
$('#panelSelectionModal').modal('show');
}
function confirmPanelSelection() {
selectedPanel = document.getElementById('panelSelect').value;
$('#panelSelectionModal').modal('hide');
selectOperation('panel');
}
function showVersionTypeModal() {
$('#updateVersionTypeModal').modal('show');
}
function showUpdateVersionModal() {
$('#updateVersionModal').modal('show');
}
function confirmUpdateVersion() {
selectedLanguage = document.getElementById('languageSelect').value;
$('#updateVersionModal').modal('hide');
selectOperation('client');
}
function showSingboxVersionSelector() {
$('#optionsModal').modal('hide');
$('#versionSelectionModal').modal('show');
}
function showSingboxVersionSelectorForChannelTwo() {
$('#optionsModal').modal('hide');
$('#singboxVersionModal').modal('show');
}
function confirmSingboxVersionForChannelTwo() {
selectedSingboxVersionForChannelTwo = document.getElementById('singboxVersionSelectForChannelTwo').value;
$('#singboxVersionModal').modal('hide');
selectOperation('sing-box');
}
function showMihomoVersionSelector() {
$('#mihomoVersionSelectionModal').modal('show');
}
function confirmMihomoVersion() {
selectedMihomoVersion = document.getElementById('mihomoVersionSelect').value;
$('#mihomoVersionSelectionModal').modal('hide');
selectOperation('mihomo');
}
function addManualVersion() {
var manualVersion = document.getElementById('manualVersionInput').value;
if (manualVersion.trim() === "") {
alert("Please enter a version number");
return;
}
var select = document.getElementById('singboxVersionSelect');
var versionExists = Array.from(select.options).some(function(option) {
return option.value === manualVersion;
});
if (versionExists) {
alert("This version already exists");
return;
}
var newOption = document.createElement("option");
newOption.value = manualVersion;
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/download.php | luci-app-nekobox/htdocs/nekobox/download.php | <?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$dfOutput = [];
exec('df /', $dfOutput);
$availableSpace = 0;
if (isset($dfOutput[1])) {
$dfData = preg_split('/\s+/', $dfOutput[1]);
$availableSpace = $dfData[3] * 1024;
}
$availableSpaceInMB = $availableSpace / 1024 / 1024;
$threshold = 50 * 1024 * 1024;
echo "<script>alert('OpenWRT 剩余空间: " . round($availableSpaceInMB, 2) . " MB');</script>";
if ($availableSpace < $threshold) {
echo "<script>alert('空间不足,上传操作已停止!');</script>";
exit;
}
if (isset($_FILES['imageFile']) && is_array($_FILES['imageFile']['error'])) {
$targetDir = $_SERVER['DOCUMENT_ROOT'] . '/nekobox/assets/Pictures/';
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
}
$maxFileSize = 1024 * 1024 * 1024;
$uploadedFiles = [];
$fileErrors = [];
function cleanFilename($filename) {
$filename = preg_replace('/[^a-zA-Z0-9\-_\.]/', '', $filename);
return $filename;
}
foreach ($_FILES['imageFile']['name'] as $key => $fileName) {
$fileTmpName = $_FILES['imageFile']['tmp_name'][$key];
$fileSize = $_FILES['imageFile']['size'][$key];
$fileError = $_FILES['imageFile']['error'][$key];
$fileType = $_FILES['imageFile']['type'][$key];
$cleanFileName = cleanFilename($fileName);
if ($fileError === UPLOAD_ERR_OK) {
if ($fileSize > $maxFileSize) {
$fileErrors[] = "File '$fileName' exceeds the size limit!";
continue;
}
$uniqueFileName = uniqid() . '-' . basename($cleanFileName);
$targetFile = $targetDir . $uniqueFileName;
$uploadedFilePath = '/nekobox/assets/Pictures/' . $uniqueFileName;
if (move_uploaded_file($fileTmpName, $targetFile)) {
$uploadedFiles[] = $uploadedFilePath;
} else {
$fileErrors[] = "Failed to upload file '$fileName'!";
}
} else {
$fileErrors[] = "Error uploading file '$fileName', error code: $fileError";
}
}
if (count($uploadedFiles) > 0) {
echo "<script>
alert('File(s) uploaded successfully!');
window.location.href = 'settings.php';
</script>";
} else {
if (count($fileErrors) > 0) {
foreach ($fileErrors as $error) {
echo "<script>alert('$error');</script>";
}
} else {
echo "<script>alert('No files uploaded or an error occurred during upload!');</script>";
}
}
} else {
echo "<script>alert('No files uploaded or an error occurred during upload!');</script>";
}
} else {
echo "<script>alert('No data received.');</script>";
}
?>
<?php
$proxyDir = '/www/nekobox/proxy/';
$uploadDir = '/etc/neko/proxy_provider/';
$configDir = '/etc/neko/config/';
if (isset($_GET['file'])) {
$file = basename($_GET['file']);
$filePath = $proxyDir . $file;
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
}
$filePath = $uploadDir . $file;
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
}
$configPath = $configDir . $file;
if (file_exists($configPath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($configPath));
readfile($configPath);
exit;
}
echo 'File does not exist!';
}
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/update_meta.php | luci-app-nekobox/htdocs/nekobox/update_meta.php | <?php
ini_set('memory_limit', '128M');
$fixed_version = "v0.3.8";
function getUiVersion() {
$versionFile = '/etc/neko/ui/meta/version.txt';
if (file_exists($versionFile)) {
return trim(file_get_contents($versionFile));
} else {
return null;
}
}
function writeVersionToFile($version) {
$versionFile = '/etc/neko/ui/meta/version.txt';
file_put_contents($versionFile, $version);
}
$download_url = "https://github.com/Thaolga/neko/releases/download/$fixed_version/meta.tar";
$install_path = '/etc/neko/ui/meta';
$temp_file = '/tmp/meta-dist.tar';
if (!is_dir($install_path)) {
mkdir($install_path, 0755, true);
}
$current_version = getUiVersion();
if (isset($_GET['check_version'])) {
echo "Latest version: $fixed_version\n";
exit;
}
exec("wget -O '$temp_file' '$download_url'", $output, $return_var);
if ($return_var !== 0) {
die("Download failed");
}
if (!file_exists($temp_file)) {
die("The downloaded file does not exist");
}
echo "Start extracting the file...\n";
exec("tar -xf '$temp_file' -C '$install_path'", $output, $return_var);
if ($return_var !== 0) {
echo "Decompression failed, error message: " . implode("\n", $output);
die("Decompression failed");
}
echo "Extraction successful \n";
exec("chown -R root:root '$install_path' 2>&1", $output, $return_var);
if ($return_var !== 0) {
echo "Failed to change file owner, error message: " . implode("\n", $output) . "\n";
die();
}
echo "The file owner has been changed to root.\n";
writeVersionToFile($fixed_version);
echo "Update complete! Current version: $fixed_version";
unlink($temp_file);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/netmon.php | luci-app-nekobox/htdocs/nekobox/netmon.php | <?php
if (!function_exists('formatBytes')) {
function formatBytes($bytes, $precision = 2) {
if ($bytes <= 0) return "0 B";
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$pow = floor(log($bytes, 1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
}
function getOpenWrtTraffic() {
$result = [
'upload_speed' => '0 B/S',
'download_speed' => '0 B/S',
'upload_total' => '0 B',
'download_total' => '0 B',
'status' => 'success',
'method' => 'unknown',
'debug' => [],
'interfaces' => []
];
if (file_exists('/proc/net/dev')) {
$result['debug'][] = 'Found /proc/net/dev';
try {
$traffic = parseNetDev();
if ($traffic['rx'] > 0 || $traffic['tx'] > 0) {
$result['method'] = 'proc_net_dev';
$result['selected_interface'] = $traffic['selected_interface'] ?? 'unknown';
return calculateTrafficSpeed($result, $traffic['rx'], $traffic['tx']);
}
} catch (Exception $e) {
$result['debug'][] = '/proc/net/dev error: ' . $e->getMessage();
}
}
if (is_dir('/sys/class/net/')) {
$result['debug'][] = 'Found /sys/class/net/';
try {
$traffic = parseSysClassNet();
if ($traffic['rx'] > 0 || $traffic['tx'] > 0) {
$result['method'] = 'sys_class_net';
return calculateTrafficSpeed($result, $traffic['rx'], $traffic['tx']);
}
} catch (Exception $e) {
$result['debug'][] = '/sys/class/net/ error: ' . $e->getMessage();
}
}
try {
$traffic = parseWithCat();
if ($traffic['rx'] > 0 || $traffic['tx'] > 0) {
$result['method'] = 'cat_command';
return calculateTrafficSpeed($result, $traffic['rx'], $traffic['tx']);
}
} catch (Exception $e) {
$result['debug'][] = 'cat command error: ' . $e->getMessage();
}
try {
$traffic = parseIpCommand();
if ($traffic['rx'] > 0 || $traffic['tx'] > 0) {
$result['method'] = 'ip_command';
return calculateTrafficSpeed($result, $traffic['rx'], $traffic['tx']);
}
} catch (Exception $e) {
$result['debug'][] = 'ip command error: ' . $e->getMessage();
}
$result['status'] = 'error';
$result['error'] = 'No working method found for traffic monitoring';
return $result;
}
function parseNetDev() {
$netDev = '/proc/net/dev';
$rx = 0;
$tx = 0;
$interfaces = [];
if (!file_exists($netDev) || !is_readable($netDev)) {
throw new Exception("Cannot read $netDev");
}
$content = file_get_contents($netDev);
if ($content === false) {
throw new Exception("Failed to read $netDev content");
}
$lines = explode("\n", $content);
$interfacePriority = [
'eth0' => 100,
'wlan0' => 90,
'wlan1' => 89,
'pppoe' => 80,
'br-lan' => 70,
'tun0' => 60,
'tun1' => 59,
];
$foundInterfaces = [];
foreach ($lines as $line) {
if (strpos($line, ':') !== false) {
list($iface, $data) = explode(':', $line, 2);
$iface = trim($iface);
if (in_array($iface, ['lo', 'sit0', 'ip6tnl0', 'dummy0', 'docker0']) ||
strpos($iface, 'veth') === 0 || strpos($iface, 'dheth') === 0) {
continue;
}
$stats = preg_split('/\s+/', trim($data));
if (count($stats) >= 9) {
$iface_rx = intval($stats[0]);
$iface_tx = intval($stats[8]);
$foundInterfaces[$iface] = [
'rx' => $iface_rx,
'tx' => $iface_tx,
'priority' => $interfacePriority[$iface] ?? 1
];
}
}
}
$hasWanInterface = false;
$wanInterfaces = ['eth0', 'pppoe-wan', 'wan'];
foreach ($wanInterfaces as $wan) {
if (isset($foundInterfaces[$wan]) &&
($foundInterfaces[$wan]['rx'] > 0 || $foundInterfaces[$wan]['tx'] > 0)) {
$hasWanInterface = true;
break;
}
}
$selectedInterface = null;
$hasWanInterface = false;
$wanInterfaces = ['eth0', 'pppoe-wan', 'wan'];
foreach ($wanInterfaces as $wan) {
if (isset($foundInterfaces[$wan]) &&
($foundInterfaces[$wan]['rx'] > 0 || $foundInterfaces[$wan]['tx'] > 0)) {
$hasWanInterface = true;
$selectedInterface = $wan;
$rx = $foundInterfaces[$wan]['rx'];
$tx = $foundInterfaces[$wan]['tx'];
$interfaces[$wan] = $foundInterfaces[$wan];
break;
}
}
if (!$hasWanInterface && !empty($foundInterfaces)) {
uasort($foundInterfaces, function($a, $b) {
return $b['priority'] - $a['priority'];
});
$selectedInterface = key($foundInterfaces);
$topInterface = reset($foundInterfaces);
if ($topInterface) {
$rx = $topInterface['rx'];
$tx = $topInterface['tx'];
$interfaces[$selectedInterface] = $topInterface;
}
}
return [
'rx' => $rx,
'tx' => $tx,
'interfaces' => $interfaces,
'selected_interface' => $selectedInterface
];
}
function parseSysClassNet() {
$rx = 0;
$tx = 0;
$interfaces = [];
$netDir = '/sys/class/net/';
if (!is_dir($netDir)) {
throw new Exception("$netDir not found");
}
$dirs = scandir($netDir);
foreach ($dirs as $iface) {
if ($iface === '.' || $iface === '..') continue;
if (in_array($iface, ['lo', 'sit0', 'ip6tnl0'])) continue;
$rxFile = $netDir . $iface . '/statistics/rx_bytes';
$txFile = $netDir . $iface . '/statistics/tx_bytes';
if (file_exists($rxFile) && file_exists($txFile)) {
$iface_rx = intval(trim(file_get_contents($rxFile)));
$iface_tx = intval(trim(file_get_contents($txFile)));
$rx += $iface_rx;
$tx += $iface_tx;
$interfaces[$iface] = ['rx' => $iface_rx, 'tx' => $iface_tx];
}
}
return ['rx' => $rx, 'tx' => $tx, 'interfaces' => $interfaces];
}
function parseWithCat() {
$rx = 0;
$tx = 0;
$output = shell_exec('cat /proc/net/dev 2>/dev/null');
if (!$output) {
throw new Exception("cat command failed");
}
$lines = explode("\n", $output);
foreach ($lines as $line) {
if (strpos($line, ':') !== false) {
list($iface, $data) = explode(':', $line, 2);
$iface = trim($iface);
if (in_array($iface, ['lo', 'sit0', 'ip6tnl0'])) continue;
$stats = preg_split('/\s+/', trim($data));
if (count($stats) >= 9) {
$rx += intval($stats[0]);
$tx += intval($stats[8]);
}
}
}
return ['rx' => $rx, 'tx' => $tx];
}
function parseIpCommand() {
$rx = 0;
$tx = 0;
$output = shell_exec('ip -s link 2>/dev/null');
if (!$output) {
throw new Exception("ip command not available");
}
$lines = explode("\n", $output);
$currentInterface = null;
for ($i = 0; $i < count($lines); $i++) {
$line = trim($lines[$i]);
if (preg_match('/^\d+:\s+(\w+):/', $line, $matches)) {
$currentInterface = $matches[1];
}
if ($currentInterface && !in_array($currentInterface, ['lo', 'sit0', 'ip6tnl0'])) {
if (preg_match('/RX:\s+bytes\s+packets\s+errors/', $line)) {
if (isset($lines[$i + 1])) {
$stats = preg_split('/\s+/', trim($lines[$i + 1]));
if (count($stats) >= 1) {
$rx += intval($stats[0]);
}
}
}
if (preg_match('/TX:\s+bytes\s+packets\s+errors/', $line)) {
if (isset($lines[$i + 1])) {
$stats = preg_split('/\s+/', trim($lines[$i + 1]));
if (count($stats) >= 1) {
$tx += intval($stats[0]);
}
}
}
}
}
return ['rx' => $rx, 'tx' => $tx];
}
function calculateTrafficSpeed($result, $rx, $tx) {
$result['upload_total'] = formatBytes($tx);
$result['download_total'] = formatBytes($rx);
$trafficFile = '/tmp/openwrt_traffic_stats.json';
$now = microtime(true);
if (file_exists($trafficFile) && is_readable($trafficFile)) {
$content = file_get_contents($trafficFile);
$savedData = json_decode($content, true);
if ($savedData && isset($savedData['samples']) && is_array($savedData['samples'])) {
$savedData['samples'][] = [
'rx' => $rx,
'tx' => $tx,
'time' => $now
];
if (count($savedData['samples']) > 8) {
$savedData['samples'] = array_slice($savedData['samples'], -8);
}
if (count($savedData['samples']) >= 2) {
$samples = $savedData['samples'];
$lastSample = end($samples);
$prevSample = $samples[count($samples) - 2];
$delta_t = $lastSample['time'] - $prevSample['time'];
if ($delta_t > 0) {
$rx_diff = $lastSample['rx'] - $prevSample['rx'];
$tx_diff = $lastSample['tx'] - $prevSample['tx'];
$download_speed = max(0, $rx_diff / $delta_t);
$upload_speed = max(0, $tx_diff / $delta_t);
$result['upload_speed'] = formatBytes($upload_speed) . '/S';
$result['download_speed'] = formatBytes($download_speed) . '/S';
$result['upload_speed_bytes'] = $upload_speed;
$result['download_speed_bytes'] = $download_speed;
if (isset($_GET['_ajax']) && isset($_GET['debug_speed'])) {
$result['debug_speed'] = [
'delta_t' => round($delta_t, 3),
'rx_diff' => $rx_diff,
'tx_diff' => $tx_diff,
'rx_current' => $lastSample['rx'],
'tx_current' => $lastSample['tx'],
'rx_previous' => $prevSample['rx'],
'tx_previous' => $prevSample['tx'],
'download_speed_bytes' => $download_speed,
'upload_speed_bytes' => $upload_speed
];
}
}
}
} else {
$savedData = ['samples' => [[
'rx' => $rx,
'tx' => $tx,
'time' => $now
]]];
}
} else {
$savedData = ['samples' => [[
'rx' => $rx,
'tx' => $tx,
'time' => $now
]]];
}
if (is_writable('/tmp/') || is_writable(dirname($trafficFile))) {
file_put_contents($trafficFile, json_encode($savedData));
}
return $result;
}
if (isset($_GET['_ajax'])) {
error_reporting(0);
ini_set('display_errors', 0);
if (ob_get_level()) {
ob_clean();
}
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
try {
$traffic = getOpenWrtTraffic();
echo json_encode($traffic, JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
echo json_encode([
'status' => 'error',
'error' => 'Exception: ' . $e->getMessage(),
'upload_speed' => '0 B/S',
'download_speed' => '0 B/S',
'upload_total' => '0 B',
'download_total' => '0 B',
'method' => 'error'
], JSON_UNESCAPED_UNICODE);
}
exit;
}
if (isset($_GET['debug'])) {
header('Content-Type: application/json');
$traffic = getOpenWrtTraffic();
if (file_exists('/proc/net/dev')) {
$lines = file('/proc/net/dev', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$traffic['raw_interfaces'] = [];
foreach ($lines as $line) {
if (strpos($line, ':') !== false) {
list($iface, $data) = explode(':', $line, 2);
$iface = trim($iface);
$stats = preg_split('/\s+/', trim($data));
if (count($stats) >= 9) {
$traffic['raw_interfaces'][$iface] = [
'rx_bytes' => intval($stats[0]),
'tx_bytes' => intval($stats[8]),
'rx_formatted' => formatBytes(intval($stats[0])),
'tx_formatted' => formatBytes(intval($stats[8])),
'note' => 'rx=download, tx=upload'
];
}
}
}
}
echo json_encode($traffic, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
}
$traffic = getOpenWrtTraffic();
?>
<meta charset="UTF-8">
<title>OpenWrt Real-time Traffic Monitor</title>
<?php include './ping.php'; ?>
<script src="./assets/js/chart.umd.js"></script>
<style>
:root {
--primary-color: #007bff;
--success-color: #28a745;
--danger-color: #dc3545;
--warning-color: #ffc107;
--info-color: #17a2b8;
--light-color: #f8f9fa;
--dark-color: #343a40;
--secondary-color: #000;
--gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--gradient-success: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
--gradient-danger: linear-gradient(135deg, #ee0979 0%, #ff6a00 100%);
--gradient-info: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--shadow-light: 0 2px 10px rgba(0,0,0,0.08);
--shadow-medium: 0 4px 20px rgba(0,0,0,0.12);
--shadow-heavy: 0 8px 40px rgba(0,0,0,0.16);
--border-radius: 12px;
--transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.header-section {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: var(--border-radius);
padding: 30px;
margin-bottom: 30px;
box-shadow: var(--shadow-medium);
text-align: center;
position: relative;
overflow: hidden;
}
.header-section::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: var(--gradient-primary);
}
.header-section h2 {
font-size: 2.5em;
font-weight: 700;
margin-bottom: 15px;
background: var(--gradient-primary);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}
.header-section h2 .icon {
font-size: 0.8em;
}
.system-info {
font-size: 1.1em;
color: var(--secondary-color);
display: flex;
align-items: center;
justify-content: center;
gap: 20px;
flex-wrap: wrap;
}
.info-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: rgba(108, 117, 125, 0.1);
border-radius: 20px;
font-weight: 500;
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
animation: pulse 2s infinite;
position: relative;
}
.status-indicator::after {
content: '';
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
border-radius: 50%;
border: 2px solid currentColor;
opacity: 0;
animation: ripple 2s infinite;
}
.status-online {
background-color: var(--success-color);
color: var(--success-color);
}
.status-offline {
background-color: var(--danger-color);
color: var(--danger-color);
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
@keyframes ripple {
0% { transform: scale(1); opacity: 0.6; }
100% { transform: scale(1.5); opacity: 0; }
}
.stats-section {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: var(--border-radius);
padding: 25px;
box-shadow: var(--shadow-light);
transition: var(--transition);
position: relative;
overflow: hidden;
}
.stat-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
transition: var(--transition);
}
.stat-card.upload::before {
background: var(--gradient-danger);
}
.stat-card.download::before {
background: var(--gradient-success);
}
.stat-card.total::before {
background: var(--gradient-info);
}
.stat-card:hover {
transform: translateY(-5px);
box-shadow: var(--shadow-medium);
}
.stat-label {
font-size: 0.9em;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 12px;
color: var(--secondary-color);
display: flex;
align-items: center;
gap: 8px;
}
.stat-value {
font-size: 2.2em;
font-weight: 700;
margin-bottom: 8px;
display: block;
transition: var(--transition);
}
.stat-card.upload .stat-value {
color: #dc3545;
}
.stat-card.download .stat-value {
color: #28a745;
}
.stat-card.total .stat-value {
color: #17a2b8;
}
.stat-description {
font-size: 0.95em;
color: var(--secondary-color);
font-weight: 500;
}
.chart-section {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: var(--border-radius);
padding: 30px;
margin-bottom: 30px;
box-shadow: var(--shadow-medium);
position: relative;
}
.chart-section::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: var(--gradient-primary);
}
.chart-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 25px;
flex-wrap: wrap;
gap: 15px;
}
.chart-title {
font-size: 1.5em;
font-weight: 700;
color: var(--dark-color);
display: flex;
align-items: center;
gap: 10px;
}
.chart-controls {
display: flex;
gap: 10px;
align-items: center;
}
.chart-toggle {
padding: 8px 16px;
border: none;
border-radius: 20px;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
font-size: 0.85em;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.chart-toggle.active {
background: var(--gradient-primary);
color: white;
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}
.chart-toggle:not(.active) {
background: rgba(108, 117, 125, 0.1);
color: var(--secondary-color);
}
.chart-toggle:hover:not(.active) {
background: rgba(108, 117, 125, 0.2);
}
.chart-container {
position: relative;
height: 400px;
width: 100%;
}
.legend-container {
display: flex;
justify-content: center;
gap: 30px;
margin-top: 20px;
flex-wrap: wrap;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: var(--dark-color);
}
.legend-color {
width: 16px;
height: 16px;
border-radius: 3px;
}
.legend-color.upload {
background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}
.legend-color.download {
background: linear-gradient(135deg, #51cf66, #40c057);
}
.footer-section {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: var(--border-radius);
padding: 20px;
box-shadow: var(--shadow-light);
text-align: center;
}
.last-update {
color: var(--secondary-color);
font-weight: 500;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.error-message {
background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
color: #721c24;
padding: 20px;
border-radius: var(--border-radius);
margin-bottom: 20px;
text-align: center;
font-weight: 600;
box-shadow: var(--shadow-light);
border: 1px solid rgba(220, 53, 69, 0.2);
}
.debug-info {
background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
color: #0c5460;
padding: 15px;
border-radius: var(--border-radius);
margin-top: 20px;
font-size: 0.9em;
box-shadow: var(--shadow-light);
}
.icon {
width: 20px;
height: 20px;
display: inline-block;
}
@media (max-width: 768px) {
body {
padding: 10px;
}
.header-section {
padding: 20px;
}
.header-section h2 {
font-size: 2em;
}
.system-info {
font-size: 1em;
gap: 15px;
}
.stats-section {
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 15px;
}
.stat-card {
padding: 20px;
}
.stat-value {
font-size: 1.8em;
}
.chart-section {
padding: 20px;
}
.chart-header {
flex-direction: column;
align-items: flex-start;
}
.chart-container {
height: 300px;
}
.legend-container {
gap: 20px;
}
}
@media (max-width: 480px) {
.stats-section {
grid-template-columns: 1fr;
}
.chart-container {
height: 250px;
}
.system-info {
flex-direction: column;
align-items: center;
}
}
.loading-spinner {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid rgba(0,0,0,0.1);
border-radius: 50%;
border-top-color: var(--primary-color);
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.stat-value {
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}
.chart-section {
transition: var(--transition);
}
.tooltip {
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 8px 12px;
border-radius: 6px;
font-size: 0.85em;
font-weight: 500;
}
</style>
<div class="container-sm container-bg px-0 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span style="color: var(--accent-color); letter-spacing: 1px;"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: #ffcc00; font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php"><i class="bi bi-house-door"></i> <span data-translate="home">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo_manager.php' ? 'active' : '' ?>" href="./mihomo_manager.php"><i class="bi bi-folder"></i> <span data-translate="manager">Manager</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php"><i class="bi bi-shop"></i> <span data-translate="template_i">Template I</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'subscription.php' ? 'active' : '' ?>" href="./subscription.php"><i class="bi bi-bank"></i> <span data-translate="template_ii">Template II</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo.php' ? 'active' : '' ?>" href="./mihomo.php"><i class="bi bi-building"></i> <span data-translate="template_iii">Template III</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'netmon.php' ? 'active' : '' ?>" href="./netmon.php"><i class="bi bi-activity"></i> <span data-translate="traffic_monitor">Traffic Monitor</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'monaco.php' ? 'active' : '' ?>" href="./monaco.php"><i class="bi bi-bank"></i> <span data-translate="pageTitle">File Assistant</span></a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-3 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-tooltip="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-tooltip="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-tooltip="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" id="toggleIpStatusBtn" class="btn btn-warning icon-btn me-2" onclick="toggleIpStatusBar()" data-tooltip="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2" data-bs-toggle="modal" data-bs-target="#portModal" data-tooltip="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn-refresh-page btn btn-orange icon-btn me-2 d-none d-sm-inline"><i class="fas fa-sync-alt"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-tooltip="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<div class="container-sm px-4">
<div class="header-section">
<h2>
<i class="bi bi-globe2"></i>
<span data-translate="traffic_monitor_title">OpenWrt Real-time Traffic Monitor</span>
<span id="status-indicator" class="status-indicator status-online"></span>
</h2>
<div class="system-info">
<div class="info-item">
<i class="bi bi-gear"></i>
<span data-translate="detection_method">Detection Method</span>:
<span id="detection-method"><?php echo $traffic['method']; ?></span>
</div>
<div class="info-item">
<i class="bi bi-plug"></i>
<span data-translate="main_interface">Main Interface</span>:
<span id="main-interface"><?php echo $traffic['selected_interface'] ?? 'unknown'; ?></span>
</div>
<div class="info-item">
<a href="?debug=1" target="_blank" style="color: #007bff; text-decoration: none; font-weight: 600;">
<i class="bi bi-search"></i>
<span data-translate="debug_info">Debug Info</span>
</a>
</div>
</div>
</div>
<div id="error-container">
<?php if ($traffic['status'] === 'error'): ?>
<div class="error-message">
<i class="bi bi-exclamation-triangle"></i>
<?php echo htmlspecialchars($traffic['error'] ?? 'Unknown error'); ?>
</div>
<?php endif; ?>
</div>
<div class="stats-section">
<div class="stat-card upload">
<div class="stat-label">
<i class="bi bi-upload"></i>
<span data-translate="upload_speed">Upload Speed</span>
</div>
<span id="upload_speed" class="stat-value"><?php echo $traffic['upload_speed']; ?></span>
<div class="stat-description" data-translate="upload_bandwidth">Real-time Upload Bandwidth</div>
</div>
<div class="stat-card download">
<div class="stat-label">
<i class="bi bi-download"></i>
<span data-translate="download_speed">Download Speed</span>
</div>
<span id="download_speed" class="stat-value"><?php echo $traffic['download_speed']; ?></span>
<div class="stat-description" data-translate="download_bandwidth">Real-time Download Bandwidth</div>
</div>
<div class="stat-card total">
<div class="stat-label">
<i class="bi bi-bar-chart-line"></i>
<span data-translate="upload_total">Total Upload</span>
</div>
<span id="upload_total" class="stat-value"><?php echo $traffic['upload_total']; ?></span>
<div class="stat-description" data-translate="upload_total_desc">Cumulative Sent Traffic</div>
</div>
<div class="stat-card total">
<div class="stat-label">
<i class="bi bi-graph-up-arrow"></i>
<span data-translate="download_total">Total Download</span>
</div>
<span id="download_total" class="stat-value"><?php echo $traffic['download_total']; ?></span>
<div class="stat-description" data-translate="download_total_desc">Cumulative Received Traffic</div>
</div>
</div>
<div class="chart-section">
<div class="chart-header">
<div class="chart-title">
<i class="bi bi-graph-up"></i>
<span data-translate="realtime_chart">Realtime Traffic Chart</span>
</div>
<div class="chart-controls">
<button class="chart-toggle active" data-range="60" data-translate="range_1min">1 Minute</button>
<button class="chart-toggle" data-range="300" data-translate="range_5min">5 Minutes</button>
<button class="chart-toggle" data-range="900" data-translate="range_15min">15 Minutes</button>
<button class="chart-toggle" data-range="1800" data-translate="range_30min">30 Minutes</button>
</div>
</div>
<div class="chart-container">
<canvas id="trafficChart"></canvas>
</div>
<div class="legend-container">
<div class="legend-item">
<div class="legend-color upload"></div>
<span data-translate="upload_speed">Upload Speed</span>
</div>
<div class="legend-item">
<div class="legend-color download"></div>
<span data-translate="download_speed">Download Speed</span>
</div>
</div>
</div>
<div class="footer-section">
<div class="last-update">
<i class="bi bi-clock"></i>
<span data-translate="last_update">Last Update</span>:
<span id="last-update" data-translate="just_now"></span>
</div>
</div>
</div>
<script>
let updateInterval;
let errorCount = 0;
const maxErrors = 3;
let chart = null;
let chartData = {
labels: [],
uploadData: [],
downloadData: []
};
let currentRange = 60;
function initChart() {
const ctx = document.getElementById('trafficChart').getContext('2d');
chart = new Chart(ctx, {
type: 'line',
data: {
labels: chartData.labels,
datasets: [{
label: translations['upload_speed'] || 'Upload Speed',
data: chartData.uploadData,
borderColor: 'rgba(220, 53, 69, 1)',
backgroundColor: 'rgba(220, 53, 69, 0.1)',
borderWidth: 3,
fill: true,
tension: 0.4,
pointBackgroundColor: 'rgba(220, 53, 69, 1)',
pointBorderColor: '#fff',
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/save_ports.php | luci-app-nekobox/htdocs/nekobox/save_ports.php | <?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$mihomo_ports = [
'socks-port' => (int)$_POST['mihomo_socks'],
'mixed-port' => (int)$_POST['mihomo_mixed'],
'redir-port' => (int)$_POST['mihomo_redir'],
'port' => (int)$_POST['mihomo_port'],
'tproxy-port' => (int)$_POST['mihomo_tproxy'],
];
$singbox_ports = [
'http_proxy' => (int)$_POST['singbox_http'],
'mixed' => (int)$_POST['singbox_mixed']
];
$selected_config_path = './lib/selected_config.txt';
if (file_exists($selected_config_path)) {
$cfg_file = trim(file_get_contents($selected_config_path));
if (file_exists($cfg_file)) {
foreach ($mihomo_ports as $key => $port) {
shell_exec("sed -i 's/^$key:.*/$key: $port/' \"$cfg_file\"");
}
}
}
$singbox_config_path = './lib/singbox.txt';
if (file_exists($singbox_config_path)) {
$singbox_file = trim(file_get_contents($singbox_config_path));
if (file_exists($singbox_file)) {
$json = file_get_contents($singbox_file);
$config = json_decode($json, true);
if ($config && isset($config['inbounds'])) {
foreach ($config['inbounds'] as &$inbound) {
if ($inbound['type'] === 'mixed' && (!isset($inbound['tag']) || $inbound['tag'] !== 'mixed-in')) {
$inbound['listen_port'] = $singbox_ports['mixed'];
}
if ($inbound['type'] === 'http' && isset($inbound['tag']) && $inbound['tag'] === 'http-in') {
$inbound['listen_port'] = $singbox_ports['http_proxy'];
}
}
file_put_contents(
$singbox_file,
json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
);
}
}
}
header('Location: index.php?port_updated=1');
exit;
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/mihomo_manager.php | luci-app-nekobox/htdocs/nekobox/mihomo_manager.php | <?php
ob_start();
include './cfg.php';
$uploadDir = '/etc/neko/proxy_provider/';
$configDir = '/etc/neko/config/';
ini_set('memory_limit', '256M');
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
if (!is_dir($configDir)) {
mkdir($configDir, 0755, true);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['fileInput'])) {
$file = $_FILES['fileInput'];
$uploadFilePath = $uploadDir . basename($file['name']);
if ($file['error'] === UPLOAD_ERR_OK) {
if (move_uploaded_file($file['tmp_name'], $uploadFilePath)) {
echo '<div class="log-message alert alert-success" role="alert" data-translate="file_upload_success" data-dynamic-content="' . htmlspecialchars(basename($file['name'])) . '"></div>';
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_upload_failed"></div>';
}
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_upload_error" data-dynamic-content="' . $file['error'] . '"></div>';
}
}
if (isset($_FILES['configFileInput'])) {
$file = $_FILES['configFileInput'];
$uploadFilePath = $configDir . basename($file['name']);
if ($file['error'] === UPLOAD_ERR_OK) {
if (move_uploaded_file($file['tmp_name'], $uploadFilePath)) {
echo '<div class="log-message alert alert-success" role="alert" data-translate="config_upload_success" data-dynamic-content="' . htmlspecialchars(basename($file['name'])) . '"></div>';
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="config_upload_failed"></div>';
}
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_upload_error" data-dynamic-content="' . $file['error'] . '"></div>';
}
}
if (isset($_POST['deleteFile'])) {
$fileToDelete = $uploadDir . basename($_POST['deleteFile']);
if (file_exists($fileToDelete) && unlink($fileToDelete)) {
echo '<div class="log-message alert alert-success" role="alert" data-translate="file_delete_success" data-dynamic-content="' . htmlspecialchars(basename($_POST['deleteFile'])) . '"></div>';
} else {
//echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_delete_failed"></div>';
}
}
if (isset($_POST['deleteConfigFile'])) {
$fileToDelete = $configDir . basename($_POST['deleteConfigFile']);
if (file_exists($fileToDelete) && unlink($fileToDelete)) {
echo '<div class="log-message alert alert-success" role="alert" data-translate="config_delete_success" data-dynamic-content="' . htmlspecialchars(basename($_POST['deleteConfigFile'])) . '"></div>';
} else {
// echo '<div class="log-message alert alert-danger" role="alert" data-translate="config_delete_failed"></div>';
}
}
if (isset($_POST['oldFileName'], $_POST['newFileName'], $_POST['fileType'])) {
$oldFileName = basename($_POST['oldFileName']);
$newFileName = basename($_POST['newFileName']);
$fileType = $_POST['fileType'];
if ($fileType === 'proxy') {
$oldFilePath = $uploadDir . $oldFileName;
$newFilePath = $uploadDir . $newFileName;
} elseif ($fileType === 'config') {
$oldFilePath = $configDir . $oldFileName;
$newFilePath = $configDir . $newFileName;
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_not_found"></div>';
exit;
}
if (file_exists($oldFilePath) && !file_exists($newFilePath)) {
if (rename($oldFilePath, $newFilePath)) {
echo '<div class="log-message alert alert-success" role="alert" data-translate="file_rename_success" data-dynamic-content="' . htmlspecialchars($oldFileName) . ' -> ' . htmlspecialchars($newFileName) . '"></div>';
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_rename_failed"></div>';
}
} else {
echo '<div class="log-message alert alert-danger" role="alert" data-translate="file_rename_exists"></div>';
}
}
if (isset($_POST['saveContent'], $_POST['fileName'], $_POST['fileType'])) {
$fileToSave = ($_POST['fileType'] === 'proxy') ? $uploadDir . basename($_POST['fileName']) : $configDir . basename($_POST['fileName']);
$contentToSave = $_POST['saveContent'];
file_put_contents($fileToSave, $contentToSave);
echo '<div class="log-message alert alert-info" role="alert" data-translate="file_save_success" data-dynamic-content="' . htmlspecialchars(basename($fileToSave)) . '"></div>';
}
}
function formatFileModificationTime($filePath) {
if (file_exists($filePath)) {
$fileModTime = filemtime($filePath);
return date('Y-m-d H:i:s', $fileModTime);
} else {
return '<span data-translate="file_not_found"></span>';
}
}
$proxyFiles = scandir($uploadDir);
$configFiles = scandir($configDir);
if ($proxyFiles !== false) {
$proxyFiles = array_diff($proxyFiles, array('.', '..'));
$proxyFiles = array_filter($proxyFiles, function($file) {
return pathinfo($file, PATHINFO_EXTENSION) !== 'txt';
});
} else {
$proxyFiles = [];
}
if ($configFiles !== false) {
$configFiles = array_diff($configFiles, array('.', '..'));
} else {
$configFiles = [];
}
function formatSize($size) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$unit = 0;
while ($size >= 1024 && $unit < count($units) - 1) {
$size /= 1024;
$unit++;
}
return round($size, 2) . ' ' . $units[$unit];
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['editFile'], $_GET['fileType'])) {
$filePath = ($_GET['fileType'] === 'proxy') ? $uploadDir. basename($_GET['editFile']) : $configDir . basename($_GET['editFile']);
if (file_exists($filePath)) {
header('Content-Type: text/plain');
echo file_get_contents($filePath);
exit;
} else {
echo '<span data-translate="file_not_found"></span>';
exit;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['downloadFile'], $_GET['fileType'])) {
$fileType = $_GET['fileType'];
$fileName = basename($_GET['downloadFile']);
$filePath = ($fileType === 'proxy') ? $uploadDir . $fileName : $configDir . $fileName;
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
} else {
echo '<span data-translate="file_not_found"></span>';
}
}
?>
<?php
$JSON_FILE = '/etc/neko/proxy_provider/subscriptions.json';
$subscriptionPath = '/etc/neko/proxy_provider/';
$notificationMessage = "";
$updateCompleted = false;
if (!file_exists($subscriptionPath)) {
mkdir($subscriptionPath, 0755, true);
}
if (!file_exists($JSON_FILE)) {
$emptySubs = [];
for ($i = 0; $i < 6; $i++) {
$emptySubs[] = [
'url' => '',
'file_name' => "subscription_" . ($i + 1) . ".yaml"
];
}
file_put_contents($JSON_FILE, json_encode($emptySubs, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
function getSubscriptionsFromFile() {
global $JSON_FILE;
if (file_exists($JSON_FILE)) {
$content = file_get_contents($JSON_FILE);
$data = json_decode($content, true);
if (!is_array($data) || count($data) < 6) {
$data = $data ?? [];
for ($i = count($data); $i < 6; $i++) {
$data[$i] = [
'url' => '',
'file_name' => "subscription_" . ($i + 1) . ".yaml"
];
}
}
return $data;
}
return [];
}
function formatBytes($bytes, $precision = 2) {
if ($bytes === INF || $bytes === "∞") return "∞";
if ($bytes <= 0) return "0 B";
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$pow = floor(log($bytes, 1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
function getSubInfo($subUrl, $userAgent = "Clash") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $subUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code !== 200 || !$response) {
return [
"http_code" => $http_code,
"sub_info" => "Request Failed",
"get_time" => time()
];
}
if (!preg_match("/subscription-userinfo: (.*)/i", $response, $matches)) {
return [
"http_code" => $http_code,
"sub_info" => "No Sub Info Found",
"get_time" => time()
];
}
$info = $matches[1];
preg_match("/upload=(\d+)/", $info, $m); $upload = isset($m[1]) ? (int)$m[1] : 0;
preg_match("/download=(\d+)/", $info, $m); $download = isset($m[1]) ? (int)$m[1] : 0;
preg_match("/total=(\d+)/", $info, $m); $total = isset($m[1]) ? (int)$m[1] : 0;
preg_match("/expire=(\d+)/", $info, $m); $expire = isset($m[1]) ? (int)$m[1] : 0;
$used = $upload + $download;
$surplus = ($total > 0) ? $total - $used : INF;
$percent = ($total > 0) ? (($total - $used) / $total) * 100 : 100;
$expireDate = "null";
$day_left = "null";
if ($expire > 0) {
$expireDate = date("Y-m-d H:i:s", $expire);
$day_left = $expire > time() ? ceil(($expire - time()) / (3600*24)) : 0;
} elseif ($expire === 0) {
$expireDate = "Long-term";
$day_left = "∞";
}
return [
"http_code" => $http_code,
"sub_info" => "Successful",
"upload" => $upload,
"download" => $download,
"used" => $used,
"total" => $total > 0 ? $total : "∞",
"surplus" => $surplus,
"percent" => round($percent, 1),
"day_left" => $day_left,
"expire" => $expireDate,
"get_time" => time()
];
}
function saveSubInfoToFile($index, $subInfo) {
$libDir = __DIR__ . '/lib';
if (!is_dir($libDir)) mkdir($libDir, 0755, true);
$filePath = $libDir . '/sub_info_' . $index . '.json';
file_put_contents($filePath, json_encode($subInfo));
}
function getSubInfoFromFile($index) {
$filePath = __DIR__ . '/lib/sub_info_' . $index . '.json';
if (file_exists($filePath)) {
return json_decode(file_get_contents($filePath), true);
}
return null;
}
function clearSubInfo($index) {
$filePath = __DIR__ . '/lib/sub_info_' . $index . '.json';
if (file_exists($filePath)) {
unlink($filePath);
return true;
}
return false;
}
$subscriptions = getSubscriptionsFromFile();
function autoCleanInvalidSubInfo($subscriptions) {
$maxSubscriptions = 6;
$cleaned = 0;
for ($i = 0; $i < $maxSubscriptions; $i++) {
$url = trim($subscriptions[$i]['url'] ?? '');
if (empty($url)) {
if (clearSubInfo($i)) {
$cleaned++;
}
}
}
return $cleaned;
}
function isValidSubscriptionContent($content) {
$keywords = ['ss', 'shadowsocks', 'vmess', 'vless', 'trojan', 'hysteria2', 'socks5', 'http'];
foreach ($keywords as $keyword) {
if (stripos($content, $keyword) !== false) {
return true;
}
}
return false;
}
autoCleanInvalidSubInfo($subscriptions);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
$index = intval($_POST['index']);
$url = trim($_POST['subscription_url'] ?? '');
$customFileName = trim($_POST['custom_file_name'] ?? "subscription_" . ($index + 1) . ".yaml");
$subscriptions[$index]['url'] = $url;
$subscriptions[$index]['file_name'] = $customFileName;
if (!empty($url)) {
$tempPath = $subscriptionPath . $customFileName . ".temp";
$finalPath = $subscriptionPath . $customFileName;
$command = "curl -s -L -o {$tempPath} " . escapeshellarg($url);
exec($command . ' 2>&1', $output, $return_var);
if ($return_var !== 0) {
$command = "wget -q --show-progress -O {$tempPath} " . escapeshellarg($url);
exec($command . ' 2>&1', $output, $return_var);
}
if ($return_var === 0 && file_exists($tempPath)) {
//echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_downloaded" data-dynamic-content="' . htmlspecialchars($url) . '"></span></div>';
$fileContent = file_get_contents($tempPath);
if (base64_encode(base64_decode($fileContent, true)) === $fileContent) {
$decodedContent = base64_decode($fileContent);
if ($decodedContent !== false && strlen($decodedContent) > 0 && isValidSubscriptionContent($decodedContent)) {
file_put_contents($finalPath, "# Clash Meta Config\n\n" . $decodedContent);
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="base64_decode_success" data-dynamic-content="' . htmlspecialchars($finalPath) . '"></span></div>';
$notificationMessage = '<span data-translate="update_success"></span>';
$updateCompleted = true;
} else {
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="base64_decode_failed"></span></div>';
$notificationMessage = '<span data-translate="update_failed"></span>';
}
}
elseif (substr($fileContent, 0, 2) === "\x1f\x8b") {
$decompressedContent = gzdecode($fileContent);
if ($decompressedContent !== false && isValidSubscriptionContent($decompressedContent)) {
file_put_contents($finalPath, "# Clash Meta Config\n\n" . $decompressedContent);
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="gzip_decompress_success" data-dynamic-content="' . htmlspecialchars($finalPath) . '"></span></div>';
$notificationMessage = '<span data-translate="update_success"></span>';
$updateCompleted = true;
} else {
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="gzip_decompress_failed"></span></div>';
$notificationMessage = '<span data-translate="update_failed"></span>';
}
}
else {
if (isValidSubscriptionContent($fileContent) && rename($tempPath, $finalPath)) {
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_downloaded_no_decode"></span></div>';
$notificationMessage = '<span data-translate="update_success"></span>';
$updateCompleted = true;
} else {
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_update_failed" data-dynamic-content="' . htmlspecialchars(implode("\n", $output)) . '"></span></div>';
$notificationMessage = '<span data-translate="update_failed"></span>';
}
}
$userAgents = ["Clash","clash","ClashVerge","Stash","NekoBox","Quantumult%20X","Surge","Shadowrocket","V2rayU","Sub-Store","Mozilla/5.0"];
$subInfo = null;
foreach ($userAgents as $ua) {
$subInfo = getSubInfo($url, $ua);
if ($subInfo['sub_info'] === "Successful") break;
}
if ($subInfo) {
saveSubInfoToFile($index, $subInfo);
}
if (file_exists($tempPath)) {
unlink($tempPath);
}
} else {
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_update_failed" data-dynamic-content="' . htmlspecialchars(implode("\n", $output)) . '"></span></div>';
$notificationMessage = '<span data-translate="update_failed"></span>';
if (file_exists($tempPath)) {
unlink($tempPath);
}
}
} else {
clearSubInfo($index);
$notificationMessage = '<span data-translate="update_failed"></span>';
}
file_put_contents($JSON_FILE, json_encode($subscriptions, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['updateAll'])) {
$updated = 0;
$failed = 0;
for ($i = 0; $i < 6; $i++) {
$url = trim($subscriptions[$i]['url'] ?? '');
$customFileName = trim($subscriptions[$i]['file_name'] ?? "subscription_" . ($i + 1) . ".yaml");
if (!empty($url)) {
$tempPath = $subscriptionPath . $customFileName . ".temp";
$finalPath = $subscriptionPath . $customFileName;
$command = "curl -s -L -o {$tempPath} " . escapeshellarg($url);
exec($command . ' 2>&1', $output, $return_var);
if ($return_var !== 0) {
$command = "wget -q --show-progress -O {$tempPath} " . escapeshellarg($url);
exec($command . ' 2>&1', $output, $return_var);
}
if ($return_var === 0 && file_exists($tempPath)) {
$fileContent = file_get_contents($tempPath);
$success = false;
if (base64_encode(base64_decode($fileContent, true)) === $fileContent) {
$decodedContent = base64_decode($fileContent);
if ($decodedContent !== false && strlen($decodedContent) > 0 && isValidSubscriptionContent($decodedContent)) {
file_put_contents($finalPath, "# Clash Meta Config\n\n" . $decodedContent);
$success = true;
}
}
elseif (substr($fileContent, 0, 2) === "\x1f\x8b") {
$decompressedContent = gzdecode($fileContent);
if ($decompressedContent !== false && isValidSubscriptionContent($decompressedContent)) {
file_put_contents($finalPath, "# Clash Meta Config\n\n" . $decompressedContent);
$success = true;
}
}
else {
if (isValidSubscriptionContent($fileContent) && rename($tempPath, $finalPath)) {
$success = true;
}
}
if ($success) {
$updated++;
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_updated_success" data-index="' . ($i + 1) . '"></span></div>';
$userAgents = ["Clash","clash","ClashVerge","Stash","NekoBox","Quantumult%20X","Surge","Shadowrocket","V2rayU","Sub-Store","Mozilla/5.0"];
$subInfo = null;
foreach ($userAgents as $ua) {
$subInfo = getSubInfo($url, $ua);
if ($subInfo['sub_info'] === "Successful") break;
}
if ($subInfo) {
saveSubInfoToFile($i, $subInfo);
}
} else {
$failed++;
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_updated_failed" data-index="' . ($i + 1) . '"></span></div>';
}
if (file_exists($tempPath)) {
unlink($tempPath);
}
} else {
$failed++;
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscription_updated_failed" data-index="' . ($i + 1) . '"></span></div>';
if (file_exists($tempPath)) {
unlink($tempPath);
}
}
}
}
if ($updated > 0) {
$notificationMessage = '<span data-translate="update_all_success" data-count="' . $updated . '"></span>';
$updateCompleted = true;
} else {
$notificationMessage = '<span data-translate="update_all_failed"></span>';
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clear'])) {
$index = $_POST['index'] ?? 0;
clearSubInfo($index);
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
?>
<?php
$shellScriptPath = '/etc/neko/core/update_mihomo.sh';
$LOG_FILE = '/etc/neko/tmp/log.txt';
$JSON_FILE = '/etc/neko/proxy_provider/subscriptions.json';
$SAVE_DIR = '/etc/neko/proxy_provider';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['createShellScript'])) {
$shellScriptContent = <<<EOL
#!/bin/bash
LOG_FILE="/etc/neko/tmp/log.txt"
JSON_FILE="/etc/neko/proxy_provider/subscriptions.json"
SAVE_DIR="/etc/neko/proxy_provider"
log() {
echo "$(date '+[ %H:%M:%S ]') \$1" >> "\$LOG_FILE"
}
log "Starting subscription update task..."
if [ ! -f "\$JSON_FILE" ]; then
log "❌ Error: JSON file does not exist: \$JSON_FILE"
exit 1
fi
jq -c '.[]' "\$JSON_FILE" | while read -r ITEM; do
URL=\$(echo "\$ITEM" | jq -r '.url')
FILE_NAME=\$(echo "\$ITEM" | jq -r '.file_name')
if [ -z "\$URL" ] || [ "\$URL" == "null" ]; then
log "⚠️ Skipping empty subscription URL, file name: \$FILE_NAME"
continue
fi
if [ -z "\$FILE_NAME" ] || [ "\$FILE_NAME" == "null" ]; then
log "❌ Error: File name is empty, skipping this URL: \$URL"
continue
fi
SAVE_PATH="\$SAVE_DIR/\$FILE_NAME"
TEMP_PATH="\$SAVE_PATH.temp"
log "🔄 Downloading: \$URL to temporary file: \$TEMP_PATH"
curl -s -L -o "\$TEMP_PATH" "\$URL"
if [ \$? -ne 0 ]; then
wget -q -O "\$TEMP_PATH" "\$URL"
fi
if [ \$? -eq 0 ]; then
log "✅ File downloaded successfully: \$TEMP_PATH"
if base64 -d "\$TEMP_PATH" > /dev/null 2>&1; then
base64 -d "\$TEMP_PATH" > "\$SAVE_PATH"
if [ \$? -eq 0 ]; then
log "📂 Base64 decoding successful, configuration saved: \$SAVE_PATH"
rm -f "\$TEMP_PATH"
else
log "⚠️ Base64 decoding failed: \$SAVE_PATH"
rm -f "\$TEMP_PATH"
fi
elif file "\$TEMP_PATH" | grep -q "gzip compressed"; then
gunzip -c "\$TEMP_PATH" > "\$SAVE_PATH"
if [ \$? -eq 0 ]; then
log "📂 Gzip decompression successful, configuration saved: \$SAVE_PATH"
rm -f "\$TEMP_PATH"
else
log "⚠️ Gzip decompression failed: \$SAVE_PATH"
rm -f "\$TEMP_PATH"
fi
else
mv "\$TEMP_PATH" "\$SAVE_PATH"
log "✅ Subscription content successfully downloaded, no decoding required"
fi
else
log "❌ Subscription update failed: \$URL"
rm -f "\$TEMP_PATH"
fi
done
log "🚀 All subscription links updated successfully!"
EOL;
if (file_put_contents($shellScriptPath, $shellScriptContent) !== false) {
chmod($shellScriptPath, 0755);
echo "<div class='log-message alert alert-success'><span data-translate='shell_script_created' data-dynamic-content='$shellScriptPath'></span></div>";
} else {
echo "<div class='log-message alert alert-danger'><span data-translate='shell_script_failed'></span></div>";
}
}
}
?>
<?php
$CRON_LOG_FILE = '/etc/neko/tmp/log.txt';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['createCronJob'])) {
$cronExpression = trim($_POST['cronExpression']);
if (empty($cronExpression)) {
file_put_contents($CRON_LOG_FILE, date('[ H:i:s ] ') . "Error: Cron expression cannot be empty.\n", FILE_APPEND);
echo "<div class='log-message alert alert-warning' data-translate='cron_expression_empty'></div>";
exit;
}
$cronJob = "$cronExpression /etc/neko/core/update_mihomo.sh";
exec("crontab -l | grep -v '/etc/neko/core/update_mihomo.sh' | crontab -", $output, $returnVarRemove);
if ($returnVarRemove === 0) {
file_put_contents($CRON_LOG_FILE, date('[ H:i:s ] ') . "Successfully removed old Cron job.\n", FILE_APPEND);
} else {
file_put_contents($CRON_LOG_FILE, date('[ H:i:s ] ') . "Failed to remove old Cron job.\n", FILE_APPEND);
}
exec("(crontab -l; echo '$cronJob') | crontab -", $output, $returnVarAdd);
if ($returnVarAdd === 0) {
file_put_contents($CRON_LOG_FILE, date('[ H:i:s ] ') . "Successfully added new Cron job: $cronJob\n", FILE_APPEND);
echo "<div class='log-message alert alert-success' data-translate='cron_job_added_success'></div>";
} else {
file_put_contents($CRON_LOG_FILE, date('[ H:i:s ] ') . "Failed to add new Cron job.\n", FILE_APPEND);
echo "<div class='log-message alert alert-danger' data-translate='cron_job_added_failed'></div>";
}
}
}
?>
<?php
$file_urls = [
'geoip' => 'https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.metadb',
'geosite' => 'https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat',
'cache' => 'https://github.com/Thaolga/neko/raw/main/cache.db'
];
$download_directories = [
'geoip' => '/etc/neko/',
'geosite' => '/etc/neko/',
'cache' => '/www/nekobox/'
];
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['file'])) {
$file = $_GET['file'];
if (isset($file_urls[$file])) {
$file_url = $file_urls[$file];
$destination_directory = $download_directories[$file];
$destination_path = $destination_directory . basename($file_url);
if (download_file($file_url, $destination_path)) {
echo "<div class='log-message alert alert-success' data-translate='file_download_success' data-dynamic-content='$destination_path'></div>";
} else {
echo "<div class='log-message alert alert-danger' data-translate='file_download_failed'></div>";
}
} else {
echo "<div class='log-message alert alert-warning' data-translate='invalid_file_request'></div>";
}
}
function download_file($url, $destination) {
$ch = curl_init($url);
$fp = fopen($destination, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
return $result !== false;
}
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clearJsonFile'])) {
$fileToClear = $_POST['clearJsonFile'];
if ($fileToClear === 'subscriptions.json') {
$filePath = '/etc/neko/proxy_provider/subscriptions.json';
if (file_exists($filePath)) {
file_put_contents($filePath, '[]');
echo '<div class="log-message alert alert-warning custom-alert-success"><span data-translate="subscriptionClearedSuccess">Subscription information cleared successfully</span></div>';
}
}
}
?>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mihomo - NekoBox</title>
<link rel="icon" href="./assets/img/nekobox.png">
<script src="./assets/bootstrap/beautify.min.js"></script>
<script src="./assets/bootstrap/js-yaml.min.js"></script>
<script src="./assets/bootstrap/jquery.min.js"></script>
<?php include './ping.php'; ?>
</head>
<style>
.custom-alert-success {
background-color: #d4edda !important;
border-color: #c3e6cb !important;
color: #155724 !important;
}
#updateNotification {
background: linear-gradient(135deg, #1e3a8a, #2563eb);
color: #fff;
border: none;
border-radius: 0.5rem;
padding: 1rem;
position: relative;
}
#updateNotification .alert-info {
background: rgba(255, 255, 255, 0.1);
color: #fff;
border: none;
}
#updateNotification .spinner-border {
filter: invert(1);
}
#dropZone i {
font-size: 50px;
color: #007bff;
animation: iconPulse 1.5s infinite;
}
@keyframes iconPulse {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.2);
opacity: 0.7;
}
100% {
transform: scale(1);
opacity: 1;
}
}
.table-hover tbody tr:hover td {
color: #cc0fa9;
}
.node-count-badge {
position: absolute;
top: 1.4rem;
right: 0.9rem;
background-color: var(--accent-color);
color: #fff;
padding: 0.2rem 0.5rem;
border-radius: 0.5rem;
font-size: 0.75rem;
font-weight: bold;
z-index: 10;
}
</style>
<?php if ($updateCompleted): ?>
<script>
if (!sessionStorage.getItem('refreshed')) {
sessionStorage.setItem('refreshed', 'true');
window.location.reload();
} else {
sessionStorage.removeItem('refreshed');
}
</script>
<?php endif; ?>
<body>
<div class="position-fixed w-100 d-flex flex-column align-items-center" style="top: 20px; z-index: 1050;">
<div id="updateNotification" class="alert alert-info alert-dismissible fade show shadow-lg" role="alert" style="display: none; min-width: 320px; max-width: 600px; opacity: 0.95;">
<div class="d-flex align-items-center">
<div class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></div>
<strong data-translate="update_notification"></strong>
</div>
<div class="alert alert-info mt-2 p-2 small">
<strong data-translate="usage_instruction"></strong>
<ul class="mb-0 pl-3">
<li data-translate="max_subscriptions"></li>
<li data-translate="no_rename"></li>
<li data-translate="supports_all_formats"></li>
</ul>
</div>
<div id="updateLogContainer" class="small mt-2"></div>
</div>
</div>
<script>
function displayUpdateNotification() {
const notification = $('#updateNotification');
const updateLogs = <?php echo json_encode($_SESSION['update_logs'] ?? []); ?>;
if (updateLogs.length > 0) {
const logsHtml = updateLogs.map(log => `<div>${log}</div>`).join('');
$('#updateLogContainer').html(logsHtml);
}
notification.fadeIn().addClass('show');
setTimeout(function() {
notification.fadeOut(300, function() {
notification.hide();
$('#updateLogContainer').html('');
});
}, 5000);
}
$(document).ready(function() {
const notificationMessageExists = <?php echo json_encode(!empty($notificationMessage)); ?>;
if (notificationMessageExists) {
const lastNotificationTime = localStorage.getItem('lastUpdateNotificationTime');
const now = Date.now();
const twentyFourHours = 24 * 60 * 60 * 1000;
if (!lastNotificationTime || now - parseInt(lastNotificationTime, 10) > twentyFourHours) {
displayUpdateNotification();
localStorage.setItem('lastUpdateNotificationTime', now.toString());
}
}
});
</script>
<div class="container-sm container-bg px-0 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/monaco.php | luci-app-nekobox/htdocs/nekobox/monaco.php | <?php
ini_set('memory_limit', '256M');
ob_start();
include './cfg.php';
$root_dir = "/";
$current_dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$current_dir = '/' . trim($current_dir, '/') . '/';
if ($current_dir == '//') $current_dir = '/';
$current_path = $root_dir . ltrim($current_dir, '/');
if (strpos(realpath($current_path), realpath($root_dir)) !== 0) {
$current_dir = '/';
$current_path = $root_dir;
}
if (isset($_GET['preview']) && isset($_GET['path'])) {
$path = preg_replace('/\/+/', '/', $_GET['path']);
$preview_path = realpath($root_dir . '/' . $path);
if ($preview_path && strpos($preview_path, realpath($root_dir)) === 0) {
if (!file_exists($preview_path)) {
header('HTTP/1.0 404 Not Found');
echo "File not found.";
exit;
}
$ext = strtolower(pathinfo($preview_path, PATHINFO_EXTENSION));
$mime_types = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'svg' => 'image/svg+xml',
'bmp' => 'image/bmp',
'webp' => 'image/webp',
'mp3' => 'audio/mpeg',
'wav' => 'audio/wav',
'ogg' => 'audio/ogg',
'flac' => 'audio/flac',
'mp4' => 'video/mp4',
'webm' => 'video/webm',
'avi' => 'video/x-msvideo',
'mkv' => 'video/x-matroska'
];
$mime_type = isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream';
header('Content-Type: ' . $mime_type);
header('Content-Length: ' . filesize($preview_path));
readfile($preview_path);
exit;
} else {
header('HTTP/1.0 404 Not Found');
echo "Invalid path.";
exit;
}
}
if (isset($_GET['action']) && $_GET['action'] === 'refresh') {
$contents = getDirectoryContents($current_path);
echo json_encode($contents);
exit;
}
if (isset($_POST['action']) && $_POST['action'] === 'delete_selected') {
if (isset($_POST['selected_paths']) && is_array($_POST['selected_paths'])) {
foreach ($_POST['selected_paths'] as $path) {
deleteItem($current_path . $path);
}
header("Location: ?dir=" . urlencode($current_dir));
exit;
}
}
if (isset($_GET['action']) && $_GET['action'] === 'get_content' && isset($_GET['path'])) {
$file_path = $current_path . $_GET['path'];
if (file_exists($file_path) && is_readable($file_path)) {
$content = file_get_contents($file_path);
header('Content-Type: text/plain; charset=utf-8');
echo $content;
exit;
} else {
http_response_code(404);
echo 'File does not exist or is not readable.';
exit;
}
}
if (isset($_GET['download'])) {
downloadFile($current_path . $_GET['download']);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'rename':
$new_name = basename($_POST['new_path']);
$old_path = $current_path . $_POST['old_path'];
$new_path = dirname($old_path) . '/' . $new_name;
renameItem($old_path, $new_path);
break;
case 'edit':
$content = $_POST['content'];
$encoding = $_POST['encoding'];
$result = editFile($current_path . $_POST['path'], $content, $encoding);
if (!$result) {
echo "<script>alert('Error: Unable to save the file.');</script>";
}
break;
case 'delete':
deleteItem($current_path . $_POST['path']);
break;
case 'chmod':
chmodItem($current_path . $_POST['path'], $_POST['permissions']);
break;
case 'create_folder':
$new_folder_name = $_POST['new_folder_name'];
$new_folder_path = $current_path . '/' . $new_folder_name;
if (!file_exists($new_folder_path)) {
mkdir($new_folder_path);
}
break;
case 'create_file':
$new_file_name = $_POST['new_file_name'];
$new_file_path = $current_path . '/' . $new_file_name;
if (!file_exists($new_file_path)) {
file_put_contents($new_file_path, '');
chmod($new_file_path, 0644);
}
break;
}
} elseif (isset($_FILES['upload'])) {
uploadFile($current_path);
}
}
function deleteItem($path) {
$path = rtrim(str_replace('//', '/', $path), '/');
if (!file_exists($path)) {
error_log("Attempted to delete non-existent item: $path");
return false;
}
if (is_dir($path)) {
return deleteDirectory($path);
} else {
if (@unlink($path)) {
return true;
} else {
error_log("Failed to delete file: $path");
return false;
}
}
}
function deleteDirectory($dir) {
if (!is_dir($dir)) {
return false;
}
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
$path = $dir . '/' . $file;
is_dir($path) ? deleteDirectory($path) : @unlink($path);
}
return @rmdir($dir);
}
function readFileWithEncoding($path) {
$content = file_get_contents($path);
$encoding = mb_detect_encoding($content, ['UTF-8', 'ASCII', 'ISO-8859-1', 'Windows-1252', 'GBK', 'Big5', 'Shift_JIS', 'EUC-KR'], true);
return json_encode([
'content' => mb_convert_encoding($content, 'UTF-8', $encoding),
'encoding' => $encoding
]);
}
function renameItem($old_path, $new_path) {
$old_path = rtrim(str_replace('//', '/', $old_path), '/');
$new_path = rtrim(str_replace('//', '/', $new_path), '/');
$new_name = basename($new_path);
$dir = dirname($old_path);
$new_full_path = $dir . '/' . $new_name;
if (!file_exists($old_path)) {
error_log("Source file does not exist before rename: $old_path");
if (file_exists($new_full_path)) {
error_log("But new file already exists: $new_full_path. Rename might have succeeded.");
return true;
}
return false;
}
$result = rename($old_path, $new_full_path);
if (!$result) {
error_log("Rename function returned false for: $old_path to $new_full_path");
if (file_exists($new_full_path) && !file_exists($old_path)) {
error_log("However, new file exists and old file doesn't. Consider rename successful.");
return true;
}
}
if (file_exists($new_full_path)) {
error_log("New file exists after rename: $new_full_path");
} else {
error_log("New file does not exist after rename attempt: $new_full_path");
}
if (file_exists($old_path)) {
error_log("Old file still exists after rename attempt: $old_path");
} else {
error_log("Old file no longer exists after rename attempt: $old_path");
}
return $result;
}
function editFile($path, $content, $encoding) {
if (file_exists($path) && is_writable($path)) {
return file_put_contents($path, $content) !== false;
}
return false;
}
function chmodItem($path, $permissions) {
chmod($path, octdec($permissions));
}
function uploadFile($destination) {
$uploaded_files = [];
$errors = [];
if (!is_dir($destination)) {
@mkdir($destination, 0755, true);
}
if (!empty($_FILES["upload"])) {
foreach ($_FILES["upload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["upload"]["tmp_name"][$key];
$name = basename($_FILES["upload"]["name"][$key]);
$target_file = rtrim($destination, '/') . '/' . $name;
if (move_uploaded_file($tmp_name, $target_file)) {
$uploaded_files[] = $name;
chmod($target_file, 0644);
} else {
$errors[] = "Failed to upload $name.";
}
} else {
$errors[] = "Upload error for file $key: " . getUploadError($error);
}
}
}
if (!empty($errors)) {
return ['error' => implode("\n", $errors)];
}
if (!empty($uploaded_files)) {
return ['success' => implode(", ", $uploaded_files)];
}
return ['error' => 'No files were uploaded'];
}
if (!function_exists('deleteDirectory')) {
function deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) return false;
}
return rmdir($dir);
}
}
function downloadFile($file) {
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
function getDirectoryContents($dir) {
$contents = array();
foreach (scandir($dir) as $item) {
if ($item != "." && $item != "..") {
$path = $dir . DIRECTORY_SEPARATOR . $item;
$perms = '----';
$size = '-';
$mtime = '-';
$owner = '-';
if (file_exists($path) && is_readable($path)) {
$perms = substr(sprintf('%o', fileperms($path)), -4);
if (!is_dir($path)) {
$size = formatSize(filesize($path));
}
$mtime = date("Y-m-d H:i:s", filemtime($path));
$owner = function_exists('posix_getpwuid') ? posix_getpwuid(fileowner($path))['name'] : fileowner($path);
}
$contents[] = array(
'name' => $item,
'path' => str_replace($dir, '', $path),
'is_dir' => is_dir($path),
'permissions' => $perms,
'size' => $size,
'mtime' => $mtime,
'owner' => $owner,
'extension' => pathinfo($path, PATHINFO_EXTENSION)
);
}
}
return $contents;
}
function formatSize($bytes) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2) . ' ' . $units[$pow];
}
$contents = getDirectoryContents($current_path);
$breadcrumbs = array();
$path_parts = explode('/', trim($current_dir, '/'));
$cumulative_path = '';
foreach ($path_parts as $part) {
$cumulative_path .= $part . '/';
$breadcrumbs[] = array('name' => $part, 'path' => $cumulative_path);
}
if (isset($_GET['action']) && $_GET['action'] === 'search' && isset($_GET['term'])) {
$searchTerm = $_GET['term'];
$searchResults = searchFiles($current_path, $searchTerm);
echo json_encode($searchResults);
exit;
}
function searchFiles($dir, $term) {
$results = array();
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::SELF_FIRST
);
$webRoot = $_SERVER['DOCUMENT_ROOT'];
$tmpDir = sys_get_temp_dir();
foreach ($files as $file) {
if ($file->isDir()) continue;
if (stripos($file->getFilename(), $term) !== false) {
$fullPath = $file->getPathname();
if (strpos($fullPath, $webRoot) === 0) {
$relativePath = substr($fullPath, strlen($webRoot));
} elseif (strpos($fullPath, $tmpDir) === 0) {
$relativePath = 'tmp' . substr($fullPath, strlen($tmpDir));
} else {
$relativePath = $fullPath;
}
$relativePath = ltrim($relativePath, '/');
$results[] = array(
'path' => $relativePath,
'dir' => dirname($relativePath) === '.' ? '' : dirname($relativePath),
'name' => $file->getFilename()
);
}
}
return $results;
}
?>
<title>Monaco - Nekobox</title>
<?php include './ping.php'; ?>
<link rel="icon" href="./assets/img/nekobox.png">
<script src="./assets/js/js-yaml.min.js"></script>
<style>
#monacoEditor {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
flex-direction: column;
box-sizing: border-box;
background-color: var(--card-bg);
z-index: 1100;
}
#monacoEditorContainer {
flex: 1;
width: 90%;
margin: 0 auto;
min-height: 0;
border-radius: 4px;
overflow: hidden;
margin-top: 40px;
z-index: 1100;
}
#editorControls {
display: flex;
align-items: center;
padding: 8px 16px;
background-color: var(--card-bg);
width: 100%;
position: fixed;
top: 0;
z-index: 1101;
box-sizing: border-box;
border-bottom: 1px solid #ccc;
}
#fontSize, #editorTheme {
display: inline-block;
width: auto;
cursor: pointer;
font-family: inherit;
font-size: 0.875rem;
font-weight: 500;
color: #ffffff !important;
background-color: var(--accent-color) !important;
border-radius: var(--radius);
border: 1px solid var(--border-color);
border-radius: 0.25rem;
padding: 0.375rem 1.75rem 0.375rem 0.75rem;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
transition: all 0.2s ease;
}
.editor-widget.find-widget {
display: flex !important;
flex-direction: column !important;
height: auto !important;
padding: 6px !important;
gap: 6px !important;
}
.editor-widget.find-widget .find-part {
display: flex !important;
flex-direction: column !important;
gap: 4px !important;
}
.editor-widget.find-widget .monaco-findInput {
order: 1 !important;
width: 100% !important;
}
.editor-widget.find-widget .replace-part {
order: 2 !important;
display: flex !important;
flex-direction: column !important;
gap: 4px !important;
}
.editor-widget.find-widget .replace-part .monaco-findInput {
width: 100% !important;
}
.editor-widget.find-widget .controls {
order: 3 !important;
display: flex !important;
gap: 6px !important;
margin-top: 4px !important;
flex-wrap: wrap !important;
}
.editor-widget.find-widget .find-actions {
order: 4 !important;
display: flex !important;
gap: 8px !important;
margin-top: 4px !important;
align-items: center !important;
}
.editor-widget.find-widget .replace-actions {
order: 5 !important;
display: flex !important;
gap: 8px !important;
margin-top: 4px !important;
align-items: center !important;
}
.editor-widget.find-widget .toggle.left {
order: -1 !important;
display: inline-flex !important;
margin-right: 8px !important;
align-self: flex-start !important;
}
.editor-widget.find-widget .matchesCount {
display: inline-block !important;
margin-right: 8px !important;
}
.editor-widget.find-widget .button {
display: inline-flex !important;
}
.editor-widget.find-widget:not(.replaceToggled) .replace-part .monaco-findInput {
display: none !important;
}
.editor-widget.find-widget.replaceToggled .replace-part .monaco-findInput {
display: block !important;
}
.editor-widget.find-widget .replace-actions {
display: flex !important;
gap: 8px !important;
margin-top: 4px !important;
}
.find-actions {
display: flex !important;
align-items: center !important;
gap: 8px !important;
}
.find-actions .codicon-widget-close {
order: 1 !important;
}
.find-actions .codicon-find-replace {
order: 2 !important;
margin-left: 8px !important;
}
.find-actions .codicon-find-replace-all {
order: 3 !important;
}
.replace-actions {
display: none !important;
}
.find-actions .button.disabled {
opacity: 0.5 !important;
pointer-events: none !important;
}
#leftControls {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
overflow-x: auto;
white-space: nowrap;
}
#statusInfo {
display: flex;
align-items: center;
gap: 12px;
font-size: 16px;
color: var(--text-primary);
margin-left: auto;
padding-left: 20px;
font-weight: bold;
}
#currentLine,
#currentColumn,
#charCount {
font-size: 17px;
color: var(--text-primary);
font-weight: bolder;
}
.ace_editor {
width: 100% !important;
height: 100% !important;
}
@media (max-width: 768px) {
#aceEditorContainer {
width: 98%;
margin-top: 40px;
margin-bottom: 0;
}
#editorControls {
width: 100%;
padding: 6px 10px;
flex-wrap: nowrap;
overflow-x: auto;
}
#editorControls select,
#editorControls button {
height: 28px;
font-size: 12px;
padding: 4px 8px;
margin-right: 8px;
min-width: 55px;
}
#statusInfo {
gap: 8px;
font-size: 11px;
flex-shrink: 0;
}
}
.action-grid {
display: grid;
grid-template-columns: repeat(5, 36px);
column-gap: 15px;
overflow: visible;
justify-content: start;
}
.action-btn {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: none;
border-radius: 6px;
transition: background-color 0.2s ease, box-shadow 0.2s ease;
}
.placeholder {
width: 36px;
height: 0;
}
.ace_error_line {
background-color: rgba(255, 0, 0, 0.2) !important;
position: absolute;
z-index: 1;
}
.upload-container {
margin-bottom: 20px;
}
.upload-area {
margin-top: 10px;
}
.upload-drop-zone {
display: flex;
flex-direction: column;
justify-content: center;
align-items: stretch;
border: 2px dashed #ccc !important;
border-radius: 8px;
padding: 25px;
background: #f8f9fa;
transition: all 0.3s ease;
cursor: pointer;
min-height: 150px;
text-align: center;
}
.upload-drop-zone .upload-icon {
align-self: center;
margin-bottom: 1rem;
font-size: 50px;
color: #6c757d;
transition: all 0.3s ease;
}
.upload-drop-zone.drag-over {
background: #e9ecef;
border-color: #0d6efd;
}
.upload-drop-zone:hover .upload-icon {
color: #0d6efd;
transform: scale(1.1);
}
.table td:nth-child(3),
.table td:nth-child(4),
.table td:nth-child(5),
.table td:nth-child(6),
.table td:nth-child(7) {
color: var(--text-primary);
}
.btn-toolbar .btn-group .btn.btn-outline-secondary {
color: var(--text-primary);
border-color: var(--text-primary);
}
.btn-toolbar .btn-group .btn.btn-outline-secondary i {
color: var(--text-primary) !important;
}
.upload-instructions,
.form-text[data-translate],
label.form-label[data-translate] {
color: var(--text-primary) !important;
}
.table th, .table td {
text-align: center !important;
}
.container-sm {
max-width: 100%;
margin: 0 auto;
}
table.table tbody tr:nth-child(odd) td {
color: var(--text-primary) !important;
}
.table tbody tr {
transition: all 0.2s ease;
position: relative;
cursor: pointer;
}
.table tbody tr:hover {
transform: translateY(-2px);
box-shadow: 0 3px 10px rgba(0,0,0,0.1);
z-index: 2;
background-color: rgba(0, 123, 255, 0.05);
}
.table tbody tr:hover td {
color: #007bff;
}
#statusInfo {
display: flex;
align-items: center;
gap: 1.5rem;
}
#lineColumnDisplay,
#charCountDisplay {
color: var(--text-primary);
font-size: 1.1rem;
}
#lineColumnDisplay::before,
#charCountDisplay::before {
font-size: 1.3rem;
}
#lineColumnDisplay .number,
#charCountDisplay .number {
font-size: 1.3rem;
}
table.table tbody tr td.folder-icon,
table.table tbody tr td.file-icon {
text-align: left !important;
}
.section-wrapper {
padding-left: 1rem;
padding-right: 1rem;
}
#siteLogo {
max-height: 50px;
height: auto;
margin-top: -25px;
}
#previewModal .modal-content {
padding: 0;
border: none;
overflow: hidden;
}
#previewModal .modal-header {
border: none;
}
#previewModal .modal-footer {
border: none;
padding: 0.75rem 1rem;
margin: 0;
}
#previewModal .modal-body {
background-color: #000;
padding: 0;
margin: 0;
width: 100%;
display: block;
min-height: 0;
}
#previewModal .modal-body img {
max-width: 100%;
max-height: 80vh;
display: block;
margin: 0 auto;
}
#previewModal .modal-body video {
width: 100%;
height: auto;
max-height: 80vh;
margin: 0;
padding: 0;
border: none;
display: block;
background-color: #000;
}
#previewModal .modal-body audio {
width: 100%;
max-width: 600px;
display: block;
margin: 0 auto;
margin-top: 40px;
margin-bottom: 40px;
}
#previewModal .modal-body p {
text-align: center;
margin: 0;
}
#fileConfirmation .alert {
border: 2px dashed #ccc !important;
padding: 1rem;
border-radius: 0.5rem;
box-shadow: 0 2px 6px rgba(0,0,0,0.08);
background-color: #f8f9fa;
text-align: left;
}
#fileConfirmation #fileList {
max-height: 180px;
overflow-y: auto;
}
#fileConfirmation #fileList span.text-truncate {
width: auto;
overflow: visible;
text-overflow: unset;
white-space: nowrap;
font-weight: 500;
margin-right: 1rem;
}
#fileConfirmation #fileList small.text-muted {
margin-left: auto;
margin-right: 0.5rem;
width: 60px;
text-align: center;
flex-shrink: 0;
}
#fileConfirmation #fileList > div {
display: flex;
align-items: center;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid #e9ecef;
}
#fileConfirmation #fileList i {
margin-right: 0.5rem;
animation: pulse 1s infinite alternate;
}
#fileConfirmation #fileList button {
border: none;
background: transparent;
color: #dc3545;
padding: 0.2rem 0.4rem;
cursor: pointer;
}
#confirmUploadBtn {
width: auto;
padding: 0.375rem 0.75rem;
margin-top: 1rem;
display: inline-block;
}
#fileConfirmation #fileList i {
animation: icon-pulse 1s infinite alternate;
}
@keyframes icon-pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
#fileConfirmation #fileList button i {
animation: x-pulse 1s infinite alternate;
}
@keyframes x-pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
.table td i.folder-icon {
color: #FFA726;
font-size: 1.1em;
}
.table td i.file-icon {
color: #4285F4;
font-size: 1.1em;
}
.table td i.file-icon:hover,
.table td i.folder-icon:hover {
opacity: 0.8;
transform: scale(1.1);
transition: all 0.3s;
}
.table td i.file-icon.fa-file-pdf { color: #FF4136; }
.table td i.file-icon.fa-file-word { color: #2B579A; }
.table td i.file-icon.fa-file-excel { color: #217346; }
.table td i.file-icon.fa-file-powerpoint { color: #D24726; }
.table td i.file-icon.fa-file-archive { color: #795548; }
.table td i.file-icon.fa-file-image { color: #9C27B0; }
.table td i.file-icon.fa-music { color: #673AB7; }
.table td i.file-icon.fa-file-video { color: #E91E63; }
.table td i.file-icon.fa-file-code { color: #607D8B; }
.table td i.file-icon.fa-file-alt { color: #757575; }
.table td i.file-icon.fa-cog { color: #555; }
.table td i.file-icon.fa-file-csv { color: #4CAF50; }
.table td i.file-icon.fa-html5 { color: #E44D26; }
.table td i.file-icon.fa-js { color: #E0A800; }
.table td i.file-icon.fa-terminal { color: #28a745; }
.table td i.file-icon.fa-list-alt { color: #007bff; }
.table td i.file-icon.fa-apple { color: #343a40; }
.table td i.file-icon.fa-android { color: #28a745; }
@media (max-width: 768px) {
#siteLogo {
display: none;
}
.row.mb-3.px-2.mt-5 {
margin-top: 1.5rem !important;
}
.btn i.fas,
.btn i.bi {
font-size: 1.2rem;
}
}
</style>
<div class="container-sm container-bg px-2 px-sm-4 mt-4">
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container-sm container px-4 px-sm-3 px-md-4">
<a class="navbar-brand d-flex align-items-center" href="#">
<?= $iconHtml ?>
<span style="color: var(--accent-color); letter-spacing: 1px;"><?= htmlspecialchars($title) ?></span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<i class="bi bi-list" style="color: var(--accent-color); font-size: 1.8rem;"></i>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0" style="font-size: 18px;">
<li class="nav-item">
<a class="nav-link <?= $current == 'index.php' ? 'active' : '' ?>" href="./index.php"><i class="bi bi-house-door"></i> <span data-translate="home">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo_manager.php' ? 'active' : '' ?>" href="./mihomo_manager.php"><i class="bi bi-folder"></i> <span data-translate="manager">Manager</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'singbox.php' ? 'active' : '' ?>" href="./singbox.php"><i class="bi bi-shop"></i> <span data-translate="template_i">Template I</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'subscription.php' ? 'active' : '' ?>" href="./subscription.php"><i class="bi bi-bank"></i> <span data-translate="template_ii">Template II</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'mihomo.php' ? 'active' : '' ?>" href="./mihomo.php"><i class="bi bi-building"></i> <span data-translate="template_iii">Template III</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'netmon.php' ? 'active' : '' ?>" href="./netmon.php"><i class="bi bi-activity"></i> <span data-translate="traffic_monitor">Traffic Monitor</span></a>
</li>
<li class="nav-item">
<a class="nav-link <?= $current == 'monaco.php' ? 'active' : '' ?>" href="./monaco.php"><i class="bi bi-bank"></i> <span data-translate="pageTitle">File Assistant</span></a>
</li>
</ul>
<div class="d-flex align-items-center">
<div class="me-3 d-block">
<button type="button" class="btn btn-primary icon-btn me-2" onclick="toggleControlPanel()" data-translate-title="control_panel"><i class="bi bi-gear"> </i></button>
<button type="button" class="btn btn-danger icon-btn me-2" data-bs-toggle="modal" data-bs-target="#langModal" data-translate-title="set_language"><i class="bi bi-translate"></i></button>
<button type="button" class="btn btn-success icon-btn me-2" data-bs-toggle="modal" data-bs-target="#musicModal" data-translate-title="music_player"><i class="bi bi-music-note-beamed"></i></button>
<button type="button" id="toggleIpStatusBtn" class="btn btn-warning icon-btn me-2" onclick="toggleIpStatusBar()" data-translate-title="hide_ip_info"><i class="bi bi-eye-slash"> </i></button>
<button type="button" class="btn btn-pink icon-btn me-2" data-bs-toggle="modal" data-bs-target="#portModal" data-translate-title="viewPortInfoButton"><i class="bi bi-plug"></i></button>
<button type="button" class="btn btn-info icon-btn me-2" onclick="document.getElementById('colorPicker').click()" data-translate-title="component_bg_color"><i class="bi bi-palette"></i></button>
<input type="color" id="colorPicker" value="#0f3460" style="display: none;">
</div>
</div>
</div>
</nav>
<div class="row align-items-center mb-4 p-3">
<div class="col-md-3 text-center text-md-start">
<img src="./assets/img/nekobox.png" id="siteLogo" alt="Neko Box" class="img-fluid" style="max-height: 100px;">
</div>
<div class="col-md-6 text-center">
<h2 class="mb-0" id="pageTitle" data-translate="pageTitle">File Assistant</h2>
</div>
<div class="col-md-3"></div>
</div>
<div class="row mb-3 px-2 mt-5">
<div class="col-12">
<div class="btn-toolbar justify-content-between">
<div class="btn-group">
<button type="button" class="btn btn-outline-secondary" onclick="goToParentDirectory()" title="Go Back" data-translate-title="goToParentDirectoryTitle">
<i class="fas fa-arrow-left"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="location.href='?dir=/'" title="Return to Root Directory" data-translate-title="rootDirectoryTitle">
<i class="fas fa-home"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="location.href='?dir=/root'" title="Return to Home Directory" data-translate-title="homeDirectoryTitle">
<i class="fas fa-user"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="location.reload()" title="Refresh Directory Content" data-translate-title="refreshDirectoryTitle">
<i class="fas fa-sync-alt"></i>
</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#searchModal" id="searchBtn" title="Search" data-translate-title="searchTitle">
<i class="fas fa-search"></i>
</button>
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#createModal" id="createBtn" title="Create New" data-translate-title="createTitle">
<i class="fas fa-plus"></i>
</button>
<button type="button" class="btn btn-outline-secondary" onclick="showUploadArea()" id="uploadBtn" title="Upload" data-translate-title="uploadTitle">
<i class="fas fa-upload"></i>
</button>
</div>
</div>
</div>
</div>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="?dir=">root</a></li>
<?php
$path = '';
$breadcrumbs = explode('/', trim($current_dir, '/'));
foreach ($breadcrumbs as $crumb) {
if (!empty($crumb)) {
$path .= '/' . $crumb;
echo '<li class="breadcrumb-item"><a href="?dir=' . urlencode($path) . '">' . htmlspecialchars($crumb) . '</a></li>';
}
}
?>
</ol>
</nav>
<div class="section-wrapper">
<div class="upload-container">
<div class="upload-area" id="uploadArea" style="display: none;">
<div class="d-flex justify-content-between align-items-center mb-2">
<p class="upload-instructions mb-0">
<span data-translate="dragHint">Drag files here or click to select files to upload</span>
</p>
<button type="button" class="btn btn-secondary btn-sm ms-2" onclick="event.stopPropagation(); hideUploadArea()" data-translate="cancel">Cancel</button>
</div>
<input type="file" name="upload[]" id="fileInput" style="display: none;" multiple>
<div class="upload-drop-zone p-4 border rounded bg-light" id="dropZone">
<i class="fas fa-cloud-upload-alt upload-icon"></i>
<div id="fileConfirmation" class="mt-3" style="display: none;">
<div class="alert alert-light border text-center">
<div id="fileList" style="max-height: 120px; overflow-y: auto;"></div>
<button id="confirmUploadBtn"
class="btn btn-primary mt-2"
onclick="event.stopPropagation();">
<i class="fas fa-upload me-1"></i>
<span data-translate="uploadBtn">Confirm Upload</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="section-wrapper">
<div class="alert alert-secondary d-none mb-3" id="toolbar">
<div class="d-flex justify-content-between flex-column flex-sm-row align-items-center">
<div class="mb-2 mb-sm-0">
<button class="btn btn-outline-primary btn-sm me-2" id="selectAllBtn" data-translate="select_all">Deselect All</button>
<span id="selectedInfo" class="text-muted small" data-translate="selected_info">{0} item(s) selected</span>
</div>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/lib/down.php | luci-app-nekobox/htdocs/nekobox/lib/down.php | <?php
$stat = shell_exec("uci get neko.cfg.enabled");
if($stat==1) $tmp = shell_exec("cat /sys/class/net/Meta/statistics/rx_bytes");
else $tmp = "0";
$data = "";
if ($tmp < 1024000) $data = number_format(($tmp/1024),1)." KB";
elseif ($tmp > 1024000 && $tmp < 1024000000) $data = number_format(($tmp/1024000),1)." MB";
elseif ($tmp > 1024000000) $data = number_format(($tmp/1024000000),2)." GB";
echo $data;
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/lib/up.php | luci-app-nekobox/htdocs/nekobox/lib/up.php | <?php
$stat = shell_exec("uci get neko.cfg.enabled");
if($stat==1) $tmp = shell_exec("cat /sys/class/net/Meta/statistics/tx_bytes");
else $tmp = "0";
$data = "";
if ($tmp < 1024000) $data = number_format(($tmp/1024),1)." KB";
elseif ($tmp > 1024000 && $tmp < 1024000000) $data = number_format(($tmp/1024000),1)." MB";
elseif ($tmp > 1024000000) $data = number_format(($tmp/1024000000),2)." GB";
echo $data;
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-app-nekobox/htdocs/nekobox/lib/log.php | luci-app-nekobox/htdocs/nekobox/lib/log.php | <?php
include '../cfg.php';
$neko_log_path="$neko_dir/tmp/log.txt";
$neko_bin_log_path="$neko_dir/tmp/neko_log.txt";
$host_now=$_SERVER['SERVER_NAME'];
if(isset($_GET['data'])){
$dt = $_GET['data'];
if ($dt == 'neko') echo shell_exec("cat $neko_log_path");
else if($dt == 'bin') echo shell_exec("cat $neko_bin_log_path | awk -F'[\"T.= ]' '{print \"[ \" $4 \" ] \" toupper($8) \" :\", substr($0,index($0,$11))}' | sed 's/.$//'");
else if($dt == 'neko_ver') echo exec("$neko_dir/core/neko -v");
else if($dt == 'core_ver') echo exec("$neko_bin -v | head -1 | awk '{print $5 \" \" $3}'");
else if($dt == 'url_dash'){
header("Content-type: application/json; charset=utf-8");
$yacd = exec (" curl -m 5 -f -s $host_now/nekobox/panel.php | grep 'href=\"h' | cut -d '\"' -f6 | head -1");
$zash = exec (" curl -m 5 -f -s $host_now/nekobox/panel.php | grep 'href=\"h' | cut -d '\"' -f6 | tail -1");
echo "{\n";
echo " \"yacd\":\"$yacd\",\n";
echo " \"zash\":\"$zash\"\n";
echo "}";
}
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/save_language.php | luci-theme-spectra/root/www/spectra/save_language.php | <?php
header('Content-Type: application/json');
$language_file = __DIR__ . '/lib/language.txt';
if (!file_exists($language_file)) {
file_put_contents($language_file, '');
}
if ($_POST['action'] == 'save_language') {
$language = $_POST['language'];
if (!empty($language)) {
file_put_contents($language_file, $language);
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => false]);
}
} elseif ($_POST['action'] == 'get_language') {
if (file_exists($language_file)) {
$current_language = trim(file_get_contents($language_file));
echo json_encode(['success' => true, 'language' => $current_language]);
} else {
echo json_encode(['success' => false]);
}
} else {
echo json_encode(['success' => false]);
}
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/save_ip_cache.php | luci-theme-spectra/root/www/spectra/save_ip_cache.php | <?php
header('Content-Type: application/json');
$cacheFile = __DIR__ . '/lib/ip_cache.json';
$input = file_get_contents('php://input');
if (!$input) {
echo json_encode(['status'=>'error','message'=>'No input data']);
exit;
}
$data = json_decode($input, true);
if (!$data) {
echo json_encode(['status'=>'error','message'=>'Invalid JSON']);
exit;
}
if (isset($data['ip'])) $data = [$data];
$cache = [];
if (file_exists($cacheFile)) {
$content = file_get_contents($cacheFile);
$cache = json_decode($content, true) ?: [];
}
$ipIndex = [];
foreach ($cache as $item) {
if (isset($item['ip'])) $ipIndex[$item['ip']] = $item;
}
foreach ($data as $item) {
if (!isset($item['ip'])) continue;
$ip = $item['ip'];
if (!isset($ipIndex[$ip])) {
$ipIndex[$ip] = [];
}
$ipIndex[$ip]['ip'] = $ip;
$ipIndex[$ip]['country'] = $item['country'] ?? $ipIndex[$ip]['country'] ?? '';
$ipIndex[$ip]['region'] = $item['region'] ?? $ipIndex[$ip]['region'] ?? '';
$ipIndex[$ip]['city'] = $item['city'] ?? $ipIndex[$ip]['city'] ?? '';
$ipIndex[$ip]['isp'] = $item['isp'] ?? $ipIndex[$ip]['isp'] ?? '';
$ipIndex[$ip]['asn'] = $item['asn'] ?? $ipIndex[$ip]['asn'] ?? '';
$ipIndex[$ip]['asn_organization'] = $item['asn_organization'] ?? $ipIndex[$ip]['asn_organization'] ?? '';
$ipIndex[$ip]['country_code'] = $item['country_code'] ?? $ipIndex[$ip]['country_code'] ?? '';
$ipIndex[$ip]['timezone'] = $item['timezone'] ?? $ipIndex[$ip]['timezone'] ?? '';
$ipIndex[$ip]['latitude'] = $item['latitude'] ?? $ipIndex[$ip]['latitude'] ?? '';
$ipIndex[$ip]['longitude'] = $item['longitude'] ?? $ipIndex[$ip]['longitude'] ?? '';
$language = $item['language'] ?? 'zh-CN';
if (!isset($ipIndex[$ip]['translations'])) {
$ipIndex[$ip]['translations'] = [];
}
$ipIndex[$ip]['translations'][$language] = [
'translatedCountry' => $item['translatedCountry'] ?? '',
'translatedRegion' => $item['translatedRegion'] ?? '',
'translatedCity' => $item['translatedCity'] ?? '',
'translatedISP' => $item['translatedISP'] ?? '',
'translatedASNOrg' => $item['translatedASNOrg'] ?? ''
];
$ipIndex[$ip]['default_language'] = $language;
$ipIndex[$ip]['last_updated'] = date('Y-m-d H:i:s');
}
$cache = array_values($ipIndex);
if (count($cache) > 500) {
$cache = array_slice($cache, -500);
}
$tempFile = $cacheFile . '.tmp';
file_put_contents($tempFile, json_encode($cache, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
rename($tempFile, $cacheFile);
echo json_encode(['status'=>'ok','message'=>'Cache saved','count'=>count($cache)]);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/order_handler.php | luci-theme-spectra/root/www/spectra/order_handler.php | <?php
$history_file = __DIR__ . '/lib/background_history.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
if (!empty($data['order']) && is_array($data['order'])) {
$new_order = array_unique($data['order']);
$dir = dirname($history_file);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents($history_file, implode("\n", $new_order));
echo "OK";
} else {
http_response_code(400);
echo "Invalid data";
}
} | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/artist_proxy.php | luci-theme-spectra/root/www/spectra/artist_proxy.php | <?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
$input = json_decode(file_get_contents('php://input'), true);
$artist = $input['artist'] ?? '';
$title = $input['title'] ?? '';
$preferredSource = $input['source'] ?? 'auto';
function fetchWithCurl($url, $headers = []) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
]);
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("CURL Error for $url: $error");
}
return [$result, $httpCode];
}
function optimizeImageUrl($url, $source) {
if (!$url) return $url;
switch ($source) {
case 'netease':
if (strpos($url, '?param=') !== false) {
$url = preg_replace('/\?param=\d+y\d+/', '?param=2000y2000', $url);
} else {
$url .= '?param=2000y2000';
}
break;
case 'itunes':
$url = str_replace(['100x100bb', '60x60bb', '30x30bb'], '2000x2000bb', $url);
break;
case 'deezer':
$url = str_replace(['cover_big', 'cover_medium', 'cover_small'], 'cover_xl', $url);
break;
}
return $url;
}
function fetchNeteaseImage($artist, $title) {
if (!empty($title)) {
$searchUrl = "https://music.163.com/api/search/get?s=" . urlencode($artist . ' ' . $title) . "&type=1&limit=1";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['result']['songs'][0]['album']['picUrl'])) {
$imageUrl = $data['result']['songs'][0]['album']['picUrl'];
return optimizeImageUrl($imageUrl, 'netease');
}
}
}
$searchUrl = "https://music.163.com/api/search/get?s=" . urlencode($artist) . "&type=100&limit=1";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['result']['artists'][0]['img1v1Url'])) {
$imageUrl = $data['result']['artists'][0]['img1v1Url'];
return optimizeImageUrl($imageUrl, 'netease');
}
}
return null;
}
function fetchItunesImage($artist, $title) {
$searchUrl = "https://itunes.apple.com/search?term=" . urlencode($artist . ' ' . $title) . "&entity=song&limit=5";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['results'][0]['artworkUrl100'])) {
return optimizeImageUrl($data['results'][0]['artworkUrl100'], 'itunes');
}
}
return null;
}
function fetchDeezerImage($artist, $title) {
if (!empty($title)) {
$searchUrl = "https://api.deezer.com/search?q=" . urlencode("artist:\"$artist\" track:\"$title\"") . "&limit=3";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['data'][0]['album']['cover_xl'])) {
return optimizeImageUrl($data['data'][0]['album']['cover_xl'], 'deezer');
}
}
}
$searchUrl = "https://api.deezer.com/search?q=" . urlencode("artist:\"$artist\"") . "&limit=1";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['data'][0]['artist']['picture_xl'])) {
return $data['data'][0]['artist']['picture_xl'];
}
}
return null;
}
function fetchLastfmImage($artist, $title) {
$apiKey = 'a496648b2d382af443aaaadf7f7f6895';
if (!empty($title)) {
$url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=" . urlencode($artist) .
"&track=" . urlencode($title) . "&api_key={$apiKey}&format=json&autocorrect=1";
list($result, $httpCode) = fetchWithCurl($url);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['track']['album']['image'])) {
$images = $data['track']['album']['image'];
if (!empty($images)) {
$largest = end($images);
if (!empty($largest['#text'])) {
return $largest['#text'];
}
}
}
}
}
$url = "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=" . urlencode($artist) .
"&api_key={$apiKey}&format=json&autocorrect=1";
list($result, $httpCode) = fetchWithCurl($url);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['artist']['image'])) {
$images = $data['artist']['image'];
if (!empty($images)) {
$largest = end($images);
if (!empty($largest['#text'])) {
return $largest['#text'];
}
}
}
}
return null;
}
$response = ['success' => false, 'message' => 'No high-quality image found'];
if (!empty($artist)) {
$imageUrl = null;
$source = '';
$sources = [
'itunes' => fn() => fetchItunesImage($artist, $title),
'netease' => fn() => fetchNeteaseImage($artist, $title),
'deezer' => fn() => fetchDeezerImage($artist, $title),
'lastfm' => fn() => fetchLastfmImage($artist, $title),
];
if ($preferredSource === 'auto') {
foreach ($sources as $name => $fetcher) {
$imageUrl = $fetcher();
if ($imageUrl) {
$source = $name;
break;
}
}
} else {
if (isset($sources[$preferredSource])) {
$imageUrl = $sources[$preferredSource]();
$source = $preferredSource;
}
if (!$imageUrl) {
foreach ($sources as $name => $fetcher) {
if ($name === $preferredSource) continue;
$imageUrl = $fetcher();
if ($imageUrl) {
$source = $name;
break;
}
}
}
}
if ($imageUrl) {
$response = [
'success' => true,
'imageUrl' => $imageUrl,
'source' => $source,
'artist' => $artist,
'title' => $title
];
}
}
echo json_encode($response);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/update_php_config.php | luci-theme-spectra/root/www/spectra/update_php_config.php | <?php
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$configFile = "/etc/php.ini";
$configChanges = [
'upload_max_filesize' => '2048M',
'post_max_size' => '2048M',
'max_file_uploads' => '100',
'memory_limit' => '2048M',
'max_execution_time' => '3600',
'max_input_time' => '3600'
];
$configData = file_get_contents($configFile);
foreach ($configChanges as $key => $value) {
$configData = preg_replace("/^$key\s*=\s*.*/m", "$key = $value", $configData);
}
if (file_put_contents($configFile, $configData) !== false) {
shell_exec("/etc/init.d/uhttpd restart > /dev/null 2>&1 &");
shell_exec("/etc/init.d/nginx restart > /dev/null 2>&1 &");
echo json_encode(["status" => "success", "message" => "PHP configuration updated and restarted successfully"]);
} else {
echo json_encode(["status" => "error", "message" => "Update failed, please check permissions!"]);
}
} else {
echo json_encode(["status" => "error", "message" => "Invalid request"]);
}
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/check_theme_update.php | luci-theme-spectra/root/www/spectra/check_theme_update.php | <?php
$repoOwner = 'Thaolga';
$repoName = 'openwrt-nekobox';
$releaseTag = '1.8.8';
$packagePattern = '/^luci-theme-spectra_(.+)_all\.ipk$/';
$latestVersion = null;
$downloadUrl = null;
$currentInstalledVersion = null;
$needsUpdate = false;
function extractMainVersion($version) {
$cleanVersion = explode('~', $version)[0];
$parts = explode('.', $cleanVersion);
if (isset($parts[0], $parts[1])) {
return $parts[0] . '.' . $parts[1];
}
return $cleanVersion;
}
try {
$installedPackages = shell_exec("opkg list-installed luci-theme-spectra 2>/dev/null");
if ($installedPackages) {
preg_match('/luci-theme-spectra\s+-\s+([0-9\.~a-zA-Z0-9]+)/', $installedPackages, $matches);
if (isset($matches[1])) {
$currentInstalledVersion = $matches[1];
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/{$repoOwner}/{$repoName}/releases/tags/{$releaseTag}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode === 200) {
$releaseData = json_decode($response, true);
if (isset($releaseData['assets']) && is_array($releaseData['assets'])) {
foreach ($releaseData['assets'] as $asset) {
if (preg_match($packagePattern, $asset['name'], $matches)) {
$latestVersion = preg_replace('/\.([^.]+)$/', '~$1', $matches[1]);
$downloadUrl = isset($asset['browser_download_url']) ? $asset['browser_download_url'] : null;
if ($currentInstalledVersion && $latestVersion) {
$currentMain = extractMainVersion($currentInstalledVersion);
$latestMain = extractMainVersion($latestVersion);
if (version_compare($latestMain, $currentMain, '>')) {
$needsUpdate = true;
}
}
break;
}
}
}
}
curl_close($ch);
} catch (Exception $e) {
//error_log("Theme update check error: " . $e->getMessage());
}
echo json_encode([
'currentVersion' => $currentInstalledVersion,
'version' => $latestVersion,
'url' => $downloadUrl,
'needsUpdate' => $needsUpdate
]);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/manage_tokens.php | luci-theme-spectra/root/www/spectra/manage_tokens.php | <?php
header('Content-Type: application/json');
$action = $_GET['action'] ?? '';
$sharesDir = __DIR__ . '/shares/';
$now = time();
$deleted = 0;
if (!is_dir($sharesDir)) {
echo json_encode(['success' => false, 'message' => 'Shares directory does not exist']);
exit;
}
foreach (glob($sharesDir . '*.json') as $file) {
$remove = false;
if ($action === 'clean') {
$data = json_decode(file_get_contents($file), true);
if (!$data) continue;
$expired = $now > ($data['expire'] ?? 0);
$exceeded = ($data['max_downloads'] ?? 0) > 0 && ($data['download_count'] ?? 0) >= $data['max_downloads'];
$remove = $expired || $exceeded;
} elseif ($action === 'delete_all') {
$remove = true;
}
if ($remove && unlink($file)) {
$deleted++;
}
}
echo json_encode(['success' => true, 'deleted' => $deleted]);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/lyrics_proxy.php | luci-theme-spectra/root/www/spectra/lyrics_proxy.php | <?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
$input = json_decode(file_get_contents('php://input'), true);
$source = $input['source'] ?? '';
$artist = $input['artist'] ?? '';
$title = $input['title'] ?? '';
$songName = $input['songName'] ?? '';
function fetchWithCurl($url, $headers = []) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
]);
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("CURL Error for $url: $error");
}
return [$result, $httpCode];
}
function fetchNeteaseLyrics($artist, $title, $songName) {
$searchKeywords = [];
if ($artist && $title) {
$searchKeywords[] = $artist . ' ' . $title;
}
if ($title) {
$searchKeywords[] = $title;
}
if ($songName && $songName !== $title) {
$searchKeywords[] = $songName;
}
foreach ($searchKeywords as $keyword) {
$searchUrl = "https://music.163.com/api/search/get?s=" . urlencode($keyword) . "&type=1&limit=3";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['result']['songs']) && count($data['result']['songs']) > 0) {
$songId = $data['result']['songs'][0]['id'];
$lyricUrl = "https://music.163.com/api/song/lyric?lv=-1&kv=-1&tv=-1&id=" . $songId;
list($lyricResult, $lyricCode) = fetchWithCurl($lyricUrl);
if ($lyricCode === 200 && $lyricResult) {
$lyricData = json_decode($lyricResult, true);
if (isset($lyricData['lrc']['lyric']) && !empty(trim($lyricData['lrc']['lyric']))) {
return [
'lyrics' => $lyricData['lrc']['lyric'],
'hasTimestamps' => true,
'source' => 'netease',
'keyword' => $keyword
];
}
}
}
}
}
return null;
}
function fetchKugouLyrics($artist, $title, $songName) {
$searchKeywords = [];
if ($artist && $title) {
$searchKeywords[] = $artist . ' ' . $title;
}
if ($title) {
$searchKeywords[] = $title;
}
foreach ($searchKeywords as $keyword) {
$searchUrl = "http://lyrics.kugou.com/search?ver=1&man=yes&client=pc&keyword=" . urlencode($keyword) . "&duration=&hash=";
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (isset($data['candidates']) && count($data['candidates']) > 0) {
$candidate = $data['candidates'][0];
$lyricUrl = "http://lyrics.kugou.com/download?ver=1&client=pc&id=" . $candidate['id'] . "&accesskey=" . $candidate['accesskey'] . "&fmt=lrc&charset=utf8";
list($lyricResult, $lyricCode) = fetchWithCurl($lyricUrl);
if ($lyricCode === 200 && $lyricResult) {
$lyricData = json_decode($lyricResult, true);
if (isset($lyricData['content']) && !empty(trim($lyricData['content']))) {
$lyrics = base64_decode($lyricData['content']);
return [
'lyrics' => $lyrics,
'hasTimestamps' => true,
'source' => 'kugou',
'keyword' => $keyword
];
}
}
}
}
}
return null;
}
function fetchLRCLibLyrics($artist, $title, $songName) {
if (!$title) return null;
$searchQuery = $title;
if ($artist) {
$searchQuery = $artist . ' ' . $title;
}
$searchUrl = "https://lrclib.net/api/search?q=" . urlencode($searchQuery);
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
if (is_array($data) && count($data) > 0) {
$songData = $data[0];
if (isset($songData['syncedLyrics']) && !empty(trim($songData['syncedLyrics']))) {
return [
'lyrics' => $songData['syncedLyrics'],
'hasTimestamps' => true,
'source' => 'lrclib'
];
} elseif (isset($songData['plainLyrics']) && !empty(trim($songData['plainLyrics']))) {
return [
'lyrics' => $songData['plainLyrics'],
'hasTimestamps' => false,
'source' => 'lrclib'
];
}
}
}
return null;
}
$response = ['success' => false, 'message' => 'No lyrics found'];
if (!empty($artist) || !empty($title) || !empty($songName)) {
$lyricsData = null;
$finalSource = '';
$sources = [
'lrclib' => fn() => fetchLRCLibLyrics($artist, $title, $songName),
'netease' => fn() => fetchNeteaseLyrics($artist, $title, $songName),
'kugou' => fn() => fetchKugouLyrics($artist, $title, $songName),
];
if ($source === 'auto') {
foreach ($sources as $name => $fetcher) {
$lyricsData = $fetcher();
if ($lyricsData) {
$finalSource = $name;
break;
}
}
} else {
if (isset($sources[$source])) {
$lyricsData = $sources[$source]();
$finalSource = $source;
}
}
if ($lyricsData) {
$response = [
'success' => true,
'lyrics' => $lyricsData['lyrics'],
'hasTimestamps' => $lyricsData['hasTimestamps'],
'source' => $finalSource,
'artist' => $artist,
'title' => $title,
'songName' => $songName
];
} else {
$response = ['success' => false, 'message' => 'No lyrics found from selected source'];
}
}
echo json_encode($response);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/theme-switcher.php | luci-theme-spectra/root/www/spectra/theme-switcher.php | <?php
$configFileSpectra = "/etc/config/spectra";
$configFileArgon = "/etc/config/argon";
function toggleModeInFile($configFile) {
if (!file_exists($configFile)) {
return ["error" => "Config file not found!"];
}
$content = file_get_contents($configFile);
preg_match("/option mode '(\w+)'/", $content, $matches);
$currentMode = $matches[1] ?? "dark";
$newMode = ($currentMode === "dark") ? "light" : "dark";
$updatedContent = preg_replace("/option mode '\w+'/", "option mode '$newMode'", $content);
if (file_put_contents($configFile, $updatedContent) !== false) {
return $newMode;
} else {
return false;
}
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$spectraMode = toggleModeInFile($configFileSpectra);
if ($spectraMode !== false) {
file_put_contents($configFileArgon, str_replace("option mode '$spectraMode'", "option mode '$spectraMode'", file_get_contents($configFileSpectra)));
echo json_encode(["success" => true, "mode" => $spectraMode]);
} else {
echo json_encode(["error" => "Failed to update spectra config!"]);
}
exit;
}
if ($_SERVER["REQUEST_METHOD"] === "GET") {
if (!file_exists($configFileSpectra)) {
echo json_encode(["mode" => "dark"]);
} else {
$content = file_get_contents($configFileSpectra);
preg_match("/option mode '(\w+)'/", $content, $matches);
$mode = $matches[1] ?? "dark";
echo json_encode(["mode" => $mode]);
}
exit;
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/file-checker.php | luci-theme-spectra/root/www/spectra/file-checker.php | <?php
header('Content-Type: application/json');
$file = $_GET['file'] ?? '';
if (empty($file)) {
echo json_encode(['exists' => false]);
exit;
}
if (strpos($file, '..') !== false || strpos($file, '/') !== false) {
echo json_encode(['exists' => false]);
exit;
}
$baseDir = __DIR__ . '/stream';
$filePath = $baseDir . '/' . $file;
if (!file_exists($baseDir)) {
mkdir($baseDir, 0755, true);
}
$exists = file_exists($filePath);
echo json_encode(['exists' => $exists]);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/weather_translation.php | luci-theme-spectra/root/www/spectra/weather_translation.php | <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');
$cacheFile = __DIR__ . '/lib/weather_translation_cache.json';
// $debugFile = __DIR__ . '/weather_translation_debug.log';
function dbg($msg) {
// global $debugFile;
// @file_put_contents($debugFile, date('c') . " " . $msg . PHP_EOL, FILE_APPEND);
}
$raw = file_get_contents('php://input');
// dbg("RECV: " . $raw);
$cacheData = ["cities" => []];
if (file_exists($cacheFile)) {
$content = @file_get_contents($cacheFile);
$decoded = @json_decode($content, true);
if (is_array($decoded)) {
$cacheData = $decoded;
} else {
// dbg("WARN: invalid JSON in cache file, resetting");
}
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_GET['action']) && $_GET['action'] === 'clear') {
$cacheData = ["cities" => []];
$json = json_encode($cacheData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$tmp = $cacheFile . '.tmp';
@file_put_contents($tmp, $json);
@rename($tmp, $cacheFile);
@chmod($cacheFile, 0666);
// dbg("ACTION: cleared all cache data");
echo json_encode(['status' => 'cache cleared'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
echo json_encode($cacheData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = @json_decode($raw, true);
if ($data === null) {
$err = json_last_error_msg();
// dbg("ERR: invalid JSON payload: " . $err);
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON payload: '.$err]);
exit;
}
if (isset($data['cities']) && is_array($data['cities'])) {
$cacheData['cities'] = $data['cities'];
// dbg("ACTION: replaced entire cities");
}
elseif (isset($data['city']) && isset($data['translations']) && is_array($data['translations'])) {
$city = trim($data['city']);
$translations = $data['translations'];
if (!isset($cacheData['cities'][$city])) {
$cacheData['cities'][$city] = ['translations' => [], 'updated' => null];
}
foreach ($translations as $lang => $langVal) {
$existingLang = $cacheData['cities'][$city]['translations'][$lang] ?? [];
if (is_string($langVal)) {
$newLang = array_replace_recursive($existingLang, ['city' => $langVal]);
} elseif (is_array($langVal)) {
$newLang = array_replace_recursive($existingLang, $langVal);
} else {
continue;
}
$cacheData['cities'][$city]['translations'][$lang] = $newLang;
}
if (isset($data['temp'])) {
$cacheData['cities'][$city]['temp'] = $data['temp'];
}
if (isset($data['icon'])) {
foreach ($translations as $lang => $_) {
$cacheData['cities'][$city]['translations'][$lang]['lastIcon'] = $data['icon'];
}
}
$cacheData['cities'][$city]['updated'] = date('c');
// dbg("ACTION: merged translations for city={$city}");
}
elseif (isset($data['key']) && isset($data['lang']) && isset($data['text'])) {
$key = trim($data['key']);
$lang = trim($data['lang']);
$text = $data['text'];
if (!isset($cacheData['cities'][$key])) {
$cacheData['cities'][$key] = ['translations' => [], 'updated' => null];
}
$cacheData['cities'][$key]['translations'][$lang] = array_replace_recursive(
$cacheData['cities'][$key]['translations'][$lang] ?? [],
['city' => $text]
);
$cacheData['cities'][$key]['updated'] = date('c');
// dbg("ACTION: set single translation for key={$key} lang={$lang}");
} else {
// dbg("ERR: unrecognized POST shape");
http_response_code(400);
echo json_encode(['error' => 'Invalid input shape']);
exit;
}
$json = json_encode($cacheData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$tmp = $cacheFile . '.tmp';
@file_put_contents($tmp, $json);
@rename($tmp, $cacheFile);
@chmod($cacheFile, 0666);
// dbg("OK: wrote cache {$cacheFile}");
echo json_encode(['status' => 'ok'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/filekit.php | luci-theme-spectra/root/www/spectra/filekit.php | <?php
ini_set('memory_limit', '256M');
$timezone = trim(shell_exec("uci get system.@system[0].zonename 2>/dev/null"));
date_default_timezone_set($timezone ?: 'UTC');
ob_start();
$root_dir = "/";
$current_dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$current_dir = '/' . trim($current_dir, '/') . '/';
if ($current_dir == '//') $current_dir = '/';
$current_path = $root_dir . ltrim($current_dir, '/');
if (strpos(realpath($current_path), realpath($root_dir)) !== 0) {
$current_dir = '/';
$current_path = $root_dir;
}
if (isset($_GET['preview']) && isset($_GET['path'])) {
$path = preg_replace('/\/+/', '/', $_GET['path']);
$preview_path = realpath($root_dir . '/' . $path);
if ($preview_path && strpos($preview_path, realpath($root_dir)) === 0) {
if (!file_exists($preview_path)) {
header('HTTP/1.0 404 Not Found');
echo "File not found.";
exit;
}
$ext = strtolower(pathinfo($preview_path, PATHINFO_EXTENSION));
$mime_types = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'svg' => 'image/svg+xml',
'bmp' => 'image/bmp',
'webp' => 'image/webp',
'mp3' => 'audio/mpeg',
'wav' => 'audio/wav',
'ogg' => 'audio/ogg',
'flac' => 'audio/flac',
'mp4' => 'video/mp4',
'webm' => 'video/webm',
'avi' => 'video/x-msvideo',
'mkv' => 'video/x-matroska'
];
$mime_type = isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream';
header('Content-Type: ' . $mime_type);
header('Content-Length: ' . filesize($preview_path));
readfile($preview_path);
exit;
} else {
header('HTTP/1.0 404 Not Found');
echo "Invalid path.";
exit;
}
}
if (isset($_GET['action']) && $_GET['action'] === 'refresh') {
$contents = getDirectoryContents($current_path);
echo json_encode($contents);
exit;
}
if (isset($_POST['action']) && $_POST['action'] === 'delete_selected') {
if (isset($_POST['selected_paths']) && is_array($_POST['selected_paths'])) {
foreach ($_POST['selected_paths'] as $path) {
deleteItem($current_path . $path);
}
header("Location: ?dir=" . urlencode($current_dir));
exit;
}
}
function readFileUtf8($path) {
$content = file_get_contents($path);
if ($content === false) return '';
if (preg_match('//u', $content)) {
return $content;
}
$encodings = ['GBK', 'GB2312', 'BIG5', 'ISO-8859-1'];
foreach ($encodings as $enc) {
$converted = @iconv($enc, 'UTF-8//IGNORE', $content);
if ($converted !== false && preg_match('//u', $converted)) {
return $converted;
}
}
return $content;
}
if (isset($_GET['action']) && $_GET['action'] === 'get_content' && isset($_GET['path'])) {
$file_path = $current_path . $_GET['path'];
if (file_exists($file_path) && is_readable($file_path)) {
$content = readFileUtf8($file_path);
header('Content-Type: text/plain; charset=utf-8');
echo $content;
exit;
} else {
http_response_code(404);
echo 'File does not exist or is not readable.';
exit;
}
}
if (isset($_GET['download'])) {
downloadFile($current_path . $_GET['download']);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'rename':
$new_name = basename($_POST['new_path']);
$old_path = $current_path . $_POST['old_path'];
$new_path = dirname($old_path) . '/' . $new_name;
renameItem($old_path, $new_path);
break;
case 'edit':
$content = $_POST['content'];
$encoding = $_POST['encoding'];
$result = editFile($current_path . $_POST['path'], $content, $encoding);
if (!$result) {
echo "<script>alert('Error: Unable to save the file.');</script>";
}
break;
case 'delete':
deleteItem($current_path . $_POST['path']);
break;
case 'chmod':
chmodItem($current_path . $_POST['path'], $_POST['permissions']);
break;
case 'create_folder':
$new_folder_name = $_POST['new_folder_name'];
$new_folder_path = $current_path . '/' . $new_folder_name;
if (!file_exists($new_folder_path)) {
mkdir($new_folder_path);
}
break;
case 'create_file':
$new_file_name = $_POST['new_file_name'];
$new_file_path = $current_path . '/' . $new_file_name;
if (!file_exists($new_file_path)) {
file_put_contents($new_file_path, '');
chmod($new_file_path, 0644);
}
break;
}
} elseif (isset($_FILES['upload'])) {
uploadFile($current_path);
}
}
function deleteItem($path) {
$path = rtrim(str_replace('//', '/', $path), '/');
if (!file_exists($path)) {
error_log("Attempted to delete non-existent item: $path");
return false;
}
if (is_dir($path)) {
return deleteDirectory($path);
} else {
if (@unlink($path)) {
return true;
} else {
error_log("Failed to delete file: $path");
return false;
}
}
}
function deleteDirectory($dir) {
if (!is_dir($dir)) {
return false;
}
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
$path = $dir . '/' . $file;
is_dir($path) ? deleteDirectory($path) : @unlink($path);
}
return @rmdir($dir);
}
function renameItem($old_path, $new_path) {
$old_path = rtrim(str_replace('//', '/', $old_path), '/');
$new_path = rtrim(str_replace('//', '/', $new_path), '/');
$new_name = basename($new_path);
$dir = dirname($old_path);
$new_full_path = $dir . '/' . $new_name;
if (!file_exists($old_path)) {
error_log("Source file does not exist before rename: $old_path");
if (file_exists($new_full_path)) {
error_log("But new file already exists: $new_full_path. Rename might have succeeded.");
return true;
}
return false;
}
$result = rename($old_path, $new_full_path);
if (!$result) {
error_log("Rename function returned false for: $old_path to $new_full_path");
if (file_exists($new_full_path) && !file_exists($old_path)) {
error_log("However, new file exists and old file doesn't. Consider rename successful.");
return true;
}
}
if (file_exists($new_full_path)) {
error_log("New file exists after rename: $new_full_path");
} else {
error_log("New file does not exist after rename attempt: $new_full_path");
}
if (file_exists($old_path)) {
error_log("Old file still exists after rename attempt: $old_path");
} else {
error_log("Old file no longer exists after rename attempt: $old_path");
}
return $result;
}
function editFile($path, $content, $encoding) {
if (!is_writable($path)) return false;
if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
$content = substr($content, 3);
}
if (!preg_match('//u', $content)) {
$content = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
}
return file_put_contents($path, $content, LOCK_EX) !== false;
}
function chmodItem($path, $permissions) {
chmod($path, octdec($permissions));
}
function uploadFile($destination) {
$uploaded_files = [];
$errors = [];
if (!is_dir($destination)) {
@mkdir($destination, 0755, true);
}
if (!empty($_FILES["upload"])) {
foreach ($_FILES["upload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["upload"]["tmp_name"][$key];
$name = basename($_FILES["upload"]["name"][$key]);
$target_file = rtrim($destination, '/') . '/' . $name;
if (move_uploaded_file($tmp_name, $target_file)) {
$uploaded_files[] = $name;
chmod($target_file, 0644);
} else {
$errors[] = "Failed to upload $name.";
}
} else {
$errors[] = "Upload error for file $key: " . getUploadError($error);
}
}
}
if (!empty($errors)) {
return ['error' => implode("\n", $errors)];
}
if (!empty($uploaded_files)) {
return ['success' => implode(", ", $uploaded_files)];
}
return ['error' => 'No files were uploaded'];
}
if (!function_exists('deleteDirectory')) {
function deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) return false;
}
return rmdir($dir);
}
}
function downloadFile($file) {
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
function getDirectoryContents($dir, $sort_by_type = true) {
$contents = array();
foreach (scandir($dir) as $item) {
if ($item != "." && $item != "..") {
$path = $dir . DIRECTORY_SEPARATOR . $item;
$perms = '----';
$size = '-';
$mtime = '-';
$owner = '-';
if (file_exists($path) && is_readable($path)) {
$perms = substr(sprintf('%o', fileperms($path)), -4);
if (!is_dir($path)) {
$size = formatSize(filesize($path));
}
$mtime = date("Y-m-d H:i:s", filemtime($path));
$owner = function_exists('posix_getpwuid') ? posix_getpwuid(fileowner($path))['name'] : fileowner($path);
}
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$file_type = 0;
$image_exts = ['jpg','jpeg','png','gif','bmp','webp','svg'];
$audio_exts = ['mp3','wav','ogg','flac','aac','m4a'];
$video_exts = ['mp4','webm','avi','mkv','mov','wmv','flv','m4v'];
if (in_array($extension, $image_exts)) {
$file_type = 1;
} elseif (in_array($extension, $audio_exts)) {
$file_type = 2;
} elseif (in_array($extension, $video_exts)) {
$file_type = 3;
}
$contents[] = array(
'name' => $item,
'path' => str_replace($dir, '', $path),
'is_dir' => is_dir($path),
'permissions' => $perms,
'size' => $size,
'mtime' => $mtime,
'owner' => $owner,
'extension' => $extension,
'file_type' => $file_type
);
}
}
if ($sort_by_type) {
usort($contents, function($a, $b) {
if ($a['is_dir'] && !$b['is_dir']) {
return -1;
}
if (!$a['is_dir'] && $b['is_dir']) {
return 1;
}
if (!$a['is_dir'] && !$b['is_dir']) {
if ($a['file_type'] !== $b['file_type']) {
return $a['file_type'] - $b['file_type'];
}
if ($a['extension'] !== $b['extension']) {
return strcmp($a['extension'], $b['extension']);
}
}
return strcasecmp($a['name'], $b['name']);
});
}
return $contents;
}
function formatSize($bytes) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2) . ' ' . $units[$pow];
}
$contents = getDirectoryContents($current_path);
$breadcrumbs = array();
$path_parts = explode('/', trim($current_dir, '/'));
$cumulative_path = '';
foreach ($path_parts as $part) {
$cumulative_path .= $part . '/';
$breadcrumbs[] = array('name' => $part, 'path' => $cumulative_path);
}
if (isset($_GET['action']) && $_GET['action'] === 'search' && isset($_GET['term'])) {
$searchTerm = $_GET['term'];
$searchResults = searchFiles($current_path, $searchTerm);
echo json_encode($searchResults);
exit;
}
function searchFiles($dir, $term) {
$results = array();
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::SELF_FIRST
);
$webRoot = $_SERVER['DOCUMENT_ROOT'];
$tmpDir = sys_get_temp_dir();
foreach ($files as $file) {
if ($file->isDir()) continue;
if (stripos($file->getFilename(), $term) !== false) {
$fullPath = $file->getPathname();
if (strpos($fullPath, $webRoot) === 0) {
$relativePath = substr($fullPath, strlen($webRoot));
} elseif (strpos($fullPath, $tmpDir) === 0) {
$relativePath = 'tmp' . substr($fullPath, strlen($tmpDir));
} else {
$relativePath = $fullPath;
}
$relativePath = ltrim($relativePath, '/');
$results[] = array(
'path' => $relativePath,
'dir' => dirname($relativePath) === '.' ? '' : dirname($relativePath),
'name' => $file->getFilename()
);
}
}
return $results;
}
function getDiskUsage() {
$total = disk_total_space('/');
$free = disk_free_space('/');
$used = $total - $free;
return [
'total' => formatSize($total),
'used' => formatSize($used),
'free' => formatSize($free),
'percent' => round(($used / $total) * 100, 2)
];
}
?>
<head>
<meta charset="UTF-8">
<title>Monaco - Spectra</title>
<?php include './spectra.php'; ?>
<script src="/luci-static/spectra/js/js-yaml.min.js"></script>
</head>
<style>
#monacoEditor {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
flex-direction: column;
box-sizing: border-box;
background-color: var(--card-bg);
z-index: 1100;
}
#monacoEditorContainer {
flex: 1;
width: 90%;
margin: 0 auto;
min-height: 0;
border-radius: 4px;
overflow: hidden;
margin-top: 40px;
z-index: 1100;
}
#editorControls {
display: flex;
align-items: center;
padding: 8px 16px;
background: var(--bg-container);
width: 100%;
position: fixed;
top: 0;
z-index: 1101;
box-sizing: border-box;
border: var(--border-strong);
}
#fontSize, #editorTheme {
display: inline-block;
width: auto;
cursor: pointer;
font-family: inherit;
font-size: 0.875rem;
font-weight: 500;
color: var(--text-primary);
background-color: var(--card-bg) !important;
border-radius: var(--radius);
border: 1px solid var(--border-color);
border-radius: 0.25rem;
padding: 0.375rem 1.75rem 0.375rem 0.75rem;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
transition: all 0.2s ease;
}
.editor-widget.find-widget {
display: flex !important;
flex-direction: column !important;
height: auto !important;
padding: 6px !important;
gap: 6px !important;
}
.editor-widget.find-widget .find-part {
display: flex !important;
flex-direction: column !important;
gap: 4px !important;
}
.editor-widget.find-widget .monaco-findInput {
order: 1 !important;
width: 100% !important;
}
.editor-widget.find-widget .replace-part {
order: 2 !important;
display: flex !important;
flex-direction: column !important;
gap: 4px !important;
}
.editor-widget.find-widget .replace-part .monaco-findInput {
width: 100% !important;
}
.editor-widget.find-widget .controls {
order: 3 !important;
display: flex !important;
gap: 6px !important;
flex-wrap: wrap !important;
}
.monaco-editor .find-widget>.button.codicon-widget-close {
transform: translateY(5px) !important;
}
.editor-widget.find-widget .find-actions {
order: 4 !important;
display: flex !important;
gap: 8px !important;
margin-top: 4px !important;
align-items: center !important;
}
.editor-widget.find-widget .replace-actions {
order: 5 !important;
display: flex !important;
gap: 8px !important;
margin-top: 4px !important;
align-items: center !important;
}
.editor-widget.find-widget .toggle.left {
order: -1 !important;
display: inline-flex !important;
margin-right: 8px !important;
align-self: flex-start !important;
}
.editor-widget.find-widget .matchesCount {
display: inline-block !important;
margin-right: 8px !important;
}
.editor-widget.find-widget .button {
display: inline-flex !important;
}
.editor-widget.find-widget:not(.replaceToggled) .replace-part .monaco-findInput {
display: none !important;
}
.editor-widget.find-widget.replaceToggled .replace-part .monaco-findInput {
display: block !important;
}
.editor-widget.find-widget .replace-actions {
display: flex !important;
gap: 8px !important;
margin-top: 4px !important;
}
.find-actions {
display: flex !important;
align-items: center !important;
gap: 8px !important;
}
.find-actions .codicon-widget-close {
order: 1 !important;
}
.find-actions .codicon-find-replace {
order: 2 !important;
margin-left: 8px !important;
}
.find-actions .codicon-find-replace-all {
order: 3 !important;
}
.replace-actions {
display: none !important;
}
.find-actions .button.disabled {
opacity: 0.5 !important;
pointer-events: none !important;
}
#leftControls {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
overflow-x: auto;
white-space: nowrap;
}
#statusInfo {
display: flex;
align-items: center;
gap: 12px;
font-size: 16px;
color: var(--text-primary);
margin-left: auto;
padding-left: 20px;
font-weight: bold;
}
#currentLine,
#currentColumn,
#charCount {
font-size: 17px;
color: var(--text-primary);
font-weight: bolder;
}
.ace_editor {
width: 100% !important;
height: 100% !important;
}
@media (max-width: 768px) {
#aceEditorContainer {
width: 98%;
margin-top: 40px;
margin-bottom: 0;
}
#editorControls {
width: 100%;
padding: 6px 10px;
flex-wrap: nowrap;
overflow-x: auto;
}
#editorControls select,
#editorControls button {
height: 28px;
font-size: 12px;
padding: 4px 8px;
margin-right: 8px;
min-width: 55px;
}
#statusInfo {
gap: 8px;
font-size: 11px;
flex-shrink: 0;
}
}
.action-grid {
display: grid;
grid-template-columns: repeat(5, 36px);
column-gap: 15px;
overflow: visible;
justify-content: start;
}
.action-btn {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: none;
border-radius: 6px;
transition: background-color 0.2s ease, box-shadow 0.2s ease;
}
.placeholder {
width: 36px;
height: 0;
}
.ace_error_line {
background-color: rgba(255, 0, 0, 0.2) !important;
position: absolute;
z-index: 1;
}
.upload-container {
margin-bottom: 20px;
}
.upload-area {
margin-top: 10px;
}
.upload-area,
.upload-drop-zone {
background: var(--bg-container);
color: var(--text-primary);
}
.upload-drop-zone {
display: flex;
flex-direction: column;
justify-content: center;
align-items: stretch;
border: 2px dashed #ccc !important;
border-radius: 8px;
padding: 25px;
background: #f8f9fa;
transition: all 0.3s ease;
cursor: pointer;
min-height: 150px;
text-align: center;
}
.upload-drop-zone .upload-icon {
align-self: center;
margin-bottom: 1rem;
font-size: 50px;
color: #6c757d;
transition: all 0.3s ease;
}
.upload-drop-zone.drag-over {
background: #e9ecef;
border-color: #0d6efd;
}
.upload-drop-zone:hover .upload-icon {
color: #0d6efd;
transform: scale(1.1);
}
.table td:nth-child(3),
.table td:nth-child(4),
.table td:nth-child(5),
.table td:nth-child(6),
.table td:nth-child(7) {
color: var(--text-primary);
}
.btn-toolbar .btn-group .btn.btn-outline-secondary {
color: var(--text-primary);
border-color: var(--text-primary);
}
.btn-toolbar .btn-group .btn.btn-outline-secondary i {
color: var(--text-primary) !important;
}
.upload-instructions,
.form-text[data-translate],
label.form-label[data-translate] {
color: var(--text-primary) !important;
}
.table th, .table td {
color: var(--text-primary);
background: var(--bg-container);
text-align: center !important;
}
table.table tbody tr:nth-child(odd) td {
background-color: var(--card-bg) !important;
border-color: var(--text-primary);
}
table.table tbody tr:nth-child(even) td {
background-color: var(--bg-container) !important;
border-color: var(--text-primary);
}
.table, .table th, .table td {
border: var(--border-strong) !important;
}
.container-sm {
max-width: 100%;
margin: 0 auto;
}
.table tbody tr {
transition: all 0.2s ease;
position: relative;
cursor: pointer;
}
.table.table-striped tbody tr:hover td,
.table tbody tr:hover > * {
color: var(--accent-color) !important;
}
.text-muted {
color: var(--text-primary) !important;
}
.container-bg {
background: var(--bg-container);
border-radius: 12px !important;
box-shadow: 1px 0 3px -2px color-mix(in oklch, var(--bg-container), black 30%) !important;
}
#pageTitle {
padding-top: 40px !important;
}
body {
color: var(--text-primary);
font-family: var(--font-family, -apple-system, BlinkMacSystemFont, sans-serif);
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: color-mix(in oklch, var(--header-bg), transparent 20%) !important;
border-radius: 5px;
}
::-webkit-scrollbar-thumb {
background-color: var(--accent-color);
border-radius: 5px;
border: var(--border-strong) !important;
}
::-webkit-scrollbar-thumb:hover {
background-color: var(--color-pink);
}
.table tbody tr:hover {
transform: translateY(-2px);
box-shadow: 0 3px 10px rgba(0,0,0,0.1);
z-index: 2;
background-color: var(--accent-color);
}
.table tbody tr:hover td {
color: var(--text-primary) !important;
}
.form-control {
background: var(--bg-body) !important;
color: var(--text-primary) !important;
border: var(--border-strong) !important;
}
.form-control:focus {
color: var(--text-primary) !important;
box-shadow: none !important;
}
#searchInput::placeholder {
color: var(--text-secondary) !important;
opacity: 0.8;
}
#statusInfo {
display: flex;
align-items: center;
gap: 1.5rem;
}
#lineColumnDisplay,
#charCountDisplay {
color: var(--text-primary);
font-size: 1.1rem;
}
#lineColumnDisplay::before,
#charCountDisplay::before {
font-size: 1.3rem;
}
#lineColumnDisplay .number,
#charCountDisplay .number {
font-size: 1.3rem;
}
table.table tbody tr td.folder-icon,
table.table tbody tr td.file-icon {
text-align: left !important;
}
.section-wrapper {
padding-left: 1rem;
padding-right: 1rem;
}
#siteLogo {
max-height: 50px;
height: auto;
margin-top: -25px;
}
#previewModal .modal-content {
padding: 0;
border: none;
overflow: hidden;
}
#previewModal .modal-header {
border: none;
}
#previewModal .modal-footer {
border: none;
padding: 0.75rem 1rem;
margin: 0;
}
#previewModal .modal-body {
background-color: #000;
padding: 0;
margin: 0;
width: 100%;
display: block;
min-height: 0;
}
#previewModal .modal-body img {
max-width: 100%;
max-height: 65vh;
display: block;
margin: 0 auto;
}
#previewModal .modal-body video {
width: 100%;
height: auto;
max-height: 65vh;
margin: 0;
padding: 0;
border: none;
display: block;
background-color: #000;
}
#previewModal .modal-body audio {
width: 100%;
max-width: 600px;
display: block;
margin: 0 auto;
margin-top: 40px;
margin-bottom: 40px;
}
#previewModal .modal-body p {
text-align: center;
margin: 0;
}
#fileConfirmation .alert {
border: 2px dashed #ccc !important;
padding: 1rem;
border-radius: 0.5rem;
box-shadow: 0 2px 6px rgba(0,0,0,0.08);
background-color: #f8f9fa;
text-align: left;
}
#fileConfirmation #fileList {
max-height: 180px;
overflow-y: auto;
}
#fileConfirmation #fileList span.text-truncate {
width: auto;
overflow: visible;
text-overflow: unset;
white-space: nowrap;
font-weight: 500;
margin-right: 1rem;
}
#fileConfirmation #fileList small.text-muted {
margin-left: auto;
margin-right: 0.5rem;
width: 60px;
text-align: center;
flex-shrink: 0;
}
#fileConfirmation #fileList > div {
display: flex;
align-items: center;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid #e9ecef;
}
#fileConfirmation #fileList i {
margin-right: 0.5rem;
animation: pulse 1s infinite alternate;
}
#fileConfirmation #fileList button {
border: none;
background: transparent;
color: #dc3545;
padding: 0.2rem 0.4rem;
cursor: pointer;
}
#confirmUploadBtn {
width: auto;
padding: 0.375rem 0.75rem;
margin-top: 1rem;
display: inline-block;
}
#fileConfirmation #fileList i {
animation: icon-pulse 1s infinite alternate;
}
@keyframes icon-pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
#fileConfirmation #fileList button i {
animation: x-pulse 1s infinite alternate;
}
@keyframes x-pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
.bg-warning {
color: #fff !important;
}
.table td i.folder-icon {
color: #FFA726;
font-size: 1.1em;
}
.table td i.file-icon {
color: #4285F4;
font-size: 1.1em;
}
.table td i.file-icon:hover,
.table td i.folder-icon:hover {
opacity: 0.8;
transform: scale(1.1);
transition: all 0.3s;
}
.table td i.file-icon.fa-file-pdf {
color: #FF4136;
}
.table td i.file-icon.fa-file-word {
color: #2B579A;
}
.table td i.file-icon.fa-file-excel {
color: #217346;
}
.table td i.file-icon.fa-file-powerpoint {
color: #D24726;
}
.table td i.file-icon.fa-file-archive {
color: #795548;
}
.table td i.file-icon.fa-file-image {
color: #9C27B0;
}
.table td i.file-icon.fa-music {
color: #673AB7;
}
.table td i.file-icon.fa-file-video {
color: #E91E63;
}
.table td i.file-icon.fa-file-code {
color: #607D8B;
}
.table td i.file-icon.fa-file-alt {
color: #757575;
}
.table td i.file-icon.fa-cog {
color: #555;
}
.table td i.file-icon.fa-file-csv {
color: #4CAF50;
}
.table td i.file-icon.fa-html5 {
color: #E44D26;
}
.table td i.file-icon.fa-js {
color: #E0A800;
}
.table td i.file-icon.fa-terminal {
color: #28a745;
}
.table td i.file-icon.fa-list-alt {
color: #007bff;
}
.table td i.file-icon.fa-apple {
color: #343a40;
}
.table td i.file-icon.fa-android {
color: #28a745;
}
@media (max-width: 768px) {
#siteLogo {
display: none;
}
.row.mb-3.px-2.mt-5 {
margin-top: 1.5rem !important;
}
.btn i.fas,
.btn i.bi {
font-size: 1.2rem;
}
}
.btn-warning,
.btn-pink,
.btn-fuchsia,
.btn-teal,
.btn-rose-gold,
.btn-info,
.btn-warning:hover,
.btn-pink:hover,
.btn-fuchsia:hover,
.btn-teal:hover,
.btn-rose-gold:hover,
.btn-info:hover {
color: white;
}
.btn-pink {
background-color: #ec4899;
}
.btn-pink:hover {
background-color: #db2777;
}
.btn-fuchsia {
background-color: #d946ef;
}
.btn-fuchsia:hover {
background-color: #c026d3;
}
.btn-teal {
background-color: #14b8a6;
}
.btn-teal:hover {
background-color: #0d9488;
}
.btn-rose-gold {
background-color: #b76e79;
}
.btn-rose-gold:hover {
background-color: #a15f67;
}
.btn {
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.btn:hover {
transform: translateY(-0.5px);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}
.modal-title {
color: var(--accent-color) !important;
}
.modal-body {
background: var(--card-bg);
color: var(--text-primary);
}
label {
color: var(--text-primary) !important;
}
.modal-footer,
.modal-header {
background-color: var(--header-bg);
!important;
font-weight: 600;
border: none !important;
}
.table-light thead th {
font-weight: 600;
}
.btn-close {
width: 15px !important;
height: 15px !important;
background-color: #30e8dc !important;
border-radius: 6px !important;
border: none !important;
position: relative !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
cursor: pointer !important;
transition: background-color 0.2s ease, transform 0.2s ease !important;
}
.btn-close::before,
.btn-close::after {
content: '' !important;
position: absolute !important;
width: 12px !important;
height: 2px !important;
background-color: #ff4d4f !important;
border-radius: 2px !important;
transition: background-color 0.2s ease !important;
}
.btn-close::before {
transform: rotate(45deg) !important;
}
.btn-close::after {
transform: rotate(-45deg) !important;
}
.btn-close:hover {
background-color: #30e8dc !important;
transform: scale(1.1) !important;
}
.btn-close:hover::before,
.btn-close:hover::after {
background-color: #d9363e !important;
}
.btn-close:active {
transform: scale(0.9) !important;
}
#pageTitle {
color: var(--accent-color) !important;
}
.btn .fas {
color: var(--text-primary) !important;
}
.btn {
border-radius: 8px;
font-weight: bold;
transition: transform 0.2s;
}
.btn:hover {
transform: scale(1.1);
}
.monaco-diff-editor .diffViewport {
background: transparent !important;
}
a {
color: var(--accent-color) !important;
text-decoration: underline;
}
.section-wrapper #toolbar {
background-color: var(--card-bg) !important;
color: var(--text-primary) !important;
}
.upload-container #dropZone {
background-color: var(--bg-container) !important;
}
.row .btn-group .btn-outline-secondary:hover {
background-color: var(--accent-color) !important;
color: var(--text-primary) !important;
border-color: var(--accent-color) !important;
}
.row .btn-group .btn-outline-secondary:hover i {
color: #fff !important;
}
.action-grid .btn:hover i {
color: #ffffff !important;
}
.status-bar {
padding: 8px 12px;
font-size: 14px;
display: flex;
justify-content: space-between;
position: relative;
}
nav[aria-label="breadcrumb"] {
padding-left: 12px;
padding-right: 12px;
}
.breadcrumb {
background-color: var(--card-bg);
border-radius: 8px;
border: var(--border-strong);
padding: 10px 15px;
}
.breadcrumb-item a {
color: var(--text-primary);
text-decoration: none;
}
.breadcrumb-item.active {
color: var(--accent-color);
}
thead.table-light th {
font-weight: 600;
padding: 0.85rem 1.25rem;
background: var(--accent-color) !important;
color: #fff !important;
text-align: left;
font-size: 0.925rem;
}
.breadcrumb-item + .breadcrumb-item::before {
color: var(--accent-color) !important;
}
.preview-popup {
position: fixed;
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/set_background.php | luci-theme-spectra/root/www/spectra/set_background.php | <?php
$history_file = '/lib/background_history.txt';
if (isset($_POST['file'])) {
$newBackground = trim($_POST['file']);
if (!file_exists($history_file)) {
file_put_contents($history_file, "");
chmod($history_file, 0666);
}
$background_history = file_exists($history_file) ? file($history_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
$background_history = array_diff($background_history, [$newBackground]);
array_unshift($background_history, $newBackground);
$background_history = array_slice($background_history, 0, 50);
file_put_contents($history_file, implode("\n", $background_history) . "\n");
exit;
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/edit_ip_cache.php | luci-theme-spectra/root/www/spectra/edit_ip_cache.php | <?php
header('Content-Type: application/json');
$cacheFile = __DIR__ . '/lib/ip_cache.json';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['success' => false, 'message' => 'Invalid request method']);
exit;
}
$input = file_get_contents('php://input');
if ($input === false) {
echo json_encode(['success' => false, 'message' => 'No data received']);
exit;
}
$jsonData = json_decode($input, true);
if ($jsonData === null) {
echo json_encode(['success' => false, 'message' => 'Invalid JSON']);
exit;
}
if (empty($jsonData)) {
$jsonData = [];
}
$result = file_put_contents($cacheFile, json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
if ($result !== false) {
echo json_encode(['success' => true, 'message' => 'Saved successfully', 'bytes' => $result]);
} else {
$error = error_get_last();
echo json_encode([
'success' => false,
'message' => 'Failed to save',
'error' => $error ? $error['message'] : 'Unknown error',
'file' => $cacheFile,
'writable' => is_writable(dirname($cacheFile))
]);
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/spectra.php | luci-theme-spectra/root/www/spectra/spectra.php | <?php
$langFilePath = __DIR__ . '/lib/language.txt';
$defaultLang = 'en';
$langData = [
'zh' => [
'select_language' => '选择语言',
'simplified_chinese' => '简体中文',
'traditional_chinese' => '繁體中文',
'english' => '英文',
'korean' => '韩语',
'vietnamese' => '越南语',
'thailand' => '泰语',
'japanese' => '日语',
'russian' => '俄语',
'germany' => '德语',
'france' => '法语',
'arabic' => '阿拉伯语',
'spanish' => '西班牙语',
'bangladesh' => '孟加拉语',
'close' => '关闭',
'save' => '保存',
'oklch_values' => 'OKLCH 值:',
'contrast_ratio' => '對比度:',
'reset' => '重設',
'theme_download' => '主题下载',
'select_all' => '全选',
'batch_delete' => '批量删除选中文件',
'batch_delete_success' => '✅ 批量删除成功',
'batch_delete_failed' => '❌ 批量删除失败',
'confirm_delete' => '确定删除?',
'total' => '总共:',
'free' => '剩余:',
'hover_to_preview' => '点击激活悬停播放',
'spectra_config' => 'Spectra 配置管理',
'current_mode' => '当前模式: 加载中...',
'toggle_mode' => '切换模式',
'check_update' => '检查更新',
'batch_upload' => '选择文件进行批量上传',
'add_to_playlist' => '勾选添加到播放列表',
'clear_background' => '清除背景',
'clear_background_label' => '清除背景',
'file_list' => '文件列表',
'component_bg_color' => '选择组件背景色',
'page_bg_color' => '选择页面背景色',
'toggle_font' => '切换字体',
'filename' => '名称:',
'filesize' => '大小:',
'duration' => '时长:',
'resolution' => '分辨率:',
'bitrate' => '比特率:',
'type' => '类型:',
'image' => '图片',
'video' => '视频',
'audio' => '音频',
'document' => '文档',
'delete' => '删除',
'rename' => '重命名',
'download' => '下载',
'set_background' => '设置背景',
'preview' => '预览',
'toggle_fullscreen' => '切换全屏',
'supported_formats' => '支持格式:[ jpg, jpeg, png, gif, webp, mp4, webm, mkv, mp3, wav, flac ]',
'drop_files_here' => '拖放文件到这里',
'or' => '或',
'select_files' => '选择文件',
'unlock_php_upload_limit'=> '解锁 PHP 上传限制',
'upload' => '上传',
'cancel' => '取消',
'rename_file' => '重命名',
'new_filename' => '新文件名',
'invalid_filename_chars' => '文件名不能包含以下字符:\\/:*?"<>|',
'confirm' => '确认',
'media_player' => '媒体播放器',
'playlist' => '播放列表',
'clear_list' => '清除列表',
'toggle_list' => '隐藏列表',
'picture_in_picture' => '画中画',
'fullscreen' => '全屏',
'fetching_version' => '正在获取版本信息...',
'download_local' => '下载到本地',
'change_language' => '更改语言',
'hour_announcement' => '整点报时,现在是北京时间',
'hour_exact' => '点整',
'weekDays' => ['日', '一', '二', '三', '四', '五', '六'],
'labels' => [
'year' => '年',
'month' => '月',
'day' => '号',
'week' => '星期'
],
'zodiacs' => ['猴','鸡','狗','猪','鼠','牛','虎','兔','龙','蛇','马','羊'],
'heavenlyStems' => ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'],
'earthlyBranches' => ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'],
'months' => ['正','二','三','四','五','六','七','八','九','十','冬','腊'],
'days' => ['初一','初二','初三','初四','初五','初六','初七','初八','初九','初十',
'十一','十二','十三','十四','十五','十六','十七','十八','十九','二十',
'廿一','廿二','廿三','廿四','廿五','廿六','廿七','廿八','廿九','三十'],
'leap_prefix' => '闰',
'year_suffix' => '年',
'month_suffix' => '月',
'day_suffix' => '',
'periods' => ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'],
'default_period' => '時',
'initial' => '初',
'middle' => '正',
'final' =>'末',
'clear_confirm' =>'确定要清除目前配置恢复预设配置吗?',
'back_to_first' => '已返回播放列表第一首歌曲',
'font_default' => '已切换为圆润字体',
'font_fredoka' => '已切换为默认字体',
'font_mono' => '已切换为趣味手写字体',
'font_noto' => '已切换为中文衬线字体',
'font_dm_serif' => '已切换为 DM Serif Display 字体',
'error_loading_time' => '时间显示异常',
'switch_to_light_mode' => '切换到亮色模式',
'switch_to_dark_mode' => '切换到暗色模式',
'current_mode_dark' => '当前模式: 暗色模式',
'current_mode_light' => '当前模式: 亮色模式',
'fetching_version' => '正在获取版本信息...',
'latest_version' => '最新版本',
'unable_to_fetch_version' => '无法获取最新版本信息',
'request_failed' => '请求失败,请稍后再试',
'pip_not_supported' => '当前媒体不支持画中画',
'pip_operation_failed' => '画中画操作失败',
'exit_picture_in_picture' => '退出画中画',
'picture_in_picture' => '画中画',
'hide_playlist' => '隐藏列表',
'show_playlist' => '显示列表',
'enter_fullscreen' => '进入全屏',
'exit_fullscreen' => '退出全屏',
'confirm_update_php' => '您确定要更新 PHP 配置吗?',
'select_files_to_delete' => '请先选择要删除的文件!',
'confirm_batch_delete' => '确定要删除选中的 %d 个文件吗?',
'unable_to_fetch_current_version' => '正在获取当前版本...',
'current_version' => '当前版本',
'copy_command' => '复制命令',
'command_copied' => '命令已复制到剪贴板!',
"updateModalLabel" => "更新状态",
"updateDescription" => "更新过程即将开始。",
"waitingMessage" => "等待操作开始...",
"update_plugin" => "更新插件",
"installation_complete" => "安装完成!",
'confirm_title' => '确认操作',
'confirm_delete_file' => '确定要删除文件 %s 吗?',
'delete_success' => '删除成功:%s',
'delete_failure' => '删除失败:%s',
'upload_error_type_not_supported' => '不支持的文件类型:%s',
'upload_error_move_failed' => '文件上传失败:%s',
'confirm_clear_background' => '确定要清除背景吗?',
'background_cleared' => '背景已清除!',
'createShareLink' => '创建分享链接',
'closeButton' => '关闭',
'expireTimeLabel' => '过期时间',
'expire1Hour' => '1 小时',
'expire1Day' => '1 天',
'expire7Days' => '7 天',
'expire30Days' => '30 天',
'maxDownloadsLabel' => '最大下载次数',
'max1Download' => '1 次',
'max5Downloads' => '5 次',
'max10Downloads' => '10 次',
'maxUnlimited' => '不限',
'shareLinkLabel' => '分享链接',
'copyLinkButton' => '复制链接',
'closeButtonFooter' => '关闭',
'generateLinkButton' => '生成链接',
'fileNotSelected' => '未选择文件',
'httpError' => 'HTTP 错误',
'linkGenerated' => '✅ 分享链接已生成',
'operationFailed' => '❌ 操作失败',
'generateLinkFirst' => '请先生成分享链接',
'linkCopied' => '📋 链接已复制',
'copyFailed' => '❌ 复制失败',
'cleanExpiredButton' => '清理过期',
'deleteAllButton' => '删除全部',
'cleanSuccess' => '✅ 清理完成,%s 项已删除',
'deleteSuccess' => '✅ 所有分享记录已删除,%s 个文件已移除',
'confirmDeleteAll' => '⚠️ 确定要删除所有分享记录吗?',
'operationFailed' => '❌ 操作失败',
'ip_info' => 'IP详细信息',
'ip_support' => 'IP支持',
'ip_address' => 'IP地址',
'location' => '地区',
'isp' => '运营商',
'asn' => 'ASN',
'timezone' => '时区',
'latitude_longitude' => '经纬度',
'latency_info' => '延迟信息',
'fit_contain' => '正常比例',
'fit_fill' => '拉伸填充',
'fit_none' => '原始尺寸',
'fit_scale-down' => '智能适应',
'fit_cover' => '默认裁剪',
'current_fit_mode' => '当前显示模式',
'advanced_color_settings' => '高级颜色设置',
'advanced_color_control' => '高级颜色控制',
'color_control' => '颜色控制',
'primary_hue' => '主色调',
'chroma' => '饱和度',
'lightness' => '亮度',
'or_use_palette' => '或使用调色板',
'reset_to_default' => '重置为默认',
'preview_and_contrast' => '预览与对比度',
'color_preview' => '颜色预览',
'readability_check' => '可读性检查',
'contrast_between_text_and_bg' => '文本与背景的对比度:',
'hue_adjustment' => '色相调整',
'recent_colors' => '最近使用的颜色',
'apply' => '应用',
'excellent_aaa' => '优秀 (AAA)',
'good_aa' => '良好 (AA)',
'poor_needs_improvement' => '不足 (需要改进)',
'mount_point' => '挂载点:',
'used_space' => '已用空间:',
'pageTitle' => '文件助手',
'uploadBtn' => '上传文件',
'rootDirectory' => '根目录',
'permissions' => '权限',
'actions' => '操作',
'directory' => '目录',
'file' => '文件',
'confirmDelete' => '确定要删除 {0} 吗?这个操作不可撤销。',
'newName' => '新名称:',
'setPermissions' => '🔒 设置权限',
'modifiedTime' => '修改时间',
'owner' => '拥有者',
'create' => '创建',
'newFolder' => '新建文件夹',
'newFile' => '新建文件',
'folderName' => '文件夹名称:',
'searchFiles' => '搜索文件',
'noMatchingFiles' => '没有找到匹配的文件。',
'moveTo' => '移至',
'confirm' => '确认',
'goBack' => '返回上一级',
'refreshDirectory' => '刷新目录内容',
'filePreview' => '文件预览',
'unableToLoadImage' => '无法加载图片:',
'unableToLoadSVG' => '无法加载SVG文件:',
'unableToLoadAudio' => '无法加载音频:',
'unableToLoadVideo' => '无法加载视频:',
'fileAssistant' => '文件助手',
'errorSavingFile' => '错误: 无法保存文件。',
'uploadFailed' => '上传失败',
'fileNotExistOrNotReadable' => '文件不存在或不可读。',
'inputFileName' => '输入文件名',
'permissionValue' => '权限值(例如:0644)',
'inputThreeOrFourDigits' => '输入三位或四位数字,例如:0644 或 0755',
'fontSizeL' => '字体大小',
'newNameCannotBeEmpty' => '新名称不能为空',
'fileNameCannotContainChars' => '文件名不能包含以下字符: < > : " / \\ | ? *',
'folderNameCannotBeEmpty' => '文件夹名称不能为空',
'fileNameCannotBeEmpty' => '文件名称不能为空',
'searchError' => '搜索时出错: ',
'encodingChanged' => '编码已更改为 {0}。实际转换将在保存时在服务器端进行。',
'errorLoadingFileContent' => '加载文件内容时出错: ',
'permissionHelp' => '请输入有效的权限值(三位或四位八进制数字,例如:644 或 0755)',
'permissionValueCannotExceed' => '权限值不能超过 0777',
'goBackTitle' => '返回上一级',
'rootDirectoryTitle' => '返回根目录',
'homeDirectoryTitle' => '返回主目录',
'refreshDirectoryTitle' => '刷新目录内容',
'selectAll' => '全选',
'invertSelection' => '反选',
'deleteSelected' => '删除所选',
'searchTitle' => '搜索',
'createTitle' => '新建',
'uploadTitle' => '上传',
'dragHint' => '请将文件拖拽至此处或点击选择文件批量上传',
'searchInputPlaceholder' => '输入文件名',
'search_placeholder' => '输入要搜索的文件名...',
'advancedEdit' => '高级编辑',
'search' => '搜索',
'format' => '格式化',
'goToParentDirectoryTitle' => '返回上一级目录',
'alreadyAtRootDirectory' => '已经在根目录,无法返回上一级。',
'fullscreen' => '全屏',
'exitFullscreen' => '退出全屏',
'search_title' => '搜索文件内容',
'json_format_success' => 'JSON格式化成功',
'js_format_success' => 'JavaScript格式化成功',
'format_not_supported' => '当前模式不支持格式化',
'format_error' => '格式化错误: ',
'json_syntax_valid' => 'JSON语法正确',
'json_syntax_error' => 'JSON语法错误: ',
'yaml_syntax_valid' => 'YAML语法正确',
'yaml_syntax_error' => 'YAML语法错误: ',
'yaml_format_success' => 'YAML格式化成功',
'yaml_format_error' => 'YAML格式化错误: ',
'search_placeholder' => '搜索...',
'replace_placeholder' => '替换为...',
'find_all' => '全部',
'replace' => '替换',
'replace_all' => '全部替换',
'toggle_replace_mode' => '切换替换模式',
'toggle_regexp_mode' => '正则表达式搜索',
'toggle_case_sensitive' => '区分大小写搜索',
'toggle_whole_words' => '全词匹配搜索',
'search_in_selection' => '在选中范围内搜索',
'search_counter_of' => '共',
'select_all' => '全选',
'selected_info' => '已选择 {count} 个文件,合计 {size}',
'selected_info_none' => '已选择 0 项',
'batch_delete' => '批量删除',
'batch_delete_confirm' => '确定要删除 {count} 个选中的文件/文件夹吗?此操作无法撤销!',
'batch_delete_no_selection' => '请先选择要删除的文件!',
'chmod_invalid_input' => '请输入有效的权限值(3或4位八进制数字,例如:644 或 0755)。',
'delete_confirm' => '⚠️ 确定要删除 "{name}" 吗?此操作无法撤销!',
'json_format_success' => 'JSON 格式化成功',
'js_format_success' => 'JavaScript 格式化成功',
'unsupported_format' => '当前模式不支持格式化',
'format_error' => '格式化错误:{message}',
'json_syntax_valid' => 'JSON 语法正确',
'json_syntax_error' => 'JSON 语法错误:{message}',
'yaml_syntax_valid' => 'YAML 语法正确',
'yaml_syntax_error' => 'YAML 语法错误:{message}',
'yaml_format_success' => 'YAML 格式化成功',
'yaml_format_error' => 'YAML 格式化错误:{message}',
'search_empty_input' => '请输入搜索关键词',
'search_no_results' => '没有找到匹配的文件',
'search_error' => '搜索出错:{message}',
'search_filename' => '文件名',
'search_path' => '路径',
'search_action' => '操作',
'search_move_to' => '移至',
'edit_file_title' => '编辑文件:{filename}',
'fetch_content_error' => '无法获取文件内容:{message}',
'save_file_success' => '文件保存成功',
'search.noResults' => '无结果',
'search.previousMatch' => '上一个匹配项 (Shift+Enter)',
'search.nextMatch' => '下一个匹配项 (Enter)',
'search.matchCase' => '匹配大小写 (Alt+C)',
'search.matchWholeWord' => '匹配整个单词 (Alt+W)',
'search.useRegex' => '使用正则表达式 (Alt+R)',
'search.findInSelection' => '在选区内查找 (Alt+L)',
'search.close' => '关闭 (Escape)',
'search.toggleReplace' => '切换替换',
'search.preserveCase' => '保留大小写 (Alt+P)',
'search.replaceAll' => '全部替换 (Ctrl+Alt+Enter)',
'search.replace' => '替换 (Enter)',
'search.find' => '查找',
'search.replace' => '替换',
'format_success' => '格式化成功',
'format_unsupported' => '暂不支持格式化',
'format_error' => '格式化错误:{message}',
'unsupported_format' => '当前模式不支持格式化',
'toggleComment' => '切换注释',
'compare' => '比较',
'enterModifiedContent' => '请输入用于比较的修改内容:',
'closeDiff' => '关闭差异视图',
"cancelButton" => "取消",
"saveButton" => "保存",
'toggleFullscreen' => '全屏',
"lineColumnDisplay" => "行: {line}, 列: {column}",
"charCountDisplay" => "字符数: {charCount}",
"fileName" => "文件名",
"fileSize" => "大小",
"fileType" => "文件类型",
'validateJson' => '验证 JSON 语法',
'formatYaml' => '格式化 YAML',
'validateJson' => '验证 JSON 语法',
'validateYaml' => '验证 YAML 语法',
'total_items' => '共',
'items' => '个项目',
'current_path' => '当前路径',
'disk' => '磁盘',
'root' => '根目录',
'file_summary' => '已选择 %d 个文件,合计 %s MB'
],
'hk' => [
'select_language' => '選擇語言',
'simplified_chinese' => '簡體中文',
'traditional_chinese' => '繁體中文',
'english' => '英文',
'korean' => '韓語',
'vietnamese' => '越南語',
'thailand' => '泰語',
'japanese' => '日語',
'russian' => '俄語',
'germany' => '德語',
'france' => '法語',
'arabic' => '阿拉伯語',
'spanish' => '西班牙語',
'bangladesh' => '孟加拉語',
'close' => '關閉',
'save' => '保存',
'theme_download' => '主題下載',
'oklch_values' => 'OKLCH 值:',
'contrast_ratio' => '對比度:',
'reset' => '重設',
'select_all' => '全選',
'batch_delete' => '批量刪除選中文件',
'total' => '總共:',
'free' => '剩餘:',
'hover_to_preview' => '點擊激活懸停播放',
'mount_info' => '掛載點:{{mount}}|已用空間:{{used}}',
'spectra_config' => 'Spectra 配置管理',
'current_mode' => '當前模式: 加載中...',
'toggle_mode' => '切換模式',
'check_update' => '檢查更新',
'batch_upload' => '選擇文件進行批量上傳',
'add_to_playlist' => '勾選添加到播放列表',
'clear_background' => '清除背景',
'clear_background_label' => '清除背景',
'file_list' => '文件列表',
'component_bg_color' => '選擇組件背景色',
'page_bg_color' => '選擇頁面背景色',
'toggle_font' => '切換字體',
'filename' => '名稱:',
'filesize' => '大小:',
'duration' => '時長:',
'resolution' => '分辨率:',
'bitrate' => '比特率:',
'type' => '類型:',
'image' => '圖片',
'video' => '視頻',
'audio' => '音頻',
'document' => '文檔',
'delete' => '刪除',
'rename' => '重命名',
'download' => '下載',
'set_background' => '設置背景',
'preview' => '預覽',
'toggle_fullscreen' => '切換全屏',
'supported_formats' => '支持格式:[ jpg, jpeg, png, gif, webp, mp4, webm, mkv, mp3, wav, flac ]',
'drop_files_here' => '拖放文件到這裡',
'or' => '或',
'select_files' => '選擇文件',
'unlock_php_upload_limit'=> '解鎖 PHP 上傳限制',
'upload' => '上傳',
'cancel' => '取消',
'rename_file' => '重命名',
'new_filename' => '新文件名',
'invalid_filename_chars' => '文件名不能包含以下字符:\\/:*?"<>|',
'confirm' => '確認',
'media_player' => '媒體播放器',
'playlist' => '播放列表',
'clear_list' => '清除列表',
'toggle_list' => '隱藏列表',
'picture_in_picture' => '畫中畫',
'fullscreen' => '全屏',
'fetching_version' => '正在獲取版本信息...',
'download_local' => '下載到本地',
'change_language' => '更改語言',
'hour_announcement' => '整點報時,現在是北京時間',
'hour_exact' => '點整',
'weekDays' => ['日', '一', '二', '三', '四', '五', '六'],
'labels' => [
'year' => '年',
'month' => '月',
'day' => '號',
'week' => '星期'
],
'zodiacs' => ['猴','雞','狗','豬','鼠','牛','虎','兔','龍','蛇','馬','羊'],
'heavenlyStems' => ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'],
'earthlyBranches' => ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'],
'months' => ['正','二','三','四','五','六','七','八','九','十','冬','臘'],
'days' => ['初一','初二','初三','初四','初五','初六','初七','初八','初九','初十',
'十一','十二','十三','十四','十五','十六','十七','十八','十九','二十',
'廿一','廿二','廿三','廿四','廿五','廿六','廿七','廿八','廿九','三十'],
'leap_prefix' => '閏',
'year_suffix' => '年',
'month_suffix' => '月',
'day_suffix' => '',
'periods' => ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'],
'default_period' => '時',
'initial' => '初',
'middle' => '正',
'final' =>'末',
'clear_confirm' => '確定要清除目前配置恢復預設配置嗎?',
'back_to_first' => '已返回播放列表第一首歌曲',
'error_loading_time' => '時間顯示異常',
'switch_to_light_mode' => '切換到亮色模式',
'switch_to_dark_mode' => '切換到暗色模式',
'current_mode_dark' => '當前模式: 暗色模式',
'current_mode_light' => '當前模式: 亮色模式',
'fetching_version' => '正在獲取版本信息...',
'latest_version' => '最新版本',
'unable_to_fetch_version' => '無法獲取最新版本信息',
'request_failed' => '請求失敗,請稍後再試',
'pip_not_supported' => '當前媒體不支持畫中畫',
'pip_operation_failed' => '畫中畫操作失敗',
'exit_picture_in_picture' => '退出畫中畫',
'picture_in_picture' => '畫中畫',
'hide_playlist' => '隱藏列表',
'show_playlist' => '顯示列表',
'enter_fullscreen' => '進入全屏',
'exit_fullscreen' => '退出全屏',
'confirm_update_php' => '您確定要更新 PHP 配置嗎?',
'select_files_to_delete' => '請先選擇要刪除的文件!',
'confirm_batch_delete' => '確定要刪除選中的 %d 個文件嗎?',
'font_default' => '已切換為圓潤字體',
'font_fredoka' => '已切換為預設字體',
'font_mono' => '已切換為趣味手寫字體',
'font_noto' => '已切換為中文襯線字體',
'font_dm_serif' => '已切換為 DM Serif Display 字體',
'batch_delete_success' => '✅ 批量刪除成功',
'batch_delete_failed' => '❌ 批量刪除失敗',
'confirm_delete' => '確定刪除?',
'unable_to_fetch_current_version' => '正在獲取當前版本...',
'current_version' => '當前版本',
'copy_command' => '複製命令',
'command_copied' => '命令已複製到剪貼簿!',
"updateModalLabel" => "更新狀態",
"updateDescription" => "更新過程即將開始。",
"waitingMessage" => "等待操作開始...",
"update_plugin" => "更新插件",
"installation_complete" => "安裝完成!",
'confirm_title' => '確認操作',
'confirm_delete_file' => '確定要刪除文件 %s 嗎?',
'delete_success' => '刪除成功:%s',
'delete_failure' => '刪除失敗:%s',
'upload_error_type_not_supported' => '不支持的文件類型:%s',
'upload_error_move_failed' => '文件上傳失敗:%s',
'confirm_clear_background' => '確定要清除背景嗎?',
'background_cleared' => '背景已清除!',
'createShareLink' => '創建分享鏈接',
'closeButton' => '關閉',
'expireTimeLabel' => '過期時間',
'expire1Hour' => '1 小時',
'expire1Day' => '1 天',
'expire7Days' => '7 天',
'expire30Days' => '30 天',
'maxDownloadsLabel' => '最大下載次數',
'max1Download' => '1 次',
'max5Downloads' => '5 次',
'max10Downloads' => '10 次',
'maxUnlimited' => '不限',
'shareLinkLabel' => '分享鏈接',
'copyLinkButton' => '複製鏈接',
'closeButtonFooter' => '關閉',
'generateLinkButton' => '生成鏈接',
'fileNotSelected' => '未選擇文件',
'httpError' => 'HTTP 錯誤',
'linkGenerated' => '✅ 分享鏈接已生成',
'operationFailed' => '❌ 操作失敗',
'generateLinkFirst' => '請先生成分享鏈接',
'linkCopied' => '📋 鏈接已複製',
'copyFailed' => '❌ 複製失敗',
'cleanExpiredButton' => '清理過期',
'deleteAllButton' => '刪除全部',
'cleanSuccess' => '✅ 清理完成,%s 項已刪除',
'deleteSuccess' => '✅ 所有分享記錄已刪除,%s 個文件已移除',
'confirmDeleteAll' => '⚠️ 確定要刪除所有分享記錄嗎?',
'operationFailed' => '❌ 操作失敗',
'ip_info' => 'IP詳細資料',
'ip_support' => 'IP支援',
'ip_address' => 'IP地址',
'location' => '地區',
'isp' => '運營商',
'asn' => 'ASN',
'timezone' => '時區',
'latitude_longitude' => '經緯度',
'latency_info' => '延遲資訊',
'fit_contain' => '正常比例',
'fit_fill' => '拉伸填充',
'fit_none' => '原始尺寸',
'fit_scale-down' => '智能適應',
'fit_cover' => '預設裁剪',
'current_fit_mode' => '當前顯示模式',
'advanced_color_settings' => '高級顏色設定',
'advanced_color_control' => '高級顏色控制',
'color_control' => '顏色控制',
'primary_hue' => '主色調',
'chroma' => '飽和度',
'lightness' => '亮度',
'or_use_palette' => '或使用調色盤',
'reset_to_default' => '重設為預設',
'preview_and_contrast' => '預覽與對比度',
'color_preview' => '顏色預覽',
'readability_check' => '可讀性檢查',
'contrast_between_text_and_bg' => '文字與背景的對比度:',
'hue_adjustment' => '色相調整',
'recent_colors' => '最近使用的顏色',
'apply' => '套用',
'excellent_aaa' => '優秀 (AAA)',
'good_aa' => '良好 (AA)',
'poor_needs_improvement' => '不足 (需要改進)',
'mount_point' => '掛載點:',
'used_space' => '已用空間:',
'file_summary' => '已選擇 %d 個文件,合計 %s MB',
'pageTitle' => '檔案助手',
'uploadBtn' => '上傳檔案',
'rootDirectory' => '根目錄',
'permissions' => '權限',
'actions' => '操作',
'directory' => '目錄',
'file' => '檔案',
'confirmDelete' => '確定要刪除 {0} 嗎?此操作無法還原。',
'newName' => '新名稱:',
'setPermissions' => '🔒 設定權限',
'modifiedTime' => '修改時間',
'owner' => '擁有者',
'create' => '建立',
'newFolder' => '新增資料夾',
'newFile' => '新增檔案',
'folderName' => '資料夾名稱:',
'searchFiles' => '搜尋檔案',
'noMatchingFiles' => '找不到符合的檔案。',
'moveTo' => '移至',
'confirm' => '確認',
'goBack' => '返回上一級',
'refreshDirectory' => '重新整理目錄內容',
'filePreview' => '檔案預覽',
'unableToLoadImage' => '無法載入圖片:',
'unableToLoadSVG' => '無法載入SVG檔案:',
'unableToLoadAudio' => '無法載入音訊:',
'unableToLoadVideo' => '無法載入影片:',
'fileAssistant' => '檔案助手',
'errorSavingFile' => '錯誤: 無法儲存檔案。',
'uploadFailed' => '上傳失敗',
'fileNotExistOrNotReadable' => '檔案不存在或無法讀取。',
'inputFileName' => '輸入檔案名稱',
'permissionValue' => '權限值(例如:0644)',
'inputThreeOrFourDigits' => '輸入三位或四位數字,例如:0644 或 0755',
'fontSizeL' => '字型大小',
'newNameCannotBeEmpty' => '新名稱不能為空',
'fileNameCannotContainChars' => '檔案名稱不能包含以下字元: < > : " / \\ | ? *',
'folderNameCannotBeEmpty' => '資料夾名稱不能為空',
'fileNameCannotBeEmpty' => '檔案名稱不能為空',
'searchError' => '搜尋時出錯: ',
'encodingChanged' => '編碼已更改為 {0}。實際轉換將在儲存時於伺服器端進行。',
'errorLoadingFileContent' => '載入檔案內容時出錯: ',
'permissionHelp' => '請輸入有效的權限值(三位或四位八進位數字,例如:644 或 0755)',
'permissionValueCannotExceed' => '權限值不能超過 0777',
'goBackTitle' => '返回上一級',
'rootDirectoryTitle' => '返回根目錄',
'homeDirectoryTitle' => '返回主目錄',
'refreshDirectoryTitle' => '重新整理目錄內容',
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/scp add_js.php | luci-theme-spectra/root/www/spectra/scp add_js.php | <?php
$files = [
'/usr/lib/lua/luci/view/passwall/node_list/node_list.htm',
'/usr/lib/lua/luci/view/passwall2/node_list/node_list.htm'
];
$js = <<<'EOD'
<!-- Passwall Card Layout JS - Auto Inject -->
<script defer src="/luci-static/spectra/js/card_layout.js"></script>
<script>
function saveCardOrder(group) {
const translations = languageTranslations[currentLang] || languageTranslations['zh'];
const container = document.querySelector(`.cards-container[data-group="${group}"]`);
if (!container) return;
const cards = container.querySelectorAll('.node-card');
if (!cards.length) return;
const btn = document.getElementById("save_order_btn_" + group);
if (btn) btn.disabled = true;
const ids = [];
cards.forEach(card => {
const id = card.getAttribute('data-id');
if (id) ids.push(id);
});
XHR.get('<%=api.url("save_node_order")%>', {
group: group,
ids: ids.join(",")
},
function(x, result) {
if (btn) btn.disabled = false;
if (x && x.status === 200) {
const successMsg = translations['node_order_save_success'] || "Save current page order successfully.";
if (typeof showLogMessage === 'function') {
showLogMessage(successMsg);
}
if (typeof colorVoiceEnabled !== 'undefined' && colorVoiceEnabled) {
speakMessage(successMsg);
}
} else {
const errorMsg = "<%:Save failed!%>";
if (typeof showLogMessage === 'function') {
showLogMessage(errorMsg);
}
if (typeof colorVoiceEnabled !== 'undefined' && colorVoiceEnabled) {
speakMessage(errorMsg);
}
}
});
}
</script>
<!-- End Passwall Card Layout JS -->
EOD;
$markerStart = '<!-- Passwall Card Layout JS - Auto Inject -->';
$markerEnd = '<!-- End Passwall Card Layout JS -->';
$action = isset($_GET['action']) ? $_GET['action'] : 'add';
foreach ($files as $file) {
if (!file_exists($file)) continue;
$content = file_get_contents($file);
if ($action === "remove") {
$pattern = '/' . preg_quote($markerStart, '/') . '.*?' . preg_quote($markerEnd, '/') . '\s*/s';
$newContent = preg_replace($pattern, '', $content);
if ($newContent !== $content) {
file_put_contents($file, $newContent);
}
continue;
}
if (strpos($content, $markerStart) !== false) {
continue;
}
file_put_contents($file, rtrim($content, "\n") . "\n\n" . $js . "\n");
}
exit;
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/search_cache.php | luci-theme-spectra/root/www/spectra/search_cache.php | <?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$cacheDir = dirname(__FILE__) . '/cache/';
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0755, true);
}
$cacheFile = $cacheDir . 'search_cache.json';
$query = $_POST['query'] ?? ($_GET['query'] ?? '');
$type = $_POST['type'] ?? ($_GET['type'] ?? 'song');
$source = $_POST['source'] ?? ($_GET['source'] ?? 'itunes');
if (isset($_GET['get_playlist']) && $_GET['get_playlist'] === '1') {
if (file_exists($cacheFile)) {
$cacheData = json_decode(file_get_contents($cacheFile), true);
if (!$cacheData) {
echo json_encode(['success' => false, 'message' => 'Cache file corrupted']);
exit;
}
if ($cacheData['query'] === $query &&
$cacheData['type'] === $type &&
$cacheData['source'] === $source) {
echo json_encode([
'success' => true,
'data' => $cacheData,
'playlist_ready' => true
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} else {
echo json_encode(['success' => false, 'message' => 'Cache mismatch for playlist'], JSON_UNESCAPED_SLASHES);
}
} else {
echo json_encode(['success' => false, 'message' => 'No cache available for playlist'], JSON_UNESCAPED_SLASHES);
}
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$results = $_POST['results'] ?? '[]';
if (is_string($results)) {
$results = json_decode($results, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode([
'success' => false,
'message' => 'Invalid JSON data: ' . json_last_error_msg()
], JSON_UNESCAPED_SLASHES);
exit;
}
}
$uniqueResults = removeDuplicates($results, $source);
$cacheData = [
'query' => $query,
'type' => $type,
'source' => $source,
'results' => $uniqueResults,
'timestamp' => time(),
'date' => date('Y-m-d H:i:s'),
'original_count' => count($results),
'unique_count' => count($uniqueResults),
'is_playlist' => false
];
$result = file_put_contents($cacheFile, json_encode($cacheData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
if ($result === false) {
echo json_encode([
'success' => false,
'message' => 'Failed to write cache file'
], JSON_UNESCAPED_SLASHES);
exit;
}
echo json_encode([
'success' => true,
'message' => 'Cache saved (duplicates removed)',
'stats' => [
'original' => count($results),
'unique' => count($uniqueResults),
'removed' => count($results) - count($uniqueResults)
]
], JSON_UNESCAPED_SLASHES);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $query && $source) {
if (file_exists($cacheFile)) {
$cacheData = json_decode(file_get_contents($cacheFile), true);
if (!$cacheData) {
echo json_encode(['success' => false, 'message' => 'Cache file corrupted'], JSON_UNESCAPED_SLASHES);
exit;
}
if ($cacheData['query'] === $query &&
$cacheData['type'] === $type &&
$cacheData['source'] === $source) {
if (time() - $cacheData['timestamp'] < 86400) {
echo json_encode(['success' => true, 'data' => $cacheData], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} else {
echo json_encode(['success' => false, 'message' => 'Cache expired'], JSON_UNESCAPED_SLASHES);
}
} else {
echo json_encode(['success' => false, 'message' => 'Cache mismatch'], JSON_UNESCAPED_SLASHES);
}
} else {
echo json_encode(['success' => false, 'message' => 'Cache not found'], JSON_UNESCAPED_SLASHES);
}
exit;
}
if (isset($_GET['get_latest']) && $_GET['get_latest'] === '1') {
if (file_exists($cacheFile)) {
$cacheData = json_decode(file_get_contents($cacheFile), true);
if (!$cacheData) {
echo json_encode(['success' => false, 'message' => 'Cache file corrupted'], JSON_UNESCAPED_SLASHES);
exit;
}
if (time() - $cacheData['timestamp'] < 86400) {
echo json_encode(['success' => true, 'data' => $cacheData], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} else {
unlink($cacheFile);
echo json_encode(['success' => false, 'message' => 'Cache expired and deleted'], JSON_UNESCAPED_SLASHES);
}
} else {
echo json_encode(['success' => false, 'message' => 'No cache available'], JSON_UNESCAPED_SLASHES);
}
exit;
}
function removeDuplicates($results, $source) {
if (!$results || !is_array($results)) {
return [];
}
$seen = [];
$uniqueResults = [];
foreach ($results as $item) {
$uniqueId = getUniqueIdentifier($item, $source);
if (!in_array($uniqueId, $seen)) {
$seen[] = $uniqueId;
$uniqueResults[] = $item;
}
}
return $uniqueResults;
}
function getUniqueIdentifier($item, $source) {
switch($source) {
case 'itunes':
return isset($item['trackId']) ? 'itunes_' . $item['trackId'] : md5(json_encode($item, JSON_UNESCAPED_SLASHES));
case 'spotify':
return isset($item['id']) ? 'spotify_' . $item['id'] : md5(json_encode($item, JSON_UNESCAPED_SLASHES));
case 'youtube':
if (isset($item['id']['videoId'])) {
return 'youtube_' . $item['id']['videoId'];
} elseif (isset($item['id'])) {
return 'youtube_' . $item['id'];
}
return md5(json_encode($item, JSON_UNESCAPED_SLASHES));
case 'soundcloud':
return isset($item['id']) ? 'soundcloud_' . $item['id'] : md5(json_encode($item, JSON_UNESCAPED_SLASHES));
default:
$title = isset($item['trackName']) ? $item['trackName'] :
(isset($item['name']) ? $item['name'] :
(isset($item['title']) ? $item['title'] : ''));
$artist = isset($item['artistName']) ? $item['artistName'] :
(isset($item['artists'][0]['name']) ? $item['artists'][0]['name'] :
(isset($item['channelTitle']) ? $item['channelTitle'] : ''));
return md5($title . '_' . $artist);
}
}
echo json_encode(['success' => false, 'message' => 'Invalid request'], JSON_UNESCAPED_SLASHES);
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/api_keys_proxy.php | luci-theme-spectra/root/www/spectra/api_keys_proxy.php | <?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
$configFile = dirname(__FILE__) . '/api_keys.config.php';
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);
switch ($action) {
case 'get':
if (file_exists($configFile)) {
$keys = include $configFile;
echo json_encode([
'success' => true,
'keys' => $keys
]);
} else {
echo json_encode([
'success' => false,
'message' => 'Configuration file does not exist',
'keys' => [
'spotify' => ['client_id' => '', 'client_secret' => ''],
'youtube' => ['api_key' => ''],
'soundcloud' => ['client_id' => '']
]
]);
}
break;
case 'save':
if (isset($input['keys'])) {
$keys = $input['keys'];
$configContent = "<?php\nreturn [\n";
// Spotify
$configContent .= " 'spotify' => [\n";
$configContent .= " 'client_id' => '" . addslashes(trim($keys['spotify']['client_id'] ?? '')) . "',\n";
$configContent .= " 'client_secret' => '" . addslashes(trim($keys['spotify']['client_secret'] ?? '')) . "',\n";
$configContent .= " ],\n";
// YouTube
$configContent .= " 'youtube' => [\n";
$configContent .= " 'api_key' => '" . addslashes(trim($keys['youtube']['api_key'] ?? '')) . "',\n";
$configContent .= " ],\n";
// SoundCloud
$configContent .= " 'soundcloud' => [\n";
$configContent .= " 'client_id' => '" . addslashes(trim($keys['soundcloud']['client_id'] ?? '')) . "',\n";
$configContent .= " ],\n";
$configContent .= "];\n";
try {
if (file_put_contents($configFile, $configContent, LOCK_EX)) {
chmod($configFile, 0644);
echo json_encode([
'success' => true,
'message' => 'API keys saved successfully'
]);
} else {
$error = error_get_last();
echo json_encode([
'success' => false,
'message' => 'Failed to write file: ' . ($error['message'] ?? 'Unknown error')
]);
}
} catch (Exception $e) {
echo json_encode([
'success' => false,
'message' => 'Save failed: ' . $e->getMessage()
]);
}
} else {
echo json_encode([
'success' => false,
'message' => 'No key data provided'
]);
}
break;
default:
echo json_encode([
'success' => false,
'message' => 'Invalid action'
]);
break;
}
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/api_keys.config.php | luci-theme-spectra/root/www/spectra/api_keys.config.php | <?php
return [
'spotify' => [
'client_id' => '',
'client_secret' => '',
],
'youtube' => [
'api_key' => '',
],
'soundcloud' => [
'client_id' => '',
],
];
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/clear_cache.php | luci-theme-spectra/root/www/spectra/clear_cache.php | <?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$cacheDir = dirname(__FILE__) . '/cache/';
$cacheFile = $cacheDir . 'search_cache.json';
$result = [
'success' => false,
'message' => '',
'timestamp' => time()
];
if (file_exists($cacheFile)) {
if (unlink($cacheFile)) {
$result['success'] = true;
$result['message'] = 'Cache cleared successfully';
$result['deleted'] = true;
} else {
$result['message'] = 'Failed to delete cache file';
$result['error'] = error_get_last()['message'] ?? 'Unknown error';
}
} else {
$result['success'] = true;
$result['message'] = 'No cache file to clear';
$result['deleted'] = false;
}
echo json_encode($result);
exit;
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/playlist_config.php | luci-theme-spectra/root/www/spectra/playlist_config.php | <?php
header('Content-Type: application/json');
$playlistFile = __DIR__ . '/lib/playlist.txt';
$defaultPlaylistUrl = 'https://raw.githubusercontent.com/Thaolga/Rules/main/music/songs.txt';
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
if (file_exists($playlistFile)) {
$url = file_get_contents($playlistFile);
if (empty(trim($url))) {
$url = $defaultPlaylistUrl;
file_put_contents($playlistFile, $url);
}
} else {
$url = $defaultPlaylistUrl;
file_put_contents($playlistFile, $url);
}
echo json_encode(['url' => trim($url)]);
} elseif ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
$newUrl = isset($input['url']) ? trim($input['url']) : '';
if (!empty($newUrl)) {
if (file_put_contents($playlistFile, $newUrl) !== false) {
echo json_encode(['success' => true, 'message' => 'Playlist URL updated successfully']);
} else {
echo json_encode(['success' => false, 'message' => 'Failed to update playlist URL']);
}
} else {
echo json_encode(['success' => false, 'message' => 'Invalid URL provided']);
}
} else {
echo json_encode(['success' => false, 'message' => 'Unsupported request method']);
}
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/index.php | luci-theme-spectra/root/www/spectra/index.php | <?php
ini_set('memory_limit', '256M');
$base_dir = __DIR__;
$upload_dir = $base_dir . '/stream';
$allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'webm', 'mkv', 'mp3', 'wav', 'flac', 'ogg'];
$background_type = '';
$background_src = '';
$lang = $_POST['lang'] ?? $_GET['lang'] ?? 'en';
$lang = isset($langData[$lang]) ? $lang : 'en';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_file'])) {
$files = $_FILES['upload_file'];
$upload_errors = [];
foreach ($files['name'] as $key => $filename) {
if ($files['error'][$key] === UPLOAD_ERR_OK) {
$raw_filename = urldecode($filename);
$ext = strtolower(pathinfo($raw_filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed_types)) {
$upload_errors[] = sprintf($langData[$lang]['upload_error_type_not_supported'] ?? 'Unsupported file type: %s', $raw_filename);
continue;
}
$basename = pathinfo($raw_filename, PATHINFO_FILENAME);
$safe_basename = preg_replace([
'/[^\p{L}\p{N}_\- ]/u',
'/\s+/',
'/_+/',
'/-+/'
], [
'_',
'_',
'_',
'-'
], $basename);
$safe_basename = trim($safe_basename, '_.- ');
if (empty($safe_basename)) {
$safe_basename = uniqid();
}
$counter = 1;
$final_name = "{$safe_basename}.{$ext}";
$target_path = "{$upload_dir}/{$final_name}";
while (file_exists($target_path)) {
$final_name = "{$safe_basename}_{$counter}.{$ext}";
$target_path = "{$upload_dir}/{$final_name}";
$counter++;
}
if (!move_uploaded_file($files['tmp_name'][$key], $target_path)) {
$upload_errors[] = sprintf($langData[$lang]['upload_error_move_failed'] ?? 'Upload failed: %s', $final_name);
}
}
}
if (!empty($upload_errors)) {
$error_message = urlencode(implode("\n", $upload_errors));
header("Location: " . $_SERVER['PHP_SELF'] . "?error=" . $error_message);
exit;
}
}
if (isset($_GET['delete'])) {
$file = $upload_dir . '/' . basename($_GET['delete']);
if (file_exists($file)) {
unlink($file);
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
}
if (isset($_POST['rename'])) {
$oldName = $_POST['old_name'];
$newName = trim($_POST['new_name']);
$oldPath = $upload_dir . DIRECTORY_SEPARATOR . basename($oldName);
$newPath = $upload_dir . DIRECTORY_SEPARATOR . basename($newName);
$error = '';
if (!file_exists($oldPath)) {
$error = 'Original file does not exist';
} elseif ($newName === '') {
$error = 'File name cannot be empty';
} elseif (preg_match('/[\\\\\/:*?"<>|]/', $newName)) {
$error = 'Contains invalid characters: \/:*?"<>|';
} elseif (file_exists($newPath)) {
$error = 'Target file already exists';
}
if (!$error) {
if (rename($oldPath, $newPath)) {
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
} else {
$error = 'Operation failed (permissions/character issues)';
}
}
if ($error) {
echo '<div class="alert alert-danger mb-3">Error: '
. htmlspecialchars($error, ENT_QUOTES, 'UTF-8')
. '</div>';
}
}
if (isset($_GET['download'])) {
$file = $_GET['download'];
$filePath = $upload_dir . '/' . $file;
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
} else {
$error = "File not found: " . htmlspecialchars($file);
}
}
if (isset($_POST['batch_delete'])) {
$deleted_files = [];
foreach ($_POST['filenames'] as $filename) {
$file = $upload_dir . '/' . basename($filename);
if (file_exists($file)) {
unlink($file);
$deleted_files[] = $filename;
}
}
header('Content-Type: application/json');
echo json_encode(['success' => true, 'deleted_files' => $deleted_files]);
exit;
}
$files = array_diff(scandir($upload_dir), ['..', '.', '.htaccess', 'index.php']);
$files = array_filter($files, function ($file) use ($upload_dir) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
return !in_array(strtolower($ext), ['php', 'txt', 'json']) && basename($file) !== 'shares' && !is_dir($upload_dir . DIRECTORY_SEPARATOR . $file);
});
if (isset($_GET['background'])) {
$background_src = 'stream/' . htmlspecialchars($_GET['background']);
$ext = strtolower(pathinfo($background_src, PATHINFO_EXTENSION));
if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
$background_type = 'image';
} elseif (in_array($ext, ['mp4', 'webm', 'mkv'])) {
$background_type = 'video';
}
}
?>
<?php
if (!empty($_GET['error'])) {
echo '<div class="alert alert-danger mt-3 mx-3" role="alert" id="log-message">';
echo nl2br(htmlspecialchars(urldecode($_GET['error'])));
echo '</div>';
}
?>
<head>
<meta charset="utf-8">
<title>Media File Management</title>
<?php include './spectra.php'; ?>
<script>
const phpBackgroundType = '<?= $background_type ?>';
const phpBackgroundSrc = '<?= $background_src ?>';
</script>
<style>
#mainContainer { display: none; }
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
try {
const container = document.getElementById('mainContainer');
if (!container) return;
const isFullscreen = localStorage.getItem('fullscreenState') === 'true';
container.classList.toggle('container-fluid', isFullscreen);
container.classList.toggle('container-sm', !isFullscreen);
container.style.display = 'block';
const toggleBtn = document.getElementById('toggleScreenBtn');
if (toggleBtn) {
const icon = toggleBtn.querySelector('i');
icon.className = isFullscreen ? 'bi-fullscreen-exit' : 'bi-arrows-fullscreen';
}
toggleBtn.addEventListener('click', function() {
const isNowFullscreen = container.classList.contains('container-fluid');
const icon = this.querySelector('i');
container.classList.toggle('container-fluid', !isNowFullscreen);
container.classList.toggle('container-sm', isNowFullscreen);
icon.className = isNowFullscreen ? 'bi-arrows-fullscreen' : 'bi-fullscreen-exit';
localStorage.setItem('fullscreenState', !isNowFullscreen);
});
} catch (error) {
const container = document.getElementById('mainContainer');
if (container) container.style.display = 'block';
}
});
</script>
<style>
html,
body {
color: var(--text-primary);
-webkit-backdrop-filter: blur(10px);
transition: all 0.3s ease;
font-family: 'Fredoka One', cursive;
font-weight: 400;
background: inherit !important;
font-family: var(--font-family, -apple-system, BlinkMacSystemFont, sans-serif);
}
.container-bg,
.card,
.modal-content,
.table {
--bg-l: oklch(30% 0 0);
color: oklch(calc(100% - var(--bg-l)) 0 0);
}
.container-bg {
padding: 20px;
border-radius: 10px;
background: var(--bg-container);
margin-top: 15px !important;
box-shadow: 1px 0 3px -2px color-mix(in oklch, var(--bg-container), black 30%) !important;
}
.time-display {
font-size: 1.4rem !important;
color: var(--text-primary);
padding: 6px 12px !important;
display: flex !important;
align-items: center !important;
flex-wrap: wrap !important;
gap: 8px !important;
}
.week-display {
color: var(--text-secondary);
margin-left: 6px !important;
}
.lunar-text {
color: var(--text-secondary);
}
#timeDisplay {
font-weight: 500 !important;
color: var(--accent-color);
margin-left: auto !important;
}
.modern-time {
font-weight: 500 !important;
}
.ancient-time {
margin-left: 4px !important;
letter-spacing: 1px !important;
}
.card {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 1rem;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
transition: all 0.3s ease;
overflow: hidden;
}
.card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.card img,
.card video {
border-top-left-radius: 1rem;
border-top-right-radius: 1rem;
}
.card-header {
background: var(--card-bg) !important;
border-bottom: 1px solid var(--card-bg);
}
.table {
--bs-table-bg: var(--card-bg);
--bs-table-color: var(--text-primary);
--bs-table-border-color: var(--border-color);
--bs-table-striped-bg: rgba(0, 0, 0, 0.05);
}
.btn {
border-radius: 8px;
font-weight: bold;
transition: transform 0.2s;
}
.btn:hover {
transform: scale(1.1);
}
.btn-primary {
background: var(--btn-primary-bg);
border: 1px solid var(--border-color);
}
.btn-info {
background-color: var(--btn-info-bg) !important;
color: white !important;
border: none !important;
&:hover {
background-color: var(--btn-info-hover) !important;
color: white !important;
}
}
.btn-warning {
background-color: var(--btn-warning-bg) !important;
color: white !important;
border: none !important;
&:hover {
background-color: var(--btn-warning-hover) !important;
color: white !important;
}
}
#status {
font-size: 22px;
color: var(--accent-color) !important;
}
h5,
h2 {
color: var(--accent-color) !important;
font-weight: bold;
}
.img-thumbnail {
background: var(--bg-container);
border: 1px solid var(--border-color);
}
#toggleButton {
background-color: var(--sand-bg);
}
.modal-content {
background: var(--bg-container);
border: 1px solid var(--border-color);
}
.modal-header {
background: var(--header-bg);
border-bottom: 1px solid var(--border-color);
}
.modal-title {
color: var(--accent-color) !important;
}
.modal-body {
background: var(--card-bg);
color: var(--text-primary);
}
label {
color: var(--text-primary) !important;
}
label[for="selectAll"] {
margin-left: 8px;
vertical-align: middle;
}
.preview-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.file-info-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0,0,0,0.7);
color: white;
padding: 0.5rem;
transform: translateY(100%);
transition: 0.2s;
font-size: 0.8em;
}
.file-type-indicator {
position: absolute;
top: 8px;
right: 8px;
z-index: 2;
background: rgba(0,0,0,0.6);
padding: 4px 10px;
border-radius: 15px;
display: flex;
align-items: center;
gap: 6px;
backdrop-filter: blur(2px);
}
.preview-container:hover .file-info-overlay {
transform: translateY(0);
}
.preview-img {
position: absolute;
min-width: 100%;
min-height: 100%;
object-fit: cover;
}
.preview-container:hover .preview-img {
transform: scale(1.05);
}
.video-wrapper {
width: 100%;
height: 0;
padding-top: 56.25%;
position: relative;
}
.preview-video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.preview-video:hover::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 40px;
height: 40px;
background: rgba(255,255,255,0.8) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='%23000000'%3E%3Cpath d='M8 5v14l11-7z'/%3E%3C/svg%3E") no-repeat center;
border-radius: 50%;
opacity: 0.8;
pointer-events: none;
}
.card:hover .preview-img {
transform: scale(1.03);
}
.fileCheckbox {
margin-right: 8px;
transform: scale(1.2);
}
#previewImage, #previewVideo {
max-width: 100%;
max-height: 100vh;
object-fit: contain;
}
.card-body.pt-2.mt-2 .d-flex {
justify-content: center;
}
.card-body.pt-2.mt-2 .d-flex .btn {
margin: 0 5px;
}
.d-flex {
white-space: nowrap;
}
#playlistContainer .list-group-item {
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
padding: 0.75rem 1rem;
word-wrap: break-word;
word-break: break-word;
overflow-wrap: break-word;
white-space: normal;
background-color: var(--card-bg);
color: var(--playlist-text);
border-left: var(--item-border);
}
#playlistContainer .list-group-item:hover {
background-color: var(--item-hover-bg) !important;
box-shadow: var(--item-hover-shadow);
transform: scale(1.02);
--playlist-text: oklch(100% 0 0);
color: var(--playlist-text);
}
[data-theme="light"] #playlistContainer .list-group-item:hover {
--playlist-text: oklch(20% 0 0);
}
#playlistContainer .badge {
width: 24px;
text-align: center;
font-weight: normal;
background-color: var(--btn-primary-bg);
color: var(--text-primary);
}
#playlistContainer .delete-item {
opacity: 0.6;
transition: opacity 0.3s;
color: var(--text-primary);
}
#playlistContainer .delete-item:hover {
opacity: 1;
}
#playlistContainer {
overflow-x: hidden;
overflow-y: auto;
background-color: var(--bg-container);
}
#playlistContainer .text-truncate {
display: inline-block;
width: 100%;
white-space: normal;
word-wrap: break-word;
word-break: break-word;
font-size: 1.1em;
line-height: 1.4;
color: var(--text-primary);
}
#playlistContainer .list-group-item {
padding: 1rem 1.5rem;
margin-bottom: 3px;
border-radius: 6px;
transition: all 0.3s ease;
background-color: var(--card-bg);
color: var(--text-primary);
}
#playlistContainer .list-group-item:nth-child(odd) {
background-color: var(--card-bg);
border-left: 3px solid var(--border-color);
color: var(--text-primary);
}
#playlistContainer .list-group-item:nth-child(even) {
background-color: var(--card-bg);
border-left: 3px solid var(--border-color);
color: var(--text-primary);
}
#playlistContainer .list-group-item.active {
background: var(--color-accent) !important;
border-color: var(--color-accent);
box-shadow: none;
z-index: 2;
color: var(--text-primary);
}
#playlistContainer .list-group-item:hover {
background-color: var(--color-accent);
transform: translateX(5px);
cursor: pointer;
}
.text-muted {
color: var(--accent-color) !important;
font-size: 1.2em;
letter-spacing: 0.5px;
opacity: 0.7;
}
::-webkit-scrollbar {
width: 8px;
opacity: 0 !important;
transition: opacity 0.3s ease-in-out;
}
::-webkit-scrollbar-thumb {
background: var(--accent-color);
border-radius: 4px;
}
::-webkit-scrollbar-track {
margin: 50px 0;
}
body:hover,
.container:hover,
#playlistContainer:hover {
overflow-x: hidden !important;
overflow-y: auto !important;
}
#playlistContainer {
cursor: default;
}
#playlistContainer:hover {
cursor: grab;
}
#playlistContainer:active {
cursor: grabbing;
}
::-webkit-scrollbar:horizontal {
display: none !important;
height: 0 !important;
}
@supports (scrollbar-width: none) {
html {
scrollbar-width: none !important;
}
}
.drop-zone {
position: relative;
border: 2px dashed transparent;
border-radius: 10px;
padding: 2rem;
z-index: 1;
}
.drop-zone::before {
content: "";
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
z-index: -1;
border: 2px dashed var(--bs-primary);
border-radius: 10px;
animation: border-wave 2s linear infinite;
pointer-events: none;
mask-image: linear-gradient(90deg, #000 50%, transparent 0%);
mask-size: 10px 100%;
mask-repeat: repeat;
-webkit-mask-image: linear-gradient(90deg, #000 50%, transparent 0%);
-webkit-mask-size: 10px 100%;
-webkit-mask-repeat: repeat;
}
@keyframes border-wave {
0% {
mask-position: 0 0;
}
100% {
mask-position: 100% 0;
}
}
.drop-zone:hover::before {
border-color: var(--accent-color);
}
.upload-icon {
font-size: 50px;
color: var(--accent-color);
margin-bottom: 15px;
}
.upload-text {
font-size: 18px;
font-weight: 500;
color: var(--text-primary);
margin-bottom: 10px;
}
#customUploadButton {
--btn-hover-bg: color-mix(in oklch, var(--btn-primary-bg), white 8%);
background: var(--btn-primary-bg);
position: relative;
overflow: hidden;
&: :after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(circle at 50% 50%,
oklch(100% 0 0 / 0.15) 0%,
transparent 70%);
opacity: 0;
transition: opacity 0.3s ease;
}
&:hover {
background: var(--btn-hover-bg);
transform: translateY(-2px) scale(1.05);
&: :after {
opacity: 1;
}
}
}
.file-list {
max-height: 200px;
overflow-y: auto;
background: var(--file-list-bg);
border: 1px solid var(--file-list-border);
scrollbar-width: thin;
scrollbar-color: var(--accent-color) transparent;
&: :-webkit-scrollbar-thumb {
background: var(--accent-color);
border-radius: 4px;
}
}
.file-list-item {
border-bottom-color: color-mix(in oklch, var(--file-list-border), transparent 50%);
transition: background 0.2s ease;
&: hover {
background: color-mix(in oklch, var(--btn-primary-bg), transparent 80%);
}
}
.remove-file {
color: var(--accent-color) !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.remove-file:hover {
color: oklch(65% 0.25 15) !important;
filter: drop-shadow(0 0 4px oklch(65% 0.3 15 / 0.3));
transform: scale(1.15);
}
[data-theme="light"] .remove-file:hover {
color: oklch(50% 0.3 15) !important;
filter: drop-shadow(0 0 6px oklch(50% 0.3 15 / 0.2));
}
@keyframes danger-pulse {
0% {
opacity: 0.8;
}
50% {
opacity: 1;
}
100% {
opacity: 0.8;
}
}
.remove-file:hover::after {
position: absolute;
right: -1.2em;
top: 50%;
transform: translateY(-50%);
animation: danger-pulse 1.5s ease infinite;
filter: hue-rotate(-20deg);
}
.file-list-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
min-height: 42px;
}
.remove-file {
display: inline-flex !important;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
margin-left: 12px;
font-size: 1.25rem;
vertical-align: middle;
position: relative;
top: 1px;
}
.bi-file-earmark {
font-size: 1.1rem;
margin-right: 10px;
position: relative;
top: -1px;
}
.file-list-item > div:first-child {
display: inline-flex;
align-items: center;
max-width: calc(100% - 40px);
line-height: 1.4;
}
.file-list-item:last-child {
border-bottom: none;
}
.file-list-item i {
color: var(--accent-color);
margin-right: 8px;
}
.btn-close {
width: 15px !important;
height: 15px !important;
background-color: #30e8dc !important;
border-radius: 6px !important;
border: none !important;
position: relative !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
cursor: pointer !important;
transition: background-color 0.2s ease, transform 0.2s ease !important;
}
.btn-close::before,
.btn-close::after {
content: '' !important;
position: absolute !important;
width: 12px !important;
height: 2px !important;
background-color: #ff4d4f !important;
border-radius: 2px !important;
transition: background-color 0.2s ease !important;
}
.btn-close::before {
transform: rotate(45deg) !important;
}
.btn-close::after {
transform: rotate(-45deg) !important;
}
.btn-close:hover {
background-color: #30e8dc !important;
transform: scale(1.1) !important;
}
.btn-close:hover::before,
.btn-close:hover::after {
background-color: #d9363e !important;
}
.btn-close:active {
transform: scale(0.9) !important;
}
.card:hover .fileCheckbox {
filter: drop-shadow(0 0 3px rgba(13, 110, 253, 0.5));
}
@media (max-width: 576px) {
.fileCheckbox {
transform: scale(1.1) !important;
}
}
</style>
<style>
.custom-btn {
padding: 4px 8px;
font-size: 14px;
gap: 4px;
}
.custom-btn i {
font-size: 16px;
}
.d-flex .custom-btn {
margin: 0 4px;
}
.share-btn.custom-btn {
background-color: #ffc107;
color: #fff;
padding: 6px 8px;
font-size: 14px;
}
.share-btn.custom-btn i {
font-size: 16px;
}
.set-bg-btn.custom-btn {
background-color: #17a2b8;
color: #fff;
padding: 6px 8px;
font-size: 14px;
}
#previewModal .modal-body {
height: 65vh;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
#previewImage,
#previewVideo {
max-height: 100%;
width: 100%;
object-fit: contain;
}
#previewAudio {
width: auto;
max-width: 80%;
margin: 20px auto 0;
display: block;
border-radius: 10px;
padding: 5px 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#previewAudio.d-none {
display: none;
}
.hover-tips {
font-size: 1.3rem;
color: var(--accent-color);
margin-top: 10px;
}
.file-info-overlay p {
margin-bottom: 0.5rem;
text-align: left;
}
.preview-nav-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 3rem;
color: var(--nav-btn-color);
cursor: pointer;
z-index: 1000;
opacity: 0;
transition: opacity 0.3s;
}
.modal-content:hover .preview-nav-btn {
opacity: 1;
}
#prevBtn {
left: 20px;
}
#nextBtn {
right: 20px;
}
.loading-spinner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40px;
height: 40px;
border: 3px solid var(--border-color);
border-top: 3px solid var(--accent-color);
border-radius: 50%;
animation: spin 1s linear infinite;
display: none;
}
@keyframes spin {
0% { transform: translate(-50%, -50%) rotate(0deg); }
100% { transform: translate(-50%, -50%) rotate(360deg); }
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
.drag-handle {
cursor: grab;
z-index: 10;
user-select: none;
}
.sortable-chosen .drag-handle {
cursor: grabbing;
}
[data-filename] {
cursor: grab;
}
.sortable-chosen {
cursor: grabbing !important;
}
.upload-area i {
animation: pulse 1s infinite;
}
.file-checkbox-wrapper {
opacity: 0;
transition: opacity 0.2s ease-in-out;
}
.fileCheckbox:checked + .file-checkbox-wrapper,
.file-checkbox-wrapper.force-visible {
opacity: 1 !important;
}
@media (min-width: 768px) {
.card:hover .file-checkbox-wrapper:not(.force-visible) {
opacity: 1;
}
}
@media (max-width: 767.98px) {
.file-checkbox-wrapper {
opacity: 1 !important;
}
}
@media (max-width: 576px) {
.card-body .btn {
font-size: 0.75rem !important;
padding: 0.25rem 0.5rem !important;
white-space: nowrap;
}
}
@media (max-width: 768px) {
#previewAudio {
width: 95% !important;
max-width: none;
}
}
@media (max-width: 768px) {
.me-3.d-flex.gap-2.mt-4.ps-2 {
flex-direction: column;
align-items: flex-start;
gap: 0.3rem;
padding-left: 15px;
margin-bottom: 0.5rem !important;
}
@media (max-width: 768px) {
.controls {
gap: 0.1rem;
}
.controls .control-btn {
font-size: 0.7rem;
padding: 0.1rem 0.2rem;
border-radius: 50%;
}
.controls .btn {
padding: 0.1rem 0.2rem;
}
}
@media (max-width: 575.98px) {
.time-display {
display: flex !important;
flex-wrap: wrap !important;
gap: 0.25rem 0.5rem !important;
font-size: 1.05rem !important;
}
.time-display > span {
box-sizing: border-box;
white-space: nowrap !important;
overflow: visible !important;
}
.time-display > span:nth-child(1),
.time-display > span:nth-child(2) {
flex: 0 0 33.33% !important;
order: 1;
}
.time-display > span:nth-child(3),
.time-display > span:nth-child(4) {
flex: 0 0 100% !important;
order: 2;
margin-top: 0.25rem !important;
text-align: center !important;
}
.lunar-text {
font-size: 1.05rem !important;
letter-spacing: -0.3px !important;
}
}
@media (max-width: 576px) {
#fontToggleBtn {
margin-right: 8px;
}
#langBtnWrapper {
margin-left: 6px;
}
}
@media (max-width: 576px) {
.share-btn.custom-btn {
display: none !important;
}
}
@media (max-width: 576px) {
.custom-btn {
margin-right: 0px !important;
}
}
@media (max-width: 575.98px) {
#fontToggleBtn {
min-height: 26px;
padding: 8px 14px;
}
#fontToggleBtn i {
font-size: 1.1rem;
}
}
@media (max-width: 576px) {
.card-body .custom-btn {
padding: 0.2rem 0.3rem !important;
font-size: 0.8rem !important;
}
}
@media (max-width: 576px) {
#fileGrid .card {
padding: 0.25rem;
}
#fileGrid .card .card-body {
padding: 0.25rem;
}
#fileGrid .card h5,
#fileGrid .card p,
#fileGrid .card .file-info-overlay p {
font-size: 0.75rem;
margin: 0.125rem 0;
}
#fileGrid .card .preview-container {
max-height: 180px;
overflow: hidden;
}
#fileGrid .card .custom-btn {
padding: 0.25rem 0.4rem;
font-size: 0.75rem;
}
}
@media (max-width: 768px) {
.btn i {
font-size: 0.8rem !important;
margin-left: 3px;
}
}
@media (max-width: 575.98px) {
#selectAll-container input[type="checkbox"] {
transform: scale(1) !important;
width: 1em !important;
height: 1em !important;
margin-left: 0 !important;
margin-right: 0.3rem !important;
flex-shrink: 0;
}
#selectAll-container {
flex-wrap: nowrap !important;
gap: 0.2rem !important;
overflow-x: auto;
}
#selectAll-container input[type="checkbox"] {
margin-right: 0.15rem !important;
}
#selectAll-container label[for="selectAll"] {
margin-right: 0.2rem !important;
}
#selectAll-container input[type="color"],
#selectAll-container button {
margin-right: 0.2rem !important;
}
}
</style>
<div class="container-sm container-bg text-center mt-4" id="mainContainer">
<div class="alert alert-secondary d-none" id="toolbar">
<div class="d-flex justify-content-between flex-column flex-sm-row">
<div>
<button class="btn btn-outline-primary" id="selectAllBtn" data-translate="select_all"></button>
<span id="selectedInfo"></span>
</div>
<button class="btn btn-danger" id="batchDeleteBtn" data-translate="batch_delete"></button>
</div>
</div>
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center py-2">
<div class="time-display">
<span id="dateDisplay"></span>
<span id="weekDisplay"></span>
<span id="lunarDisplay" class="lunar-text"></span>
<span id="timeDisplay"></span>
</div>
<div class="weather-display d-flex align-items-center d-none d-sm-inline">
<i id="weatherIcon" class="wi wi-na" style="font-size:28px; margin-right:4px;"></i>
<span id="cityNameDisplay" style="color:var(--accent-color); font-weight:700;"></span>
<span id="weatherText" style="color:var(--accent-color); font-weight: 700;"></span>
</div>
</div>
<div class="card-header d-flex flex-column flex-md-row justify-content-between align-items-center text-center gap-2">
<h5 class="mb-0" style="line-height: 40px; height: 40px;" data-translate="spectra_config"></h5>
<p id="status" class="mb-0"><span data-translate="current_mode"></span></p>
<button id="toggleButton" onclick="toggleConfig()" class="btn btn-primary" data-translate="toggle_mode"></button>
</div>
<div class="d-flex align-items-center">
<?php
$mountPoint = '/';
$freeSpace = @disk_free_space($mountPoint);
$totalSpace = @disk_total_space($mountPoint);
$usedSpace = $totalSpace - $freeSpace;
function formatSize($bytes) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$index = 0;
while ($bytes >= 1024 && $index < count($units) - 1) {
$bytes /= 1024;
$index++;
}
return round($bytes, 2) . ' ' . $units[$index];
}
?>
<div class="me-3 d-flex gap-2 mt-2 ps-2"
data-translate-tooltip="mount_info" data-mount-point="<?= $mountPoint ?>" data-used-space="<?= $usedSpace ? formatSize($usedSpace) : 'N/A' ?>" data-tooltip="">
<span class="btn btn-primary btn-sm mb-2 d-none d-sm-inline"><i class="bi bi-hdd"></i> <span data-translate="total">Total:</span><?= $totalSpace ? formatSize($totalSpace) : 'N/A' ?></span>
<span class="btn btn-success btn-sm mb-2 d-none d-sm-inline"><i class="bi bi-hdd"></i> <span data-translate="free">Free:</span><?= $freeSpace ? formatSize($freeSpace) : 'N/A' ?></span>
</div>
<button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#updateConfirmModal" data-translate-tooltip="check_update"><i class="fas fa-cloud-download-alt"></i> <span class="btn-label"></span></button>
<button class="btn btn-warning ms-2" data-bs-toggle="modal" data-bs-target="#uploadModal" data-translate-tooltip="batch_upload"><i class="bi bi-upload"></i> <span class="btn-label"></span></button>
<button class="btn btn-primary ms-2" id="openPlayerBtn" data-bs-toggle="modal" data-bs-target="#playerModal" data-translate-tooltip="add_to_playlist"><i class="bi bi-play-btn"></i> <span class="btn-label"></span></button>
<button class="btn btn-success ms-2 d-none d-sm-inline" id="toggleScreenBtn" data-translate-tooltip="toggle_fullscreen"><i class="bi bi-arrows-fullscreen"></i></button>
<button type="button" class="btn btn-primary ms-2 d-none d-sm-inline" onclick="showIpDetailModal()" data-translate-tooltip="ip_info"><i class="fa-solid fa-satellite-dish"></i></button>
<button class="btn btn-danger ms-2" id="clearBackgroundBtn" data-translate-tooltip="clear_background"><i class="bi bi-trash"></i> <span class="btn-label"></span></button>
</div>
</div>
<h2 class="mt-3 mb-0" data-translate="file_list">File List</h2>
<div class="card-body">
<?php if (isset($error)): ?>
<div class="alert alert-danger"><?= $error ?></div>
<?php endif; ?>
<div class="d-flex align-items-center mb-3 ps-2" id="selectAll-container">
<input type="checkbox" id="selectAll" class="form-check-input me-2 shadow-sm" style="width: 1.05em; height: 1.05em; border-radius: 0.35em; margin-left: 1px; transform: scale(1.2)">
<label for="selectAll" class="form-check-label fs-5 ms-1" style="margin-right: 10px;" data-translate="select_all">Select All</label>
<div class="ms-auto" style="margin-right: 20px;">
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#langModal">
<img id="flagIcon" src="/luci-static/ipip/flags/<?php echo $flagFile; ?>" style="width:24px; height:16px">
<span data-translate="change_language">Change Language</span>
</button>
</div>
</div>
<?php
$history_file = './lib/background_history.txt';
$background_history = file_exists($history_file) ? file($history_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
usort($files, function ($a, $b) use ($background_history) {
$posA = array_search($a, $background_history);
$posB = array_search($b, $background_history);
return ($posA === false ? PHP_INT_MAX : $posA) - ($posB === false ? PHP_INT_MAX : $posB);
});
?>
<div id="fileGrid" class="row row-cols-2 row-cols-md-4 row-cols-lg-5 g-4">
<?php foreach ($files as $file):
$path = $upload_dir . '/' . $file;
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | true |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/install_theme.php | luci-theme-spectra/root/www/spectra/install_theme.php | <?php
set_time_limit(300);
ini_set('max_execution_time', 300);
header('Content-Type: text/plain');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
if (ob_get_level()) ob_end_clean();
ob_implicit_flush(true);
function executeCommand($command) {
$output = [];
$status = 0;
exec($command . ' 2>&1', $output, $status);
return ['status' => $status, 'output' => implode("\n", $output)];
}
function fetchAssetsFromRelease($repoOwner, $repoName, $releaseTag) {
$url = "https://api.github.com/repos/$repoOwner/$repoName/releases/tags/$releaseTag";
$tempFile = '/tmp/github_release.json';
$command = "wget -q --header='User-Agent: PHP' -O $tempFile '$url' 2>/dev/null || curl -s -H 'User-Agent: PHP' -o $tempFile '$url' 2>/dev/null";
$result = executeCommand($command);
if ($result['status'] !== 0) {
return ['error' => "Failed to fetch release data: " . $result['output']];
}
$response = file_get_contents($tempFile);
if ($response === false) {
return ['error' => 'Failed to read temporary release data file'];
}
unlink($tempFile);
$releaseData = json_decode($response, true);
if (isset($releaseData['assets']) && count($releaseData['assets']) > 0) {
foreach ($releaseData['assets'] as $asset) {
if (preg_match('/luci-theme-spectra_([0-9A-Za-z.\-_]+)_all.ipk/', $asset['name'], $matches)) {
return [
'url' => $asset['browser_download_url'],
'filename' => $asset['name']
];
}
}
}
return ['error' => 'No matching asset found'];
}
function logStep($message) {
echo $message . "\n";
flush();
ob_flush();
usleep(100000);
}
$repoOwner = 'Thaolga';
$repoName = 'openwrt-nekobox';
$releaseTag = '1.8.8';
logStep("🚀 Starting theme installation...");
logStep("📡 Fetching release information...");
$assetData = fetchAssetsFromRelease($repoOwner, $repoName, $releaseTag);
if (isset($assetData['error'])) {
logStep("❌ Error: " . $assetData['error']);
exit;
}
logStep("✅ Release info fetched successfully");
logStep("📦 Package: " . $assetData['filename']);
$latestFile = $assetData['filename'];
$downloadUrl = $assetData['url'];
logStep("🔄 Updating package list...");
$updateResult = executeCommand('opkg update');
if ($updateResult['status'] !== 0) {
logStep("❌ Error during opkg update: " . $updateResult['output']);
exit;
}
logStep("✅ Package list updated");
logStep("📥 Installing dependencies...");
$installResult = executeCommand('opkg install wget grep sed');
if ($installResult['status'] !== 0) {
logStep("❌ Error installing dependencies: " . $installResult['output']);
exit;
}
logStep("✅ Dependencies installed");
logStep("⬇️ Downloading theme package...");
$downloadResult = executeCommand("wget -O /tmp/$latestFile '$downloadUrl' 2>/dev/null || curl -s -L -o /tmp/$latestFile '$downloadUrl' 2>/dev/null");
if ($downloadResult['status'] !== 0 || !file_exists("/tmp/$latestFile")) {
logStep("❌ Error downloading the package: " . $downloadResult['output']);
exit;
}
logStep("✅ Package downloaded");
logStep("🔧 Installing theme...");
logStep("⏳ Installing theme package, please wait...");
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
$installThemeResult = executeCommand("opkg install --force-reinstall /tmp/$latestFile");
echo "Package installation completed.\n";
flush();
if ($installThemeResult['status'] !== 0) {
logStep("❌ Error installing the package: " . $installThemeResult['output']);
exit;
}
logStep("✅ Theme installed successfully");
logStep("🧹 Cleaning up...");
$cleanupResult = executeCommand("rm -f /tmp/$latestFile");
if ($cleanupResult['status'] !== 0) {
logStep("⚠️ Warning cleaning up: " . $cleanupResult['output']);
} else {
logStep("✅ Cleanup completed");
}
logStep("🎉 INSTALLATION_SUCCESS");
?> | php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/download.php | luci-theme-spectra/root/www/spectra/download.php | <?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$token = $_GET['token'] ?? '';
if (empty($token)) {
http_response_code(400);
die(json_encode(['success' => false, 'message' => 'Invalid sharing link']));
}
$sharesDir = __DIR__ . '/shares/';
$shareFile = $sharesDir . $token . '.json';
if (!file_exists($shareFile)) {
http_response_code(404);
die(json_encode(['success' => false, 'message' => 'Failed to parse sharing record']));
}
$shareData = json_decode(file_get_contents($shareFile), true);
if (!$shareData) {
http_response_code(500);
die(json_encode(['success' => false, 'message' => 'Failed to parse sharing record']));
}
if (time() > ($shareData['expire'] ?? 0)) {
unlink($shareFile);
http_response_code(410);
die(json_encode(['success' => false, 'message' => 'The link has expired']));
}
$maxDownloads = intval($shareData['max_downloads'] ?? 0);
$downloadCount = intval($shareData['download_count'] ?? 0);
if ($maxDownloads > 0 && $downloadCount >= $maxDownloads) {
unlink($shareFile);
http_response_code(410);
die(json_encode(['success' => false, 'message' => 'The maximum number of downloads has been reached']));
}
$shareData['download_count'] = $downloadCount + 1;
file_put_contents($shareFile, json_encode($shareData, JSON_PRETTY_PRINT));
$filePath = __DIR__ . '/' . $shareData['filename'];
if (!file_exists($filePath)) {
http_response_code(404);
die(json_encode(['success' => false, 'message' => 'The file does not exist']));
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/share.php | luci-theme-spectra/root/www/spectra/share.php | <?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? '';
if ($action === 'create') {
$filename = $data['filename'] ?? '';
$expire = intval($data['expire'] ?? 86400);
$maxDownloads = intval($data['max_downloads'] ?? 0);
try {
$token = bin2hex(random_bytes(16));
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Token generation failed']);
exit;
}
$expireTime = time() + $expire;
$sharesDir = __DIR__ . '/shares/';
if (!is_dir($sharesDir)) {
mkdir($sharesDir, 0755, true);
}
$shareData = [
'filename' => $filename,
'token' => $token,
'expire' => $expireTime,
'max_downloads' => $maxDownloads,
'download_count' => 0,
'created_at' => time(),
];
$recordFile = $sharesDir . $token . '.json';
if (false === file_put_contents($recordFile, json_encode($shareData, JSON_PRETTY_PRINT))) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Failed to save the sharing record']);
exit;
}
echo json_encode(['success' => true, 'token' => $token]);
exit;
}
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Invalid action']);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
Thaolga/openwrt-nekobox | https://github.com/Thaolga/openwrt-nekobox/blob/b05d73029a294dd0e31105d17dc9542a7272f48d/luci-theme-spectra/root/www/spectra/search_proxy.php | luci-theme-spectra/root/www/spectra/search_proxy.php | <?php
$apiKeys = [];
$configFile = dirname(__FILE__) . '/api_keys.config.php';
if (file_exists($configFile)) {
$apiKeys = include $configFile;
} else {
$sampleConfig = "<?php\nreturn [\n 'spotify' => [\n 'client_id' => 'YOUR_SPOTIFY_CLIENT_ID',\n 'client_secret' => 'YOUR_SPOTIFY_CLIENT_SECRET'\n ],\n 'youtube' => [\n 'api_key' => 'YOUR_YOUTUBE_API_KEY'\n ],\n 'soundcloud' => [\n 'client_id' => 'YOUR_SOUNDCLOUD_CLIENT_ID'\n ]\n];";
file_put_contents($configFile, $sampleConfig);
}
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
$input = json_decode(file_get_contents('php://input'), true);
$source = $input['source'] ?? '';
$query = $input['query'] ?? '';
$type = $input['type'] ?? 'song';
$limit = $input['limit'] ?? 50;
$offset = $input['offset'] ?? 0;
$pageToken = $input['pageToken'] ?? null;
function fetchWithCurl($url, $headers = []) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
]);
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("CURL Error for $url: $error");
}
return [$result, $httpCode];
}
function searchSpotify($query, $type, $limit, $offset, $apiKeys) {
global $apiKeys;
if (empty($apiKeys['spotify']['client_id']) || empty($apiKeys['spotify']['client_secret'])) {
return ['success' => false, 'message' => 'Spotify API keys not configured'];
}
$clientId = $apiKeys['spotify']['client_id'];
$clientSecret = $apiKeys['spotify']['client_secret'];
$tokenUrl = 'https://accounts.spotify.com/api/token';
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $tokenUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode($clientId . ':' . $clientSecret),
'Content-Type: application/x-www-form-urlencoded'
],
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 10
]);
$tokenResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
error_log('Spotify Token CURL Error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode !== 200) {
error_log('Spotify Token API Error: ' . $tokenResponse);
return ['success' => false, 'message' => 'Failed to get access token. HTTP Code: ' . $httpCode];
}
$tokenData = json_decode($tokenResponse, true);
if (empty($tokenData['access_token'])) {
return ['success' => false, 'message' => 'Invalid token response'];
}
$accessToken = $tokenData['access_token'];
$searchTypeMap = [
'song' => 'track',
'artist' => 'artist',
'album' => 'album',
'playlist' => 'playlist'
];
$apiSearchType = $searchTypeMap[$type] ?? 'track';
$searchUrl = 'https://api.spotify.com/v1/search?' . http_build_query([
'q' => $query,
'type' => $apiSearchType,
'limit' => $limit,
'offset' => $offset
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $searchUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $accessToken,
'Content-Type: ' . 'application/json'
],
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 10
]);
$searchResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
error_log('Spotify Search CURL Error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode !== 200) {
error_log('Spotify Search API Error (' . $httpCode . '): ' . $searchResponse);
return ['success' => false, 'message' => 'Spotify search failed. HTTP Code: ' . $httpCode];
}
$searchData = json_decode($searchResponse, true);
$items = [];
$keyForItems = $apiSearchType . 's';
if (isset($searchData[$keyForItems]['items'])) {
$items = $searchData[$keyForItems]['items'];
}
return [
'success' => true,
'results' => $items,
'total' => $searchData[$keyForItems]['total'] ?? 0
];
}
function searchYouTube($query, $type, $apiKeys, $pageToken = null) {
global $apiKeys;
if (empty($apiKeys['youtube']['api_key'])) {
return ['success' => false, 'message' => 'YouTube API key not configured'];
}
$apiKey = $apiKeys['youtube']['api_key'];
$searchUrl = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" .
urlencode($query) . "&maxResults=50&type=video&key=$apiKey";
if ($pageToken) {
$searchUrl .= "&pageToken=" . urlencode($pageToken);
}
list($result, $httpCode) = fetchWithCurl($searchUrl);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
$items = [];
if (isset($data['items']) && count($data['items']) > 0) {
$videoIds = array_map(function($item) {
return $item['id']['videoId'] ?? '';
}, $data['items']);
$videoIds = array_filter($videoIds);
$videoDetails = [];
if (!empty($videoIds)) {
$videoIds = array_slice($videoIds, 0, 50);
$idsString = implode(',', $videoIds);
$videosUrl = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet&id=" .
urlencode($idsString) . "&key=$apiKey";
list($videosResult, $videosCode) = fetchWithCurl($videosUrl);
if ($videosCode === 200 && $videosResult) {
$videosData = json_decode($videosResult, true);
if (isset($videosData['items'])) {
foreach ($videosData['items'] as $videoItem) {
$videoId = $videoItem['id'] ?? '';
$thumbnails = $videoItem['snippet']['thumbnails'] ??
($item['snippet']['thumbnails'] ?? []);
$videoDetails[$videoId] = [
'duration' => $videoItem['contentDetails']['duration'] ?? null,
'thumbnails' => $thumbnails
];
}
}
}
}
foreach ($data['items'] as $item) {
$videoId = $item['id']['videoId'] ?? '';
$details = $videoDetails[$videoId] ?? [];
$items[] = [
'id' => $videoId,
'title' => $item['snippet']['title'] ?? '',
'description' => $item['snippet']['description'] ?? '',
'channelTitle' => $item['snippet']['channelTitle'] ?? '',
'thumbnails' => $details['thumbnails'] ?? $item['snippet']['thumbnails'] ?? [],
'duration' => $details['duration'] ?? null,
'publishedAt' => $item['snippet']['publishedAt'] ?? '',
'channelId' => $item['snippet']['channelId'] ?? '',
'previewUrl' => $videoId ? "https://www.youtube.com/watch?v=" . $videoId : '',
'proxyUrl' => $videoId ? "/spectra/youtube_proxy.php?action=stream&videoId=" . $videoId : ''
];
}
}
return [
'success' => true,
'results' => $items,
'total' => $data['pageInfo']['totalResults'] ?? 0,
'nextPageToken' => $data['nextPageToken'] ?? null,
'prevPageToken' => $data['prevPageToken'] ?? null
];
}
return ['success' => false, 'message' => 'YouTube search failed. HTTP Code: ' . $httpCode];
}
function searchITunes($query, $type, $limit, $offset) {
$entity = 'song';
if ($type === 'artist') $entity = 'musicArtist';
if ($type === 'album') $entity = 'album';
if ($type === 'playlist') $entity = 'musicTrack';
$totalNeeded = min($offset + $limit, 200);
$url = "https://itunes.apple.com/search?term=" . urlencode($query) .
"&entity=$entity&limit=$totalNeeded";
list($result, $httpCode) = fetchWithCurl($url);
if ($httpCode === 200 && $result) {
$data = json_decode($result, true);
$allItems = $data['results'] ?? [];
$items = array_slice($allItems, $offset, $limit);
return [
'success' => true,
'results' => $items,
'total' => count($allItems)
];
}
return ['success' => false, 'message' => 'iTunes search failed'];
}
$response = ['success' => false, 'message' => 'Search source not supported'];
switch ($source) {
case 'spotify':
$response = searchSpotify($query, $type, $limit, $offset, $apiKeys);
break;
case 'youtube':
$response = searchYouTube($query, $type, $apiKeys, $pageToken);
break;
case 'itunes':
$response = searchITunes($query, $type, $limit, $offset);
break;
case 'soundcloud':
$response = [
'success' => false,
'message' => 'SoundCloud search requires OAuth authentication'
];
break;
}
echo json_encode($response);
?>
| php | MIT | b05d73029a294dd0e31105d17dc9542a7272f48d | 2026-01-05T04:42:29.558843Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/server.php | server.php | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Department.php | app/Department.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'department';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/EmployeeSalary.php | app/EmployeeSalary.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EmployeeSalary extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'employee_salary';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/State.php | app/State.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class State extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'state';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Division.php | app/Division.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Division extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'division';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/User.php | app/User.php | <?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = ['remember_token'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/City.php | app/City.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'city';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Employee.php | app/Employee.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Country.php | app/Country.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'country';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Exceptions/Handler.php | app/Exceptions/Handler.php | <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('login'));
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Kernel.php | app/Http/Kernel.php | <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/ProfileController.php | app/Http/Controllers/ProfileController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the user profile.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('profile');
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/Controller.php | app/Http/Controllers/Controller.php | <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/DivisionController.php | app/Http/Controllers/DivisionController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Division;
class DivisionController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$divisions = Division::paginate(5);
return view('system-mgmt/division/index', ['divisions' => $divisions]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('system-mgmt/division/create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validateInput($request);
Division::create([
'name' => $request['name']
]);
return redirect()->intended('system-management/division');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$division = Division::find($id);
// Redirect to division list if updating division wasn't existed
if ($division == null || count($division) == 0) {
return redirect()->intended('/system-management/division');
}
return view('system-mgmt/division/edit', ['division' => $division]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$division = Division::findOrFail($id);
$this->validateInput($request);
$input = [
'name' => $request['name']
];
Division::where('id', $id)
->update($input);
return redirect()->intended('system-management/division');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Division::where('id', $id)->delete();
return redirect()->intended('system-management/division');
}
/**
* Search division from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'name' => $request['name']
];
$divisions = $this->doSearchingQuery($constraints);
return view('system-mgmt/division/index', ['divisions' => $divisions, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = Division::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
private function validateInput($request) {
$this->validate($request, [
'name' => 'required|max:60|unique:division'
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/EmployeeManagementController.php | app/Http/Controllers/EmployeeManagementController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Response;
use App\Employee;
use App\City;
use App\State;
use App\Country;
use App\Department;
use App\Division;
class EmployeeManagementController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$employees = DB::table('employees')
->leftJoin('city', 'employees.city_id', '=', 'city.id')
->leftJoin('department', 'employees.department_id', '=', 'department.id')
->leftJoin('state', 'employees.state_id', '=', 'state.id')
->leftJoin('country', 'employees.country_id', '=', 'country.id')
->leftJoin('division', 'employees.division_id', '=', 'division.id')
->select('employees.*', 'department.name as department_name', 'department.id as department_id', 'division.name as division_name', 'division.id as division_id')
->paginate(5);
return view('employees-mgmt/index', ['employees' => $employees]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
// $cities = City::all();
// $states = State::all();
$countries = Country::all();
$departments = Department::all();
$divisions = Division::all();
return view('employees-mgmt/create', ['countries' => $countries,
'departments' => $departments, 'divisions' => $divisions]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validateInput($request);
// Upload image
$path = $request->file('picture')->store('avatars');
$keys = ['lastname', 'firstname', 'middlename', 'address', 'city_id', 'state_id', 'country_id', 'zip',
'age', 'birthdate', 'date_hired', 'department_id', 'department_id', 'division_id'];
$input = $this->createQueryInput($keys, $request);
$input['picture'] = $path;
// Not implement yet
// $input['company_id'] = 0;
Employee::create($input);
return redirect()->intended('/employee-management');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$employee = Employee::find($id);
// Redirect to state list if updating state wasn't existed
if ($employee == null || count($employee) == 0) {
return redirect()->intended('/employee-management');
}
$cities = City::all();
$states = State::all();
$countries = Country::all();
$departments = Department::all();
$divisions = Division::all();
return view('employees-mgmt/edit', ['employee' => $employee, 'cities' => $cities, 'states' => $states, 'countries' => $countries,
'departments' => $departments, 'divisions' => $divisions]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$employee = Employee::findOrFail($id);
$this->validateInput($request);
// Upload image
$keys = ['lastname', 'firstname', 'middlename', 'address', 'city_id', 'state_id', 'country_id', 'zip',
'age', 'birthdate', 'date_hired', 'department_id', 'department_id', 'division_id'];
$input = $this->createQueryInput($keys, $request);
if ($request->file('picture')) {
$path = $request->file('picture')->store('avatars');
$input['picture'] = $path;
}
Employee::where('id', $id)
->update($input);
return redirect()->intended('/employee-management');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Employee::where('id', $id)->delete();
return redirect()->intended('/employee-management');
}
/**
* Search state from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'firstname' => $request['firstname'],
'department.name' => $request['department_name']
];
$employees = $this->doSearchingQuery($constraints);
$constraints['department_name'] = $request['department_name'];
return view('employees-mgmt/index', ['employees' => $employees, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = DB::table('employees')
->leftJoin('city', 'employees.city_id', '=', 'city.id')
->leftJoin('department', 'employees.department_id', '=', 'department.id')
->leftJoin('state', 'employees.state_id', '=', 'state.id')
->leftJoin('country', 'employees.country_id', '=', 'country.id')
->leftJoin('division', 'employees.division_id', '=', 'division.id')
->select('employees.firstname as employee_name', 'employees.*','department.name as department_name', 'department.id as department_id', 'division.name as division_name', 'division.id as division_id');
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where($fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
/**
* Load image resource.
*
* @param string $name
* @return \Illuminate\Http\Response
*/
public function load($name) {
$path = storage_path().'/app/avatars/'.$name;
if (file_exists($path)) {
return Response::download($path);
}
}
private function validateInput($request) {
$this->validate($request, [
'lastname' => 'required|max:60',
'firstname' => 'required|max:60',
'middlename' => 'required|max:60',
'address' => 'required|max:120',
'country_id' => 'required',
'zip' => 'required|max:10',
'age' => 'required',
'birthdate' => 'required',
'date_hired' => 'required',
'department_id' => 'required',
'division_id' => 'required'
]);
}
private function createQueryInput($keys, $request) {
$queryInput = [];
for($i = 0; $i < sizeof($keys); $i++) {
$key = $keys[$i];
$queryInput[$key] = $request[$key];
}
return $queryInput;
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/ReportController.php | app/Http/Controllers/ReportController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use Excel;
use Illuminate\Support\Facades\DB;
use Auth;
use PDF;
class ReportController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index() {
date_default_timezone_set('asia/ho_chi_minh');
$format = 'Y/m/d';
$now = date($format);
$to = date($format, strtotime("+30 days"));
$constraints = [
'from' => $now,
'to' => $to
];
$employees = $this->getHiredEmployees($constraints);
return view('system-mgmt/report/index', ['employees' => $employees, 'searchingVals' => $constraints]);
}
public function exportExcel(Request $request) {
$this->prepareExportingData($request)->export('xlsx');
redirect()->intended('system-management/report');
}
public function exportPDF(Request $request) {
$constraints = [
'from' => $request['from'],
'to' => $request['to']
];
$employees = $this->getExportingData($constraints);
$pdf = PDF::loadView('system-mgmt/report/pdf', ['employees' => $employees, 'searchingVals' => $constraints]);
return $pdf->download('report_from_'. $request['from'].'_to_'.$request['to'].'pdf');
// return view('system-mgmt/report/pdf', ['employees' => $employees, 'searchingVals' => $constraints]);
}
private function prepareExportingData($request) {
$author = Auth::user()->username;
$employees = $this->getExportingData(['from'=> $request['from'], 'to' => $request['to']]);
return Excel::create('report_from_'. $request['from'].'_to_'.$request['to'], function($excel) use($employees, $request, $author) {
// Set the title
$excel->setTitle('List of hired employees from '. $request['from'].' to '. $request['to']);
// Chain the setters
$excel->setCreator($author)
->setCompany('HoaDang');
// Call them separately
$excel->setDescription('The list of hired employees');
$excel->sheet('Hired_Employees', function($sheet) use($employees) {
$sheet->fromArray($employees);
});
});
}
public function search(Request $request) {
$constraints = [
'from' => $request['from'],
'to' => $request['to']
];
$employees = $this->getHiredEmployees($constraints);
return view('system-mgmt/report/index', ['employees' => $employees, 'searchingVals' => $constraints]);
}
private function getHiredEmployees($constraints) {
$employees = Employee::where('date_hired', '>=', $constraints['from'])
->where('date_hired', '<=', $constraints['to'])
->get();
return $employees;
}
private function getExportingData($constraints) {
return DB::table('employees')
->leftJoin('city', 'employees.city_id', '=', 'city.id')
->leftJoin('department', 'employees.department_id', '=', 'department.id')
->leftJoin('state', 'employees.state_id', '=', 'state.id')
->leftJoin('country', 'employees.country_id', '=', 'country.id')
->leftJoin('division', 'employees.division_id', '=', 'division.id')
->select('employees.firstname', 'employees.middlename', 'employees.lastname',
'employees.age','employees.birthdate', 'employees.address', 'employees.zip', 'employees.date_hired',
'department.name as department_name', 'division.name as division_name')
->where('date_hired', '>=', $constraints['from'])
->where('date_hired', '<=', $constraints['to'])
->get()
->map(function ($item, $key) {
return (array) $item;
})
->all();
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/CityController.php | app/Http/Controllers/CityController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\City;
use App\State;
class CityController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth')->only(["index", "create", "store", "edit", "update", "search", "destroy"]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$cities = DB::table('city')
->leftJoin('state', 'city.state_id', '=', 'state.id')
->select('city.id', 'city.name', 'state.name as state_name', 'state.id as state_id')
->paginate(5);
return view('system-mgmt/city/index', ['cities' => $cities]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$states = State::all();
return view('system-mgmt/city/create', ['states' => $states]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
State::findOrFail($request['state_id']);
$this->validateInput($request);
city::create([
'name' => $request['name'],
'state_id' => $request['state_id']
]);
return redirect()->intended('system-management/city');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$city = city::find($id);
// Redirect to city list if updating city wasn't existed
if ($city == null || count($city) == 0) {
return redirect()->intended('/system-management/city');
}
$states = State::all();
return view('system-mgmt/city/edit', ['city' => $city, 'states' => $states]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$city = City::findOrFail($id);
$this->validate($request, [
'name' => 'required|max:60'
]);
$input = [
'name' => $request['name'],
'state_id' => $request['state_id']
];
City::where('id', $id)
->update($input);
return redirect()->intended('system-management/city');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
City::where('id', $id)->delete();
return redirect()->intended('system-management/city');
}
public function loadCities($stateId) {
$cities = City::where('state_id', '=', $stateId)->get(['id', 'name']);
return response()->json($cities);
}
/**
* Search city from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'name' => $request['name']
];
$cities = $this->doSearchingQuery($constraints);
return view('system-mgmt/city/index', ['cities' => $cities, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = City::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
private function validateInput($request) {
$this->validate($request, [
'name' => 'required|max:60|unique:city'
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/UserManagementController.php | app/Http/Controllers/UserManagementController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\User;
class UserManagementController extends Controller
{
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/user-management';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::paginate(5);
return view('users-mgmt/index', ['users' => $users]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('users-mgmt/create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validateInput($request);
User::create([
'username' => $request['username'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
'firstname' => $request['firstname'],
'lastname' => $request['lastname']
]);
return redirect()->intended('/user-management');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
// Redirect to user list if updating user wasn't existed
if ($user == null || count($user) == 0) {
return redirect()->intended('/user-management');
}
return view('users-mgmt/edit', ['user' => $user]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$constraints = [
'username' => 'required|max:20',
'firstname'=> 'required|max:60',
'lastname' => 'required|max:60'
];
$input = [
'username' => $request['username'],
'firstname' => $request['firstname'],
'lastname' => $request['lastname']
];
if ($request['password'] != null && strlen($request['password']) > 0) {
$constraints['password'] = 'required|min:6|confirmed';
$input['password'] = bcrypt($request['password']);
}
$this->validate($request, $constraints);
User::where('id', $id)
->update($input);
return redirect()->intended('/user-management');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::where('id', $id)->delete();
return redirect()->intended('/user-management');
}
/**
* Search user from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'username' => $request['username'],
'firstname' => $request['firstname'],
'lastname' => $request['lastname'],
'department' => $request['department']
];
$users = $this->doSearchingQuery($constraints);
return view('users-mgmt/index', ['users' => $users, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = User::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
private function validateInput($request) {
$this->validate($request, [
'username' => 'required|max:20',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'firstname' => 'required|max:60',
'lastname' => 'required|max:60'
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/StateController.php | app/Http/Controllers/StateController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\State;
use App\Country;
class StateController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth')->only(["index", "create", "store", "edit", "update", "search", "destroy"]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$states = DB::table('state')
->leftJoin('country', 'state.country_id', '=', 'country.id')
->select('state.id', 'state.name', 'country.name as country_name', 'country.id as country_id')
->paginate(5);
return view('system-mgmt/state/index', ['states' => $states]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$countries = Country::all();
return view('system-mgmt/state/create', ['countries' => $countries]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Country::findOrFail($request['country_id']);
$this->validateInput($request);
State::create([
'name' => $request['name'],
'country_id' => $request['country_id']
]);
return redirect()->intended('system-management/state');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$state = State::find($id);
// Redirect to state list if updating state wasn't existed
if ($state == null || count($state) == 0) {
return redirect()->intended('/system-management/state');
}
$countries = Country::all();
return view('system-mgmt/state/edit', ['state' => $state, 'countries' => $countries]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$state = State::findOrFail($id);
$this->validate($request, [
'name' => 'required|max:60'
]);
$input = [
'name' => $request['name'],
'country_id' => $request['country_id']
];
State::where('id', $id)
->update($input);
return redirect()->intended('system-management/state');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
State::where('id', $id)->delete();
return redirect()->intended('system-management/state');
}
public function loadStates($countryId) {
$states = State::where('country_id', '=', $countryId)->get(['id', 'name']);
return response()->json($states);
}
/**
* Search state from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'name' => $request['name']
];
$states = $this->doSearchingQuery($constraints);
return view('system-mgmt/state/index', ['states' => $states, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = State::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
private function validateInput($request) {
$this->validate($request, [
'name' => 'required|max:60|unique:state'
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/DepartmentController.php | app/Http/Controllers/DepartmentController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Department;
class DepartmentController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$departments = Department::paginate(5);
return view('system-mgmt/department/index', ['departments' => $departments]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('system-mgmt/department/create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validateInput($request);
Department::create([
'name' => $request['name']
]);
return redirect()->intended('system-management/department');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$department = Department::find($id);
// Redirect to department list if updating department wasn't existed
if ($department == null || count($department) == 0) {
return redirect()->intended('/system-management/department');
}
return view('system-mgmt/department/edit', ['department' => $department]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$department = Department::findOrFail($id);
$this->validateInput($request);
$input = [
'name' => $request['name']
];
Department::where('id', $id)
->update($input);
return redirect()->intended('system-management/department');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Department::where('id', $id)->delete();
return redirect()->intended('system-management/department');
}
/**
* Search department from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'name' => $request['name']
];
$departments = $this->doSearchingQuery($constraints);
return view('system-mgmt/department/index', ['departments' => $departments, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = department::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
private function validateInput($request) {
$this->validate($request, [
'name' => 'required|max:60|unique:department'
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/CountryController.php | app/Http/Controllers/CountryController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Country;
class CountryController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$countries = Country::paginate(5);
return view('system-mgmt/country/index', ['countries' => $countries]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('system-mgmt/country/create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validateInput($request);
Country::create([
'name' => $request['name'],
'country_code' => $request['country_code']
]);
return redirect()->intended('system-management/country');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$country = Country::find($id);
// Redirect to country list if updating country wasn't existed
if ($country == null || count($country) == 0) {
return redirect()->intended('/system-management/country');
}
return view('system-mgmt/country/edit', ['country' => $country]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$country = Country::findOrFail($id);
$input = [
'name' => $request['name'],
'country_code' => $request['country_code']
];
$this->validate($request, [
'name' => 'required|max:60'
]);
Country::where('id', $id)
->update($input);
return redirect()->intended('system-management/country');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Country::where('id', $id)->delete();
return redirect()->intended('system-management/country');
}
/**
* Search country from database base on some specific constraints
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function search(Request $request) {
$constraints = [
'name' => $request['name'],
'country_code' => $request['country_code']
];
$countries = $this->doSearchingQuery($constraints);
return view('system-mgmt/country/index', ['countries' => $countries, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = country::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->paginate(5);
}
private function validateInput($request) {
$this->validate($request, [
'name' => 'required|max:60|unique:country',
'country_code' => 'required|max:3|unique:country'
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/DashboardController.php | app/Http/Controllers/DashboardController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('dashboard');
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/Auth/LoginController.php | app/Http/Controllers/Auth/LoginController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/dashboard';
/**
* Determine if the user has too many failed login attempts.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function hasTooManyLoginAttempts ($request) {
$maxLoginAttempts = 2;
$lockoutTime = 5; // 5 minutes
return $this->limiter()->tooManyAttempts(
$this->throttleKey($request), $maxLoginAttempts, $lockoutTime
);
}
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/Auth/ForgotPasswordController.php | app/Http/Controllers/Auth/ForgotPasswordController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/Auth/ResetPasswordController.php | app/Http/Controllers/Auth/ResetPasswordController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/login';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Controllers/Auth/RegisterController.php | app/Http/Controllers/Auth/RegisterController.php | <?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Middleware/RedirectIfAuthenticated.php | app/Http/Middleware/RedirectIfAuthenticated.php | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
return $next($request);
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Middleware/TrimStrings.php | app/Http/Middleware/TrimStrings.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as BaseTrimmer;
class TrimStrings extends BaseTrimmer
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Middleware/EncryptCookies.php | app/Http/Middleware/EncryptCookies.php | <?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Http/Middleware/VerifyCsrfToken.php | app/Http/Middleware/VerifyCsrfToken.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Console/Kernel.php | app/Console/Kernel.php | <?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Providers/BroadcastServiceProvider.php | app/Providers/BroadcastServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Providers/RouteServiceProvider.php | app/Providers/RouteServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Providers/EventServiceProvider.php | app/Providers/EventServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Providers/AppServiceProvider.php | app/Providers/AppServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
hoadv/employee-mgmt-laravel5.4-adminlte | https://github.com/hoadv/employee-mgmt-laravel5.4-adminlte/blob/5e15dfc4c71bbeec165be4e4337c1acc6b84f387/app/Providers/AuthServiceProvider.php | app/Providers/AuthServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
| php | MIT | 5e15dfc4c71bbeec165be4e4337c1acc6b84f387 | 2026-01-05T04:43:07.369163Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.