<?php

//var_dump($_SERVER); die();

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$country = cache(
    function() use ($ip) {
        return ip2country($ip);
    },
    MD5($ip),
    3600 * 24 * 30
);
$path = @$_GET['wpath'];
$query = @$_GET['wquery'];

$path  = ltrim(($path !== '/index.html' ? '/' . ltrim($path, '/') : '/') . ($query!='' ? '?' . $query : ''), '/');
$country = $country ? $country : browser2country();


file_put_contents('../var/log/com-weiche.log', date('Y-m-d H:i:s') . "\t" . $ip . "\t" . $country . "\t" . @$_SERVER["HTTP_ACCEPT_LANGUAGE"] . "\t/" . $path . "\r\n", FILE_APPEND);

if($country === 'DE' || in_array($country, ['BE', 'NL', 'PL', 'FR'])) {
	redirect('https://www.cutcut.de/' . $path);
} 

// else
redirect('https://www.cutcut.at/' . $path);

function get_Client_Prefered_Language ($getSortedList = true, $acceptedLanguages = false)
{
	//https://stackoverflow.com/a/11161193/3177115
	
    if (empty($acceptedLanguages))
        $acceptedLanguages = $_SERVER["HTTP_ACCEPT_LANGUAGE"];

    // regex inspired from @GabrielAnderson on http://stackoverflow.com/questions/6038236/http-accept-language
    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})*)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $acceptedLanguages, $lang_parse);
    $langs = $lang_parse[1];
    $ranks = $lang_parse[4];

    // (create an associative array 'language' => 'preference')
    $lang2pref = array();
    for($i=0; $i<count($langs); $i++)
        $lang2pref[$langs[$i]] = (float) (!empty($ranks[$i]) ? $ranks[$i] : 1);

    // (comparison function for uksort)
    $cmpLangs = function ($a, $b) use ($lang2pref) {
        if ($lang2pref[$a] > $lang2pref[$b])
            return -1;
        elseif ($lang2pref[$a] < $lang2pref[$b])
            return 1;
        elseif (strlen($a) > strlen($b))
            return -1;
        elseif (strlen($a) < strlen($b))
            return 1;
        else
            return 0;
    };

    // sort the languages by prefered language and by the most specific region
    uksort($lang2pref, $cmpLangs);

    if ($getSortedList)
        return $lang2pref;

    // return the first value's key
    reset($lang2pref);
	
    return key($lang2pref);
}

function browser2country() {
	$langs = get_Client_Prefered_Language();
	foreach($langs As $lang => $prio) {
		if(stripos($langs, 'at') !== false) return 'AT';
		if(stripos($langs, 'ch') !== false) return 'CH';
		if(stripos($langs, 'de') !== false) return 'DE';
		if(stripos($langs, 'fr') !== false) return 'FR';
		if(stripos($langs, 'it') !== false) return 'IT';
	}
	return false;
}

function redirect($url) {
	header("HTTP/1.1 302 Moved Temporarily"); 
	header("Location: $url"); 
	header("Connection: close");
	die();
}

function ip2country($ip, $timeout = 3) {
	$url='http://ip-api.com/json/' . $ip;
	$ch=curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    //curl_setopt($ch, CURLOPT_VERBOSE, 1);
    //curl_setopt($ch, CURLOPT_STDERR, fopen('debug.log', 'w'));
	
	$result=curl_exec($ch);
	
	$countryCode = false;
	if($result && is_string($result)) {
		if($json = json_decode($result, true)) {
			if(isset($json['countryCode'])) {
				$countryCode = $json['countryCode'];
			}
		}
	}
		
	curl_close($ch);
	
	return $countryCode;
}

function cache($fkt, $hash, $seconds = 180) {

    // create cache directory if not exists
    $path = '../var/cache/data/ip2location/';
    if(!file_exists($path)) {
        mkdir($path, 0750, true);
    }

    // cleanup cache files older than ttl days
    $files = glob(rtrim($path, '/') . "/*");
    foreach ($files as $file) {
        if (is_file($file)) {
            $daysToKeep = max(1, (int)regmatch('/\-(\d+)(\.^\-*)?$/', $file, 1));
            if ((time() - ($daysToKeep * 3600 * 24)) > filemtime($file)) {
                unlink($file);
            }
        }
    }

    // read / write / execute 
    $cacheFile = rtrim($path, '/') . '/cache-' . MD5(json_encode($fkt)) . '-' . MD5($hash) . '-' . ceil($seconds / 3600 / 24);
    if(file_exists($cacheFile)) {
        if($seconds > 0 && (filemtime($cacheFile) > time() - $seconds)) {
            $ret = json_decode(file_get_contents($cacheFile));
            //Logger::debug('Cache success: ' . $hash, false);
            return $ret;
        } else {
            unlink($cacheFile);
        }
    }
    $ret = $fkt();
    $json = json_encode($ret);
    if($json != '' && $ret) {
        file_put_contents($cacheFile, $json);
    }

    // return result
    return $ret;
}

function regmatch($regex, $strg, $item = false) {
    if(preg_match($regex, $strg, $matches) != 0) {
        if($item!==false && count($matches) >= $item) {
            return $matches[$item];
        } elseif($item === false) {
            return $matches;
        } else {
            return false;
        }
    };
    return null;
}