<?php

$redirect_name = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';

# Hack für DTS#542617
$uri = $_SERVER['REQUEST_URI'];
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$hrf = strpos( $redirect_name, "hr-fernsehen.de" );

##var_dump($_SERVER);

debug("host/uri/referer", "$redirect_name - $uri - $referer");
#debug("strpos", $hrf);
#debug("strcasecmp",  strcasecmp($uri, "/allewetter") );
#if( ($hrf >= 0) && strcasecmp($uri, "/alleswissen") == 0 ) {
#	debug("Alleswissen!",  "http://".$redirect_name."/".$uri );
#	header('HTTP/1.0 301 Moved Permanently');
#        header('Location: http://www.hr-online.de/website/fernsehen/sendungen/index.jsp?rubrik=18876');
#	exit();
#};
#if( $redirect_name == "podcast.you-fm.de" ) {
#	debug( "PODCAST:", $_SERVER);
#};
//ersetzt hronline.de durch hr-online.de
$redirect_name = preg_replace("/hronline.de/", "hr-online.de", $redirect_name);
$redirect_name = rtrim($redirect_name, "/");

function debug($title, $object) {
  file_put_contents("/tmp/debug.log", date("--Y-m-d H:i:s--").$title."--\n".var_export($object, 1)."\n", FILE_APPEND);
}
#debug($redirect_name, array());

$wildcards = array(
	"hrinfo" => "https://hr-inforadio.de/index.html",
	"rechteszene" => "http://blogs.hr-online.de/hr-info-hessens-rechte/",
	"funkkolleg"  => "https://www.hr-inforadio.de/themen/funkkolleg/index.html",
	"hessischer-rundfunk.de" => "https://www.hr.de/index.html",
	"hrwerbung.de" => "https://www.hr-werbung.de/index.html",
	"you-fm.de" => "https://www.you-fm.de/index.html",
	"youfm.de" => "https://www.you-fm.de/index.html",
	"hr.de" => "https://www.hr.de/index.html",
	"hr1.de" => "https://www.hr1.de/index.html",
	"hr2.de" => "https://www.hr2.de/index.html",
	"hr3.de" => "https://www.hr3.de/index.html",
	"hr4.de" => "https://www.hr4.de/index.html",
	"hr2kultur.de" => "https://www.hr2.de/index.html",
	"hr2-kultur.de" => "https://www.hr2.de/index.html",
	"clubnight.de" => "https://www.you-fm.de/music/index.html",
	"hronline.de" => "https://www.hessenschau.de/index.html",
	"hrrundfunkrat.de" => "https://www.hr-rundfunkrat.de/index.html",
	"hrrundfunkrat.de" => "https://www.hr-rundfunkrat.de/index.html",
	"hrbigband.de" => "https://www.hr-bigband.de/index.html",
	"hrsinfonieorchester.de" => "https://www.hr-sinfonieorchester.de/index.html",
	"hrfernsehen.de" => "https://www.hr-fernsehen.de/index.html",
	"hrinforadio.de" => "https://www.hr-inforadio.de/index.html",
	"hessenschau.de" => "https://www.hessenschau.de/index.html"
	);


// Redirect
#if (($db = sqlite_open('/var/www/database/redirect.db', 0666, $error)) === false) {
if (($db = new PDO('sqlite:/var/www/database/redirect-v3.db')) === false) {
    die("Fehler beim Aufbau der DB-Verbindung!");
} else {
	$query = $db->prepare("SELECT `id`, `location` FROM redirect WHERE `host`=:redirect_name");
	$query->bindValue(':redirect_name', $redirect_name);
	if( $query !== false ) {

		$result = $query->execute();
               	$redirect = $query->fetch();
	        if ($redirect != false) {
			var_dump($redirect);
                        system('touch /var/www/log/'.$_SERVER['SERVER_NAME'].'#'.$_SERVER['UNIQUE_ID'].'#'.$redirect['id']);
			$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$urladd = '';

			$requestURI =  str_replace("/index.php", "", $_SERVER['REQUEST_URI']);
			$redirectScheme = parse_url($redirect['location'], PHP_URL_SCHEME);
			$redirectHost = parse_url($redirect['location'], PHP_URL_HOST);
			$redirectPath = parse_url($redirect['location'], PHP_URL_PATH);
			$redirectQuery = parse_url($redirect['location'], PHP_URL_QUERY);
			if ($redirectHost == "boerse.ard.de" && !preg_match("/html$/", $requestURI)) {
				$urlAddon = "";
				if (!preg_match("/\/$/", $requestURI)) {
					$urlAddon .= "/";
				}
				$urlAddon .= "index.html";
				#syslog(LOG_INFO, "URLADDON ".$urlAddon);
				$newRedirect = "https://".$redirectHost.$requestURI.$urlAddon;
			}
			elseif (($redirectPath == "" || substr_count($requestURI, $redirectPath) > 0 || $redirectPath == "/index.html") && $requestURI != "/") {
				$newRedirect = $redirectScheme."://".$redirectHost.$requestURI;
				#syslog(LOG_INFO, "Redirect with scheme: ".$newRedirect);
				#$newRedirect = "http://".$redirectHost.$requestURI;
			} else {
				$newRedirect = $redirect['location'];
			}
			#	syslog(LOG_INFO, "REMOTE:". $_SERVER['REMOTE_ADDR'].", redirectHost: ".$redirectHost.", newRedirect: ".$newRedirect.", HTTP_HOST: ".$_SERVER['HTTP_HOST'].", requestURI: ".$requestURI.", redirectLocation: ".$redirect['location'].", redirectPath: ".$redirectPath.", redirectQuery: ".$redirectQuery);
			header('HTTP/1.0 301 Moved Permanently');
                        header('Location: '.$newRedirect);
        	} else {
			// No Match. Try wildcards:
			$arr=explode(".", $redirect_name);
			$newRedirect= "https://www.hessenschau.de/index.html";
			$host="";
			if (count($arr) > 1) {
				$hosts = array_slice($arr,-2,1);
				$host = str_replace("-", "", $hosts[0]);
				syslog(LOG_INFO, "Redirect: ".$host);
				foreach($wildcards as $target => $location) {
					if( preg_match( "/".$host."/", $target ) ) {
						$newRedirect=$location;
						syslog(LOG_INFO, "regex-Redirect: ".$host." => ".$location);
					}
				}
			} else {
				syslog(LOG_INFO, "Fallback: ".$host." => ".$newRedirect);
			};

			syslog(LOG_INFO, "Fallback: ".$host." => ".$newRedirect);
			header('HTTP/1.0 301 Moved Permanently');
                        header('Location: '.$newRedirect);
                }
	} else {
		die("Fehler!");
	}

}

?>
