<?PHP

/*
 * no.php (c) 2019 MAximilian Baehring
 *
 * Modified version of:
 *
*/
/*
 * no.php (c) 2016, 2017 Michael Franzl
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*

$backend_url = "https://www.web.de:443/";
$request_uri = $_SERVER['REQUEST_URI'];
$uri_rel = "no.php"; # URI to this file relative to public_html

$request_includes_nophp_uri = true;
if ( $request_includes_nophp_uri == false) {
    $request_uri = str_replace( $uri_rel, "/", $request_uri );
}

$is_ruby_on_rails = false;
if ( $is_ruby_on_rails == true) {
    # You have to understand the Ruby on Rails Asset pipeline to understand this.
    $request_uri = str_replace( "$uri_rel/assets", "/assets", $request_uri );
}

$url = $backend_url . $request_uri;
*/


//echo "<html><head></head><body>";
//echo "<pre>" . print_r($_SERVER,true) . "</pre>"; 


//20220612
include("no-cache.php");
//20220612


$bssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != null) && ($_SERVER['HTTPS'] == "on")) ? true : false;
//echo "\$bssl = \""  . (($bssl != false) ? "true" : "false") . "\"\r\n";exit(0);


$svip = "127.0.0.1";
$snxc = file_get_contents("etc-nginx-nginx.conf");
if (($nbip = strpos($snxc, "proxy_bind")) !== false) {
  $nbip = ($nbip + 10);
  if (($neip = strpos($snxc, ";", $nbip)) !== false) {
    $svip = trim(substr($snxc, $nbip, ($neip - $nbip)));
  }
}
//echo "\$svip = \""  . $svip . "\"\r\n";


//echo "</body></html>"; exit(0);


/*
// uncomment this to exit if no anonymity
// if ($svip == "127.0.0.1") { exit(0); }
*/


$surl = $_SERVER['REQUEST_URI'];
$siam = $_SERVER['SERVER_ADDR'];
//$siam = "95.216.194.6";
/*
$spro = "https";
$sprt = "443";
$spxy = "www.bad-homburg.de";
$spxy = "www.ecb.europa.eu";
*/
$spro = "http";
$sprt = "80";
$spxy = "10.20.30.41";

$nhcs = 0; // H(eader)C(har)S(et): -1 = need to change / 1 = changed (to iso-8859-1)
if (preg_match("/^\/download\//i", $surl)) {
  $spro= "http";
  $sprt= "80";
  $spxy = "www.take-ca.re";
  $nhcs = -1;
}
if (preg_match("/^\/downloads\//i", $surl)) {
  $spro= "http";
  $sprt= "80";
  $spxy = "www.take-ca.re";
  $nhcs = -1;
}
if (preg_match("/^\/tumblr.com\//i", $surl)) {
  $spro= "http";
  $sprt= "80";
  $spxy = "www.take-ca.re";
  $nhcs = -1;
}
if (preg_match("/^\/proxy(-|)ip($|\/$)/i", $surl)) {
/*
  $spro= "https";
  $sprt= "443";
  $spxy = "www.ip.uk.banktunnel.eu";
  $surl = "/";
*/
  $spro= "http";
  $sprt= "80";
  $spxy = "10.20.30.42";
  $surl = "/proxy-ip";
  $nhcs = 0;
}

$sURL = $spro . "://" . $spxy . ":" . $sprt . $surl;
//echo $sURL; exit(0);

function getRequestHeaders($sdel=NULL) {
    $ahdr = array();
//echo"<pre>" . htmlentities(print_r($_SERVER)) ."</pre>";
//exit(0);
    foreach($_SERVER as $skey => $sval) {
//echo"<pre>" . htmlentities($skey ." " . $sval) ."\r\n</pre>";

        if(preg_match("/^HTTP/", $skey)) { # only keep HTTP headers
            if(preg_match("/^HTTP_HOST/", $skey) == 0 && # let curl set the actual host/proxy
            preg_match("/^HTTP_ORIGIN/", $skey) == 0 &&
            preg_match("/^HTTP_CONTENT_LEN/", $skey) == 0 && # let curl set the actual content length

/* NEW */
            preg_match("/^HTTP_ACCEPT_ENCODING/", $skey) == 0 && # let curl set the actual content length
            preg_match("/^HTTP_CONNECTION/", $skey) == 0 && # let curl set the actual content length
/* NEW */
            preg_match("/^HTTPS/", $skey) == 0
            ) {
                $skey = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($skey, 5)))));
                array_push($ahdr, "$skey: $sval");
            }
        } elseif (preg_match("/^CONTENT_TYPE/", $skey)) {
            if(preg_match("/^multipart/", strtolower($sval)) && $sdel) {
                $skey = "Content-Type";
                $sval = "multipart/form-data; boundary=" . $sdel;
                array_push($ahdr, "$skey: $sval");
            }
        }
    }

/* NEW */
    array_push($ahdr, "Connection: close");
/* NEW */

//echo"<pre>" . htmlentities(print_r($ahdr)) ."</pre>";
//exit(0);
    return $ahdr;
}


//20220612
$sfic = findincache($_SERVER['REQUEST_URI'], 0);
if ($sfic != "") {
  if (file_exists("cache.tmp/" . $sfic)) {
//    $sffc = file_get_contents("cache.tmp/" . $sfic);
    $sfsc = filesize("cache.tmp/" . $sfic);
    $sftc = mime_content_type("cache.tmp/" . $sfic);
    if (($sfsc >= 1) || ($sftc != ""))  {
      header("Content-Type: " . $sftc);
      header("Content-Length: " . $sfsc);
      fpassthru(fopen(("cache.tmp/" . $sfic),"rb"));
      exit;
    }
  }
}
//20220612


function build_multipart_data_files($sdel, $sfld, $sfle) {
    # Inspiration from: https://gist.github.com/maxivak/18fcac476a2f4ea02e5f80b303811d5f :)
    $sdat = '';
    $seol = "\r\n";

    foreach ($sfld as $snam => $scon) {
        $sdat .= "--" . $sdel . $seol
            . 'Content-Disposition: form-data; name="' . $snam . "\"".$seol.$seol
            . $scon . $seol;
    }

    foreach ($sfle as $snam => $scon) {
        $sdat .= "--" . $sdel . $seol
            . 'Content-Disposition: form-data; name="' . $snam . '"; filename="' . $snam . '"' . $seol
            . 'Content-Transfer-Encoding: binary'.$seol
            ;
        $sdat .= $seol;
        $sdat .= $scon . $seol;
    }
    $sdat .= "--" . $sdel . "--".$seol;

    return $sdat;
}

//echo $sURL; exit(0);
$ourl = curl_init( $sURL );
curl_setopt( $ourl, CURLOPT_HTTPHEADER, getRequestHeaders() );
curl_setopt( $ourl, CURLOPT_FOLLOWLOCATION, true ); # follow redirects
curl_setopt( $ourl, CURLOPT_HEADER, true ); # include the headers in the output
curl_setopt( $ourl, CURLOPT_RETURNTRANSFER, true ); # return output as string

$sOUT="";
$callback = function($ourl, $sstr){
  global $sOUT;
  $sOUT .= $sstr;
  return strlen($sstr);
};
curl_setopt( $ourl, CURLOPT_WRITEFUNCTION, $callback);

if ( strtolower($_SERVER['REQUEST_METHOD']) == 'post' ) {
    curl_setopt( $ourl, CURLOPT_POST, true );
    $spst = file_get_contents("php://input");

if  (! is_null($_SERVER['CONTENT_TYPE'])) {

    if (preg_match("/^multipart/", strtolower($_SERVER['CONTENT_TYPE']))) {
        $sdel = '-------------' . uniqid();
        $spst = build_multipart_data_files($sdel, $_POST, $_FILES);
        curl_setopt( $ourl, CURLOPT_HTTPHEADER, getRequestHeaders($sdel) );
    }

}

    curl_setopt( $ourl, CURLOPT_POSTFIELDS, $spst );
}

curl_setopt($ourl , CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ourl , CURLOPT_SSL_VERIFYHOST, 0);

$sres = curl_exec( $ourl ); # reverse proxy. the actual request to the backend server.
curl_close( $ourl ); # curl is done now

//echo "SRES:" . $sres; exit(0);
//list( $sHDR, $sBDY ) = preg_split( '/([\r\n][\r\n])\\1/', $sres, 2 );

//echo "SOUT:" . $sOUT; exit(0);
list( $sHDR, $sBDY ) = preg_split( '/([\r\n][\r\n])\\1/', $sOUT, 2 );
$aHDR = preg_split( '/[\r\n]+/', $sHDR );

//echo $sHDR; exit(0);

$shdr=$sHDR;
$shdr=str_replace( $spxy, $siam, $shdr);
$shdr=str_replace( "https://" . $siam, "http://" . $siam, $shdr);

$ahdr = preg_split( '/[\r\n]+/', $shdr );


$btxt = false;
$bhtm = false;
$bcss = false;
$bjvs = false;

//echo "<pre>";
foreach ( $ahdr as $shdr ) {
//  echo $shdr . "\r\n";
  if ( preg_match( '/^Content-Type:/i', $shdr ) ) {
//    echo $shdr . "\r\n";
    $sval = preg_replace('/^Content-Type: /i', '', $shdr);
//    echo "\"" . $sval . "\"\r\n";
    if ( preg_match( '/^text/', $sval ) ) {
      $btxt=true;
//      echo "Mtxt: \""  . $sval . "\"\r\n";
//    } else {
//      echo "mtxt: \"" . $sval . "\"\r\n";
    }
    if ( preg_match( '/^text\/html/', $sval ) ) {
      $bhtm=true;
//      echo "Mhtm: \""  . $sval . "\"\r\n";
//    } else {
//      echo "mhtm: \"" . $sval . "\"\r\n";
    }
    if ( preg_match( '/^text\/css/', $sval ) ) {
      $bcss=true;
//      echo "Mcss: \""  . $sval . "\"\r\n";
//    } else {
//      echo "mcss: \"" . $sval . "\"\r\n";
    }
    if ( preg_match( '/^text\/x-js/', $sval ) ) {
      $bjvs=true;
//      echo "Mjvs: \""  . $sval . "\"\r\n";
//    } else {
//      echo "mjvs: \"" . $sval . "\"\r\n";
    }
//    $atyp = preg_split( '/[\ ]+/', $shdr );
//    print_r($sval);
  }
}
//echo "BTXT: " . (($btxt != true) ? "FALSE" : "TRUE") . "\r\n";
//echo "BHTM: " . (($bhtm != true) ? "FALSE" : "TRUE") . "\r\n";
//echo "BCSS: " . (($bcss != true) ? "FALSE" : "TRUE") . "\r\n";
//echo "BJVS: " . (($bjvs != true) ? "FALSE" : "TRUE") . "\r\n";
//echo "</pre>"; exit(0);

if ($btxt == true) {

  $sbdy=$sBDY;
  $sbdy=str_replace( $spxy, $siam, $sbdy);
  if ($bssl != true) {
    $sbdy=str_replace( "https://" . $siam, "http://" . $siam, $sbdy);
  }

}
//$aHDR = preg_split( '/[\r\n]+/', $shdr );

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

        if (( $nhcs == -1 ) && ( $bhtm == true ) && ( preg_match( '/^Content-Type:/i', $shdr ) )) {
          $shdr = "Content-Type: text/html; charset=iso-8859-1";
          $nhcs = 1;
        }

        header( $shdr );
    }
//echo "<pre>HDR: " . $shdr . "</pre>";
}
if (( $nhcs == -1 ) && ( $bhtm == true )) {
  $shdr = "Content-Type: text/html; charset=iso-8859-1";
  $nhcs = 1;
  header( $shdr );
}

//exit(0);

//$sbdy=str_replace("expectations","muhaha",$sbdy);


//20220612 commented out
/*
if ($bhtm == true) {

include("ecb-replacements.php");
//20260619 */
include("hgu2-replacements.php");
/* //20260619

}
*/
//20220612 commented out


//print htmlentities($sbdy); # return the proxied request result to the browser

/*
echo "strlen" . strlen($sBDY);
if ( strlen($sbdy) >= 2 ) {
  if (substr($sbdy,0,2) == "\r\n") {
    $sbdy=substr($sbdy,2, (strlen($sbdy)-2));
  }
}
*/

//echo $sbdy; # return the proxied request result to the browser

if ($btxt == true) {
  echo $sbdy;
} else {
//20220612
  if ($sBDY != "") {
    $sURI = $_SERVER['REQUEST_URI'];
    if (($nURI = strpos($sURI, "?" ,0)) !== false) {
      $suri=substr($sURI, 0, $nURI);
      $sqry=substr($sURI, ($nURI + 1), (strlen($sURI) - ($nURI + 1)) );
    } else {
      $suri= $sURI;
    }
    if (iscacheable($suri)) {
      writetocache($sURI,$sBDY);
    //  echo findincache($sURI, 0);
    }
  }
//20220612
  echo $sBDY;
}


?>
