<?php
	/***********************************************************************
	* Script (c) Kubwa (https://kubwa.de)
	*
	* This script was release under BSD license.
	* You are free to use, share or change this code as you wish. This
	* header must be kept intact.
	***********************************************************************/

	require_once("classes/Framework.MySql.Class.php");
	require_once("classes/GridUserInfo.php");
	require_once("classes/Http.php");
	require_once("classes/Xml.php");
	require_once("Config.php");

	/*
		This little script is looking up country, language and timezone for a ip address and caches it.
		To have a minimum of dataprotection, we are hashing the ip addresses we are looking up.
	*/
	if (empty($_GET["ip"]) || !filter_var($_GET["ip"], FILTER_VALIDATE_IP))
	 {die("NOPE");}

	$MySql = new MySql($GLOBALS["CONFIG"]["mysql"]["user"], $GLOBALS["CONFIG"]["mysql"]["pass"], $GLOBALS["CONFIG"]["mysql"]["db"], $GLOBALS["CONFIG"]["mysql"]["server"]);

	$MySql->query("DELETE FROM ip_timezones WHERE unix < {0} OR (unix < {1} AND country = '')", array(time() - 86400 * 60, time() - 86400));
	$Exists = $MySql->query("SELECT * FROM ip_timezones WHERE ip = md5({0}) LIMIT 1", array($_GET["ip"]))->fetch();
	$TimeZone = "Europe/Berlin";
	$Country = "DE";
	if (empty($Exists["ip"]))
	{
		//We can also use another service to trace the ip, if you wish so, change this code
		$TraceRequest = json_decode(HttpRequest("http://ip-api.com/json/".$_GET["ip"], "", 3), true);
		if ($TraceRequest["status"] == "success")
		{
			$TimeZone = $TraceRequest["timezone"];
			$Country = $TraceRequest["countryCode"];
		}
		$MySql->query("INSERT INTO ip_timezones (ip, timezone, country, unix)VALUES(md5({0}), {1}, {2}, {3})", array($_GET["ip"], $TimeZone, $Country, time()));
	}
	else
	{
		$TimeZone = $Exists["timezone"];
		$Country = $Exists["country"];
	}

	$Language = "DE";
	$Exists = $MySql->query("SELECT * FROM countries_lang WHERE country = {0} LIMIT 1", array(strtolower($Country)))->fetch();
	if (!empty($Exists["lang"]))
	 {$Language = strtoupper($Exists["lang"]);}

	die(implode(",", array("OK", $Country, $TimeZone, $Language, $_GET["payload"])));
?>