<?php
/**
 * HTAccess Manager
 * 
 * Safely manages .htaccess rules for blocking WordPress disclosure files
 * Uses WordPress's insert_with_markers() for safe, reversible modifications
 *
 * @package VMPFence
 * @since 2.2.2
 * @since 2.2.4 Refactored and added WAF optimization management functions and backup system and new htaccess marker for WAF optimization rules
 */

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

class VMPFence_HTAccess_Manager {
    
    /**
     * Marker name for our .htaccess rules
     */
    const MARKER = 'VMPFence Security';
    
    /**
     * Marker name for WAF optimization rules
     */
    const WAF_MARKER = 'VMPFence WAF Optimization';
    
    /**
     * Add WAF optimization to .htaccess (auto_prepend_file directive)
     * 
     * @param string $waf_file_path Full path to vmp-waf.php file
     * @return bool|WP_Error True on success, WP_Error on failure
     */
    public static function add_waf_optimization($waf_file_path) {
        // Ensure WordPress functions are available
        if (!function_exists('insert_with_markers')) {
            require_once ABSPATH . 'wp-admin/includes/misc.php';
        }
        
        $htaccess_file = ABSPATH . '.htaccess';
        
        // Check if server supports .htaccess
        $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? strtolower($_SERVER['SERVER_SOFTWARE']) : '';
        $is_apache = strpos($server_software, 'apache') !== false;
        $is_litespeed = strpos($server_software, 'litespeed') !== false;
        
        if (!$is_apache && !$is_litespeed) {
            return new WP_Error('server_not_supported', 
                'Server type not supported. auto_prepend_file optimization requires Apache or LiteSpeed.');
        }
        
        // Check if .htaccess exists and is writable
        if (!file_exists($htaccess_file)) {
            if (!@touch($htaccess_file)) {
                return new WP_Error('htaccess_not_writable', 
                    'Could not create .htaccess file.');
            }
        }
        
        if (!is_writable($htaccess_file)) {
            return new WP_Error('htaccess_not_writable', 
                'The .htaccess file is not writable. Please make it writable (chmod 644).');
        }
        
        // Check if WAF file exists
        if (!file_exists($waf_file_path)) {
            return new WP_Error('waf_file_missing', 
                'WAF file does not exist. Cannot add optimization.');
        }
        
        // Remove old "VMPFence Security" markers if they exist
        $htaccess_content = @file_get_contents($htaccess_file);
        if ($htaccess_content !== false) {
            $old_marker_pattern = '/# BEGIN VMPFence Security.*?# END VMPFence Security\n?/s';
            if (preg_match($old_marker_pattern, $htaccess_content)) {
                $htaccess_content = preg_replace($old_marker_pattern, '', $htaccess_content);
                @file_put_contents($htaccess_file, $htaccess_content);
            }
        }
        
        // Define WAF optimization rules
        $rules = self::get_waf_optimization_rules($waf_file_path);
        
        // Use WordPress's safe insert_with_markers function
        $result = insert_with_markers($htaccess_file, self::WAF_MARKER, $rules);
        
        if ($result) {
            return true;
        } else {
            return new WP_Error('htaccess_write_failed', 
                'Failed to write WAF optimization to .htaccess.');
        }
    }
    
    /**
     * Remove WAF optimization from .htaccess
     * 
     * @return bool True on success, false on failure
     */
    public static function remove_waf_optimization() {
        // Ensure WordPress functions are available
        if (!function_exists('insert_with_markers')) {
            require_once ABSPATH . 'wp-admin/includes/misc.php';
        }
        
        $htaccess_file = ABSPATH . '.htaccess';
        
        if (!file_exists($htaccess_file)) {
            return true; // Nothing to remove
        }
        
        if (!is_writable($htaccess_file)) {
            return false;
        }
        
        // Read htaccess content
        $htaccess_content = @file_get_contents($htaccess_file);
        if ($htaccess_content === false) {
            return false;
        }
        
        // Remove the entire WAF block including markers
        $pattern = '/# BEGIN ' . preg_quote(self::WAF_MARKER, '/') . '.*?# END ' . preg_quote(self::WAF_MARKER, '/') . '\n?/s';
        $htaccess_content = preg_replace($pattern, '', $htaccess_content);
        
        // Write back to file
        $result = @file_put_contents($htaccess_file, $htaccess_content);
        
        return $result !== false;
    }
    
    /**
     * Get WAF optimization rules for .htaccess
     * 
     * @param string $waf_file_path Full path to vmp-waf.php
     * @return array Array of rule lines
     */
    private static function get_waf_optimization_rules($waf_file_path) {
        // Normalize path separators for .htaccess (use forward slashes)
        $normalized_path = str_replace('\\', '/', $waf_file_path);
        
        // Detect server type
        $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? strtolower($_SERVER['SERVER_SOFTWARE']) : '';
        $is_litespeed = strpos($server_software, 'litespeed') !== false;
        
        if ($is_litespeed) {
            // LiteSpeed-specific directives
            return array(
                '<IfModule LiteSpeed>',
                '    php_value auto_prepend_file \'' . $normalized_path . '\'',
                '</IfModule>',
                '<IfModule lsapi_module>',
                '    php_value auto_prepend_file \'' . $normalized_path . '\'',
                '</IfModule>',
            );
        } else {
            // Apache directives
            return array(
                '<IfModule mod_php5.c>',
                '    php_value auto_prepend_file \'' . $normalized_path . '\'',
                '</IfModule>',
                '<IfModule mod_php7.c>',
                '    php_value auto_prepend_file \'' . $normalized_path . '\'',
                '</IfModule>',
                '<IfModule mod_php.c>',
                '    php_value auto_prepend_file \'' . $normalized_path . '\'',
                '</IfModule>',
            );
        }
    }
    
    /**
     * Check if WAF optimization is currently active
     * 
     * @return bool True if WAF optimization exists, false otherwise
     */
    public static function waf_optimization_exists() {
        $htaccess_file = ABSPATH . '.htaccess';
        
        if (!file_exists($htaccess_file)) {
            return false;
        }
        
        $content = file_get_contents($htaccess_file);
        return strpos($content, '# BEGIN ' . self::WAF_MARKER) !== false;
    }
}
