#!/usr/bin/env python

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

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

__priority__ = PRIORITY.LOW

def dependencies():
    pass

def tamper(payload, **kwargs):
    """
    Replaces (MySQL) instances of space character (' ') with comments '/**_**/'

    Tested against:
        * MySQL 5.0 and 5.5

    Notes:
        * Useful to bypass weak and bespoke web application firewalls

    >>> tamper('SELECT id FROM users')
    'SELECT/**_**/id/**_**/FROM/**_**/users'
    """

    retVal = payload

    if payload:
        retVal = ""
        quote, doublequote, firstspace = False, False, False

        # 遍历payload中的每个字符
        for i in xrange(len(payload)):
            # 如果第一个字符不是空格，则将firstspace设置为True，并将retVal添加"/**_**/"
            if not firstspace:
                if payload[i].isspace():
                    firstspace = True
                    retVal += "/**_**/"
                    continue

            # 如果字符是单引号，则将quote取反
            elif payload[i] == '\'':
                quote = not quote

            # 如果字符是双引号，则将doublequote取反
            elif payload[i] == '"':
                doublequote = not doublequote

            # 如果字符是空格，且不是在双引号或单引号中，则将retVal添加"/**_**/"
            elif payload[i] == " " and not doublequote and not quote:
                retVal += "/**_**/"
                continue

            # 将字符添加到retVal中
            retVal += payload[i]

    return retVal
