<?php
defined('ABSPATH') || exit;

/**
 * Pattern Integration Utilities
 * 
 * Functions for integrating external malware pattern definitions
 * with WPFort's pattern scanning system.
 */

/**
 * Convert Eli's GPL-licensed patterns to WPFort format
 *
 * @param array $eli_patterns The patterns in Eli's format
 * @return array The patterns in WPFort format
 */
function wpsec_convert_eli_patterns($eli_patterns) {
    $converted_patterns = [
        'php' => [],
        'js' => [],
        'html' => [],
        'htaccess' => [] // New category for .htaccess files
    ];
    
    // Map severity levels based on category
    $severity_mapping = [
        'potential' => 'medium',
        'known' => 'high',
        'db_scan' => 'medium',
        'htaccess' => 'high'
    ];
    
    // Process each category from Eli's patterns
    foreach ($eli_patterns as $category => $patterns) {
        if ($category === 'firewall') {
            continue; // Handled separately
        }
        
        foreach ($patterns as $name => $pattern_data) {
            // Determine which WPFort category to place this pattern in
            $target_category = 'php'; // Default
            
            if ($category === 'htaccess') {
                $target_category = 'htaccess';
            } elseif ($category === 'db_scan') {
                $target_category = 'html';
            } elseif (strpos($name, 'javascript') !== false || 
                      strpos($name, 'script') !== false ||
                      strpos($name, 'iframe') !== false) {
                $target_category = 'js';
            }
            
            // Create pattern entry with enriched metadata
            $converted_patterns[$target_category][] = [
                'id' => $pattern_data[0],
                'name' => ucfirst(str_replace('_', ' ', $name)),
                'pattern' => $pattern_data[1],
                'severity' => $severity_mapping[$category] ?? 'medium',
                'confidence' => wpsec_calculate_pattern_confidence($pattern_data[1], $category),
                'description' => isset($pattern_data[2]) ? $pattern_data[2] : "Suspected malware pattern: $name",
                'source' => 'eli_plugin',
                'exclude_patterns' => [], // Optional exclusions to avoid false positives
                'category' => $category // Original category for reference
            ];
        }
    }
    
    return $converted_patterns;
}

/**
 * Calculate confidence score based on pattern complexity
 *
 * @param string $pattern The regex pattern
 * @param string $category The original category
 * @return int Confidence score (0-100)
 */
function wpsec_calculate_pattern_confidence($pattern, $category) {
    // More complex patterns get higher confidence
    $complexity = substr_count($pattern, '(?') + substr_count($pattern, '\\d') + 
                 substr_count($pattern, '[^') + substr_count($pattern, '{');
    
    $base_score = 70; // Default confidence
    
    // Known malware gets higher confidence
    if ($category === 'known') {
        $base_score = 90;
    }
    
    // Adjust based on complexity (more complex = more specific = higher confidence)
    return min(95, $base_score + ($complexity * 2));
}

/**
 * Integrate selected firewall rules from Eli's patterns
 *
 * @param array $eli_patterns The patterns in Eli's format
 * @return array Selected firewall rules in WPFort format
 */
function wpsec_integrate_firewall_rules($eli_patterns) {
    // Only select firewall rules that complement WPFort's existing system
    $selected_rules = [];
    
    // Specific exploit vectors worth adding
    $priority_vectors = [
        'RevSlider', // Revolution Slider exploits
        'UserEnum',  // User enumeration protection
        'Traversal', // Directory traversal
        'UploadPHP', // PHP upload protection
        'usersAPI'   // REST API user data protection
    ];
    
    if (!isset($eli_patterns['firewall'])) {
        return $selected_rules;
    }
    
    foreach ($priority_vectors as $vector) {
        if (isset($eli_patterns['firewall'][$vector])) {
            $rule = $eli_patterns['firewall'][$vector];
            $selected_rules[$vector] = [
                'id' => $rule[0],
                'name' => $rule[1],
                'description' => $rule[2],
                'check_type' => $rule[3], // SERVER, REQUEST, etc.
                'pattern' => $rule[4],
                'additional_checks' => array_slice($rule, 5), // Any additional checks
                'enabled' => true
            ];
        }
    }
    
    return $selected_rules;
}

/**
 * Load Eli's patterns from the bundled JSON file
 *
 * @return array The patterns in Eli's format
 */
function wpsec_load_eli_patterns() {
    $patterns_file = dirname(__FILE__) . '/../data/eli-patterns.json';
    
    if (!file_exists($patterns_file)) {
        wpsec_debug_log('❌ Eli patterns file not found: ' . $patterns_file, 'error');
        return [];
    }
    
    $json_content = file_get_contents($patterns_file);
    if (!$json_content) {
        wpsec_debug_log('❌ Failed to read Eli patterns file', 'error');
        return [];
    }
    
    $patterns = json_decode($json_content, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        wpsec_debug_log('❌ JSON decode error: ' . json_last_error_msg(), 'error');
        return [];
    }
    
    return $patterns;
}
