<?php

// CONFIGURATION ===================================================
// DKS endpoint WITHOUT /api. If, for example, the actual DKS api is to be found
// at http://my.server.com/api/ (so that the version information can be fetched 
// with http://my.server.com/api/version), just place "http://my.server.com" here
$DKS_URL = "http://127.0.0.1:8080";
// If API is secured, specify either Username/Password ...
$DKS_USERNAME = "duden";
$DKS_PASSWORD = "duden";

// ...or in case of DKS version >=1.6, you can use an API token as well (recommended)
//$DKS_API_TOKEN = "E1S2BWQFJ4R8QMNM";
$DKS_API_TOKEN = null;
// END OF CONFIGURATION ============================================

$PROXY_SCRIPT_NAME = "duden-correction-server-connector.php";

$request_uri = $_SERVER['REQUEST_URI'];

// Remove preceeding parts of the request URL
// So that http://my.server.com/my/web/server/path/duden-correction-server-connector.php/api/version
// is boiled down to http://$DKS_URL/api/version
// regardless of path depth
$found_proxy_pos = strpos($request_uri,$PROXY_SCRIPT_NAME);
if ( $found_proxy_pos !== FALSE ) {
    $request_uri = substr($request_uri, $found_proxy_pos + strlen($PROXY_SCRIPT_NAME) );
}

$url = str_replace('?function=','/api/',$DKS_URL . $request_uri);

function getRequestHeaders($DKS_API_TOKEN = null)
{
    $headers = array();
    if ( isset($DKS_API_TOKEN) ) {
        array_push($headers, "Authorization: Bearer ".$DKS_API_TOKEN);
    }
    foreach ($_SERVER as $key => $value) {
        if (preg_match("/^HTTP/", $key)) { # only keep HTTP headers
            if (
                preg_match("/^HTTP_HOST/", $key) == 0 && # let curl set the actual host/proxy
                preg_match("/^HTTP_ORIGIN/", $key) == 0 &&
                preg_match("/^HTTP_CONTENT_LEN/", $key) == 0 && # let curl set the actual content length
                preg_match("/^HTTPS/", $key) == 0
            ) {
                $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
                array_push($headers, "$key: $value");
            }
        }
    }
    return $headers;
}

function setCurlOptions($curl,$DKS_API_TOKEN,$DKS_USERNAME,$DKS_PASSWORD) 
{
    curl_setopt($curl, CURLOPT_HTTPHEADER, getRequestHeaders($DKS_API_TOKEN));
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); # follow redirects
    curl_setopt($curl, CURLOPT_HEADER, true); # include the headers in the output
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); # return output as string
    curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // force HTTP 1.0 as workaround for CHUNKED_ENCODING_ERROR
    // see: https://stackoverflow.com/a/40529406
    if (isset($DKS_USERNAME) && isset($DKS_PASSWORD)) {
        curl_setopt($curl, CURLOPT_USERPWD, $DKS_USERNAME . ":" . $DKS_PASSWORD);
    }
    if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
        curl_setopt($curl, CURLOPT_POST, true);
        $post_data = file_get_contents("php://input");
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    }
}

$curl = curl_init($url);
setCurlOptions($curl,$DKS_API_TOKEN,$DKS_USERNAME,$DKS_PASSWORD);
$contents = curl_exec($curl);
curl_close($curl);

list($header_text, $contents) = preg_split('/([\r\n][\r\n])\\1/', $contents, 2);

$headers_arr = preg_split('/[\r\n]+/', $header_text);

// Propagate headers to response.
foreach ($headers_arr as $header) {
    if (!preg_match('/^Transfer-Encoding:/i', $header)) {
        if (preg_match('/^Location:/i', $header)) {
            # rewrite absolute local redirects to relative ones
            $header = str_replace($DKS_URL, "/", $header);
        }
        header($header);
    }
}

print $contents;
