<?php
require "mojangapi.php";

function endsWith($string, $endString) 
{ 
    $len = strlen($endString); 
    if ($len == 0) { 
        return true; 
    } 
    return (substr($string, -$len) === $endString); 
} 

$user = $_GET["user"];

if (endsWith($user, ".png")) {
    $user = trim($user, ".png");
}



if ((!file_exists("cache/".$user.".png")) or (time()-filemtime("cache/".$user.".png") > 120)) {
    if (file_exists("cache/".$user.".png")) {
        unlink("cache/".$user.".png");
    }
    $uuid = MojangAPI::getUuid($user);
    $skin = MojangAPI::getSkin($uuid);

    $skin = imagecreatefromstring($skin);
    imageAlphaBlending($skin, true);
    imageSaveAlpha($skin, true);
    imagepng($skin, "cache/".$user.".png");
}
else {
    $skin = imagecreatefrompng("cache/".$user.".png");
    imageAlphaBlending($skin, true);
    imageSaveAlpha($skin, true);
}

header('Content-Type: image/png');
imagepng($skin);
imagedestroy($skin);

exit;