<?php
//zOOm Gallery//
/** 
-----------------------------------------------------------------------
|  zOOm Image Gallery! by Mike de Boer - a multi-gallery component    |
-----------------------------------------------------------------------

-----------------------------------------------------------------------
|                                                                     |
| Date: October, 2004                                                 |
| Author: Mike de Boer, <http://www.mikedeboer.nl>                    |
| Copyright: copyright (C) 2004 by Mike de Boer                       |
| Description: zOOm Image Gallery, a multi-gallery component for      |
|              Mambo based on RSGallery by Ronald Smit. It's the most |
|              feature-rich gallery component for Mambo!              |
| Filename: toolbox.class.php                                         |
| Version: 2.1.4                                                      |
|                                                                     |
-----------------------------------------------------------------------
-----------------------------------------------------------------------
|                                                                     |
| What is the toolbox? --> well, it's an object that bundles all      |
| medium-manipulation tools into one convenient class.                |
| These tools would include:                                          |
|                                                                     |
| - Image resizing                                                    |
| - Image rotating                                                    |
| - Image watermarking with custom TrueType fonts                     |
| - Parse Directories for media types                                 |
| - PDF/ documents searching                                          |
| - Video JPEG capturing                                              |
| - ALL tools have implementations for the following manipulation     |
|   software: ImageMagick, NetPBM, GD1.x and GD2.x.                   |
|                                                                     |
-----------------------------------------------------------------------
**/
// MOS Intruder Alerts
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

class toolbox{
	var $_isBackend = null;
	var $_conversiontype = null;
	var $_IM_path = null;
	var $_NETPBM_path = null;
	var $_FFMPEG_path = null;
	var $_PDF_path = null;
	var $_use_FFMPEG = null;
	var $_use_PDF = null;
	var $_JPEGquality = null;
    var $_err_num = null;
    var $_err_names = array();
    var $_err_types = array();
	var $_wmtext = null;
	var $_wmdatfmt = null;
	var $_wmfont = null;
	var $_wmfont_size = null;
	var $_wmrgbtext = null;
	var $_wmrgbtsdw = null;
	var $_wmhotspot = null;
	var $_wmtxp = null;
	var $_wmtyp = null;
	var $_wmsxp = null;
	var $_wmsyp = null;
    var $_buffer = null;
	
	function toolbox(){
		// constructor of the toolbox - primary init...
		global $zoom, $mosConfig_absolute_path;
		$this->_isBackend = $zoom->_isBackend;
		$this->_conversiontype = $zoom->_CONFIG['conversiontype'];
		$this->_IM_path = $zoom->_CONFIG['IM_path'];
		$this->_NETPBM_path = $zoom->_CONFIG['NETPBM_path'];
		$this->_FFMPEG_path = $zoom->_CONFIG['FFMPEG_path'];
		$this->_PDF_path = $zoom->_CONFIG['PDF_path'];
		$this->_JPEGquality = $zoom->_CONFIG['JPEGquality'];
		// load watermark settings...
		if (!isset($zoom->_CONFIG['wmtext']))
			$this->_wmtext = "[date]";
		if (!isset($zoom->_CONFIG['wmfont']))
			$this->_wmfont = "ARIAL.TTF";
		if (!isset($zoom->_CONFIG['wmfont_size']))
			$this->_wmfont_size = 12;
		if (!isset($zoom->_CONFIG['wmrgbtext']))
			$this->_wmrgbtext = "FFFFFF";
		// truetype font shadow color in hex format...
		if (!isset($zoom->_CONFIG['wmrgbtsdw']))
			$this->_wmrgbtsdw = "000000";
		if (!isset($zoom->_CONFIG['wmhotspot']))
			$this->_wmhotspot = 8;
		$this->_wmdatfmt = "Y-m-d";
		// watermark offset coordinates...t = top and s = side.
		$this->_wmtxp = 0;
		$this->_wmtyp = 0;
		$this->_wmsxp = 1;
		$this->_wmsyp = 1;
		if ($zoom->_isAdmin) {
			switch ($this->_conversiontype){
				//Imagemagick
				case 1:
					if($this->_IM_path == 'auto'){
						$this->_IM_path = '';
					}else{
						if($this->_IM_path){
							if(!is_dir($this->_IM_path)){
									echo "<div align=\"center\"><font color=\"red\">Error: your ImageMagick path is not correct! Please (re)specify it in the Admin-system under 'Settings'</font><br />";
								}
						}
					}
					break;
				//NetPBM
				case 2:
					if($this->_NETPBM_path == 'auto'){
						$this->_NETPBM_path ='';
					}else{
						if($this->_NETPBM_path){
							if(!is_dir($this->_NETPBM_path)){
									echo "<div align=\"center\"><font color=\"red\">Error: your NetPBM path is not correct! Please (re)specify it in the Admin-system under 'Settings'</font><br /></div>";
								}
						}
					}
					break;
				//GD1
				case 3:
					if (!function_exists('imagecreatefromjpeg')) {
					    echo "<div align=\"center\"><font color=\"red\">PHP running on your server does not support the GD image library, check with your webhost if ImageMagick is installed</font><br /></div>";
					}
					break;
				//GD2
				case 4:
					if (!function_exists('imagecreatefromjpeg')) {
					    echo "<div align=\"center\"><font color=\"red\">Error: PHP running on your server does not support the GD image library, check with your webhost if ImageMagick is installed</font><br /></div>";
					}
					if (!function_exists('imagecreatetruecolor')) {
					    echo "<div align=\"center\"><font color=\"red\">Error: PHP running on your server does not support GD version 2.x, please switch to GD version 1.x on the config page</font><br /></div>";
					}
					break;
			}
			if($this->_FFMPEG_path == 'auto'){
				$this->_FFMPEG_path = '';
			}else{
				if($this->_FFMPEG_path){
					if(is_dir($this->_FFMPEG_path)){
						$this->_use_FFMPEG = true;
					}else{
						$this->_use_FFMPEG = false;
					}
				}
			}
			if($this->_PDF_path == 'auto'){
				$this->_PDF_path = '';
			}else{
				if($this->_PDF_path){
					if(is_dir($this->_PDF_path)){
						$this->_use_PDF = true;
					}else{
						$this->_use_PDF = false;
					}
				}
			}
		}		
		// toolbox ready for use...
	}
    function processImage($image, $filename, $keywords, $name, $descr, $rotate, $degrees = 0, $copyMethod = 1){
		global $mosConfig_absolute_path, $zoom;
		$imagepath = $zoom->_CONFIG['imagepath'];
		$catdir = $zoom->_gallery->getDir();
		$filename = urldecode($filename);
        // replace every space-character with a single "_"
	    $filename = ereg_replace(" ", "_", $filename);
     	// Get rid of extra underscores
     	$filename = ereg_replace("_+", "_", $filename);
     	$filename = ereg_replace("(^_|_$)", "", $filename);
		$tag = ereg_replace(".*\.([^\.]*)$", "\\1", $filename);
		$tag = strtolower($tag);
		$zoom->checkDuplicate($filename);
		$filename = $zoom->_tempname;
        if($zoom->acceptableFormat($tag)){
            // File is an image/ movie/ document...
            $file = $mosConfig_absolute_path."/".$imagepath.$catdir."/".$filename;
            $desfile = $mosConfig_absolute_path."/".$imagepath.$catdir."/thumbs/".$filename;
            if($copyMethod == 1){
                if (!move_uploaded_file("$image", "$file")){
                    // some error occured while moving file, register this...
                    $this->_err_num++;
                    $this->_err_names[$this->_err_num] = $filename;
                    $this->_err_types[$this->_err_num] = _ZOOM_ALERT_MOVEFAILURE;
                    return false;
                }
            }elseif($copyMethod == 2){
                if (!fs_copy("$image", "$file")){
                    // some error occured while moving file, register this...
                    $this->_err_num++;
                    $this->_err_names[$this->_err_num] = $filename;
                    $this->_err_types[$this->_err_num] = _ZOOM_ALERT_MOVEFAILURE;
                    return false;
                }
            }
            @chmod("$file", 0644);
            $size = $zoom->_CONFIG['size'];
           if($zoom->isImage($tag)){
           	   $imginfo = getimagesize($file);
           	   // get image EXIF & IPTC data from file to save it in viewsize image and get a thumbnail...
           	   if ($zoom->_CONFIG['readEXIF'] && $tag === "jpg"){
           	   	// Retreive the EXIF, XMP and Photoshop IRB information from
				// the existing file, so that it can be updated later on...
				$jpeg_header_data = get_jpeg_header_data( $file );
				$EXIF_data = get_EXIF_JPEG($file);
				$XMP_data = read_XMP_array_from_text( get_XMP_text( $jpeg_header_data ) );
                $IRB_data = get_Photoshop_IRB( $jpeg_header_data );
                $new_ps_file_info = get_photoshop_file_info($EXIF_data, $XMP_data, $IRB_data);
                // Check if there is a default for the date defined
                if ( ( ! array_key_exists( 'date', $new_ps_file_info ) ) ||
                	( ( array_key_exists( 'date', $new_ps_file_info ) ) &&
                	( $new_ps_file_info['date'] == '' ) ) )
                {
                	// No default for the date defined
                	// figure out a default from the file
                	// Check if there is a EXIF Tag 36867 "Date and Time of Original"
                	if ( ( $EXIF_data != FALSE ) &&
                		( array_key_exists( 0, $EXIF_data ) ) &&
                		( array_key_exists( 34665, $EXIF_data[0] ) ) &&
                		( array_key_exists( 0, $EXIF_data[0][34665] ) ) &&
                		( array_key_exists( 36867, $EXIF_data[0][34665][0] ) ) )
                	{
                    	// Tag "Date and Time of Original" found - use it for the default date
                    	$new_ps_file_info['date'] = $EXIF_data[0][34665][0][36867]['Data'][0];
                    	$new_ps_file_info['date'] = preg_replace( "/(\d\d\d\d):(\d\d):(\d\d)( \d\d:\d\d:\d\d)/", "$1-$2-$3", $new_ps_file_info['date'] );
                    }
                    // Check if there is a EXIF Tag 36868 "Date and Time when Digitized"
                    else if ( ( $EXIF_data != FALSE ) &&
                    	( array_key_exists( 0, $EXIF_data ) ) &&
                    	( array_key_exists( 34665, $EXIF_data[0] ) ) &&
                    	( array_key_exists( 0, $EXIF_data[0][34665] ) ) &&
                    	( array_key_exists( 36868, $EXIF_data[0][34665][0] ) ) )
                    {
                    	// Tag "Date and Time when Digitized" found - use it for the default date
                    	$new_ps_file_info['date'] = $EXIF_data[0][34665][0][36868]['Data'][0];
                    	$new_ps_file_info['date'] = preg_replace( "/(\d\d\d\d):(\d\d):(\d\d)( \d\d:\d\d:\d\d)/", "$1-$2-$3", $new_ps_file_info['date'] );
                    }
                    // Check if there is a EXIF Tag 306 "Date and Time"
                    else if ( ( $EXIF_data != FALSE ) &&
                    	( array_key_exists( 0, $EXIF_data ) ) &&
                    	( array_key_exists( 306, $EXIF_data[0] ) ) )
                    {
                    	// Tag "Date and Time" found - use it for the default date
                    	$new_ps_file_info['date'] = $EXIF_data[0][306]['Data'][0];
                    	$new_ps_file_info['date'] = preg_replace( "/(\d\d\d\d):(\d\d):(\d\d)( \d\d:\d\d:\d\d)/", "$1-$2-$3", $new_ps_file_info['date'] );
                    }else{
                    	// Couldn't find an EXIF date in the image
                    	// Set default date as creation date of file
                    	$new_ps_file_info['date'] = date ("Y-m-d", filectime( $file ));
                    }
                }
           	   }
               if($rotate){
                   if(!$zoom->_toolbox->rotateImage($file, $file, $filename, $degrees)){
                       $this->_err_num++;
                       $this->_err_names[$this->_err_num] = $filename;
                       $this->_err_types[$this->_err_num] = "Error rotating image";
                       return false;
                   }
               }
               // if the image size is greater than the given maximum: resize it!               
               if($imginfo[0] > $zoom->_CONFIG['maxsize'] || $imginfo[1] > $zoom->_CONFIG['maxsize']){
               		$viewsize = $mosConfig_absolute_path."/".$imagepath.$catdir."/viewsize/".$filename;
               		if(!$zoom->_toolbox->resizeImage($file, $viewsize, $zoom->_CONFIG['maxsize'], $filename)){
               			if ($zoom->_CONFIG['readEXIF'] && ($tag === "jpg" || $tag = "jpeg")){
               				// put the EXIF info back in the resized file...
               				// Update the JPEG header information with the new Photoshop File Info
               				// NOTE: this only seems to work with GD2.x. Why? I don't know ;-)
                        	$jpeg_header_data = put_photoshop_file_info( $jpeg_header_data, $new_ps_file_info, $EXIF_data, $XMP_data, $IRB_data );
                        	if (put_jpeg_header_data( $file, $viewsize, $jpeg_header_data ) == false) {
                       			$this->_err_num++;
			                    $this->_err_names[$this->_err_num] = $filename;
			                    $this->_err_types[$this->_err_num] = _ZOOM_ALERT_IMGERROR;
			                    return false;
                        	}
               			}
               		   $this->_err_num++;
	                   $this->_err_names[$this->_err_num] = $filename;
	                   $this->_err_types[$this->_err_num] = _ZOOM_ALERT_IMGERROR;
	                   return false;
               		}
               }
               // resize to thumbnail...
               // JPEG files often carry pre-made thumbnails in them, so we'll use that one
               // if it exists at all.
               if ($zoom->_CONFIG['readEXIF'] && ($tag === "jpg" || $tag = "jpeg") && count($EXIF_data) >= 2 && is_array($EXIF_data[1][513]) && !empty($EXIF_data[1][513]['Data'])){
           			if(!$zoom->writefile($desfile, $EXIF_data[1][513]['Data'])){
	           			$this->_err_num++;
	                   	$this->_err_names[$this->_err_num] = $filename;
	                   	$this->_err_types[$this->_err_num] = _ZOOM_ALERT_IMGERROR;
	                   	return false;
           			}
               }elseif(!$zoom->_toolbox->resizeImage($file, $desfile, $size, $filename)){
                   $this->_err_num++;
                   $this->_err_names[$this->_err_num] = $filename;
                   $this->_err_types[$this->_err_num] = _ZOOM_ALERT_IMGERROR;
                   return false;
               }
           }elseif($zoom->isDocument($tag)){
               if($zoom->isIndexable($tag) && $this->_use_PDF){
                	if(!$this->indexDocument($file, $filename)){
                	   $this->_err_num++;
                       $this->_err_names[$this->_err_num] = $filename;
                       $this->_err_types[$this->_err_num] = _ZOOM_ALERT_INDEXERROR;
                       return false;
                	}
               }
           }elseif($zoom->isMovie($tag)){
               //if movie is 'thumbnailable' -> make a thumbnail then!
               if($zoom->isThumbnailable($tag) && $this->_use_FFMPEG){
                   if(!$zoom->_toolbox->createMovieThumb($file, $size, $filename)){
                       $this->_err_num++;
                       $this->_err_names[$this->_err_num] = $filename;
                       $this->_err_types[$this->_err_num] = _ZOOM_ALERT_IMGERROR;
                       return false;
                   }
               }
           }
           // replace space-characters in combination with a comma with 'air'...or nothing!
           $keywords = ereg_replace(", ", ",", $keywords);
           if(empty($name))
           	$name = $zoom->_CONFIG['tempName'];
           $zoom->saveImage($filename, $keywords, $name, $descr, $zoom->_gallery->_id);
        }else{
            //Not the right format, register this...
            $this->_err_num++;
            $this->_err_names[$this->_err_num] = $filename;
            $this->_err_types[$this->_err_num] = _ZOOM_ALERT_WRONGFORMAT_MULT;
            return false;
        }
        return true;
    }
	function resizeImage($file, $desfile, $size, $filename = ""){
		switch ($this->_conversiontype){
			//Imagemagick
			case 1:
				if($this->resizeImageIM($file, $desfile, $size))
					return true;
				else
					return false;
				break;
			//NetPBM
			case 2:
				if($this->resizeImageNETPBM($file,$desfile,$size,$filename))
					return true;
				else
					return false;
				break;
			//GD1
			case 3:
				if($this->resizeImageGD1($file, $desfile, $size))
					return true;
				else
					return false;
				break;
			//GD2
			case 4:
				if($this->resizeImageGD2($file, $desfile, $size))
					return true;
				else
					return false;
				break;
		}
		return true;
	}
	function resizeImageIM($src_file, $dest_file, $new_size){
		$cmd = $this->_IM_path."convert -resize $new_size \"$src_file\" \"$dest_file\"";
		exec($cmd, $output, $retval);
		if($retval)
			return false;
		else
			return true;
	}
	function resizeImageNETPBM($src_file,$des_file,$new_size,$orig_name){
		$quality = $this->_JPEGquality;
		$imginfo = getimagesize($src_file);
		if ($imginfo == null)
			return false;
		// height/width
		$srcWidth = $imginfo[0];
		$srcHeight = $imginfo[1];
		$ratio = max($srcWidth, $srcHeight) / $new_size;
		$ratio = max($ratio, 1.0);
		$destWidth = (int)($srcWidth / $ratio);
		$destHeight = (int)($srcHeight / $ratio);
		if (eregi("\.png", $orig_name)){
			$cmd = $this->_NETPBM_path . "pngtopnm $src_file | " . $this->_NETPBM_path . "pnmscale -xysize $destWidth $destHeight | " . $this->_NETPBM_path . "pnmtopng > $des_file" ; 
		}
		else if (eregi("\.(jpg|jpeg)", $orig_name)){
			$cmd = $this->_NETPBM_path . "jpegtopnm $src_file | " . $this->_NETPBM_path . "pnmscale -xysize $destWidth $destHeight | " . $this->_NETPBM_path . "ppmtojpeg -quality=$quality > $des_file" ;
		}
		else if (eregi("\.gif", $orig_name)){
			$cmd = $this->_NETPBM_path . "giftopnm $src_file | " . $this->_NETPBM_path . "pnmscale -xysize $destWidth $destHeight | " . $this->_NETPBM_path . "ppmquant 256 | " . $this->_NETPBM_path . "ppmtogif > $des_file" ; 
		}else{
			return false;
		}
		exec($cmd, $output, $retval);
		if($retval)
			return false;
		else
			return true;
	}
	function resizeImageGD1($src_file, $dest_file, $new_size){
		$imginfo = getimagesize($src_file);
		if ($imginfo == null)
			return false;
		// GD can only handle JPG & PNG images
		if ($imginfo[2] != 2 && $imginfo[2] != 3){
			return false;
		}
		// height/width
		$srcWidth = $imginfo[0];
		$srcHeight = $imginfo[1];
		$ratio = max($srcWidth, $srcHeight) / $new_size;
		$ratio = max($ratio, 1.0);
		$destWidth = (int)($srcWidth / $ratio);
		$destHeight = (int)($srcHeight / $ratio);
		if ($imginfo[2] == 2)
			$src_img = imagecreatefromjpeg($src_file);
		else
			$src_img = imagecreatefrompng($src_file);
		if (!$src_img)
			return false;
		$dst_img = imagecreate($destWidth, $destHeight);
		imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
		if ($imginfo[2] == 2)
			imagejpeg($dst_img, $dest_file, $this->_JPEGquality);
		else
			imagepng($dst_img, $dest_file);
		imagedestroy($src_img);
		imagedestroy($dst_img);
		return true; 
	}
	function resizeImageGD2($src_file, $dest_file, $new_size){
		$imginfo = getimagesize($src_file);
		if ($imginfo == null)
			return false;
		// GD can only handle JPG & PNG images
		if ($imginfo[2] != 2 && $imginfo[2] != 3){
			return false;
		}
		// height/width
		$srcWidth = $imginfo[0];
		$srcHeight = $imginfo[1];
		$ratio = max($srcWidth, $srcHeight) / $new_size;
		$ratio = max($ratio, 1.0);
		$destWidth = (int)($srcWidth / $ratio);
		$destHeight = (int)($srcHeight / $ratio);
		if ($imginfo[2] == 2)
			$src_img = imagecreatefromjpeg($src_file);
		else
			$src_img = imagecreatefrompng($src_file);
		if (!$src_img)
			return false;
		$dst_img = imagecreatetruecolor($destWidth, $destHeight);
		imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
		if ($imginfo[2] == 2)
			imagejpeg($dst_img, $dest_file, $this->_JPEGquality);
		else
			imagepng($dst_img, $dest_file);
		imagedestroy($src_img);
		imagedestroy($dst_img);
		return true;
	}
	function rotateImage($file, $desfile, $filename, $degrees){
		$degrees = intval($degrees);
		switch ($this->_conversiontype){
			//Imagemagick
			case 1:
				if($this->rotateImageIM($file, $desfile, $degrees))
					return true;
				else
					return false;
				break;
			//NetPBM
			case 2:
				if($this->rotateImageNETPBM($file,$desfile, $filename, $degrees))
					return true;
				else
					return false;
				break;
			//GD1
			case 3:
				if($this->rotateImageGD1($file, $desfile, $degrees))
					return true;
				else
					return false;
				break;
			//GD2
			case 4:
				if($this->rotateImageGD2($file, $desfile, $degrees))
					return true;
				else
					return false;
				break;
		}
		return true;
	}
	function rotateImageIM($file, $desfile, $degrees){
		$cmd = $this->_IM_path."convert -rotate $degrees \"$file\" \"$desfile\"";
		exec($cmd, $output, $retval);
		if($retval)
			return false;
		else
			return true;
	}
	function rotateImageNETPBM($file, $desfile, $filename, $degrees){
		$quality = $this->_JPEGquality;
		$fileOut = "$file.1";
		fs_copy($file,$fileOut); 
		if (eregi("\.png", $filename)){
			$cmd = $this->_NETPBM_path . "pngtopnm $file | " . $this->_NETPBM_path . "pnmrotate $degrees | " . $this->_NETPBM_path . "pnmtopng > $fileOut" ; 
		}
		else if (eregi("\.(jpg|jpeg)", $filename)){
			$cmd = $this->_NETPBM_path . "jpegtopnm $file | " . $this->_NETPBM_path . "pnmrotate $degrees | " . $this->_NETPBM_path . "ppmtojpeg -quality=$quality > $fileOut" ;
		}
		else if (eregi("\.gif", $orig_name)){
			$cmd = $this->_NETPBM_path . "giftopnm $file | " . $this->_NETPBM_path . "pnmrotate $degrees | " . $this->_NETPBM_path . "ppmquant 256 | " . $this->_NETPBM_path . "ppmtogif > $fileOut" ; 
		}else{
			return false;
		}
		exec($cmd, $output, $retval);
		if($retval){
			return false;
		}else{
			$erg = fs_rename($fileOut, $desfile); 
			return true;
		}
	}
	function rotateImageGD1($file, $desfile, $degrees){
		$imginfo = getimagesize($file);
		if ($imginfo == null)
			return false;
		// GD can only handle JPG & PNG images
		if ($imginfo[2] != 2 && $imginfo[2] != 3){
			return false;
		}
		if ($imginfo[2] == 2)
			$src_img = imagecreatefromjpeg($file);
		else
			$src_img = imagecreatefrompng($file);
		if (!$src_img)
			return false;
		// The rotation routine...
		$src_img = imagerotate($src_img, $degrees, 0);
		$dst_img = imagecreate($imginfo[0], $imginfo[1]);
		imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
		if ($imginfo[2] == 2)
			imagejpeg($dst_img, $desfile, $this->_JPEGquality);
		else
			imagepng($dst_img, $desfile);
		imagedestroy($src_img);
		imagedestroy($dst_img);
		return true; 
	}
	function rotateImageGD2($file, $desfile, $degrees){
		$imginfo = getimagesize($file);
		if ($imginfo == null)
			return false;
		// GD can only handle JPG & PNG images
		if ($imginfo[2] != 2 && $imginfo[2] != 3){
			return false;
		}
		if ($imginfo[2] == 2)
			$src_img = imagecreatefromjpeg($file);
		else
			$src_img = imagecreatefrompng($file);
		if (!$src_img)
			return false;
		// The rotation routine...
		$src_img = imagerotate($src_img, $degrees, 0);
		$dst_img = imagecreatetruecolor($imginfo[0], $imginfo[1]);
		imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
		if ($imginfo[2] == 2)
			imagejpeg($dst_img, $desfile, $this->_JPEGquality);
		else
			imagepng($dst_img, $desfile);
		imagedestroy($src_img);
		imagedestroy($dst_img);
		return true;
	}
	// watermark by Elf Qrin ( http://www.ElfQrin.com/ ) - modified for use with zOOm.
	function watermark($file, $desfile) {
		$suffx = substr($file,strlen($file)-4,4);
		if ($suffx == ".jpg" || $suffx == "jpeg" || $suffx == ".png") {
			$text = str_replace("[date]",date($this->_wmdatfmt),$this->_wmtext);
			if ($suffx == ".jpg" || $suffx == "jpeg") {
				$image = imagecreatefromjpeg($file);
			}
			if ($suffx == ".png") {
				$image = imagecreatefrompng($file);
			}
			$rgbtext = HexDec($this->_wmrgbtext);
			$txtr = floor($rgbtext/pow(256,2));
			$txtg = floor(($rgbtext%pow(256,2))/pow(256,1));
			$txtb = floor((($rgbtext%pow(256,2))%pow(256,1))/pow(256,0));
			
			$rgbtsdw = HexDec($this->_wmrgbtsdw);
			$tsdr = floor($rgbtsdw/pow(256,2));
			$tsdg = floor(($rgbtsdw%pow(256,2))/pow(256,1));
			$tsdb = floor((($rgbtsdw%pow(256,2))%pow(256,1))/pow(256,0));
			
			$coltext = imagecolorallocate($image,$txtr,$txtg,$txtb);
			$coltsdw = imagecolorallocate($image,$tsdr,$tsdg,$tsdb);
			
			if ($this->_wmhotspot != 0) {
				$ix = imagesx($image);
				$iy = imagesy($image);
				$tsw = strlen($text)*$this->_wmfont_size/imagefontwidth($this->_wmfont)*3;
				$tsh = $this->_wmfont_size/imagefontheight($this->_wmfont);
				switch ($this->_wmhotspot) {
					case 1:
						$txp = $this->_wmtxp;
						$typ = $tsh*$tsh+imagefontheight($this->_wmfont)*2+$this->_wmtyp;
						break;
					case 2:
						$txp = floor(($ix-$tsw)/2);
						$typ = $tsh*$tsh+imagefontheight($this->_wmfont)*2+$this->_wmtyp;
						break;
					case 3:
						$txp = $ix-$tsw-$txp;
						$typ = $tsh*$tsh+imagefontheight($this->_wmfont)*2+$this->_wmtyp;
						break;
					case 4:
						$txp = $this->_wmtxp;
						$typ = floor(($iy-$tsh)/2);
						break;
					case 5:
						$txp = floor(($ix-$tsw)/2);
						$typ = floor(($iy-$tsh)/2);
						break;
					case 6:
						$txp = $ix-$tsw-$this->_wmtxp;
						$typ = floor(($iy-$tsh)/2);
						break;
					case 7:
						$txp = $this->_wmtxp;
						$typ = $iy-$tsh-$this->_wmtyp;
						break;
					case 8:
						$txp = floor(($ix-$tsw)/2);
						$typ = $iy-$tsh-$this->_wmtyp;
						break;
					case 9:
						$txp = $ix-$tsw-$this->_wmtxp;
						$typ = $iy-$tsh-$this->_wmtyp;
						break;
				}
			}
			ImageTTFText($image, $this->_wmfont_size, 0, $txp+$sxp, $typ+$syp, $coltsdw, $this->_wmfont,$text);
			ImageTTFText($image, $this->_wmfont_size, 0, $txp, $typ, $coltext, $this->wmfont, $text);	
			if ($suffx == ".jpg" || $suffx == "jpeg") {
				imagejpeg($image, $desfile, $this->_JPEGquality);
			}elseif($suffx == ".png"){
				imgepng($image, $desfile);
			}
			imagedestroy($image);
			return true;
		}else{
			return false;
		}
	}
	function createMovieThumb($file, $size, $filename){
		global $mosConfig_absolute_path, $zoom;
		if($this->_FFMPEG_path == 'auto'){
			$this->_FFMPEG_path = '';
		}else{
			if($this->_FFMPEG_path){
				if(!is_dir($this->_FFMPEG_path)){
						die("Error: your FFmpeg path is not correct! Please (re)specify it in the Admin-system under 'Settings'");
					}
			}
		}
		$tempdir = uniqid('zoom_');
		$gen_images = array();
		$gen_path = $mosConfig_absolute_path."/media/".$tempdir;
		// the file has the extension 'mpg' or 'avi' or 'whatever' and needs to be 'jpg'...
		$desfile = ereg_replace("(.*)\.([^\.]*)$", "\\1", $filename).".jpg";
		if(mkdir($gen_path, 0777)){
			$cmd = $this->_FFMPEG_path."ffmpeg -an -y -t 0:0:0.001 -ss 0:0:0.000 -i \"$file\" -f image -img jpeg \"$gen_path/file%d.jpg\"";
			exec($cmd, $output, $retval);
			if(!$retval){
				$gen_images = $this->parseDir($gen_path);
				$the_thumb = round(sizeof($gen_images) / 2) - 1;
				$the_thumb = $gen_path."/".$gen_images[$the_thumb];
				$target = $mosConfig_absolute_path."/".$zoom->_CONFIG['imagepath'].$zoom->_gallery->getDir()."/thumbs/".$desfile;
				if(!$this->resizeImage($the_thumb, $target, $size, $desfile)){
					return false;
				}
			}else{
				return false;
			}
			$zoom->deldir($gen_path);
			return true;
		}else{
			return false;
		}
	}
	function searchPdf(&$file, $searchText){
        global $zoom, $mosConfig_absolute_path;
        $file->getInfo();
        $source = $mosConfig_absolute_path."/".$zoom->_CONFIG['imagepath'].$file->getDir()."/".ereg_replace("(.*)\.([^\.]*)$", "\\1", $file->_filename).".txt";
        if(fs_is_file($source)){
        	$txt = strtolower(file_get_contents($source));
        	if(preg_match("/$searchText/", $txt)){
        		return true;
        	}else{
        		return false;
        	}
        	unset($txt);
        }else{
        	return false;
        }
	}
	function indexDocument($file, $filename){
		global $mosConfig_absolute_path, $zoom;
		// this function will contain the algorithm to index a document (like a pdf)...
		// Method: use PDFtoText to create a plain ASCII text-file, which can be easily
		//         searched through. The text-file will be placed into the same dir as the
		//         original pdf.
		if($this->_PDF_path == 'auto'){
			$this->_PDF_path = '';
		}else{
			if($this->_PDF_path){
				if(!is_dir($this->_PDF_path)){
						die("Error: your PDFtoText path is not correct! Please (re)specify it in the Admin-system under 'Settings'");
					}
			}
		}
		$desfile = ereg_replace("(.*)\.([^\.]*)$", "\\1", $filename).".txt";
		$target = $mosConfig_absolute_path."/".$zoom->_CONFIG['imagepath'].$zoom->_gallery->getDir()."/".$desfile;
		$cmd = $this->_PDF_path."pdftotext \"$file\" \"$target\"";
		exec($cmd, $output, $retval);
		if(!$retval)
			return true;
		else
			return false;
	}
	function parseDir($dir){
		global $zoom;
		// start the scan...(open the local dir)
		$images = array();
		$handle = fs_opendir($dir);
		while (($file = readdir($handle)) != false) {
			if ($file != "." && $file != "..") {
				$tag = ereg_replace(".*\.([^\.]*)$", "\\1", $file);
				$tag = strtolower($tag);
				if ($zoom->acceptableFormat($tag)) {
					// Tack it onto images...
					$images[] = $file;
				}
			}
		}
		closedir($handle);
		return $images;
	}
	function getImageLibs(){
		// do auto-detection on the available graphics libraries
		// This assumes the executables are within the shell's path
		$imageLibs= array();
		unset($output, $status);
		exec('convert -version', $output, $status);
		if(!$status){
			if(preg_match("/imagemagick[ \t]+([0-9\.]+)/i",$output[0],$matches))
			   $imageLibs['imagemagick'] = $matches[0];
		}
		unset($output, $status);
		exec('jpegtopnm -version 2>&1',  $output, $status);
		if(!$status){
			if(preg_match("/netpbm[ \t]+([0-9\.]+)/i",$output[0],$matches))
			   $imageLibs['netpbm'] = $matches[0];
		}
		unset($output, $status);
		exec('ffmpeg -h',  $output, $status);
		if(!empty($output[0])){
			if(preg_match("/ffmpeg[[:space:]]+/",$output[0],$matches)){
			   $imageLibs['ffmpeg'] = $matches[0];
			}
		}
		unset($output, $status);
		$GDfuncList = get_extension_funcs('gd');
		ob_start();
		@phpinfo(INFO_MODULES);
		$output=ob_get_contents();
		ob_end_clean();
		$matches[1]='';
		if(preg_match("/GD Version[ \t]*(<[^>]+>[ \t]*)+([^<>]+)/s",$output,$matches)){
			$gdversion = $matches[2];
		}
		if( $GDfuncList ){
		 if( in_array('imagegd2',$GDfuncList) )
			$imageLibs['gd2'] = $gdversion;
		 else
			$imageLibs['gd1'] = $gdversion;
		}
		return $imageLibs;
	}	
	//--------------------Error handling functions-------------------------//
	function displayErrors(){
        global $zoom;
		if ($this->_err_num <> 0){
			echo '<center><table border="0" cellpadding="3" cellspacing="0" width="70%">';
			echo '<tr class="sectiontableheader"><td width="100" align="left">Image Name</td><td align="left">Error type</td></tr>';
			$tabcnt = 0;
			for ($x = 0; $x <= $this->_err_num; $x++){
				echo '<tr class="'.$zoom->tabclass[$tabcnt].'" align="left"><td>'.$this->_err_names[$x].'</td><td align="left">'.$this->_err_types[$x].'</td></tr>';
				if ($tabcnt == 1){
	    			$tabcnt = 0;
				} else {
					$tabcnt++;
	    		}
			}
			echo "</table></center>";
		}
	}
	//--------------------END error handling functions----------------------//
}
