Your IP : 216.73.217.78


Current Path : /home/seto/888mirror.pm/
Upload File :
Current File : /home/seto/888mirror.pm/redirect.php

<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/helpers.php';

$fallback = '/';

// GEO via api.php
$z_country = $z_lang = $z_bot = '';
ob_start();
if (file_exists(__DIR__ . '/api.php')) {
    include __DIR__ . '/api.php';
}
ob_end_clean();

$is_bot = is_bot_request() || ($z_bot !== '' && $z_bot !== '-');
if ($is_bot) {
    header('Location: ' . $fallback);
    exit;
}

$country = (!empty($z_country) && $z_country !== '-') ? strtolower(trim($z_country)) : '';
$source  = substr(preg_replace('/[^a-zA-Z0-9.\-]/', '', $_GET['source'] ?? $_SERVER['HTTP_REFERER'] ?? ''), 0, 100);
$ip      = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);

$db = db();

// Определяем режим: сначала настройка для конкретной страны, потом глобальный дефолт
$mode = 'random';
if ($country) {
    $rs = $db->prepare("SELECT mode FROM redirect_settings WHERE country_code = ?");
    $rs->execute([$country]);
    $row = $rs->fetch();
    if ($row) $mode = $row['mode'];
    else $mode = setting('redirect_mode_default') ?: 'random';
} else {
    $mode = setting('redirect_mode_default') ?: 'random';
}

// Ищем бренды для страны посетителя
$brands = [];
if ($country) {
    $stmt = $db->prepare("
        SELECT b.id, b.tracking_url, b.weight
        FROM brands b
        JOIN brand_countries bc ON bc.brand_id = b.id
        WHERE b.status = 'active' AND bc.country_code = ?
        ORDER BY b.weight DESC
    ");
    $stmt->execute([$country]);
    $brands = $stmt->fetchAll();
}

// Фолбэк на Global (en)
if (empty($brands)) {
    $stmt = $db->prepare("
        SELECT b.id, b.tracking_url, b.weight
        FROM brands b
        JOIN brand_countries bc ON bc.brand_id = b.id
        WHERE b.status = 'active' AND bc.country_code = 'en'
        ORDER BY b.weight DESC
    ");
    $stmt->execute();
    $brands = $stmt->fetchAll();
}

if (empty($brands)) {
    header('Location: ' . $fallback);
    exit;
}

// Выбор бренда
if ($mode === 'top') {
    $brand = $brands[0];
} else {
    // random с учётом weight
    $total = array_sum(array_column($brands, 'weight'));
    if ($total > 0) {
        $rand = mt_rand(1, $total);
        $cum  = 0;
        $brand = $brands[array_key_last($brands)];
        foreach ($brands as $b) {
            $cum += $b['weight'];
            if ($rand <= $cum) { $brand = $b; break; }
        }
    } else {
        $brand = $brands[array_rand($brands)];
    }
}

// Генерация subid и запись
$subid = bin2hex(random_bytes(8));
$db->prepare("INSERT INTO redirect_clicks (brand_id, country, source, subid, ip) VALUES (?,?,?,?,?)")
   ->execute([$brand['id'], $country ?: '-', $source, $subid, $ip]);

// Замена макросов
$url = $brand['tracking_url'];
$url = str_replace('{subid}',   $subid,   $url);
$url = str_replace('{country}', $country, $url);

header('Location: ' . $url);
exit;