\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7 \8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh \00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€ \00 $\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95 59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9 C/// File Manager

File Manager

Path: /opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/wordpress/

Viewing File: wp_rules.py

"""WordPress rules file management.

This module provides utilities for loading and parsing wp-rules.yaml
from the files.imunify360.com index system.

Available for both AV and IM360 modes.
"""

import logging
import yaml
import zipfile
from pathlib import Path

from defence360agent.files import Index

logger = logging.getLogger(__name__)

# WordPress rules file names within the index
WP_RULES_ZIP_FILENAME = "wp-rules.zip"
WP_RULES_VERSION_FILENAME = "VERSION"


def find_file_in_index(index: Index, filename: str) -> Path | None:
    """
    Find a file path from the index by filename.

    Args:
        index: files.Index object
        filename: Name of the file to find (e.g., WP_RULES_ZIP_FILENAME)

    Returns:
        Path to the file or None if not found
    """
    for item in index.items():
        if item["name"] == filename:
            file_path = Path(index.localfilepath(item["url"]))

            if file_path.exists():
                return file_path
    logger.error("%s not found in %s", filename, index.files_path(index.type))
    return None


def extract_wp_rules_yaml(zip_path: Path) -> dict | None:
    """
    Extract and parse wp-rules.yaml from the zip file.

    Args:
        zip_path: Path to wp-rules.zip file

    Returns:
        Parsed YAML data as dict or None if extraction/parsing fails
    """
    try:
        with zipfile.ZipFile(zip_path, "r") as zip_file:
            with zip_file.open("wp-rules.yaml") as yaml_file:
                rules_data = yaml.safe_load(yaml_file)
    except (zipfile.BadZipFile, KeyError, yaml.YAMLError) as e:
        logger.error("Failed to extract or parse wp-rules.yaml: %s", e)
        return None

    if not isinstance(rules_data, dict):
        logger.error("Invalid wp-rules.yaml format: %s", rules_data)
        return None
    return rules_data


def get_wp_rules_data(index: Index) -> dict | None:
    """
    Retrieve the latest WordPress rules and return them as a dictionary.

    Args:
        index: The files.Index object used to locate the wp-rules.zip file.

    Returns:
        The parsed wp-rules data as a dictionary.
        If the wp-rules archive or data cannot be found or parsed, returns None.

    Note:
        This function returns the raw rules data. Callers that need to modify
        rules based on product mode (e.g., ANTIVIRUS_MODE) should do so after
        calling this function.
    """
    # Find wp-rules.zip file
    zip_path = find_file_in_index(index, WP_RULES_ZIP_FILENAME)
    if not zip_path:
        return None

    # Extract and parse wp-rules.yaml
    rules_data = extract_wp_rules_yaml(zip_path)
    if not rules_data:
        return None
    logger.info("Successfully parsed wp-rules.yaml")

    return rules_data


def get_wp_ruleset_version(index: Index) -> str:
    """
    Retrieve the WordPress ruleset version string from the VERSION file.

    Args:
        index: The files.Index object used to locate the VERSION file.

    Returns:
        The version string from the VERSION file.
        If the VERSION file cannot be found or read, returns "NA".
    """
    # Find VERSION file
    version_path = find_file_in_index(index, WP_RULES_VERSION_FILENAME)
    if not version_path:
        return "NA"

    try:
        version_string = version_path.read_text().strip()
        logger.info("Successfully read wp-rules version: %s", version_string)
        return version_string
    except Exception as e:
        logger.error("Failed to read VERSION file: %s", e)
        return "NA"