<?php
/*
i - inside(in box crop)
o - outside(in box add bars)
n - normal(resize image)
*/
// IMPORTANT: image endpoint — never echo PHP notices/warnings into the response
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);
require_once __DIR__ . '/../legacy_php56_compat.php';
include("../_config.php");

function resizeJPG($filename,$maxW,$maxH,$mode){

	list($width,$height)=getimagesize($filename);
	
	if($mode=="a"){
		if($maxW/$width+$maxH/$height>2)
			$mode="t";
		else
			$mode="o";
	}
	
	if($mode=="i"||$mode=="n")if($width/$height>$maxW/$maxH)$percent=$maxW/$width; else $percent=$maxH/$height;
	if($mode=="o")if($width/$height>$maxW/$maxH)$percent=$maxH/$height; else $percent=$maxW/$width;

	$new_width=$width*$percent;
	$new_height=$height*$percent;
	// Resample
	if($mode=="t"||$mode=="i"||$mode=="o")$image_p=imagecreatetruecolor($maxW,$maxH);
	if($mode=="n")$image_p=imagecreatetruecolor($new_width,$new_height);
	$image=imagecreatefromjpeg($filename);
	$white=imagecolorallocate($image_p,255,255,255);
	imagefill($image_p,0,0,$white);

	if($mode=="n")imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width,$new_height,$width,$height);
	if($mode=="i")imagecopyresampled($image_p, $image, -($new_width-$maxW)/2, -($new_height-$maxH)/2, 0, 0, $new_width, $new_height, $width, $height);
	if($mode=="o")imagecopyresampled($image_p, $image, 0, 0, (($new_width-$maxW)/2)/$percent, (($new_height-$maxH)/2)/$percent, $new_width, $new_height, $width, $height);

	if($mode=="t"){
		for($i=0;$i<=$maxW/$width;$i++)
			for($j=0;$j<=$maxH/$height;$j++)
				imagecopy($image_p,$image,$i*$width,$j*$height,0,0,$width,$width);
	}

	imagejpeg($image_p,substr($filename,0,strlen($filename)-4)."..".$maxW."x".$maxH."..".$mode.".jpg",98);
	imagejpeg($image_p,NULL,98);
	imagedestroy($image_pI);
	imagedestroy($imageI);
}

header("Content-type: image/jpeg");

$aux=split("upload/",$_SERVER['REQUEST_URI']);
$FN=$aux[1];

$aux=split("\.\.",$FN);

$FNorig=str_replace("%20"," ",$aux[0].".jpg");
$FN=str_replace("%20"," ",$FN);
if(file_exists($FN)){
	readfile($FN);
}else{
	if(str_replace($aux[1],"",$allowedIMGsizes)==$allowedIMGsizes){
		$im=imagecreate(300,20);
		$bg=imagecolorallocate($im, 255, 255, 255);
		$textcolor=imagecolorallocate($im, rand(0,33), rand(0,33), rand(0,33));
		imagestring($im,5,0,0,"IMGsize not allowed: ".$aux[1],$textcolor);
		imagejpeg($im,NULL,50);
	}else{
		$wh=split("x",$aux[1]);
		$width=$wh[0];
		$height=$wh[1];
		$mode=str_replace(".jpg","",$aux[2]);
		if(file_exists($FNorig))
			resizeJPG($FNorig,$width,$height,$mode);
	}
}
?>
