<?
require_once '../autoload/class.Image.php';
error_reporting( 0 );

$img      = $_GET['img'];

$width    = $_GET['w'];
if ( !$width )
  $width = 500;

$height   = $_GET['h'];
if ( !$height )
  $height = 500;

$crop_w   = $_GET['c_w'];
$crop_h   = $_GET['c_h'];

$img_md5    = md5( $img . $height . $width . $crop_h . $crop_w );
$cache_dir  = 'temp/' . $img_md5[0] . '/' . $img_md5[1] . '/' . $img_md5[2] . '/';

if ( !file_exists( '../' . $cache_dir . $img_md5 ) )
{
  $img = new ImageManipulator( '../' . $img );
  $img -> resample( $width, $height );

  if ( $crop_w && $crop_h )
  {       
    $centreX = round( $img -> getWidth() / 2 );
    $centreY = round( $img -> getHeight() / 2 );

    $x1 = $centreX - $crop_w / 2;
    $y1 = $centreY - $crop_h / 2;

    $x2 = $centreX + $crop_w / 2;
    $y2 = $centreY + $crop_h / 2;

    $img -> crop( $x1, $y1, $x2, $y2 );
  }

  $img -> save( '../' . $cache_dir . $img_md5 );
  chmod( '../' . $cache_dir . $img_md5, 0755 );
}

header( 'Cache-Control: public' );
header( "Content-type: image/jpeg" );
readfile( '../' . $cache_dir . $img_md5 );