<?php
/**
 * 性能优化配置文件
 * 修复网络阻塞的服务器资源保护措施
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 服务器资源限制和初始化逻辑已移至 inc/init-config.php

/**
 * 文件上传优化和安全检查（包含PHP木马防护）
 */
function nenghui_optimize_file_upload($file) {
    // 检查文件大小
    $max_size = 50 * 1024 * 1024; // 50MB
    if ($file['size'] > $max_size) {
        $file['error'] = '文件大小不能超过50MB';
        return $file;
    }
    
    // 允许的文件类型：图片格式和PDF
    $allowed_types = array(
        'image/jpeg', 
        'image/png', 
        'image/gif', 
        'image/webp', 
        'image/svg+xml',
        'application/pdf'
    );
    
    // 明确禁止的文件类型（包含PHP木马常用类型）
    $forbidden_types = array(
        'application/zip',
        'application/x-zip-compressed',
        'application/x-rar-compressed',
        'application/x-7z-compressed',
        'application/x-tar',
        'application/gzip',
        'application/x-executable',
        'application/x-msdownload',
        'text/x-php',
        'application/x-php',
        'text/php',
        'application/php',
        'text/x-script.php',
        'application/x-httpd-php',
        'application/x-httpd-php-source',
        'text/html',
        'text/javascript',
        'application/javascript',
        'text/x-shellscript'
    );
    
    // 检查是否为禁止的文件类型
    if (in_array($file['type'], $forbidden_types)) {
        $file['error'] = '出于安全考虑，不允许上传此类型的文件';
        return $file;
    }
    
    // 获取文件信息
    $file_info = pathinfo($file['name']);
    $filename = strtolower($file['name']);
    $extension = isset($file_info['extension']) ? strtolower($file_info['extension']) : '';
    
    // PHP木马防护：检查双重扩展名
    if (preg_match('/\.(php|phtml|php3|php4|php5|php7|phps|pht|phar)\./i', $filename)) {
        $file['error'] = '检测到可疑的双重扩展名，上传被拒绝';
        return $file;
    }
    
    // 扩展的危险扩展名列表（包含PHP木马常用扩展名）
    $forbidden_extensions = array(
        'zip', 'rar', '7z', 'tar', 'gz', 'exe', 'bat', 'cmd', 'com', 'scr', 'msi',
        'php', 'php3', 'php4', 'php5', 'php7', 'phtml', 'phps', 'pht', 'phar',
        'js', 'html', 'htm', 'xhtml', 'shtml', 'jsp', 'asp', 'aspx',
        'pl', 'py', 'rb', 'sh', 'bash', 'cgi', 'htaccess', 'htpasswd'
    );
    
    if (in_array($extension, $forbidden_extensions)) {
        $file['error'] = '不允许上传 .' . $extension . ' 格式的文件';
        return $file;
    }
    
    // PHP木马防护：检查可疑文件名模式
    $suspicious_patterns = array(
        '/shell/i', '/webshell/i', '/backdoor/i', '/trojan/i', '/hack/i',
        '/exploit/i', '/bypass/i', '/upload/i', '/cmd/i', '/eval/i',
        '/base64/i', '/decode/i', '/phpinfo/i', '/system/i', '/exec/i'
    );
    
    if (is_array($suspicious_patterns) && !empty($suspicious_patterns)) {
        foreach ($suspicious_patterns as $pattern) {
            if (preg_match($pattern, $filename)) {
                $file['error'] = '检测到可疑文件名，上传被拒绝';
                return $file;
            }
        }
    }
    
    // 检查是否为允许的文件类型
    if (!in_array($file['type'], $allowed_types)) {
        $file['error'] = '只允许上传图片文件（JPEG, PNG, GIF, WebP, SVG）和PDF文档';
        return $file;
    }
    
    // PHP木马防护：文件内容检查（针对图片文件）
    if (strpos($file['type'], 'image/') === 0 && $file['tmp_name']) {
        $content_check = nenghui_check_file_content($file['tmp_name']);
        if (!$content_check['safe']) {
            $file['error'] = $content_check['message'];
            return $file;
        }
    }
    
    return $file;
}

/**
 * PHP木马防护：检查文件内容是否包含恶意代码
 */
function nenghui_check_file_content($file_path) {
    if (!file_exists($file_path)) {
        return array('safe' => false, 'message' => '文件不存在');
    }
    
    // 读取文件前1KB内容进行检查
    $content = file_get_contents($file_path, false, null, 0, 1024);
    
    if ($content === false) {
        return array('safe' => false, 'message' => '无法读取文件内容');
    }
    
    // PHP木马常用的危险函数和关键词
    $dangerous_patterns = array(
        '/<\?php/i', '/<\?=/i', '/<\?\s/i', '/<script/i',
        '/eval\s*\(/i', '/exec\s*\(/i', '/system\s*\(/i', '/shell_exec\s*\(/i',
        '/passthru\s*\(/i', '/file_get_contents\s*\(/i', '/file_put_contents\s*\(/i',
        '/fopen\s*\(/i', '/fwrite\s*\(/i', '/fputs\s*\(/i',
        '/base64_decode\s*\(/i', '/gzinflate\s*\(/i', '/str_rot13\s*\(/i',
        '/assert\s*\(/i', '/preg_replace\s*\(/i', '/create_function\s*\(/i',
        '/call_user_func/i', '/\$_GET/i', '/\$_POST/i', '/\$_REQUEST/i',
        '/\$_COOKIE/i', '/\$_SERVER/i', '/\$_SESSION/i', '/\$_FILES/i'
    );
    
    if (is_array($dangerous_patterns) && !empty($dangerous_patterns)) {
        foreach ($dangerous_patterns as $pattern) {
            if (preg_match($pattern, $content)) {
                return array('safe' => false, 'message' => '检测到可疑代码，上传被拒绝');
            }
        }
    }
    
    // 检查是否包含PHP标签但不是SVG文件
    if (preg_match('/<\?/i', $content) && !preg_match('/<svg/i', $content)) {
        return array('safe' => false, 'message' => '检测到PHP代码，上传被拒绝');
    }
    
    return array('safe' => true, 'message' => '文件安全');
}
// 暂时关闭文件上传限制，以便上传插件
// add_filter('wp_handle_upload_prefilter', 'nenghui_optimize_file_upload');

/**
 * PHP木马防护：上传后文件安全处理
 */
function nenghui_secure_uploaded_file($file) {
    if (isset($file['file'])) {
        // 重命名文件，移除可能的恶意扩展名
        $file_info = pathinfo($file['file']);
        $safe_filename = sanitize_file_name($file_info['filename']);
        $extension = strtolower($file_info['extension']);
        
        // 确保文件名安全
        $safe_filename = preg_replace('/[^a-zA-Z0-9_-]/', '', $safe_filename);
        if (empty($safe_filename)) {
            $safe_filename = 'upload_' . time();
        }
        
        $new_filename = $safe_filename . '.' . $extension;
        $new_file_path = $file_info['dirname'] . '/' . $new_filename;
        
        // 如果文件名发生变化，重命名文件
        if ($file['file'] !== $new_file_path && file_exists($file['file'])) {
            if (rename($file['file'], $new_file_path)) {
                $file['file'] = $new_file_path;
                $file['url'] = str_replace(basename($file['url']), $new_filename, $file['url']);
            }
        }
        
        // 设置安全的文件权限
        if (file_exists($file['file'])) {
            chmod($file['file'], 0644);
        }
        
        // 记录上传日志
        nenghui_log_file_upload($file['file'], $file['type']);
    }
    
    return $file;
}
add_filter('wp_handle_upload', 'nenghui_secure_uploaded_file');

/**
 * PHP木马防护：记录文件上传日志
 */
function nenghui_log_file_upload($file_path, $file_type) {
    $log_entry = sprintf(
        "[%s] File uploaded: %s (Type: %s) by User: %s (IP: %s)\n",
        date('Y-m-d H:i:s'),
        basename($file_path),
        $file_type,
        get_current_user_id(),
        $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    );
    
    $upload_dir = wp_upload_dir();
    $log_file = $upload_dir['basedir'] . '/upload_security.log';
    
    // 确保日志文件安全
    if (!file_exists($log_file)) {
        file_put_contents($log_file, "# Upload Security Log\n");
        chmod($log_file, 0600);
    }
    
    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

/**
 * PHP木马防护：定期清理可疑文件
 */
function nenghui_scan_and_clean_uploads() {
    $upload_dir = wp_upload_dir();
    $scan_dir = $upload_dir['basedir'];
    
    if (!is_dir($scan_dir)) {
        return;
    }
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($scan_dir),
        RecursiveIteratorIterator::LEAVES_ONLY
    );
    
    $suspicious_files = array();
    
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $filename = $file->getFilename();
            $filepath = $file->getPathname();
            
            // 检查可疑文件扩展名
            $dangerous_extensions = array('php', 'php3', 'php4', 'php5', 'phtml', 'phps');
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            
            if (is_array($dangerous_extensions) && !empty($dangerous_extensions) && in_array($extension, $dangerous_extensions)) {
                $suspicious_files[] = $filepath;
                // 立即删除可疑文件
                if (unlink($filepath)) {
                    nenghui_log_security_action('Deleted suspicious file: ' . $filepath);
                }
            }
            
            // 检查双重扩展名
            if (preg_match('/\.(php|phtml|php3|php4|php5|php7|phps)\./i', $filename)) {
                $suspicious_files[] = $filepath;
                if (unlink($filepath)) {
                    nenghui_log_security_action('Deleted file with double extension: ' . $filepath);
                }
            }
        }
    }
    
    return $suspicious_files;
}

/**
 * PHP木马防护：记录安全操作日志
 */
function nenghui_log_security_action($message) {
    $log_entry = sprintf(
        "[%s] SECURITY: %s (IP: %s)\n",
        date('Y-m-d H:i:s'),
        $message,
        $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    );
    
    $upload_dir = wp_upload_dir();
    $log_file = $upload_dir['basedir'] . '/security_actions.log';
    
    if (!file_exists($log_file)) {
        file_put_contents($log_file, "# Security Actions Log\n");
        chmod($log_file, 0600);
    }
    
    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

// 每天执行一次安全扫描
if (!wp_next_scheduled('nenghui_security_scan')) {
    wp_schedule_event(time(), 'daily', 'nenghui_security_scan');
}
add_action('nenghui_security_scan', 'nenghui_scan_and_clean_uploads');

// 图片压缩、内存监控和临时文件清理功能已移至 inc/init-config.php