<?php
$target_dir = "capes/";
$uuid = $_POST["uuid"];
$uploadOk = 1;
$imageFileType = strtolower(pathinfo(basename($_FILES["imageToUpload"]["name"]), PATHINFO_EXTENSION));

// Check if is an image
if(isset($_POST["submit"])) {
	$check = getimagesize($_FILES["imageToUpload"]["tmp_name"]);
	if($check !== false) {
		$uploadOk = 1;
	} else {
		echo "File is not an image.\n";
		$uploadOk = 0;
	}
}

if(strlen($_POST["uuid"]) > 16) {//Larger than 16 = UUID
	
	$uuid = strtolower(str_replace(' ', '', $uuid));
	
	$response = file_get_contents("https://api.mojang.com/user/profiles/".$uuid."/names");

	if (!isValidDomain($response)) {//Check if valid uuid
		
		echo "UUID is not valid.\n";
		$uploadOk = 0;	

	}	
	
} else {//Less than 16 = name
	
	$response = file_get_contents("https://api.mojang.com/users/profiles/minecraft/".$uuid);
	
	if (!isValidDomain($response)) {//uuid is actually name
		echo "Not a valid name.\n";
		$uploadOk = 0;
	} else {
		$json = json_decode($response, true);
		$uuid = $json["id"];
	}
	
}


// Check file dimensions
$size = getimagesize($_FILES["imageToUpload"]["tmp_name"]);
$width = $size[0];
$height = $size[1];
$checkbase = log($width,2);
if(! ($height * 2 == $width && $width >= 64 && $width <=512 && floor($checkbase) == $checkbase)) {
	echo "Image dimensions are not correct\n";
	$uploadOk = 0;
}

// Only allow certain formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
	echo "Sorry, only JPG, JPEG, and PNG files are allowed.\n";
	$uploadOk = 0;
}

$target_file = $target_dir . $uuid;

if ($uploadOk == 0) {
	echo "Your file was NOT uploaded.";
} else {
	if (move_uploaded_file($_FILES["imageToUpload"]["tmp_name"], $target_file)) {
		
		$usersfileloc = "./users";
		$users = file_get_contents ($usersfileloc);
		
		$usersarr = json_decode ($users);
	
		if (!in_array ($uuid, $usersarr)) {

			array_push ($usersarr, $uuid);
			$newusers = json_encode ($usersarr);
			file_put_contents($usersfileloc, $newusers);

		}
		echo "The file " . htmlspecialchars( basename( $_FILES["imageToUpload"]["name"])) . " was uploaded.";
	} else {
		echo "There was an error uploading your file.";
	}
}




function isValidDomain($response) {
	
	if ($response) {
	
		if(isJson($response)) {

			$data = json_decode($response, true);
			if(array_key_exists("error", $data)) {
				return false;
			}

		}

		return true;

	}

	return false;
}

function isJson($string) {

	json_decode($string);
	return (json_last_error() == JSON_ERROR_NONE);

}


?>
