<?php
#CMS - CMS Made Simple
#(c)2004 by Ted Kulp (wishy@users.sf.net)
#This project's homepage is: http://cmsmadesimple.sf.net
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
/*
* PHP Image Resize Class
* USAGE
* —-
* To use this class simply call it with the following details:
*
*       Path to original image,
*       Path to save new image,
*       Resize type,
*       Resize Data
*     

* The resize type can be one of four:
*       W   =   Width
*       H   =   Height
*       P   =   Percentage
*       C   =   Custom 

*

* All of these take integers except Custom that takes an array of two integers - for width and height.
*       $objResize = new SuperSizer('myImage.png', 'myThumb.png', 'W', '400');
*       $objResize = new SuperSizer('myImage.jpg', 'myThumb.jpg', 'H', '150');
*       $objResize = new SuperSizer('myImage.gif', 'myThumb.gif', 'P', '50');
*       $objResize = new SuperSizer('myImage.png', 'myThumb.png', 'C', array('400', '300'));
*
* When resizing by width, height and percentage, the image will keep its original ratio. Custom will simply resizes the image to whatever values you want - without keeping the original ratio.
*
* The class can handle jpg, png and gif images.
*
* The class will always save the image that it resizes, however you can also have it display the image: 
*       $objResize->showImage($resize->im2);
*
* The class holds the original image in the variable 'im' and the new image in 'im2'. Therefore the code above will show the newly created image.
*
* You can get information about the image by doing the following:
*       print_r($objResize->findResourceDetails($objResize->resOriginalImage));
*       print_r($objResize->findResourceDetails($objResize->resResizedImage)); 
*
* This will be useful if you wish to retrieve any details about the images.
*  
* By default the class will stop you from enlarging your images (or else they will look grainy) and if you want to do this you must turn off the protection mode by passing a 5th parameter  
*  
*      $objResize = new SuperSizer('myImage.gif', 'myEnlargedImage.gif', 'P', '200', false);  
*
*/


class SuperSizer {
 var $strOriginalImagePath;
 var $strResizedImagePath;
 var $arrOriginalDetails;
 var $arrResizedDetails;
 var $resOriginalImage; 
 var $resResizedImage;
 var $boolProtect = true; 
 
 
 /*  
 *  
 *   @Method:      __constructor  
 *   @Parameters:   5
 *   @Param-1:      strPath - String - The path to the image
 *   @Param-2:      strSavePath - String - The path to save the new image to 

 *   @Param-3:      strType - String - The type of resize you want to perform
 *   @Param-4:      value - Number/Array - The resize dimensions  
 *   @Param-5:      boolProect - Boolen - Protects the image so that it doesnt resize an image if its already smaller  
 *   @Description:   Calls the JLB_Pagination method so its php 4 compatible  
 *  
 */
 function __constructor($strPath, $strSavePath, $strType = 'W', $value = '150', $Quality = '85', $boolProtect = true){
    $this->SuperSizer($strPath, $strSavePath, $strType, $value); 
 }
 
 /*  
 *  
 *   @Method:      SuperSizer  
 *   @Parameters:   5
 *   @Param-1:      strPath - String - The path to the image
 *   @Param-2:      strSavePath - String - The path to save the new image to
 *   @Param-3:      strType - String - The type of resize you want to perform 

 *   @Param-4:      value - Number/Array - The resize dimensions  
 *   @Param-5:      boolProect - Boolen - Protects the image so that it doesnt resize an image if its already smaller  
 *   @Description:   Calls the JLB_Pagination method so its php 4 compatible  
 *  
 */
 function SuperSizer($strPath, $strSavePath, $strType = 'W', $value = '150', $Quality = '85', $boolProtect = true){
    //save the image/path details
    $this->strOriginalImagePath = str_replace(" ", "%20", $strPath);
    $this->strResizedImagePath = $strSavePath; 

    $this->boolProtect = $boolProtect;  
    
    //get the image dimensions
    $this->arrOriginalDetails = getimagesize($this->strOriginalImagePath);
    $this->arrResizedDetails = $this->arrOriginalDetails;
    
    //create an image resouce to work with
    $this->resOriginalImage = $this->createImage($this->strOriginalImagePath);
    //select the image resize type
    switch(strtoupper($strType)){
       case 'P':
          $this->resizeToPercent($value);
          break;
       case 'H':
          $this->resizeToHeight($value);
          break;
       case 'C':
          $this->resizeToCustom($value);
          break;
       case 'W':
       default:
          $this->resizeToWidth($value); 
          break;
    }  
 }

 /*  
 *  
 *   @Method:      findResourceDetails  
 *   @Parameters:   1  
 *   @Param-1:      resImage - Resource - The image resource you want details on  
 *   @Description:   Returns an array of details about the resource identifier that you pass it  
 *  
 */ 

 function findResourceDetails($resImage){
    //check to see what image is being requested
    if($resImage==$this->resResizedImage){                              
       //return new image details
       return $this->arrResizedDetails;
    }else{
       //return original image details
       return $this->arrOriginalDetails;
    }
 }

 /*  
 *  
 *   @Method:      updateNewDetails     
 *   @Parameters:   0  
 *   @Description:   Updates the width and height values of the resized details array  
 *  
 */ 

 function updateNewDetails(){
    $this->arrResizedDetails[0] = imagesx($this->resResizedImage);
    $this->arrResizedDetails[1] = imagesy($this->resResizedImage);
 }
    
 /*  
 *  
 *   @Method:      createImage  
 *   @Parameters:   1  
 *   @Param-1:      strImagePath - String - The path to the image  
 *   @Description:   Created an image resource of the image path passed to it  
 *  
 */ 

 function createImage($strImagePath){
    //get the image details
    $arrDetails = $this->findResourceDetails($strImagePath);
      
    //choose the correct function for the image type  
    switch($arrDetails['mime']){
       case 'image/jpeg':
          return imagecreatefromjpeg($strImagePath);
          break;
       case 'image/png':
          return imagecreatefrompng($strImagePath);
          break;
       case 'image/gif':
          return imagecreatefromgif($strImagePath);
          break;
    }
 } 
 
 /*  
 *  
 *   @Method:      saveImage  
 *   @Parameters:   1  
 *   @Param-1:      numQuality - Number - The quality to save the image at  
 *   @Description:   Saves the resize image  
 *  
 */ 

 function saveImage($numQuality = 85){
    switch($this->arrResizedDetails['mime']){
       case 'image/jpeg':
          imagejpeg($this->resResizedImage, $this->strResizedImagePath, $numQuality);
          break;
       case 'image/png':
          // imagepng = [0-9] (not [0-100])           
          imagepng($this->resResizedImage, $this->strResizedImagePath, 7);
          break;
       case 'image/gif':
          imagegif($this->resResizedImage, $this->strResizedImagePath); 
          break;
    }
 }
 
 /*  
 *  
 *   @Method:      showImage  
 *   @Parameters:   1  
 *   @Param-1:      resImage - Resource - The resource of the image you want to display  
 *   @Description:   Displays the image resouce on the screen  
 *  
 */ 

 function showImage($resImage){
    //get the image details
    $arrDetails = $this->findResourceDetails($resImage);
      
    //set the correct header for the image we are displaying  
    header("Content-type: ".$arrDetails['mime']);
      
    switch($arrDetails['mime']){
       case 'image/jpeg':
          return imagejpeg($resImage);
          break;
       case 'image/png':
          return imagepng($resImage);
          break;
       case 'image/gif':
          return imagegif($resImage); 
          break;
    }
 }
 
 /*  
 *  
 *   @Method:      destroyImage  
 *   @Parameters:   1  
 *   @Param-1:      resImage - Resource - The image resource you want to destroy  
 *   @Description:   Destroys the image resource and so cleans things up  
 *  
 */ 

 function destroyImage($resImage){
    imagedestroy($resImage);
 }
 
 /*  
 *  
 *   @Method:      _resize  
 *   @Parameters:   2  
 *   @Param-1:      numWidth - Number - The width of the image in pixels  
 *   @Param-2:      numHeight - Number - The height of the image in pixes  
 *   @Description:   Resizes the image by creatin a new canvas and copying the image over onto it. DONT CALL THIS METHOD DIRECTLY - USE THE METHODS BELOW  
 *  
 */ 

 function _resize($numWidth, $numHeight){
    //check for image protection  
    if($this->_imageProtect($numWidth, $numHeight)){     
       if($this->arrOriginalDetails['mime']=='image/jpeg'){
          //JPG image
          $this->resResizedImage = imagecreatetruecolor($numWidth, $numHeight);
       }else if($this->arrOriginalDetails['mime']=='image/gif'){
          //GIF image
			$this->resResizedImage = imagecreatetruecolor($numWidth, $numHeight);
			imagealphablending($this->resResizedImage, false);
			imagesavealpha($this->resResizedImage,true);
			$transparent = imagecolorallocatealpha($this->resResizedImage, 255, 255, 255, 127);
			imagefilledrectangle($this->resResizedImage, 0, 0, $numWidth, $numHeight, $transparent);
			imagecolortransparent($this->resResizedImage, $transparent);
       }else if($this->arrOriginalDetails['mime']=='image/png'){  
          //PNG image  
          $this->resResizedImage = imagecreatetruecolor($numWidth, $numHeight);  
          imagecolortransparent($this->resResizedImage, imagecolorallocate($this->resResizedImage, 0, 0, 0));   
          // Turn off transparency blending (temporarily)
			imagealphablending($this->resResizedImage, false);
	 
			// Create a new transparent color for image
			$color = imagecolorallocatealpha($this->resResizedImage, 0, 0, 0, 127);
	 
			// Completely fill the background of the new image with allocated color.
			imagefill($this->resResizedImage, 0, 0, $color);
	 
			// Restore transparency blending
			imagesavealpha($this->resResizedImage, true);
 
       }  
   
       //update the image size details  
       $this->updateNewDetails();  
      
       //do the actual image resize  
       imagecopyresized($this->resResizedImage, $this->resOriginalImage, 0, 0, 0, 0, $numWidth, $numHeight, $this->arrOriginalDetails[0], $this->arrOriginalDetails[1]); 

       //saves the image  
       $this->saveImage();  
    }  
 }

 /*  
 *  
 *   @Method:      _imageProtect  
 *   @Parameters:   2  
 *   @Param-1:      numWidth - Number - The width of the image in pixels  
 *   @Param-2:      numHeight - Number - The height of the image in pixes  
 *   @Description:   Checks to see if we should allow the resize to take place or not depending on the size the image will be resized to  
 *  
 */     
 function _imageProtect($numWidth, $numHeight){  
    if($this->boolProtect AND ($numWidth > $this->arrOriginalDetails[0] OR $numHeight > $this->arrOriginalDetails[1])){  
       return 0;  
    }
    return 1;  
 }  
  

 /*  
 *  
 *   @Method:      resizeToWidth  
 *   @Parameters:   1  
 *   @Param-1:      numWidth - Number - The width to resize to in pixels  
 *   @Description:   Works out the height value to go with the width value passed, then calls the resize method.  
 *  
 */
 function resizeToWidth($numWidth){ 

    $numHeight=(int)(($numWidth*$this->arrOriginalDetails[1])/$this->arrOriginalDetails[0]);
    $this->_resize($numWidth, $numHeight);   
 }

 /*  
 *  
 *   @Method:      resizeToHeight  
 *   @Parameters:   1  
 *   @Param-1:      numHeight - Number - The height to resize to in pixels  
 *   @Description:   Works out the width value to go with the height value passed, then calls the resize method.  
 *  
 */ 

 function resizeToHeight($numHeight){
    $numWidth=(int)(($numHeight*$this->arrOriginalDetails[0])/$this->arrOriginalDetails[1]);
    $this->_resize($numWidth, $numHeight);   
 }
 
 /*  
 *  
 *   @Method:      resizeToPercent  
 *   @Parameters:   1  
 *   @Param-1:      numPercent - Number - The percentage you want to resize to  
 *   @Description:   Works out the width and height value to go with the percent value passed, then calls the resize method.  
 *  
 */ 

 function resizeToPercent($numPercent){
    $numWidth = (int)(($this->arrOriginalDetails[0]/100)*$numPercent);
    $numHeight = (int)(($this->arrOriginalDetails[1]/100)*$numPercent);
    $this->_resize($numWidth, $numHeight);   
 }

 /*  
 *  
 *   @Method:      resizeToCustom  
 *   @Parameters:   1  
 *   @Param-1:      size - Number/Array - Either a number of array of numbers for the width and height in pixels  
 *   @Description:   Checks to see if array was passed and calls the resize method with the correct values.  
 *  
 */ 

 function resizeToCustom($size){
    if(!is_array($size)){
       $this->_resize((int)$size, (int)$size);
    }else{
       $this->_resize((int)$size[0], (int)$size[1]);
    }
 }
 
}



function smarty_cms_function_supersizer($params, &$smarty) {
	global $gCms;
	$config =& $gCms->GetConfig(); 
	
	//get and set the parameters
	$debugIT = isset($params['debugIT']) ? $params['debugIT']:false;
	$noOutPut = isset($params['noOutPut']) ? $params['noOutPut']:false;
	$path = isset($params['path']) ? $params['path']:false;
	$Prefix = isset($params['Prefix']) ? $params['Prefix']:'';
	$Suffix = isset($params['Suffix']) ? $params['Suffix']:'';
	$Subdir = isset($params['Subdir']) ? $params['Subdir'] : "";
	$stripTags  = isset($params['stripTags']) ? $params['stripTags'] : false;
	if($stripTags==true){
			$path = preg_replace('/.*src=([\'"])((?:(?!\1).)*)\1.*/si','$2',$path);
	}
	
	$URL = isset($params['URL']) ? $params['URL']:'';
	$Assign = isset($params['Assign']) ? $params['Assign']:'';
	$OlDextension = substr($path, (strrpos($path,".")+1));
	$extension = strtolower(substr($path, (strrpos($path,".")+1)));
	$filebasename = basename($path, $OlDextension);
	
	if(!isset($params['width']) && !isset($params['height']) && !isset($params['percentage'])) {
		$percentage = 25;
	}else{
		$width = isset($params['width']) ? intval($params['width']) : 0;
		$height = isset($params['height']) ? intval($params['height']) : 0;
		$percentage = isset($params['percentage']) ? intval($params['percentage']) : 0;
	}
	
	if(isset($Subdir)){
		if ((substr($Subdir, 0,1))=="/"){substr_replace($Subdir, '', 0, 1);}
		if ((substr($Subdir, -1))!="/"){$Subdir.="/";}
	}
	
	$rootUrl = isset($params['rootUrl']) ? $params['rootUrl'] : $config['uploads_url'];
	$filename=$config['uploads_path']."/SuperSizerTmp/".$Subdir.$Prefix.$filebasename."-w".$width."-h".$height."-p".$percentage.$Suffix.".".$extension;	
	$fileLINK=$rootUrl."/SuperSizerTmp/".$Subdir.$Prefix.$filebasename."-w".$width."-h".$height."-p".$percentage.$Suffix.".".$extension;
	$Protect= isset($params['Protect']) ? $params['Protect'] : true;
	if(file_exists($filename)){
		if($debugIT==true){
				unlink ($filename);
				//smarty_cms_function_supersizer($params, &$smarty);
			}
	}
	
	if(!file_exists($filename)){
		if(!file_exists($config['uploads_path']."/SuperSizerTmp/".$Subdir)){
			mkdir($config['uploads_path']."/SuperSizerTmp/".$Subdir, 0777, true);
		}
		$Quality = isset($params['Quality']) ? intval($params['Quality']) : 85;
		if($width>0 || $height>0) {
			if ($width>0 && $height==0){
				 $objResize = new SuperSizer($path, $filename, 'W', $width, $Quality, $Protect);
			}elseif($height>0 && $width==0){
				 $objResize = new SuperSizer($path, $filename, 'H', $height, $Quality, $Protect);
			}else{
				$objResize = new SuperSizer($path, $filename, 'C', array($width, $height), $Quality, $Protect);
			}
		}else{
			$objResize = new SuperSizer($path, $filename, 'P', $percentage, $Quality, $Protect);
		}
		if($debugIT==true){
			echo '<h2 class="title">Original Image</h2><pre>';
			print_r($objResize->findResourceDetails($objResize->resOriginalImage));
			echo '</pre><h2 class="title">Resized Image</h2><pre>';
			print_r($objResize->findResourceDetails($objResize->resResizedImage)); 
			echo '</pre>';
			error_reporting(E_ALL);
		}
	}
	if($noOutPut==false){
		
		if($URL!=true){
			$class = isset($params['class']) ? ' class="'.$params['class'].'" ':'';
			$alt = isset($params['alt']) ? ' alt="'.$params['alt'].'" ':'';
			$id = isset($params['id']) ? ' id="'.$params['id'].'" ':'';
			$title = isset($params['title']) ? ' title="'.$params['title'].'" ':'';
			
			if($Assign!=''){
				$smarty->assign($Assign,"<img src=\"$fileLINK\" $title $id $class $alt />");
			}else{
				echo "<img src=\"$fileLINK\" $title $id $class $alt />";
			}
		}else{
			if($Assign!=''){
				$smarty->assign($Assign,$fileLINK);
			}else{
				echo $fileLINK;
			}
		}
		
	}
}


function smarty_cms_help_function_supersizer() {
	?>

	<h3>What does this tag do?</h3>
	<ul>
	<li>Creates a resized version of an image on the fly.</li>
    <li>Creates a cached version of the image to be severed.</li>
	<li>It supports any image format supported by the GD library</li>
    <li>It supports Subdomain image severing for optimal setup</li>
	</ul>
	<h3>How do I use this tag?</h3>
<blockquote><b>Just insert the tag into your template/page like in one of the examples here: </b><br />
  <CODE>1. {supersizer path='uploads/images/test.jpg' percentage='25'}</CODE><CODE><br>
  2. {supersizer path='uploads/images/test.jpg' width='320'} <em>(With aspect ratio)</em></CODE><CODE><br>
  3. {supersizer path='uploads/images/test.jpg' height='240'} <em>(With aspect ratio)</em></CODE><CODE><br>
  4. {supersizer path='uploads/images/test.jpg' width='150' height='140'} <em>(Aspect ratio depends on given width, height)</em></CODE><CODE><br>
  5. {supersizer path="$LogoSub" width='150' rootUrl="http://media.domain.org/uploads"}</CODE><CODE><br>
  5. {supersizer path="$LogoSub" width='150' Quality=55 Protect=false}</CODE><CODE><br>
  5. {supersizer path="$LogoSub" width='150' class='LogoImg' alt="$Name" rootUrl="http://media.domain.org/uploads" Quality=55}</CODE>
  
  </blockquote>
	<h3>What parameters does it take?</h3>
	<ul>
	<li><CODE>path</CODE> - Image full pathname eg: uploads/images/test.jpg or $entry->logo_path in Company Directory etc...</li>
    <li><CODE>rootUrl</CODE> <em>(optional)</em> - supersizer creates a temp director in the upload folder.  If you move the path to the uplaod to a subdomain you may guide the output with this.</li>
        <ul style="list-style-position:inside;"><li><strong>Exapmle:</strong> you changed <CODE>$config['uploads_path'] = '/var/www/vhosts/domain.org/httpdocs/uploads';</CODE> </li>
            <li><strong>to</strong> <CODE>$config['uploads_path'] = '/var/www/vhosts/domain.org/subdomains/media/httpdocs/uploads';</CODE></li>
            <li>now the uploads url would not work as it would be <u>http://www.domain.org/uploads</u></li>
            <li><strong>So</strong> it can be changed here to <u>http://media.domain.org/uploads</u>  <font color="red"><strong>(NOTE: watch your / )</strong></font></li>
            <li>For an example visit <a href="http://www.northcentralidaho.org/SERVICES-and-MERCHANTS.html" target="_blank">http://www.northcentralidaho.org/SERVICES-and-MERCHANTS.html</a> and drill down to a company to which you'll see images coming from the subdomain</li>
        </ul>
    </li>
    <li><CODE>Protect</CODE> <em>(optional)</em> - Don't resize if smaller.. ie: don't size up if true  <font color="red"><strong>( true/false )</strong></font></li>
	<li><CODE>Quality</CODE> <em>(optional)</em> - Resize image at set Quality default is 85 <font color="red"><strong>(NOTE: 1-100 )</strong></font>.</li>
    <li><CODE>class</CODE> <em>(optional)</em> - Add a class</li>
    <li><CODE>alt</CODE> <em>(optional)</em> - Add an alt</li>
    <li><CODE>id</CODE> <em>(optional)</em> - Add an id</li>
    <li><CODE>title</CODE> <em>(optional)</em> - Add a title</li>
    <li><CODE>stripTag</CODE> <em>(optional)</em> - stripTag take a full img tag passed in by the param path="" and makes it usable for SuperSizer <font color="red"><strong>( true/false )</strong></font></li>   
    
	<li><CODE>URL</CODE> <em>(optional)</em> - just sizes and outputs the url.  you could use this in and XML output, lets say to make a map icon for CGGoogleMaps thru a CGFeedmaker output of a kml/xml</li>
    <li><CODE>noOutPut</CODE> <em>(optional)</em> - just sizes the image.  This is good for galleries</li>
    <li><CODE>Prefix</CODE> <em>(optional)</em> - Add a Prefix to the temp file name</li>
    <li><CODE>Suffix</CODE> <em>(optional)</em> - Add a Suffix to the temp file name</li>    
    <li><CODE>Subdir</CODE> <em>(optional)</em> - Create Subfolders -- Organize your photos from within the SuperSizerTmp folder <font color="red"><strong>( Subdir=$oneuser.id or Subdir="foo/bar")</strong></font></li>  
    
    <li><CODE>percentage</CODE> <em>(optional)</em> - Resize image in percent of original eg. 50%.</li>
	<li><CODE>width</CODE> <em>(optional)</em> - Resize image on width and height will resize accordingly to keep aspect ratio</li>
	<li><CODE>height</CODE> <em>(optional)</em> - Resize image on height and width will resize accordingly to keep aspect ratio </li>
	
    <li><CODE>Assign</CODE> <em>(optional)</em> - Assign the output (return the smarty assignment)  Use in conjunction with out without URL</li>
    <li><CODE>debugIT</CODE> <em>(optional)</em> - Get an array of the pre and post images... the original and the resized <font color="red"><strong><br/>( true/false )<em> This information is required for any support</em></strong></font><br/></li>
<h3>Note:</h3>
    <CODE>height</CODE> and <CODE>width</CODE> <em>(optional)</em> 
    <font color="red"><strong>Important:</strong></font>You may use width in conjunction with height in order to resize image to an absolute size of your control. Aspect ratio is then, dependent on the values you use. If no parameters for resizing are passed (except for the path) then a resizing with a percentage value of 25% is performed by default</li>
	</ul>
    
    <br /><br />
    <p><strong>Author:</strong> jeremyBass &lt;jeremybass@cableone.net&gt;<br />
    <strong>Website:</strong> <a href="www.corbensproducts.com" target="_blank">CorbensProducts.com</a><br />
    <strong>Support more mods like this:</strong><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="8817675">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form><br/>

    <strong>Version:</strong> 1.0, 10.10.2009</p>
	<?php
}

function smarty_cms_about_function_supersizer() {
	?>
	<p>Author: jeremyBass &lt;jeremybass@cableone.net&gt;<br />
	<br />
    Version: 1.0, 10.10.2009</p>
	<?php
}
?>
