<?php

require_once('mysql.php');

if(isset($_GET['uid']) && $uid = intval($_GET['uid']) > -1) {
	$uid = intval($_GET['uid']);
	$query = "SELECT avatar, avatar_updated, UNIX_TIMESTAMP(avatar_updated) as avatar_time FROM users WHERE uid = ".$uid;
	
	$q = mysql_query($query) or die(mysql_error());
	$res = mysql_fetch_assoc($q);
	
	$send_304 = false;
	
	if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
		if(intval(strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) === intval($res['avatar_time'])) {
			$send_304 = true;
		}
	}
	
	header("Cache-Control: private, max-age=10800, pre-check=10800");
	header("Pragma: private");
	header("Expires: " . date(DATE_RFC822, strtotime(" 2 day")));
	
	
	if ($send_304) {
        // Sending 304 response to browser
        // "Browser, your cached version of image is OK
        // we're not sending anything new to you"
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $res['avatar_time']).' GMT', true, 304);
    }
    else {
		header('Last-Modified: '.gmdate('D, d M Y H:i:s', $res['avatar_time']).' GMT', true, 200);
		
		if($res['avatar'] === "") {
			$image = imagecreatefrompng("default_avatar.png");
		}
		else {
			$image = imagecreatefromstring($res['avatar']);
		}
		
		header('Content-Type: image/png');
		ob_start(function ($s) {
			header("Content-Length: ".strlen($s));
			return $s;
		});
		imagepng($image);
		ob_end_flush();
		imagedestroy($image);
	}
}
