File: /var/www/cod67/data/www/cod67.ru/public_html/similar_hold/index.php
<?php
error_reporting(E_ALL);
$config = require __DIR__ . '/config.php';
/** Пути **/
$statsDir = __DIR__ . '/stats';
$dailyFile = $statsDir . '/daily.json';
$monthlyFile = $statsDir . '/monthly.json';
$logDir = $statsDir . '/logs';
if (!is_dir($statsDir)) mkdir($statsDir, 0777, true);
if (!is_dir($logDir)) mkdir($logDir, 0777, true);
/** ====== ФУНКЦИИ ====== */
function load_json($f){ return file_exists($f) ? (json_decode(file_get_contents($f), true) ?: []) : []; }
function save_json($f,$d){ file_put_contents($f,json_encode($d,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)); }
/** Логирование */
function write_log($msg) {
global $logDir;
$file = $logDir . '/' . date('Y-m-d') . '.log';
$time = date('[H:i:s]');
file_put_contents($file, "$time $msg\n", FILE_APPEND);
}
/** Telegram уведомление */
function telegram_notify($text) {
global $config;
if (!$config['telegram_enabled']) return;
$token = $config['telegram_bot_token'];
$chat = $config['telegram_chat_id'];
$url = "https://api.telegram.org/bot$token/sendMessage";
@file_get_contents($url . '?' . http_build_query([
'chat_id' => $chat,
'text' => $text
]));
}
/** URL доступность */
function url_alive($url) {
$headers = @get_headers($url);
if (!$headers) return false;
return strpos($headers[0], '200') !== false;
}
/** Очистка старых логов */
function cleanup_logs() {
global $logDir, $config;
$files = glob($logDir . '/*.log');
$keep = $config['log_keep_days'];
foreach ($files as $file) {
if (filemtime($file) < time() - 86400 * $keep) {
unlink($file);
}
}
}
cleanup_logs();
/** Загружаем статистику */
$dailyStats = load_json($dailyFile);
$monthlyStats = load_json($monthlyFile);
$today = date('Y-m-d');
$month = date('Y-m');
/** Сброс статистики */
if (($dailyStats['date'] ?? null) !== $today)
$dailyStats = ['date'=>$today,'links'=>[]];
if (($monthlyStats['month'] ?? null) !== $month)
$monthlyStats = ['month'=>$month,'links'=>[]];
/** Читаем список ссылок */
$linksFile = __DIR__ . '/links.txt';
if (!file_exists($linksFile)) die("links.txt отсутствует");
$links = array_filter(array_map('trim', explode("\n", file_get_contents($linksFile))));
$links = array_values($links);
/** Определяем текущий URL */
$is_https =
(isset($_SERVER['HTTP_CF_VISITOR']) && json_decode($_SERVER['HTTP_CF_VISITOR'], true)['scheme'] === 'https') ||
(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') ||
(isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on');
$current_url = strtok(($is_https ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]","?");
$current_index = array_search($current_url, $links);
if ($current_index === false)
die("URL не найден в списке");
/** ====== ПОИСК РАБОТАЮЩЕЙ ССЫЛКИ ====== */
$total = count($links);
$checked = 0;
while ($checked < $total) {
$current_index = ($current_index + 1) % $total;
$url = $links[$current_index];
$d = $dailyStats['links'][$url] ?? 0;
$m = $monthlyStats['links'][$url] ?? 0;
/** Лимиты */
if ($d >= $config['daily_limit'] || $m >= $config['monthly_limit']) {
write_log("Ограничение: $url (day=$d, month=$m)");
$checked++;
continue;
}
/** Проверка доступности */
if (!url_alive($url)) {
write_log("Недоступен: $url");
telegram_notify("⚠️ Недоступен сайт: $url");
echo "<p>Сайт недоступен: $url</p>";
sleep(5);
$checked++;
continue;
}
/** Обновляем статистику */
$dailyStats['links'][$url] = $d + 1;
$monthlyStats['links'][$url] = $m + 1;
save_json($dailyFile,$dailyStats);
save_json($monthlyFile,$monthlyStats);
write_log("Редирект на: $url");
?>
<!doctype html>
<html lang="en">
<meta name="referrer" content="no-referrer"/>
<meta http-equiv="refresh" content="0.4;url=<?php echo htmlspecialchars($url); ?>">
<head><meta charset="UTF-8"><title>Redirecting...</title></head>
<body></body>
</html>
<?php
exit;
}
write_log("Нет доступных ссылок.");
telegram_notify("❌ Все ссылки исчерпаны или недоступны!");
die("Нет доступных ссылок.");