#!/usr/bin/env python

"""
Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

from lib.core.compat import xrange  # 导入兼容库中的xrange函数，用于兼容Python 2和3的range函数
from lib.core.enums import PRIORITY  # 从核心库导入优先级枚举

# 设置优先级为最高
__priority__ = PRIORITY.HIGHEST

def dependencies():
    pass

def tamper(payload, **kwargs):
    """
    Replaces instances like 'IFNULL(A, B)' with 'CASE WHEN ISNULL(A) THEN (B) ELSE (A) END' counterpart

    Requirement:
        * MySQL
        * SQLite (possibly)
        * SAP MaxDB (possibly)

    Tested against:
        * MySQL 5.0 and 5.5

    Notes:
        * Useful to bypass very weak and bespoke web application firewalls
          that filter the IFNULL() functions

    >>> tamper('IFNULL(1, 2)')
    'CASE WHEN ISNULL(1) THEN (2) ELSE (1) END'
    """

    if payload and payload.find("IFNULL") > -1:  # 如果payload不为空且包含'IFNULL'
        while payload.find("IFNULL(") > -1:  # 遍历所有'IFNULL'语句
            index = payload.find("IFNULL(")  # 找到'IFNULL'的位置
            depth = 1 # 初始化括号深度
            comma, end = None, None  # 初始化逗号位置和结束位置

            # 遍历payload以找到'IFNULL'语句的结束位置
            for i in xrange(index + len("IFNULL("), len(payload)):
                if depth == 1 and payload[i] == ',':
                    comma = i  # 记录逗号位置

                elif depth == 1 and payload[i] == ')':
                    end = i  # 记录结束位置
                    break

                elif payload[i] == '(':
                    depth += 1  # 增加括号深度


                elif payload[i] == ')':
                    depth -= 1  # 减少括号深度

            # 如果找到逗号和结束位置，则进行替换
            if comma and end:
                _ = payload[index + len("IFNULL("):comma]  # 提取参数A
                __ = payload[comma + 1:end].lstrip() # 提取参数B
                newVal = "CASE WHEN ISNULL(%s) THEN (%s) ELSE (%s) END" % (_, __, _)  # 构造新的CASE语句
                payload = payload[:index] + newVal + payload[end + 1:]  # 替换原IFNULL语句
            else:
                break  # 如果不符合条件，则终止循环

    return payload
