<?php

function http_parse_headers( $header ) {
    $retVal = array();
    $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
    foreach( $fields as $field ) {
        if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
            $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
            if( isset($retVal[$match[1]]) ) {
                $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
            } else {
                $retVal[$match[1]] = trim($match[2]);
            }
        }
    }
    return $retVal;
}

$script_start = microtime(true);
$server_get_url = "https://api.ultracart.com/cgi-bin/UCCheckoutAPIJSON"; 
$post_data = file_get_contents('php://input');

foreach($_SERVER as $i=>$val) {
  if (strpos($i, 'HTTP_') === 0) {
    $name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
    $header[] = "$name: $val";
  }
}

if(isset($_SERVER['CONTENT_TYPE'])){
  $content_type = $_SERVER['CONTENT_TYPE'];
} else {
  $content_type = 'application/json';
}

$header[] = "Content-Type: ". $content_type;
$header[] = "Content-Length: ". strlen($post_data);
$header[] = "X-UC-Forwarded-For: " . $_SERVER['REMOTE_ADDR'];

$ch = curl_init( $server_get_url );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_ENCODING, 1);

if ( strlen($post_data)>0 ){
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}

$response = curl_exec($ch);
$script_end = microtime(true);

if (curl_errno($ch)) {
    print curl_error($ch);
} else {
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $response_headers = http_parse_headers($header);
    foreach($response_headers as $i=>$val) {
      if($i != 'Content-Encoding' && $i != 'Vary' && $i != 'Connection' && $i != 'Transfer-Encoding'){
        header("$i: $val");
      }
    }
    header(sprintf("X-UltraCart-Proxy-Elapsed-Time:  %f seconds", $script_end-$script_start));
    $body = substr($response, $header_size);
    echo $body;
    curl_close($ch);
}
?>