<?php
/**
 * @package	HikaShop for Joomla!
 * @version	2.0.0
 * @author	hikashop.com
 * @copyright	(C) 2010-2012 HIKARI SOFTWARE. All rights reserved.
 * @license	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
defined('_JEXEC') or die('Restricted access');
?><?php
class hikashopImageHelper{

	function hikashopImageHelper(){
		$config =& hikashop_config();
		$uploadFolder = ltrim(JPath::clean(html_entity_decode($config->get('uploadfolder'))),DS);
		$uploadFolder = rtrim($uploadFolder,DS).DS;
		$this->uploadFolder_url = str_replace(DS,'/',$uploadFolder);
		$this->uploadFolder = JPATH_ROOT.DS.$uploadFolder;
		$app = JFactory::getApplication();
		if($app->isAdmin()){
			$this->uploadFolder_url = '../'.$this->uploadFolder_url;
		}else{
			$this->uploadFolder_url = rtrim(JURI::base(true),'/').'/'.$this->uploadFolder_url;
		}
		$this->thumbnail = $config->get('thumbnail',1);
		$this->thumbnail_x=$config->get('thumbnail_x',100);
		$this->thumbnail_y=$config->get('thumbnail_y',100);
		$this->main_thumbnail_x=$this->thumbnail_x;
		$this->main_thumbnail_y=$this->thumbnail_y;
		$this->main_uploadFolder_url = $this->uploadFolder_url;
		$this->main_uploadFolder = $this->uploadFolder;

		static $done = false;
		static $override = false;
		if(!$done){
			$done = true;
			$chromePath = JPATH_THEMES.DS.$app->getTemplate().DS.'html'.DS.'hikashop_image.php';
			if (file_exists($chromePath)){
				require_once ($chromePath);
				$override = true;
			}
		}
		$this->override = $override;
	}

	function display($path,$addpopup=true,$alt="",$options='',$optionslink='', $width=0, $height=0, $ap=false){
		$html = '';

		if(!$this->_checkImage($this->uploadFolder.$path)){
			$config =& hikashop_config();
			$path = $config->get('default_image');
			if($path == 'barcode.png'){
				$this->uploadFolder_url=HIKASHOP_IMAGES;
				$this->uploadFolder=HIKASHOP_MEDIA.'images'.DS;
			}

			if(!$this->_checkImage($this->uploadFolder.$path)){
				$this->uploadFolder_url = $this->main_uploadFolder_url;
				$this->uploadFolder = $this->main_uploadFolder;
				return $html;
			}
		}

		list($this->width, $this->height) = getimagesize($this->uploadFolder.$path);
		if($width!=0 && $height!=0){
			$module=array();
			$module[0]=$height;
			$module[1]=$width;
			$this->main_thumbnail_x=$width;
			$this->main_thumbnail_y=$height;

			$html = $this->displayThumbnail($path,$alt,is_string($addpopup),$options, $module, $ap);
		}else{
			$html = $this->displayThumbnail($path,$alt,is_string($addpopup),$options, $ap);
		}
		if($addpopup){
			$config =& hikashop_config();
			$popup_x=$config->get('max_x_popup',760);
			$popup_y=$config->get('max_y_popup',480);
			$this->width+=20;
			$this->height+=30;
			if($this->width>$popup_x) $this->width = $popup_x;
			if($this->height>$popup_y) $this->height = $popup_y;
			if(is_string($addpopup)){
				static $first=true;
				if($first){
					if($this->override && function_exists('hikashop_image_toggle_js')){
						$js = hikashop_image_toggle_js($this);
					}else{
					$js = '
					function hikashopChangeImage(id,url,x,y,obj){
						image=document.getElementById(id);
						if(image){
							image.src=url;
							if(x) image.width=x;
							if(y) image.height=y;
						}
						image_link = document.getElementById(id+\'_link\');
						if(image_link){
							image_link.href=obj.href;
							image_link.rel=obj.rel;
						}


						var myEls = getElementsByClass(\'hikashop_child_image\');
						for ( i=0;i<myEls.length;i++ ) {
							if (!myEls[i]) {
							} else {
								myEls[i].style.border=\'1px solid #bbb\';
							}
						}

						obj.childNodes[0].style.border=\'1px solid\';
						mydiv=document.getElementById(\'cloud-zoom-big\');

						url = url.replace("thumbnail_350x250/", "");
						if (mydiv) {
							mydiv.style.background=\'url(\'+obj.childNodes[0].src.replace("thumbnail_350x250/", "")+\')\';
						}
						
						myref=document.getElementById(\'acloud-zoom\');
						myref.href=url;

						jQuery(".cloud-zoom, .cloud-zoom-gallery").CloudZoom();
						jQuery(".cloud-zoom-lens, .mousetrap, .cloud-zoom-big").remove();
						return false;

					}

					function getElementsByClass(searchClass,node,tag) {
						var classElements = new Array();
						if ( node == null )
							node = document;
						if ( tag == null )
							tag = \'*\';
						var els = node.getElementsByTagName(tag);
						var elsLen = els.length;
						var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
						for (i = 0, j = 0; i < elsLen; i++) {
							if ( pattern.test(els[i].className) ) {
								classElements[j] = els[i];
								j++;
							}
						}
						return classElements;
					}

					window.addEvent(\'domready\', function() {
						image_link = document.getElementById(\'hikashop_image_small_link_first\');
						if(image_link){
							image_link.childNodes[0].style.border=\'1px solid\';
						}
					});

					';
					}
					$doc = JFactory::getDocument();
					$doc->addScriptDeclaration("\n<!--\n".$js."\n//-->\n");
					$first=false;
					$optionslink.=' id="hikashop_image_small_link_first" ';
					JHTML::_('behavior.modal');
				}
				if(!empty($this->no_size_override)){
					$this->thumbnail_x = '';
					$this->thumbnail_y = '';
					$this->uploadFolder_url_thumb = $this->uploadFolder_url.$path;
				}
				if($this->override && function_exists('hikashop_small_image_link_render')){
					$html = hikashop_small_image_link_render($this,$path,$addpopup,$optionslink,$html,$alt);
				}else{
					$html = '<a title="'.$alt.'" class="hikashop_image_small_link" rel="{handler: \'image\'}" href="'.$this->uploadFolder_url.$path.'" onclick="SqueezeBox.fromElement(this,{parse: \'rel\'});return false;" target="_blank" onmouseover="return hikashopChangeImage(\''.$addpopup.'\',\''.$this->uploadFolder_url_thumb.'\',\''.$this->thumbnail_x.'\',\''.$this->thumbnail_y.'\',this);" '.$optionslink.'>'.$html.'</a>';
				}
			}else{
				JHTML::_('behavior.modal');

				if($this->override && function_exists('hikashop_image_link_render')){
					$html = hikashop_image_link_render($this,$path,$addpopup,$optionslink,$html,$alt);
				}else{
					$html = '<a title="'.$alt.'" rel="{handler: \'image\'}" target="_blank" href="'.$this->uploadFolder_url.$path.'" onclick="SqueezeBox.fromElement(this,{parse: \'rel\'});return false;" '.$optionslink.'>'.$html.'</a>';
				}
			}
		}
		$this->uploadFolder_url = $this->main_uploadFolder_url;
		$this->uploadFolder = $this->main_uploadFolder;
		return $html;
	}

	function _checkImage($path){
		if(!empty($path)){
			jimport('joomla.filesystem.file');
			if(JFile::exists($path)){
				return true;
			}
		}
		return false;
	}

	function checkSize(&$width,&$height,&$row){
		$exists=false;
		if(!empty($row->file_path)){
			jimport('joomla.filesystem.file');
			if(JFile::exists(HIKASHOP_MEDIA.'upload'.DS.$row->file_path)){
				$exists=true;
			}else{
				$exists=false;
			}
		}

		if(!$exists){
			$config =& hikashop_config();
			$path = $config->get('default_image');
			if($path == 'barcode.png'){
				$file_path=HIKASHOP_MEDIA.'images'.DS.'barcode.png';
			}
			if(!empty($path)){
				jimport('joomla.filesystem.file');
				if(JFile::exists($this->main_uploadFolder.$path)){
					$exists=true;
				}
			}else{
				$exists=false;
			}
			if($exists){
				$file_path=$this->main_uploadFolder.$path;
			}
		}else{
			$file_path=$this->main_uploadFolder.$row->file_path;
		}
		if(!empty($file_path)){
			$theImage= new stdClass();
			list($theImage->width, $theImage->height) = getimagesize($file_path);
			if(empty($width)){
				list($width, $height) = $this->scaleImage($theImage->width, $theImage->height, 0, $height);
			}
			if(empty($height)){
				list($width, $height) = $this->scaleImage($theImage->width, $theImage->height, $width, 0);
			}
		}

	}


	function getPath($file_path,$url=true){
		if($url){
			return $this->uploadFolder_url.$file_path;
		}
		return $this->uploadFolder.$file_path;
	}

	function displayThumbnail($path,$alt='',$reduceSize=false,$options='',$module=false,$ap=false){
		if((empty($this->main_thumbnail_x) && !empty($this->main_thumbnail_y)) || (empty($this->main_thumbnail_y) && !empty($this->main_thumbnail_x))){
			$module[0]=$this->main_thumbnail_y;
			$module[1]=$this->main_thumbnail_x;
		}
		$new = $this->scaleImage($this->width, $this->height,$this->main_thumbnail_x,$this->main_thumbnail_y);

		if($new!==false){
			$this->thumbnail_x=$new[0];
			$this->thumbnail_y=$new[1];
		}else{
			$this->thumbnail_x = $this->width;
			$this->thumbnail_y = $this->height;
		}

		if($module){
			if(empty($this->main_thumbnail_y)){$this->main_thumbnail_y=0;}
			if(empty($this->main_thumbnail_x)){$this->main_thumbnail_x=0;}
			$folder='thumbnail_'.$this->main_thumbnail_y.'x'.$this->main_thumbnail_x;
		}else{
			$folder='thumbnail_'.$this->thumbnail_y.'x'.$this->thumbnail_x;
		}
		if ($ap) {
			$folder = '';
		}

		if(!$reduceSize && !$module ){
			$options.=' height="'.$this->thumbnail_y.'" width="'.$this->thumbnail_x.'" ';
		}
		if($this->thumbnail){
			jimport('joomla.filesystem.file');
			$ok = true;
			if(!JFile::exists($this->uploadFolder.$folder.DS.$path)){
				if($module){
					$ok = $this->generateThumbnail($path, $module);
				}
				else{
					$ok = $this->generateThumbnail($path);
				}
			}

			if($ok){
				if(is_array($ok)){
					$folder='thumbnail_'.$ok[0].'x'.$ok[1];
				}
				if ($ap) {
					$folder = '';
				}
				$this->uploadFolder_url_thumb=$this->uploadFolder_url.$folder.'/'.$path;
				return '<img src="'.$this->uploadFolder_url_thumb.'" alt="'.$alt.'" '.$options.' />';
			}
		}
		$this->uploadFolder_url_thumb=$this->uploadFolder_url.$path;

		return '<img src="'.$this->uploadFolder_url_thumb.'" alt="'.$alt.'" '.$options.' />';
	}

	function generateThumbnail($file_path, $module=false){
		$ok = true;
		if($this->thumbnail){
			$ok = false;
			$gd_ok = false;
			if (function_exists('gd_info')) {
				$gd = gd_info();
				if (isset ($gd["GD Version"])) {
					$gd_ok = true;
					list($this->width, $this->height) = getimagesize($this->uploadFolder.$file_path);
					$config =& hikashop_config();
					if($module){
						$thumbnail_x=$module[1];
						$thumbnail_y=$module[0];
					}
					else{
						$thumbnail_x=$config->get('thumbnail_x',100);
						$thumbnail_y=$config->get('thumbnail_y',100);
					}
					if(!$thumbnail_x && !$thumbnail_y){
						return true;
					};
					$new = $this->scaleImage($this->width, $this->height,$thumbnail_x,$thumbnail_y);
					if($new!==false){
						if(empty($thumbnail_y)){$thumbnail_y=0;}
						if(empty($thumbnail_x)){$thumbnail_x=0;}
						$ok = $this->_resizeImage($file_path, $new[0], $new[1], $this->uploadFolder.'thumbnail_'.$thumbnail_y.'x'.$thumbnail_x.DS);
						if($ok & !$module){
							$ok = array($new[1],$new[0]);
						}
					}
				}
			}
			if(!$gd_ok){
				$app =& JFactory::getApplication();
				if($app->isAdmin()){
					$app->enqueueMessage('The PHP GD extension could not be found. Thus, it is impossible to generate thumbnails in PHP from your images. If you want HikaShop to generate thumbnails you need to install GD or ask your hosting company to do so. Otherwise, you can deactivate thumbnails creation in the configuration of HikaShop and this message won\'t be displayed');
				}
			}
		}
		return $ok;
	}

	function resizeImage($file_path,$type='image'){
		$config =& hikashop_config();
		$image_x=$config->get('image_x',0);
		$image_y=$config->get('image_y',0);
		$watermark_name = $config->get('watermark','');
		$ok = true;
		if(($image_x || $image_y) || !empty($watermark_name)){
			$ok = false;
			$gd_ok = false;
			if (function_exists('gd_info')) {
				$gd = gd_info();

				if (isset ($gd["GD Version"])) {
					$gd_ok = true;
					$new = getimagesize($this->uploadFolder.$file_path);
					$this->width=$new[0];
					$this->height=$new[1];

					if(!$image_x && !$image_y && empty($watermark_name)){
						return true;
					}
					if($image_x || $image_y){
						$new = $this->scaleImage($this->width, $this->height,$image_x,$image_y);
						if($new===false){
							$new = array($this->width,$this->height);
						}
					}

					$ok = $this->_resizeImage($file_path,$new[0],$new[1],$this->uploadFolder,$type);
				}
			}
			if(!$gd_ok){
				$app =& JFactory::getApplication();
				if($app->isAdmin()){
					$app->enqueueMessage('The PHP GD extension could not be found. Thus, it is impossible to process your images in PHP. If you want HikaShop to process your images, you need to install GD or ask your hosting company to do so. Otherwise, you can deactivate thumbnails creation, remove your watermark image if any, and clear the image max width and height in the configuration of HikaShop and this message won\'t be displayed');
				}
			}
		}
		return $ok;
	}


	function _resizeImage($file_path,$newWidth,$newHeight,$dstFolder='',$type='thumbnail'){
		$image = $this->uploadFolder.$file_path;

		if(empty($dstFolder)){
			$dstFolder = $this->uploadFolder.'thumbnail_'.$this->thumbnail_y.'x'.$this->thumbnail_x.DS;
		}
		$watermark_path = '';

		if($type=='image'){
			if(hikashop_level(2)){
				$config =& hikashop_config();
				$watermark_name = $config->get('watermark','');

				if(!empty($watermark_name)){
					$watermark_path = $this->main_uploadFolder.$watermark_name;

					if(!$this->_checkImage($watermark_path)){
						$watermark_path = '';
					}else{
						$wm_extension = strtolower(substr($watermark_path,strrpos($watermark_path,'.')+1));

						$watermark = $this->_getImage($watermark_path,$wm_extension);
						if($watermark){
							if(in_array($wm_extension,array('gif','png'))){
								imagealphablending($watermark, false);
								imagesavealpha($watermark,true);
							}
						}else{
							$watermark_path = '';
						}
					}
				}
			}
		}

		$extension = strtolower(substr($file_path,strrpos($file_path,'.')+1));

		$img = $this->_getImage($image,$extension);
		if(!$img) return false;

		if(in_array($extension,array('gif','png'))){
			imagealphablending($img, false);
			imagesavealpha($img,true);
		}
		if($newWidth!=$this->width || $newHeight!=$this->height){

			$thumb = ImageCreateTrueColor($newWidth, $newHeight);

			if(in_array($extension,array('gif','png'))){
				$trnprt_indx = imagecolortransparent($img);

				if ($trnprt_indx >= 0) {
					$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
					$trnprt_indx = imagecolorallocate($thumb, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
					imagefill($thumb, 0, 0, $trnprt_indx);
					imagecolortransparent($thumb, $trnprt_indx);
				}elseif($extension=='png'){
					imagealphablending($thumb, false);
					$color = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
					imagefill($thumb, 0, 0, $color);
					imagesavealpha($thumb,true);
				}
			}
			if(function_exists("imageAntiAlias")) {
				imageAntiAlias($thumb,true);
			}
			if(function_exists("imagecopyresampled")){
				ImageCopyResampled($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight,$this->width, $this->height);
			}else{
				ImageCopyResized($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight,$this->width, $this->height);
			}
		}else{
			$thumb =& $img;
		}

		if(!empty($watermark_path)){
			list($wm_width,$wm_height) = getimagesize($watermark_path);
			$padding = 3;
			$dest_x = $newWidth - $wm_width - $padding;
			$dest_y = $newHeight - $wm_height - $padding;
			$trnprt_color=null;
			if(in_array($extension,array('gif','png'))){
				$trnprt_indx = imagecolortransparent($img);
				if ($trnprt_indx >= 0) {
					$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
				}
			}
			$this->imagecopymerge_alpha($thumb, $watermark, $dest_x, $dest_y, 0, 0, $wm_width, $wm_height, (int)$config->get('opacity',0),$trnprt_color);
			imagedestroy($watermark);
		}

		$dest = $dstFolder.$file_path;
		ob_start();
		switch($extension){
			case 'gif':
				$status = imagegif($thumb);
				break;
			case 'jpg':
			case 'jpeg':
				$status = imagejpeg($thumb,null,100);
				break;
			case 'png':
				$status = imagepng($thumb,null,0);
				break;
		}

		$imageContent = ob_get_clean();

		$status = $status && JFile::write($dest,$imageContent);
		imagedestroy($img);
		@imagedestroy($thumb);
		return $status;
	}

	function _getImage($image,$extension){
		switch($extension){
			case 'gif':
				return ImageCreateFromGIF($image);
				break;
			case 'jpg':
			case 'jpeg':
				return ImageCreateFromJPEG($image);
				break;
			case 'png':
				return ImageCreateFromPNG($image);
				break;
		}
	}


	function scaleImage($x,$y,$cx,$cy) {
		if(empty($cx)){
			$cx = 9999;
		}
		if(empty($cy)){
			$cy = 9999;
		}
			if ($x>=$cx || $y>=$cy) {
					if ($x>0) $rx=$cx/$x;
					if ($y>0) $ry=$cy/$y;
					if ($rx>$ry) {
							$r=$ry;
					} else {
							$r=$rx;
					}
					$x=intval($x*$r);
					$y=intval($y*$r);
					return array($x,$y);
			}
			return false;
	}








	function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, $trans = NULL)
	{
		$dst_w = imagesx($dst_im);
		$dst_h = imagesy($dst_im);

		$src_x = max($src_x, 0);
		$src_y = max($src_y, 0);
		$dst_x = max($dst_x, 0);
		$dst_y = max($dst_y, 0);
		if ($dst_x + $src_w > $dst_w)
			$src_w = $dst_w - $dst_x;
		if ($dst_y + $src_h > $dst_h)
			$src_h = $dst_h - $dst_y;

		for($x_offset = 0; $x_offset < $src_w; $x_offset++)
			for($y_offset = 0; $y_offset < $src_h; $y_offset++)
			{
				$srccolor = imagecolorsforindex($src_im, imagecolorat($src_im, $src_x + $x_offset, $src_y + $y_offset));
				$dstcolor = imagecolorsforindex($dst_im, imagecolorat($dst_im, $dst_x + $x_offset, $dst_y + $y_offset));

				if (is_null($trans) || ($srccolor !== $trans))
				{
					$src_a = $srccolor['alpha'] * $pct / 100;
					$src_a = 127 - $src_a;
					$dst_a = 127 - $dstcolor['alpha'];
					$dst_r = ($srccolor['red'] * $src_a + $dstcolor['red'] * $dst_a * (127 - $src_a) / 127) / 127;
					$dst_g = ($srccolor['green'] * $src_a + $dstcolor['green'] * $dst_a * (127 - $src_a) / 127) / 127;
					$dst_b = ($srccolor['blue'] * $src_a + $dstcolor['blue'] * $dst_a * (127 - $src_a) / 127) / 127;
					$dst_a = 127 - ($src_a + $dst_a * (127 - $src_a) / 127);
					$color = imagecolorallocatealpha($dst_im, $dst_r, $dst_g, $dst_b, $dst_a);
					if (!imagesetpixel($dst_im, $dst_x + $x_offset, $dst_y + $y_offset, $color))
						return false;
					imagecolordeallocate($dst_im, $color);
				}
			}
		return true;
	}

}