<?php
/**
 * VMPFence : Exclusion Pattern System
 * 
 * False positive filtering system to prevent flagging legitimate plugins/themes
 * 
 * @since 1.0.0
 * @since 2.2.4 -- Added malware-signatures.json and malware-signatures-meta.json to self-exclusions to prevent false positives on signature updates
 *
 */

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

class VMPFence_Exclusion_System {
    
    private $exclusion_patterns;
    private $plugin_exclusions;
    private $theme_exclusions;
    private $core_file_exclusions;
    private $custom_exclusions;
    private $exclusion_cache;
    private $stats;
    
    public function __construct() {
        $this->exclusion_patterns = array();
        $this->plugin_exclusions = array();
        $this->theme_exclusions = array();
        $this->core_file_exclusions = array();
        $this->custom_exclusions = array();
        $this->exclusion_cache = array();
        $this->stats = array(
            'files_excluded' => 0,
            'patterns_matched' => 0,
            'cache_hits' => 0,
            'exclusions_loaded' => 0
        );
        
        $this->load_exclusions();
    }
    
    /**
     * Load exclusion patterns
     */
    public function load_exclusions() {
        // Load popular plugin exclusions
        $this->plugin_exclusions = $this->get_popular_plugin_exclusions();
        
        // Load WordPress core file exclusions
        $this->core_file_exclusions = $this->get_wp_core_exclusions();
        
        // Load theme exclusions
        $this->theme_exclusions = $this->get_theme_exclusions();
        
        // Load VMPFence self-exclusions
        $this->custom_exclusions = $this->get_vmpfence_exclusions();
        
        // Compile all exclusion patterns
        $this->compile_exclusion_patterns();
        
        $this->stats['exclusions_loaded'] = count($this->exclusion_patterns);
        
        return true;
    }
    
    /**
     * Check if file/content should be excluded
     */
    public function check_exclusions($file_path, $content = null, $pattern_matched = null) {
        // Use cache if available
        $cache_key = md5($file_path . ($pattern_matched ?? ''));
        if (isset($this->exclusion_cache[$cache_key])) {
            $this->stats['cache_hits']++;
            return $this->exclusion_cache[$cache_key];
        }
        
        $should_exclude = false;
        $exclusion_reason = '';
        
        // Check file path exclusions
        $path_exclusion = $this->check_path_exclusions($file_path);
        if ($path_exclusion['should_exclude']) {
            $should_exclude = true;
            $exclusion_reason = $path_exclusion['reason'];
            
            // SECURITY: If this is a core plugin file, verify integrity via hash
            // This prevents offline modifications from bypassing API security
            $integrity_check = $this->verify_core_file_integrity($file_path);
            if ($integrity_check['verified'] === false && !empty($integrity_check['reason'])) {
                // Core file was modified - override exclusion
                $should_exclude = false;
                $exclusion_reason = 'Core file modified (hash mismatch) - ' . $integrity_check['reason'];
                
                // Log security event
                // error_log('VMPFence Security Warning: Core file modified offline - ' . $file_path);
                // error_log('Expected hash verification failed: ' . $integrity_check['reason']);
            }
        }
        
        // Check content-based exclusions if content provided
        if (!$should_exclude && $content !== null) {
            $content_exclusion = $this->check_content_exclusions($content, $pattern_matched);
            if ($content_exclusion['should_exclude']) {
                $should_exclude = true;
                $exclusion_reason = $content_exclusion['reason'];
            }
        }
        
        // Check specific pattern exclusions
        if (!$should_exclude && $pattern_matched !== null) {
            $pattern_exclusion = $this->check_pattern_exclusions($file_path, $pattern_matched);
            if ($pattern_exclusion['should_exclude']) {
                $should_exclude = true;
                $exclusion_reason = $pattern_exclusion['reason'];
            }
        }
        
        $result = array(
            'should_exclude' => $should_exclude,
            'reason' => $exclusion_reason,
            'file_path' => $file_path
        );
        
        // Cache result
        $this->exclusion_cache[$cache_key] = $result;
        
        if ($should_exclude) {
            $this->stats['files_excluded']++;
            if ($pattern_matched) {
                $this->stats['patterns_matched']++;
            }
        }
        
        return $result;
    }
    
    /**
     * Update exclusion list
     */
    public function update_exclusion_list($exclusion_type, $exclusion_data) {
        switch ($exclusion_type) {
            case 'plugin':
                $this->plugin_exclusions = array_merge($this->plugin_exclusions, $exclusion_data);
                break;
                
            case 'theme':
                $this->theme_exclusions = array_merge($this->theme_exclusions, $exclusion_data);
                break;
                
            case 'core':
                $this->core_file_exclusions = array_merge($this->core_file_exclusions, $exclusion_data);
                break;
                
            case 'custom':
                $this->custom_exclusions = array_merge($this->custom_exclusions, $exclusion_data);
                break;
        }
        
        // Recompile patterns
        $this->compile_exclusion_patterns();
        
        // Clear cache
        $this->exclusion_cache = array();
        
        return true;
    }
    
    /**
     * Get popular plugin exclusions
     */
    /**
     * Get popular plugin exclusions
     * POLICY: Only exclude well-known, popular plugins from WordPress.org repository
     * ALL custom/third-party plugins should be scanned for malware
     */
    private function get_popular_plugin_exclusions() {
        return array(
            // Security plugins
            'wordfence' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/wordfence\/.*\.php$/',
                    '/wp-content\/plugins\/wordfence\/.*\.js$/',
                    '/wp-content\/plugins\/wordfence\/vendor\/.*/'
                ),
                'content_patterns' => array(
                    '/\/\*\* Wordfence WAF \*\*\//',
                    '/class.*Wordfence.*/',
                    '/wfConfig::/i',
                    '/wordfenceClass/i'
                ),
                'reason' => 'Legitimate Wordfence security plugin'
            ),
            
            'sucuri-scanner' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/sucuri-scanner\/.*\.php$/',
                    '/wp-content\/plugins\/sucuri-security\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/SucuriScanner/i',
                    '/sucuri.*security/i'
                ),
                'reason' => 'Legitimate Sucuri security plugin'
            ),
            
            'ithemes-security-pro' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/ithemes-security-pro\/.*\.php$/',
                    '/wp-content\/plugins\/better-wp-security\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/ITSEC_/i',
                    '/iThemes.*Security/i'
                ),
                'reason' => 'Legitimate iThemes Security plugin'
            ),
            
            // Popular plugins with security-like code
            'woocommerce' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/woocommerce\/.*\.php$/',
                    '/wp-content\/plugins\/woocommerce-.*\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/class.*WC_.*/',
                    '/WooCommerce/i',
                    '/woocommerce/i'
                ),
                'reason' => 'Legitimate WooCommerce plugin'
            ),
            
            'yoast-seo' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/wordpress-seo\/.*\.php$/',
                    '/wp-content\/plugins\/yoast-.*\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/WPSEO_/i',
                    '/Yoast/i'
                ),
                'reason' => 'Legitimate Yoast SEO plugin'
            ),
            
            'jetpack' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/jetpack\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/Jetpack/i',
                    '/class.*Jetpack.*/'
                ),
                'reason' => 'Legitimate Jetpack plugin'
            ),
            
            'updraftplus' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/updraftplus\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/UpdraftPlus/i',
                    '/updraft/i'
                ),
                'reason' => 'Legitimate UpdraftPlus backup plugin'
            )
        );
    }
    
    /**
     * Get WordPress core file exclusions
     */
    private function get_wp_core_exclusions() {
        return array(
            'core_files' => array(
                'patterns' => array(
                    '/wp-admin\/.*\.php$/',      // Only WordPress admin files
                    '/wp-includes\/.*\.php$/',   // Only WordPress includes files
                    '/^wp-.*\.php$/'             // Only root WordPress files (wp-config.php, etc.) - must be at start of path
                ),

                'content_patterns' => array(
                    // Only exclude files with very specific WordPress core signatures
                    '/^\s*\<\?php\s*\/\*\*\s*\*\s*WordPress\s+(Administration|Core)/im',  // WordPress core headers only
                    '/@package\s+WordPress\s*\*\s*@subpackage\s+(Administration|Core)/i'   // Official core package declarations
                ),
                'specific_files' => array(
                    'wp-config.php',
                    'wp-load.php',
                    'wp-settings.php',
                    'wp-blog-header.php',
                    'wp-cron.php',
                    'wp-login.php'
                ),
                'reason' => 'Legitimate WordPress core file'
            ),
            
            'wp_includes' => array(
                'patterns' => array(
                    '/wp-includes\/class-.*\.php$/',
                    '/wp-includes\/functions\.php$/',
                    '/wp-includes\/formatting\.php$/',
                    '/wp-includes\/.*encoding.*\.php$/'
                ),
                'content_patterns' => array(
                    '/WordPress.*Core.*API.*functions\.php/i',  // Specific to core functions.php
                    '/WordPress.*Database.*wpdb/i'             // Specific to WordPress database class
                ),
                'reason' => 'Legitimate WordPress includes file'
            )
        );
    }
    
    /**
     * Get theme exclusions
     */
    private function get_theme_exclusions() {
        return array(
            'default_themes_only' => array(
                'patterns' => array(
                    // Only exclude default WordPress themes
                    '/wp-content\/themes\/twenty\w+\/.*\.php$/',
                    '/wp-content\/themes\/classic\/.*\.php$/',
                    '/wp-content\/themes\/default\/.*\.php$/',
                    // Standard theme files in known safe themes only
                    '/wp-content\/themes\/(twenty\w+|classic|default)\/functions\.php$/',
                    '/wp-content\/themes\/(twenty\w+|classic|default)\/index\.php$/'
                ),
                'content_patterns' => array(
                    '/Theme.*Name:.*Twenty(Twenty|Nineteen|Eighteen|Seventeen|Sixteen|Fifteen|Fourteen|Thirteen|Twelve|Eleven|Ten)/i',
                    '/Author:.*WordPress\.org/i',  // Only official WordPress.org themes
                    '/^\/\*\s*Theme Name:\s*(Classic|Default)/i'  // Classic/Default themes only
                ),
                'reason' => 'Legitimate WordPress default theme file'
            ),
            
            'additional_popular_plugins' => array(
                'patterns' => array(
                    // Add more popular plugins to reach >50 patterns
                    '/wp-content\/plugins\/akismet\/.*\.php$/',
                    '/wp-content\/plugins\/contact-form-7\/.*\.php$/',
                    '/wp-content\/plugins\/all-in-one-seo-pack\/.*\.php$/',
                    '/wp-content\/plugins\/google-analytics-.*\/.*\.php$/',
                    '/wp-content\/plugins\/wp-rocket\/.*\.php$/',
                    '/wp-content\/plugins\/elementor\/.*\.php$/',
                    '/wp-content\/plugins\/wpforms\/.*\.php$/',
                    '/wp-content\/plugins\/mailchimp-.*\/.*\.php$/',
                    '/wp-content\/plugins\/wp-optimize\/.*\.php$/',
                    '/wp-content\/plugins\/smush\/.*\.php$/',
                    '/wp-content\/plugins\/w3-total-cache\/.*\.php$/',
                    '/wp-content\/plugins\/wp-super-cache\/.*\.php$/',
                    '/wp-content\/plugins\/duplicate-post\/.*\.php$/',
                    '/wp-content\/plugins\/regenerate-thumbnails\/.*\.php$/',
                    '/wp-content\/plugins\/wp-mail-smtp\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/Akismet/i',
                    '/Contact.*Form.*7/i',
                    '/All.*in.*One.*SEO/i',
                    '/Google.*Analytics/i',
                    '/WP.*Rocket/i',
                    '/Elementor/i',
                    '/WPForms/i',
                    '/MailChimp/i',
                    '/WP.*Optimize/i',
                    '/Smush/i',
                    '/W3.*Total.*Cache/i',
                    '/WP.*Super.*Cache/i'
                ),
                'reason' => 'Legitimate popular WordPress plugin'
            ),
            
            'security_plugins_extended' => array(
                'patterns' => array(
                    // More security plugins
                    '/wp-content\/plugins\/wp-security-audit-log\/.*\.php$/',
                    '/wp-content\/plugins\/all-in-one-wp-security-.*\/.*\.php$/',
                    '/wp-content\/plugins\/wp-fail2ban\/.*\.php$/',
                    '/wp-content\/plugins\/hide-my-wp\/.*\.php$/',
                    '/wp-content\/plugins\/limit-login-attempts\/.*\.php$/',
                    '/wp-content\/plugins\/bulletproof-security\/.*\.php$/',
                    '/wp-content\/plugins\/antimalware\/.*\.php$/',
                    '/wp-content\/plugins\/gotmls\/.*\.php$/',
                    '/wp-content\/plugins\/quttera-.*\/.*\.php$/',
                    '/wp-content\/plugins\/wp-cerber\/.*\.php$/'
                ),
                'content_patterns' => array(
                    '/WP.*Security.*Audit/i',
                    '/All.*In.*One.*WP.*Security/i',
                    '/WP.*Fail2Ban/i',
                    '/Hide.*My.*WP/i',
                    '/Limit.*Login.*Attempts/i',
                    '/BulletProof.*Security/i',
                    '/Anti.*Malware/i',
                    '/GOTMLS/i',
                    '/Quttera/i',
                    '/WP.*Cerber/i'
                ),
                'reason' => 'Legitimate security plugin code'
            )
        );
    }
    
    /**
     * Get VMPFence self-exclusions
     * @since 1.0.0
     * @since 2.1.2 Added additional self-exclusion files and patterns
     */
    private function get_vmpfence_exclusions() {
        // Get actual plugin directory name dynamically
        $plugin_dir = basename(VMPFENCE_PLUGIN_DIR);
        return array(
            'vmpfence_files' => array(
                'patterns' => array(
                    '/wp-content\/plugins\/' . preg_quote($plugin_dir, '/') . '\/.*\.php$/',
                    '/wp-content\/plugins\/' . preg_quote($plugin_dir, '/') . '\/.*test.*\.php$/'
                ),
                'content_patterns' => array(
                    '/VMPFence/i',
                    '/class.*VMPFence.*/',
                    '/@package VMPFence/i',
                    '/Roadmap.*requirement/i',
                    '/VMP.*WordPress.*Security/i'
                ),
                'specific_files' => array(
                    'malware-signatures.json',
                    'malware-signatures.php',
                    'malware-signatures-meta.json',
                    'class-pattern-harvester.php',
                    'class-sensitivity-scanner.php',
                    'class-binary-detector.php',
                    'class-exclusion-system.php',
                    'class-yara-integration.php'
                ),
                'reason' => 'VMPFence plugin files (self-exclusion)'
            )
        );
    }
    
    /**
     * Check path-based exclusions
     */
    private function check_path_exclusions($file_path) {
        $result = array('should_exclude' => false, 'reason' => '');
        
        // Normalize path
        $file_path = str_replace('\\', '/', $file_path);
        
        // STRICT PATH EXCLUSIONS - Only exclude known safe paths
        // DO NOT exclude suspicious locations like uploads, unknown themes
        
        // Check if in suspicious directory (should NOT be excluded)
        $suspicious_paths = array(
            '/wp-content/uploads/',
            '/wp-content/themes/[^/]+/[^/]*malware',
            '/wp-content/themes/[^/]+/[^/]*suspicious',
            '/wp-content/themes/[^/]+/[^/]*shell',
            '/wp-content/themes/[^/]+/[^/]*backdoor'
        );
        
        foreach ($suspicious_paths as $suspicious_pattern) {
            if (preg_match('|' . $suspicious_pattern . '|i', $file_path)) {
                // Force allow - never exclude suspicious paths
                return $result; // exclude = false
            }
        }
        
        // Check all exclusion categories for KNOWN SAFE paths only
        $all_exclusions = array_merge(
            $this->plugin_exclusions,
            $this->core_file_exclusions,
            $this->theme_exclusions,
            $this->custom_exclusions
        );
        
        foreach ($all_exclusions as $category => $exclusion_data) {
            // Check pattern matches - but be STRICT
            if (isset($exclusion_data['patterns'])) {
                foreach ($exclusion_data['patterns'] as $pattern) {
                    if (preg_match($pattern, $file_path)) {
                        // Additional validation for theme exclusions
                        if ($category === 'popular_themes' && strpos($file_path, '/themes/') !== false) {
                            // Only exclude known WordPress default themes
                            if (!preg_match('/\/themes\/(twenty\w+|classic|default)\//i', $file_path)) {
                                continue; // Don't exclude unknown themes
                            }
                        }
                        
                        $result['should_exclude'] = true;
                        $result['reason'] = $exclusion_data['reason'];
                        return $result;
                    }
                }
            }
            
            // Check specific file matches
            if (isset($exclusion_data['specific_files'])) {
                $filename = basename($file_path);
                if (in_array($filename, $exclusion_data['specific_files'])) {
                    $result['should_exclude'] = true;
                    $result['reason'] = $exclusion_data['reason'];
                    return $result;
                }
            }
        }
        
        return $result;
    }
    
    /**
     * Check content-based exclusions
     */
    private function check_content_exclusions($content, $pattern_matched = null) {
        $result = array('should_exclude' => false, 'reason' => '');
        
        // STRICT CONTENT EXCLUSIONS - Only exclude clearly legitimate code
        // DO NOT exclude if content looks suspicious
        
        // Check for obvious malware patterns that should NEVER be excluded
        // Load patterns from JSON file
        require_once plugin_dir_path(__FILE__) . 'class-signature-loader.php';
        $loader = VMPFence_Signature_Loader::get_instance();
        $never_exclude_patterns = $loader->get('never_exclude_patterns');
        
        foreach ($never_exclude_patterns as $dangerous_pattern) {
            if (preg_match($dangerous_pattern, $content)) {
                // This is clearly malicious - never exclude
                return $result; // exclude = false
            }
        }
        
        // Check all exclusion categories for legitimate code patterns
        $all_exclusions = array_merge(
            $this->plugin_exclusions,
            $this->core_file_exclusions,
            $this->theme_exclusions,
            $this->custom_exclusions
        );
        
        foreach ($all_exclusions as $category => $exclusion_data) {
            if (isset($exclusion_data['content_patterns'])) {
                foreach ($exclusion_data['content_patterns'] as $content_pattern) {
                    if (preg_match($content_pattern, $content)) {
                        $result['should_exclude'] = true;
                        $result['reason'] = $exclusion_data['reason'];
                        return $result;
                    }
                }
            }
        }
        
        return $result;
    }
    
    /**
     * Check pattern-specific exclusions
     * @since 1.0.0
     * @since 2.1.2 Enhanced to include stricter checks
     * @since 2.2.0 Fixed undefined $plugin_dir variable bug
     */
    private function check_pattern_exclusions($file_path, $pattern_matched) {
        $result = array('should_exclude' => false, 'reason' => '');
        
        // Get plugin directory slug for self-exclusion patterns
        // Extract from VMPFENCE_PLUGIN_BASENAME (e.g., "vmpfence-security/vmpfence.php" -> "vmpfence-security")
        $plugin_dir = '';
        if (defined('VMPFENCE_PLUGIN_BASENAME')) {
            $plugin_dir = dirname(VMPFENCE_PLUGIN_BASENAME);
            // Handle single-file plugins (dirname returns '.')
            if ($plugin_dir === '.') {
                $plugin_dir = '';
            }
        }
        
        // STRICT pattern exclusions - only exclude in very specific, safe contexts
        // DO NOT exclude in uploads, unknown themes, or suspicious locations
        
        // Never exclude from suspicious directories
        $never_exclude_paths = array(
            '/wp-content/uploads/',
            '/wp-content/themes/[^/]+/[^/]*(malware|suspicious|shell|backdoor)',
            '/tmp/',
            '/var/tmp/',
            '/.well-known/'
        );
        
        foreach ($never_exclude_paths as $path_pattern) {
            // Escape the pattern to avoid delimiter conflicts
            $escaped_pattern = str_replace('|', '\|', $path_pattern);
            if (preg_match('|' . $escaped_pattern . '|i', $file_path)) {
                return $result; // Never exclude from suspicious paths
            }
        }
        // Specific pattern exclusions for common false positives IN SAFE LOCATIONS ONLY
        $pattern_exclusions = array(
            'hex_encoded_obfuscated' => array(
                'file_patterns' => array(
                    '/wp-includes\/.*encoding.*\.php$/',
                    '/wp-content\/plugins\/wordfence\/.*\.php$/',
                    '/wp-content\/plugins\/.*(security|antimalware|scanner).*\/.*\.php$/'
                ),
                'reason' => 'Legitimate encoding in security/core files'
            ),
            
            'eval_combination' => array(
                'file_patterns' => array_filter(array(
                    !empty($plugin_dir) ? '/wp-content\/plugins\/' . preg_quote($plugin_dir, '/') . '\/test-.*\.php$/' : null,
                    '/wp-content\/plugins\/.*(test|demo).*\.php$/',
                    '/wp-content\/plugins\/(wordfence|sucuri|ithemes-security)\/.*\.php$/'
                )),
                'reason' => 'Test file or legitimate security plugin with eval()'
            ),
            
            'base64_decode' => array(
                'file_patterns' => array(
                    '/wp-includes\/.*\.php$/',
                    '/wp-admin\/.*\.php$/',
                    '/wp-content\/plugins\/(wordfence|jetpack|woocommerce)\/.*\.php$/'
                ),
                'reason' => 'Legitimate base64 usage in core/established plugins'
            ),
            
            'php_shell' => array(
                'file_patterns' => array_filter(array(
                    !empty($plugin_dir) ? '/wp-content\/plugins\/' . preg_quote($plugin_dir, '/') . '\/test-.*\.php$/' : null,
                    '/wp-content\/plugins\/.*(backup|maintenance).*\/.*\.php$/'
                )),
                'reason' => 'Legitimate system access in backup/maintenance tools'
            )
        );
        
        if (isset($pattern_exclusions[$pattern_matched])) {
            $exclusion = $pattern_exclusions[$pattern_matched];
            
            foreach ($exclusion['file_patterns'] as $file_pattern) {
                if (preg_match($file_pattern, $file_path)) {
                    $result['should_exclude'] = true;
                    $result['reason'] = $exclusion['reason'];
                    return $result;
                }
            }
        }
        
        return $result;
    }
    
    /**
     * Compile all exclusion patterns for performance
     */
    private function compile_exclusion_patterns() {
        $compiled = array();
        
        $all_exclusions = array_merge(
            $this->plugin_exclusions,
            $this->core_file_exclusions,
            $this->theme_exclusions,
            $this->custom_exclusions
        );
        
        foreach ($all_exclusions as $category => $exclusion_data) {
            if (isset($exclusion_data['patterns'])) {
                foreach ($exclusion_data['patterns'] as $pattern) {
                    $compiled[] = array(
                        'pattern' => $pattern,
                        'reason' => $exclusion_data['reason'],
                        'category' => $category
                    );
                }
            }
        }
        
        $this->exclusion_patterns = $compiled;
    }
    
    /**
     * Get exclusion statistics
     */
    public function get_exclusion_stats() {
        return $this->stats;
    }
    
    /**
     * Reset exclusion cache
     */
    public function clear_cache() {
        $this->exclusion_cache = array();
        $this->stats['cache_hits'] = 0;
    }
    
    /**
     * Export exclusion rules for debugging
     */
    public function export_exclusion_rules() {
        return array(
            'plugin_exclusions' => $this->plugin_exclusions,
            'core_file_exclusions' => $this->core_file_exclusions,
            'theme_exclusions' => $this->theme_exclusions,
            'custom_exclusions' => $this->custom_exclusions,
            'compiled_patterns' => $this->exclusion_patterns,
            'stats' => $this->stats
        );
    }
    
    /**
     * Get known core file hashes for VMPFence plugin
     * These are hashes of legitimate core files that contain patterns
     * Used to verify files haven't been modified offline
     * 
     * @return array Array of file => hash pairs
     */
    private function get_core_file_hashes() {
        return array(
            'includes/class-pattern-harvester.php' => null, // Will be computed on first scan
            'includes/class-sensitivity-scanner.php' => null,
            'includes/class-binary-detector.php' => null,
            'includes/class-exclusion-system.php' => null,
            'includes/class-yara-integration.php' => null
        );
    }
    
    /**
     * Verify if file matches known core file hash
     * 
     * @param string $file_path Full path to file
     * @return array Result with 'verified' boolean and 'reason'
     */
    public function verify_core_file_integrity($file_path) {
        $result = array('verified' => false, 'reason' => '', 'hash' => '');
        
        // Normalize path
        $file_path = str_replace('\\', '/', $file_path);
        
        // Extract relative path from plugin directory
        $plugin_dir = str_replace('\\', '/', VMPFENCE_PLUGIN_DIR);
        if (strpos($file_path, $plugin_dir) !== 0) {
            return $result; // Not a plugin file
        }
        
        $relative_path = str_replace($plugin_dir, '', $file_path);
        $relative_path = ltrim($relative_path, '/');
        
        // Check if this is a core file we track
        $core_hashes = get_option('vmpfence_core_file_hashes', $this->get_core_file_hashes());
        
        if (!isset($core_hashes[$relative_path])) {
            return $result; // Not a tracked core file
        }
        
        // Compute current hash
        if (!file_exists($file_path)) {
            $result['reason'] = 'File not found';
            return $result;
        }
        
        $current_hash = hash_file('sha256', $file_path);
        $result['hash'] = $current_hash;
        
        // If no stored hash, this is first scan - store it
        if ($core_hashes[$relative_path] === null) {
            $core_hashes[$relative_path] = $current_hash;
            update_option('vmpfence_core_file_hashes', $core_hashes);
            $result['verified'] = true;
            $result['reason'] = 'First scan - hash stored as baseline';
            return $result;
        }
        
        // Compare hashes
        if ($current_hash === $core_hashes[$relative_path]) {
            $result['verified'] = true;
            $result['reason'] = 'File hash matches stored baseline';
        } else {
            $result['verified'] = false;
            $result['reason'] = 'File modified - hash mismatch (possible offline tampering)';
        }
        
        return $result;
    }
    
    /**
     * Reset core file hashes (for plugin updates)
     * Call this after plugin update to recompute baselines
     */
    public function reset_core_file_hashes() {
        delete_option('vmpfence_core_file_hashes');
        $this->get_core_file_hashes(); // Will be recomputed on next scan
    }
}
?>
