<?php

//////////////////////////////////////////////////////////////////////////////
class Img
{
    private $image;
	private $fileExtension;
    private $thumbnailName;
	private $thumbnailDir;
	public $quality = 80;

	//////////////////////////////////////////////////////////////////////////
	static public function get($filepath, $params = array()){
        $thumbWidth  = $params['width'] = isset($params['width']) ? $params['width'] : 112;
        $thumbHeight = $params['height'] = isset($params['height']) ? $params['height'] : 112;
        
    //    $params['watermark'] = 'images/watermark.png';

	    if (empty($filepath))
	    {
	    	return $filepath;
	    }
		$filepath = $_SERVER['DOCUMENT_ROOT'].'/'.trim($filepath,'/');
		
	    if (!file_exists($filepath) || !is_file($filepath))
	    { 

		    if (!file_exists($filepath) || !is_file($filepath))
		    {
		        return self::getLink($filepath);
			}
	    }

		$fileinfo = pathinfo($filepath);

		$fileExtension = $fileinfo['extension'];
		$thumbnailDir = dirname($filepath)."/thumbs"; 

		if (!file_exists($thumbnailDir))	{	mkdir($thumbnailDir);	}

		$thumbnailDir .= ($thumbWidth) ? "/".$thumbWidth : "/".$thumbHeight;

		$thumbnailDir .= ($thumbHeight) ? "x".$thumbHeight : "x".$thumbWidth;

		if (!file_exists($thumbnailDir))	{	mkdir($thumbnailDir);	}

		$thumbnailName = $fileinfo['filename'].".".$fileExtension;
		$thumbnailPath = "$thumbnailDir/$thumbnailName";

		if (file_exists($thumbnailPath) && 
			(filemtime($filepath) == filemtime($thumbnailPath)))
		{
			 return self::getLink($thumbnailPath);
		}

		self::create($filepath, $thumbnailPath, $params);

		return self::getLink($thumbnailPath);
	}
	
	public static function getMimeType($file,$magicFile=null,$checkExtension=true)
	{
		if(function_exists('finfo_open'))
		{
			$options=defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
			$info=$magicFile===null ? finfo_open($options) : finfo_open($options,$magicFile);

			if($info && ($result=finfo_file($info,$file))!==false)
				return $result;
		}

		if(function_exists('mime_content_type') && ($result=mime_content_type($file))!==false)
			return $result;

		return $checkExtension ? self::getMimeTypeByExtension($file) : null;
	}
	
	public static function getMimeTypeByExtension($file,$magicFile=null)
	{
		if(($ext=pathinfo($file,PATHINFO_EXTENSION))!=='')
		{
			if($ext == 'jpeg' || $ext == 'JPEG') return 'image/jpeg';
			if($ext == 'jpg' || $ext == 'JPG') return 'image/jpg';
			if($ext == 'gif') return 'image/gif';
			if($ext == 'png') return 'image/png';
		}
		return null;
	}

	//////////////////////////////////////////////////////////////////////////
	private static function create($srcFilename, $dstFilename, $params)
	{
        $fillColor   = isset($params['fillColor']) ? $params['fillColor'] : 0xFFFFFF;

		$fileinfo = pathinfo($srcFilename);
		$fileExtension = $fileinfo['extension']; 
	

		switch (strtolower(self::getMimeType($srcFilename)))
		{
			case 'image/jpg':		$image = @imagecreatefromjpeg($srcFilename); $saveFn = 'imagejpeg'; $saveQuality = 80;	break;
			case 'image/jpeg':    	$image = @imagecreatefromjpeg($srcFilename); $saveFn = 'imagejpeg'; $saveQuality = 80;	break;
			case 'image/png':		$image = @imagecreatefrompng($srcFilename);  $saveFn = 'imagepng';  $saveQuality = 5;	break;
			case 'image/gif':		$image = @imagecreatefromgif($srcFilename);  $saveFn = 'imagepng';  $saveQuality = NULL;	break;
	
			default:	    return;
							//throw new CException("Unable to create thumbnail. Unsupported image format: $fileExtension");
		}

		if (!$image)
		{
			//throw new CException("Unable to create thumbnail. imagecreatefromXXX function failed");
		}

		$imgWidth	= imagesx($image);
	    $imgHeight	= imagesy($image);

        if (isset($params['crop']) && $params['crop'])
		{
			$imgScale    = $imgWidth/$imgHeight;
    	    $thumbScale  = $params['width']/$params['height'];

			if ($imgScale <= $thumbScale) 
			{
				$imgHeight = $imgWidth/$thumbScale;
			} 
			else 
			{
				$imgWidth = $imgHeight*$thumbScale;
			}
		}

        if (isset($params['min-width']) && ($params['min-width'] > $imgWidth))   $params['width'] =  $params['min-width'];
        if (isset($params['min-height']) && ($params['min-height'] > $imgHeight))   $params['height'] =  $params['min-height'];

        $thumbGeometry = self::getThumbnailGeometry($imgWidth, $imgHeight, $params['width'], $params['height']);

		$thumbImage = imagecreatetruecolor($thumbGeometry['width'] + $thumbGeometry['padding-left']*2,
                                         $thumbGeometry['height'] + $thumbGeometry['padding-top']*2);
		if ($thumbGeometry['padding-top'] || $thumbGeometry['padding-left'])
		{
			$fcolor = imagecolorallocate($thumbImage,   ($fillColor >> 16) & 0xFF,
												        ($fillColor >> 8) & 0xFF,
													    ($fillColor >> 0) & 0xFF);
			imagefill($thumbImage, 0,0, $fcolor);
		}

		if (!$thumbImage)
		{
			//throw new CException("imagecreatetruecolor function failed");
		}

		if (($fileExtension == "gif") || ($fileExtension == "png"))
		{
		    imagecolortransparent($thumbImage, imagecolorallocatealpha($thumbImage, 0, 0, 0, 127));
		    imagealphablending($thumbImage, false);
		    imagesavealpha($thumbImage, true);
		}

		if (!imagecopyresampled($thumbImage, $image, $thumbGeometry['padding-left'], $thumbGeometry['padding-top'], 0, 0,
                                $thumbGeometry['width'], $thumbGeometry['height'], $imgWidth, $imgHeight))
		{
			//throw new CException("Unable to create thumbnail. imagecopyresized function failed");
		}
		

		///////////////////////////////
	//	$params['watermark'] = '/themes/ecofermer/images/watermark/watermark.png';
		//$params['watermarkPosition'] = 'center center';
        self::applyWatermark($thumbImage, $thumbGeometry, $params);

		if (!$saveFn($thumbImage, $dstFilename, $saveQuality))
		{
			//throw new CException("Unable to create thumbnail. imagexxx function failed");
		}

		$srcTime = filemtime($srcFilename);
		touch($dstFilename, $srcTime);
	}

    //////////////////////////////////////////////////////////////////////////
    protected static function applyWatermark($img, $imgGeometry, $params)
    { 
        if (!isset($params['watermark']))
        {
            return false;
        }
        else if ($params['watermark'] === true)
        {
            //$watermarkFile =  Yii::getPathOfAlias('webroot')."/".Yii::app()->params['watermarkFile'];
        }
        else if (is_string($params['watermark']))
        {
            $watermarkFile =  $_SERVER['DOCUMENT_ROOT'].'/'.$params['watermark'];
        }
        else
        {
            return;
        }

        if (!file_exists($watermarkFile) || !($wtmkImg = imagecreatefrompng($watermarkFile)))
        {
            return;
        }

        $wtmkWidth	= imagesx($wtmkImg);
        $wtmkHeight	= imagesy($wtmkImg);

        $scale = min( $imgGeometry['width']/$wtmkWidth,$imgGeometry['height']/$wtmkHeight)*0.5;

        $scaledThumbWidth  = $scale < 1.0 ? $scale * $wtmkWidth : $wtmkWidth;
        $scaledThumbHeight = $scale < 1.0 ? $scale * $wtmkHeight : $wtmkHeight;

        $centerX = ($imgGeometry['width'] - $scaledThumbWidth)/2;
        $centerY = ($imgGeometry['height'] - $scaledThumbHeight)/2;
        
        imagealphablending($img, true);
		imagealphablending($wtmkImg, true);

        if (!imagecopyresampled($img, $wtmkImg,
                                $centerX + $imgGeometry['padding-left'], $centerY + $imgGeometry['padding-top'], 0, 0,
                                $scaledThumbWidth, $scaledThumbHeight, $wtmkWidth, $wtmkHeight))
        {
            //throw new CException("Unable to create thumbnail. imagecopyresized function failed");
        }
    }

    //////////////////////////////////////////////////////////////////////////
    protected static function getThumbnailGeometry($imgWidth, $imgHeight, $thumbWidth, $thumbHeight)
    {
        $retval = array('width'=>0, 'height'=>0, 'padding-top'=>0, 'padding-left'=>0);

        if (!$thumbWidth && !$thumbHeight)
        {
            $retval['width']  = $imgWidth;
            $retval['height'] = $imgHeight;
        }
        else if ($thumbWidth && !$thumbHeight)
        {
            $retval['width'] = $thumbWidth;
            $retval['height'] = floor($imgHeight*($thumbWidth / $imgWidth));
        }
        else if (!$thumbWidth && $thumbHeight)
        {
            $retval['height']= $thumbHeight;
            $retval['width'] = floor($imgWidth*($thumbHeight / $imgHeight));
        }
        else
        {
            $scale = min( $thumbWidth/$imgWidth, $thumbHeight/$imgHeight );

            $retval['width']  = $scale < 1.0 ? $scale * $imgWidth : $imgWidth;
            $retval['height'] = $scale < 1.0 ? $scale * $imgHeight : $imgHeight;


            $retval['padding-left'] = ($thumbWidth - $retval['width'])/2;
            $retval['padding-top']  = ($thumbHeight - $retval['height'])/2;
        }
        return $retval;
    }

	//////////////////////////////////////////////////////////////////////////
	private static function getLink($path)
	{
	    if (substr($path, 0, strlen($_SERVER['DOCUMENT_ROOT'].'/')) == $_SERVER['DOCUMENT_ROOT'].'/')
	    {
	    	$path =  substr($path, strlen($_SERVER['DOCUMENT_ROOT'].'/'));
	    }
		$path = '/'.ltrim($path,'/');
		return $path;
	}
}
