<?php
  /**************************************************************************\
  * phpGroupWare - Image Editor                                              *
  * http://www.phpgroupware.org                                              *
  * This application written by Miles Lott <milosch@phpgroupware.org>        *
  * --------------------------------------------                             *
  * some methods borrowed from OIC v1.0.6 - the Online Image Converter       *
  *   Copyright (C) 2001 Ray Lopez (http://www.TheDreaming.com)              *
  * --------------------------------------------                             *
  *  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.                                              *
  \**************************************************************************/

  /* $Id: class.img.inc.php,v 1.6 2001/12/18 18:18:24 milosch Exp $ */

	/* Image conversion and manipulation class */
	class img
	{
		var $debug = False;
		var $tmpfile = '';
		var $tmpdir = '';
		/*
		  Note, GD supports WBMP. This is not the Windoze bitmap format, but
		  the monochrome bitmaps used in PDAs, etc.
		  */
		var $convertArray = array('Please select','GIF','JPG','PNG','WBMP');
		var $angles       = array();
		/*
		  This is the function to be used for resize, etc.
		  A check is done in the constructor for the nicer function available in gd 2.X.
		  Since there is no way to really check, make sure your gd version is correct in admin.
		*/
		var $icr = 'imagecopyresized';

		/*
		  This setting is used to call convert.  This is the default.
		  Used for rotate, and for conversion if no internal GIF support available.
		*/
		var $convertcmd   = '/usr/X11R6/bin/convert';

		function img($debug=False)
		{
			$this->debug   = $debug;
			$this->angles  = array(lang('Please select'),'90','180','270');
			$this->docroot = $GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'];

			if(!function_exists('imagecreate'))
			{
				echo 'No GD support in this PHP install!';
				exit;
			}

			$this->tmpdir  = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
			$this->urlbase = $GLOBALS['phpgw_info']['server']['webserver_url'] . '/img/images/';

			/*
			  Set the location of the convert command.
			*/
			$config = CreateObject('phpgwapi.config','img');
			$config->read_repository();
			$current_config = $config->config_data;
			$this->convertcmd = $current_config['convert_cmd'] ? $current_config['convert_cmd'] : $this->convertcmd;

			if($current_config['gd_version'] >= 2)
			{
				$this->icr = 'imagecopyresampled';
			}
		}

		function smartcopy($src,$dest)
		{
			$srctype  = $this->img_type($src);
			$desttype = $this->img_type($dest);
			if($this->debug)
			{
				echo '<br>smartcopy()' . "\n";
				echo '<br>Source file: ' . $src . "\n";
				echo '<br>Target file: ' . $dest . "\n";
				echo '<br>Source type: ' . $srctype . "\n";
				echo '<br>Target type: ' . $desttype . "\n";
			}

			if($srctype == $desttype)
			{
				copy($src,$dest);
				unlink($src);
				return $dest;
			}
			else
			{
				switch ($srctype)
				{
					case '1':
						$ext = 'gif';
						break;
					case '2':
						$ext = 'jpg';
						break;
					case '3':
						$ext = 'png';
						break;
					case '4':
						$ext = 'bmp';
				}
				switch ($desttype)
				{
					case '1':
						$oldext = 'gif';
						break;
					case '2':
						$oldext = 'jpg';
						break;
					case '3':
						$oldext = 'png';
						break;
					case '4':
						$oldext = 'bmp';
				}
				$newdest = ereg_replace("\.$oldext",".$ext",$dest);
				if($this->debug)
				{
					echo '<br>Old ext: ' . $oldext . "\n";
					echo '<br>New ext: ' . $ext . "\n";
					echo '<br>NEW Target file: ' . $newdest . "\n";
				}
				copy($src,$newdest);
				unlink($tmpfile);
				return $newdest;
			}
		}

		function img_type($imgfile)
		{
			$imgarray = getimagesize($imgfile);
			if($this->debug)
			{
				echo '<br>img->img_type(): ' . $imgfile . "\n";
				_debug_array($imgarray);
			}
			return $imgarray[2];
		}

		/* Save the temporary file into the document tree, or wherever */
		function save($imagefile,$dest='',$extra='')
		{
			$imagefile = ereg_replace($this->tmpdir,'',$imagefile);
			if($dest)
			{
				$dest = ereg_replace($this->tmpdir,'',$dest);
				$destfile = $dest;
				$dest = PHPGW_APP_ROOT . SEP . 'images' . SEP . $destfile . $extra;
			}
			else
			{
				$destfile = $imagefile;
				$dest = PHPGW_APP_ROOT . SEP . 'images' . SEP . $destfile . $extra;
			}
			$url = $this->urlbase . $destfile . $extra;
			if($this->debug)
			{
				echo '<br>img->save(): ' . $this->tmpdir . $imagefile . ' as ' . $dest;
			}
			copy($this->tmpdir . $imagefile,$dest);
			return $url;
		}

		/* Create a tmp filename */
		function tmp_file($name='phpgwimg_')
		{
			srand((double)microtime()*1000000);
			return($this->tmpdir . $name . rand(1,100000));
		}

		/* format conversion routines */
		function image2jpg($im,$dest='')
		{
			if (imagetypes() & IMG_JPG)
			{
				$filename = $this->tmp_file() . '.jpg';
				imagejpeg($im, $filename);
				if($this->debug)
				{
					echo '<br>img->image2jpg(): calling img->save(' . $filename . ',' . $dest . ')';
				}
				return $this->save($filename,$dest);
			}
		}

		function image2gif($im,$dest='')
		{
			if (imagetypes() & IMG_GIF)
			{
				$filename = $this->tmp_file() . '.gif';
				imagegif($im, $filename);
				if($this->debug)
				{
					echo '<br>img->image2gif(): calling img->save(' . $filename . ',' . $dest . ')';
				}
				return $this->save($filename,$dest);
			}
			else
			{
				$filename = $this->tmp_file() . '.png';
				imagepng($im, $filename);

				/* Try to call convert to do this, maybe it can handle gif */
				if($this->debug)
				{
					echo '<br>img->image2gif: calling img->_convert(' . $filename . ",''," . 'gif)';
				}
				return $this->_convert($filename,'','gif');
			}
		}

		function image2bmp($im,$dest='')
		{
			if (imagetypes() & IMG_WBMP)
			{
				$filename = $this->tmp_file() . '.bmp';
				imagewbmp($im, $filename);
				if($this->debug)
				{
					echo '<br>img->image2bmp(): calling img->save(' . $filename . ',' . $dest . ')';
				}
				return $this->save($filename,$dest);
			}
		}

		function image2png($im,$dest='')
		{
			if (imagetypes() & IMG_PNG)
			{
				$filename = $this->tmp_file() . '.png';
				imagepng($im, $filename);
				if($this->debug)
				{
					echo '<br>img->image2png(): calling img->save(' . $filename . ',' . $dest . ')';
				}
				return $this->save($filename,$dest);
			}
		}

		/* Create a scaled thumbnail image */
		function thumbnail($im,$width,$height,$dstW=100,$format='jpg')
		{
			$filename = $this->tmp_file() . '.' . $format;
			$dstH = $this->_get_thumbsize($width,$height,$dstW);

			/* Create a new image handle */
			$newim = imagecreate($dstW,$dstH);
			if($this->debug)
			{
				echo '<br>img->thumbnail(): calling img->_resize($newim,$im,"'
					. $dstX . '","' . $dstY . '","' . $srcX . '","' . $srcY . '","'
					. $dstW . '","' . $dstH . '","' . $width . '","' . $height
					. '","' . $filename . '","' . $format . '")';
			}
			return ($this->_resize($newim,$im,$dstX,$dstY,$srcX,$srcY,$dstW,$dstH,$width,$height,$filename,$format));
		}

		/* Resize an image */
		function resize($im,$width,$height,$dstW,$dstH,$format='png')
		{
			$filename = $this->tmp_file();
			$newim = imagecreate($dstW,$dstH);
			if($this->debug)
			{
				echo '<br>img->resize(): calling img->_resize($newim,$im,0,0,0,0,"'
					. $dstW . '","' . $dstH . '","' . $width . '","' . $height
					. '","' . $filename . '","' . $format . '")';
			}
			return ($this->_resize($newim,$im,0,0,0,0,$dstW,$dstH,$width,$height,$filename,$format));
		}

		/* Crop an image using upper left corner and size attributes */
		function crop($im,$width,$height,$dstW,$dstH,$srcX,$srcY,$format='png')
		{
			$filename = $this->tmp_file() . '.' . $format;
			$newim = imagecreate($dstW,$dstH);

			$cmd = $this->icr . '($newim,$im,$dstX,$dstY,$srcX,$srcY,$dstW,$dstH,$width,$height);';
			eval($cmd);
			if($this->debug)
			{
				echo '<br>img->crop(): calling img->_resize($newim,$im,"'
					. $dstX . '","' . $dstY . '","' . $srcX . '","' . $srcY . '","'
					. $dstW . '","' . $dstH . '","' . $width . '","' . $height
					. '","' . $filename . '","' . $format . '")';
			}
			return ($this->_resize($newim,$im,$dstX,$dstY,$srcX,$srcY,$dstW,$dstH,$width,$height,$filename,$format));
		}

		/* This one is special.  It uses the convert command (part of ImageMagick). */
		function rotate($im,$angle=90)
		{
			if($this->convertcmd)
			{
				$tmpfile = $this->tmp_file('phpgwimg_rot_');
				if (imagetypes() & IMG_PNG)
				{
					imagepng($im, $tmpfile);
					$ext = '.png';
				}
				else
				{
					imagejpeg($im, $tmpfile);
					$ext = '.jpg';
				}

				if(@stat($tmpfile))
				{
					$tmp = $this->tmp_file('phpgwimg_rot_');
					$cmd = $this->convertcmd . ' ' . $tmpfile . ' -rotation ' . $angle . ' ' . $tmp;
					if($this->debug)
					{
						echo '<br>img->rotate(): ' . $cmd;
					}
					passthru($cmd);
					if($this->debug)
					{
						echo '<br>img->rotate(): calling img->save(' . $tmp . ",''," . $ext . ')';
					}
					return $this->save($tmp,'',$ext);
				}
			}
		}

		/* Used mainly for gif support */
		function convert($src,$type)
		{
			$dest = ereg_replace("\.gif",".$type",$src);
			$cmd  = $this->convertcmd . ' ' . $src . ' ' . $dest;
			if($this->debug)
			{
				echo '<br>img->convert(): ' . $cmd;
			}
			passthru($cmd);

			return $dest;
		}

		function _convert($src,$dest='',$type='')
		{
			if($type)
			{
				if($dest)
				{
					$tmp = ereg_replace($this->tmpdir,'',$dest);
				}
				else
				{
					$tmp = $this->tmp_file() . '.' . $type;
				}
				$cmd = $this->convertcmd . ' ' . $src . ' ' . $tmp;
				if($this->debug)
				{
					echo '<br>img->_convert(): ' . $cmd;
				}
				passthru($cmd);
				if($this->debug)
				{
					echo '<br>img->_convert(): calling img->save(' . $tmp . ')';
				}
				return $this->save($tmp,'');
			}
		}

		/* Called by crop() and thumbnail() to check valid formats, resize, and save an image */
		function _resize($newim,$im,$dstX,$dstY,$srcX,$srcY,$dstW,$dstH,$width,$height,$filename,$format)
		{
			$cmd = $this->icr . '($newim,$im,$dstX,$dstY,$srcX,$srcY,$dstW,$dstH,$width,$height);';
			eval($cmd);
			switch ($format)
			{
				case 'bmp':
					if (imagetypes() & IMG_WBMP)
					{
						imagewbmp($newim, $filename);
					}
					break;
				case 'gif':
					if (imagetypes() & IMG_GIF)
					{
						imagegif($newim, $filename);
					}
					else
					{
						imagepng($newim, $filename);
						copy ($filename,$filename . '.png');
						unlink($filename);
						if($this->debug)
						{
							echo '<br>img->_resize(): calling img->_convert(' . $filename . '.png' . ",''," . 'gif)';
						}
						$this->_convert($filename . '.png','','gif');
					}
					break;
				case 'jpg':
					if (imagetypes() & IMG_JPG)
					{
						imagejpeg($newim, $filename);
					}
					break;
				case 'png':
				default:
					if (imagetypes() & IMG_PNG)
					{
						imagepng($newim, $filename);
					}
			}
			if($this->debug)
			{
				echo '<br>img->_resize(): calling img->save(' . $filename . ')';
			}
			return $this->save($filename);
		}

		/* Calculate thumbnail image height using width and original image size */
		function _get_thumbsize($width,$height,$newW='100')
		{
			$mult  = $width / $newW;
			$newH  = round($height / $mult);
			return $newH;
		}
	}
?>
