<?php

require 'inc/global.fnc.php';

header('Content-type: image/jpeg');
$file = isset($_GET['file']) ? $_GET['file'] : '';
$h = isset($_GET['h']) ? (int) $_GET['h'] : 100;
$w = isset($_GET['w']) ? (int) $_GET['w'] : 100;

if (!$file || !is_readable($file) || !$h || !$w) {
	error404();
}

$ext = strtolower(end(explode('.', $file)));
list($oW, $oH) = getimagesize($file);

switch ($ext) {
	case 'jpeg':
	case 'jpg':
		$oImg = @imagecreatefromjpeg($file);
		break;

	case 'gif':
		$oImg = @imagecreatefromgif($file);
		break;

	case 'png':
		$oImg = @imagecreatefrompng($file);
		break;

	default:
		error404();
}

if (!$oImg) {
	error404();
}

$img = imagecreatetruecolor($w, $h);

$wm = $oW / $w;
$hm = $oH / $h;
$h_height = $h / 2;
$w_height = $w / 2;

if ($oW > $oH ) {
	$adjustedW = $oW / $hm;
	imagecopyresampled($img, $oImg , -($adjustedW / 2 - $w_height), 0, 0, 0, $adjustedW, $h, $oW , $oH);
} elseif ($oW < $oH || $oW === $oH ) {
	$adjustedH = $oH / $wm;
	imagecopyresampled($img , $oImg , 0, -($adjustedH / 2 - $h_height), 0, 0, $w, $adjustedH, $oW , $oH);
} else {
	imagecopyresampled($img , $oImg , 0, 0, 0, 0, $w, $h, $oW , $oH);
}

imagejpeg($img);