<?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 is the new visitorboard code.
		It will generate a nice looking png image that is being shown on the visitorboard inworld.
	*/

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

	//Handle languagefile
	LoadLanguages();
	$SelLang = strtolower($_GET["l"]);
	if (!isset($GLOBALS["LanguageData"][$SelLang])) {$SelLang = "en";}

	//Look up timezone, country and the (hopefulle) correct language for the region that requests this image
	$ListOfTimezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
	$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($_SERVER["REMOTE_ADDR"]))->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/".$_SERVER["REMOTE_ADDR"], "", 3), true);
		if ($TraceRequest["status"] == "success")
		{
			$TimeZone = $TraceRequest["timezone"];
			$Country = $TraceRequest["countryCode"];
		}
		//To have a minimum of dataprotection, we are hashing the cached ip addresses
		$MySql->query("INSERT INTO ip_timezones (ip, timezone, country, unix)VALUES(md5({0}), {1}, {2}, {3})", array($_SERVER["REMOTE_ADDR"], $TimeZone, $Country, time()));
	}
	else
	{
		$TimeZone = $Exists["timezone"];
		$Country = $Exists["country"];
	}
	if (in_array(strtolower($TimeZone), $ListOfTimezones))
	 {date_default_timezone_set($TimeZone);}

	//So, now lets start with requesting all required information from the visitors grids
	$UserMem = array();
	$AllUsers = explode(";", $_GET["u"]);
	for ($i = 0; $i < count($AllUsers); ++$i)
	{
		$SingleUser = explode(",", $AllUsers[$i]);
		for ($z = 0; $z < count($SingleUser); ++$z)
		 {$SingleUser[$z] = trim($SingleUser[$z]);}
		if (!empty($SingleUser[0]) && !empty($SingleUser[1]))
		{
			//The magic is done here
			$UserInfo = new GridUser($SingleUser[0], $SingleUser[1], realpath(dirname(__FILE__)));
			$Info = $UserInfo->ToArray();
			if ($Info !== false)
			{
				$UserMem[] = array("uuid"	=> $Info["uuid"],
								   "name"	=> $Info["firstname"]." ".$Info["lastname"],
								   "grid"	=> $Info["homegrid"],
								   "title"	=> $Info["title"],
								   "unix"	=> date("d.m.Y H:i", (int)$SingleUser[2]));
			}
		}
	}
	$UserMem = array_reverse($UserMem);


	//Now we are starting to render the image
	$Image = imagecreatetruecolor(1024, 512);

	$Colors["white"] = imagecolorallocate($Image, 255, 255, 255);
	$Colors["red"] = imagecolorallocate($Image, 140, 0, 0);
	$Colors["blue"] = imagecolorallocate($Image, 0, 0, 140);
	$Colors["green"] = imagecolorallocate($Image, 0, 60, 0);
	$Colors["whitealpha"] = imagecolorallocatealpha($Image, 255, 255, 255, 96);

	$Background = imagecreatefromjpeg("Img/Blackboard.jpg");
	imagecopyresampled($Image, $Background, 0, 0, 0, 0, 1024, 512, imagesx($Background), imagesy($Background));

	$Size = imageftbbox(26, 0, "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_1"]);
	$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
	imagefttext($Image, 26, 0, 20, 20 + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_1"]);

	$Size = imageftbbox(24, 0, "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_2"]);
	$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
	imagefttext($Image, 24, 0, 20, 240 + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_2"]);

	$x = 20;
	$y = 65;
	for ($i = 0; $i < count($UserMem); ++$i)
	{
		if ($i < 2)
		 {$ImgSize = 160;}
		else
		 {$ImgSize = 92;}
		if ($i > 0)
		{
			if ($i < 2)
			 {$x = $x + 512;}
			else
			{
				$x = $x + 1024 / 3;
				if ($i == 2)
				{
					$x = 20;
					$y = 280;
				}
				if ($x >= 1024)
				{
					$x = 20;
					$y = $y + 120;
				}
			}
		}
		$UserImage = MakeBorderOnImage(imagecreatefromjpeg("UserImage/".$UserMem[$i]["uuid"].".jpg"), "ChalkBorder");
		imagecopyresampled($Image, $UserImage, $x, $y, 0, 0, $ImgSize, $ImgSize, imagesx($UserImage), imagesy($UserImage));

		if ($i < 2)
		{
			$LocalY = $y;

			$Size = imageftbbox(12, 0, "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_name"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 12, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_name"]);
			$LocalY = $LocalY + $Size[1] + 5;

			$Size = imageftbbox(18, 0, "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["name"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 18, 0, $x + $ImgSize + 10 + 10, $LocalY + $Size[1], $Colors["red"], "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["name"]);
			$LocalY = $LocalY + $Size[1] + 2;

			$Size = imageftbbox(11, 0, "Fonts/DJB Chalk It Up.ttf", "» ".$UserMem[$i]["title"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 11, 0, $x + $ImgSize + 10 + 10, $LocalY + $Size[1], $Colors["green"], "Fonts/DJB Chalk It Up.ttf", "» ".$UserMem[$i]["title"]);
			$LocalY = $LocalY + $Size[1] + 10;

			$Size = imageftbbox(12, 0, "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_from"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 12, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_from"]);
			$LocalY = $LocalY + $Size[1] + 5;

			$Size = imageftbbox(18, 0, "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["grid"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 18, 0, $x + $ImgSize + 10 + 10, $LocalY + $Size[1], $Colors["blue"], "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["grid"]);
			$LocalY = $LocalY + $Size[1] + 10;

			$Size = imageftbbox(12, 0, "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_time"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 12, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $GLOBALS["LanguageData"][$SelLang]["title_time"]);
			$LocalY = $LocalY + $Size[1] + 5;

			$Size = imageftbbox(18, 0, "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["unix"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 18, 0, $x + $ImgSize + 10 + 10, $LocalY + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["unix"]);
			$LocalY = $LocalY + $Size[1] + 10;
		}
		else
		{
			$LocalY = $y;

			$Size = imageftbbox(14, 0, "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["name"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 14, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["red"], "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["name"]);
			$LocalY = $LocalY + $Size[1] + 2;

			$Size = imageftbbox(9, 0, "Fonts/DJB Chalk It Up.ttf", "» ".$UserMem[$i]["title"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 9, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["green"], "Fonts/DJB Chalk It Up.ttf", "» ".$UserMem[$i]["title"]);
			$LocalY = $LocalY + $Size[1] + 10;

			$Size = imageftbbox(14, 0, "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["grid"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 14, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["blue"], "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["grid"]);
			$LocalY = $LocalY + $Size[1] + 10;

			$Size = imageftbbox(14, 0, "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["unix"]);
			$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
			imagefttext($Image, 14, 0, $x + $ImgSize + 10, $LocalY + $Size[1], $Colors["white"], "Fonts/DJB Chalk It Up.ttf", $UserMem[$i]["unix"]);
			$LocalY = $LocalY + $Size[1] + 10;
		}

	}

	$Size = imageftbbox(10, 0, "Fonts/BlackOpsOne-Regular.ttf", "KUBWA");
	$Size = array(abs($Size[0]) + abs($Size[2]), abs($Size[1]) + abs($Size[5]));
	imagefttext($Image, 10, 0, 1024 - $Size[0] - 15, 512 - $Size[1], $Colors["whitealpha"], "Fonts/BlackOpsOne-Regular.ttf", "KUBWA");

	header("content-type: image/png");
	imagepng($Image);



	//A little helper function which puts a nice frame around a users image
	function MakeBorderOnImage($Image, $Border)
	{
		imagealphablending($Image, false);
		imagesavealpha($Image, true);
		$Border = imagecreatefrompng("Img/".$Border.".png");
		$ScaledBorder = imagecreatetruecolor(imagesx($Image), imagesy($Image));
		imagecopyresampled($ScaledBorder, $Border, 0, 0, 0, 0, imagesx($Image), imagesy($Image), imagesx($Border), imagesy($Border));
		if (round(rand(0, 3)) == 1) {imageflip($ScaledBorder, IMG_FLIP_HORIZONTAL);}
		if (round(rand(0, 3)) == 2) {imageflip($ScaledBorder, IMG_FLIP_VERTICAL);}
		if (round(rand(0, 3)) == 3) {imageflip($ScaledBorder, IMG_FLIP_BOTH);}
		$ScaledBorder = imagerotate($ScaledBorder, 3 - rand(0, 6), imagecolorallocate($ScaledBorder, 76, 255, 0), true);
		$Transparent = imagecolorallocatealpha ($Image, 255, 255, 255, 127);
		for ($y = 0; $y < imagesy($ScaledBorder); ++$y)
		{
			for ($x = 0; $x < imagesx($ScaledBorder); ++$x)
			{
				$rgb = imagecolorsforindex($ScaledBorder, imagecolorat($ScaledBorder, $x, $y));
				if ($rgb["green"] >= 250 && $rgb["red"] < 100 && $rgb["blue"] < 100)
				 {imagesetpixel($Image, $x, $y, $Transparent);}
				else
				{
					if ($rgb["red"] > 0 && $rgb["green"] > 0 && $rgb["blue"] > 0 && rand(0, 1000) > 100)
					 {imagesetpixel($Image, $x, $y, imagecolorallocatealpha($Image, 255, 255, 255, $rgb["alpha"]));}
				}
			}
		}
		return $Image;
	}


	//Language variable handling (kind of shitty)
	$GLOBALS["LanguageData"] = array();
	function LoadLanguages()
	{
		$Temp = file_get_contents("Language/lang.txt");
		$Temp = explode("\n", str_replace("\r", "", $Temp));
		$CurLng = "";
		for ($i = 0; $i < count($Temp); ++$i)
		{
			$Line = trim(explode("#", $Temp[$i])[0]);
			if (!empty($Line))
			{
				if (substr($Line, 0, 1) == "[")
				{
					$CurLng = substr($Line, 1, -1);
					$GLOBALS["LanguageData"][strtolower($CurLng)] = array();
				}
				else
				{
					if (!empty($CurLng))
					{
						$KeyPair = explode("=", $Line, 2);
						$GLOBALS["LanguageData"][strtolower($CurLng)][strtolower(trim($KeyPair[0]))] = trim($KeyPair[1]);
					}
				}
			}
		}
	}
?>