<?php
/**
 * VMPFence Premium Plugin Whitelist
 * 
 * Manages trusted premium/commercial/custom plugins that should be excluded
 * from YARA scanning to prevent false positives.
 * 
 * Premium plugins are NOT available on WordPress.org, so they have no official
 * checksums. This class maintains a whitelist to automatically trust their files.
 * 
 * @package VMPFence
 * @since 2.1.0
 */

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

class VMPFence_Premium_Plugin_Whitelist {
    
    /**
     * Option key for custom whitelisted plugins
     */
    const CUSTOM_WHITELIST_KEY = 'vmpfence_custom_plugin_whitelist';
    
    /**
     * Built-in whitelist of known premium/commercial plugins
     * 
     * Structure: ['plugin-slug' => 'Human-readable name']
     */
    private static function get_builtin_whitelist() {
        return array(
            // WPML Suite (Premium Translation Plugin)
            'sitepress-multilingual-cms' => 'WPML Multilingual CMS',
            'wpml-string-translation' => 'WPML String Translation',
            'wpml-translation-management' => 'WPML Translation Management',
            'wpml-media-translation' => 'WPML Media Translation',
            'wpml-sticky-links' => 'WPML Sticky Links',
            'wpml-cms-nav' => 'WPML CMS Navigation',
            'wpml-rest-api' => 'WPML REST API',
            
            // Yoast Premium
            'wordpress-seo-premium' => 'Yoast SEO Premium',
            'wpseo-local' => 'Yoast Local SEO',
            'wpseo-news' => 'Yoast News SEO',
            'wpseo-video' => 'Yoast Video SEO',
            'wpseo-woocommerce' => 'Yoast WooCommerce SEO',
            
            // Wordfence (Premium Security)
            'wordfence' => 'Wordfence Security',
            
            // Akismet (Commercial)
            'akismet' => 'Akismet Anti-Spam',
            
            // Gravity Forms (Premium Forms)
            'gravityforms' => 'Gravity Forms',
            'gravityformscli' => 'Gravity Forms CLI',
            'gravityformswebhooks' => 'Gravity Forms Webhooks',
            
            // Advanced Custom Fields PRO
            'advanced-custom-fields-pro' => 'Advanced Custom Fields PRO',
            
            // WPBakery (Visual Composer)
            'js_composer' => 'WPBakery Page Builder',
            
            // Elementor Pro
            'elementor-pro' => 'Elementor Pro',
            
            // Slider Revolution
            'revslider' => 'Slider Revolution',
            
            // LayerSlider
            'LayerSlider' => 'LayerSlider',
            
            // All in One WP Migration Extensions
            'all-in-one-wp-migration-unlimited-extension' => 'All-in-One WP Migration Unlimited Extension',
            'all-in-one-wp-migration-multisite-extension' => 'All-in-One WP Migration Multisite Extension',
            
            // WooCommerce Extensions (Premium)
            'woocommerce-subscriptions' => 'WooCommerce Subscriptions',
            'woocommerce-bookings' => 'WooCommerce Bookings',
            'woocommerce-memberships' => 'WooCommerce Memberships',
            'woocommerce-product-bundles' => 'WooCommerce Product Bundles',
            
            // Toolset (Premium Development Tools)
            'types' => 'Toolset Types',
            'toolset-blocks' => 'Toolset Blocks',
            
            // SiteGround Plugins (Hosting-specific)
            'sg-cachepress' => 'SiteGround Optimizer',
            'sg-security' => 'SiteGround Security',
            'siteground-central' => 'SiteGround Central',
            
            // Bundled/Default WordPress Plugins
            'hello' => 'Hello Dolly',
            'hello-dolly' => 'Hello Dolly',
            
            // Custom/Internal Plugins
            'vmpfence' => 'VMP Fence Security',
            'vmp-fence-security' => 'VMP Fence Security',
            
            // Analytics & Tracking (Commercial)
            'google-analytics-for-wordpress' => 'MonsterInsights (Premium)',
            'wordpress-posthog' => 'WordPress PostHog',
            
            // OTGS Installer (WPML Support)
            'otgs-installer-plugin' => 'OTGS Installer',
            
            // WPForms Pro
            'wpforms' => 'WPForms Lite', // Can be free or pro
            'wpforms-lite' => 'WPForms Lite',
            
            // Jetpack (Commercial Features)
            'jetpack' => 'Jetpack',
            
            // Other Common Premium Plugins
            'wp-rocket' => 'WP Rocket',
            'oxygen' => 'Oxygen Builder',
            'bb-plugin' => 'Beaver Builder',
            'wp-optimize-premium' => 'WP-Optimize Premium',
            'updraftplus' => 'UpdraftPlus Premium',
        );
    }
    
    /**
     * Get complete whitelist (built-in + custom)
     * 
     * @return array Associative array of slug => name
     */
    public static function get_whitelist() {
        $builtin = self::get_builtin_whitelist();
        $custom = get_option(self::CUSTOM_WHITELIST_KEY, array());
        
        if (!is_array($custom)) {
            $custom = array();
        }
        
        return array_merge($builtin, $custom);
    }
    
    /**
     * Check if a plugin is whitelisted
     * 
     * @param string $plugin_slug Plugin slug or directory name
     * @return bool True if whitelisted
     */
    public static function is_whitelisted($plugin_slug) {
        $whitelist = self::get_whitelist();
        return isset($whitelist[$plugin_slug]);
    }
    
    /**
     * Add a plugin to custom whitelist
     * 
     * @param string $plugin_slug Plugin slug
     * @param string $plugin_name Human-readable name
     * @return bool Success
     */
    public static function add_to_whitelist($plugin_slug, $plugin_name) {
        $custom = get_option(self::CUSTOM_WHITELIST_KEY, array());
        
        if (!is_array($custom)) {
            $custom = array();
        }
        
        $custom[$plugin_slug] = $plugin_name;
        
        return update_option(self::CUSTOM_WHITELIST_KEY, $custom);
    }
    
    /**
     * Remove a plugin from custom whitelist
     * 
     * @param string $plugin_slug Plugin slug
     * @return bool Success
     */
    public static function remove_from_whitelist($plugin_slug) {
        $custom = get_option(self::CUSTOM_WHITELIST_KEY, array());
        
        if (!is_array($custom)) {
            return true;
        }
        
        if (isset($custom[$plugin_slug])) {
            unset($custom[$plugin_slug]);
            return update_option(self::CUSTOM_WHITELIST_KEY, $custom);
        }
        
        return true;
    }
    
    /**
     * Get all files for a whitelisted plugin
     * 
     * @param string $plugin_slug Plugin slug
     * @return array Array of file paths relative to ABSPATH
     */
    public static function get_plugin_files($plugin_slug) {
        $plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_slug;
        
        if (!is_dir($plugin_dir)) {
            return array();
        }
        
        $files = array();
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($plugin_dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $full_path = $file->getPathname();
                $relative_path = str_replace(ABSPATH, '', $full_path);
                $relative_path = str_replace('\\', '/', $relative_path);
                $relative_path = ltrim($relative_path, '/');
                
                $files[] = $relative_path;
            }
        }
        
        return $files;
    }
    
    /**
     * Get statistics about whitelisted plugins
     * 
     * @return array Statistics
     */
    public static function get_statistics() {
        $whitelist = self::get_whitelist();
        $builtin = self::get_builtin_whitelist();
        $custom = get_option(self::CUSTOM_WHITELIST_KEY, array());
        
        // Count installed whitelisted plugins
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $all_plugins = get_plugins();
        $installed_whitelisted = 0;
        $total_files_whitelisted = 0;
        
        foreach ($all_plugins as $plugin_path => $plugin_data) {
            $plugin_slug = dirname($plugin_path);
            if ($plugin_slug === '.') {
                $plugin_slug = basename($plugin_path, '.php');
            }
            
            if (self::is_whitelisted($plugin_slug)) {
                $installed_whitelisted++;
                $total_files_whitelisted += count(self::get_plugin_files($plugin_slug));
            }
        }
        
        return array(
            'total_whitelist_count' => count($whitelist),
            'builtin_count' => count($builtin),
            'custom_count' => is_array($custom) ? count($custom) : 0,
            'installed_whitelisted' => $installed_whitelisted,
            'total_files_whitelisted' => $total_files_whitelisted
        );
    }
}
