<?php

$path = $_SERVER['DOCUMENT_ROOT']."/files/"; // path immagini
//$uri = $_SERVER['REQUEST_URI'];

$username = $_GET['u'];
$format = $_GET['f'];
$application = $_GET['a'];

$fullPath = profile_name_user_image($path, $username, $format, $application);

//echo $fullPath;

if (is_readable ($fullPath)){

    $fd = fopen ($fullPath, "r");

    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
	case "jpg":
	header("Content-type: image/jpeg");
	break;
	default;
	header("Content-type: application/octet-stream");
	header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    }
    header("Content-length: $fsize");
    header("Cache-control: private");
    while(!feof($fd)) {
	$buffer = fread($fd, 2048);
	echo $buffer;
    }

    fclose ($fd);

}

 
/*
 * ogni percorso di immagini ha una cartella che raggruppa gli utenti,
 * questa cartella è data dalle prime tre lettere del nickname
 */
function userImagePath($name){	
	return strtolower(substr("a_". $name , 0 , (strlen($name)>=3) ? 5 : strlen($name)));
}

/*
 * fornisce il nome immagine dell'utente (avatar)
 * dalle componenti
 */
function profile_name_user_image($percorso_immagini, $account_name, $alias, $applicazione)
{
	$account_name_2=$account_name;
	
	if(!$alias) $alias = "44x44";

	/*
	 * il punto all'inizio dà problemi in linux
	 */
	if (substr($account_name_2,0,1)==".")
	{
	   $account_name_2="avatar".$account_name;
	}

	$filepath =  $percorso_immagini.userImagePath($account_name)."/".$account_name_2."_".$alias.".jpg";	

	if (!is_readable ($filepath))
	{
	  $filepath = default_image($percorso_immagini, $alias, $applicazione);
	}
    return $filepath;
}

function default_image($percorso_immagini, $alias="44x44", $applicazione)
{
  $defaultPath = $percorso_immagini."avatar_".$alias.".jpg";
  
  if($applicazione && is_readable ($percorso_immagini.$applicazione."/avatar_".$alias.".jpg")){
     $defaultPath = $percorso_immagini.$applicazione."/avatar_".$alias.".jpg";
  }
  return $defaultPath;
}
?>

