<?php

/*
** Fishlib - a collection of utilities for db-driven applications in PHP
** Copyright (C) 2002  LTWD, LLC DBA The Madfish Group
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library 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
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

require_once('fishbase.class.php');
if (!
defined('Image_DefaultThumbWidth'))
    
define('Image_DefaultThumbWidth'100);
class 
FishImage extends FishBase
{
    var 
$image NULL;
    var 
$width NULL;
    var 
$height NULL;
    var 
$src NULL;
    var 
$alt NULL;

    var 
$src_dir '/images/';
    var 
$file_dir NULL;
    var 
$file NULL;

    function 
__construct()
    {
        
$args func_get_args();
        
$this->constructor($args);
    }

    function 
FishImage()
    {
        
$args func_get_args();
        
$this->constructor($args);
    }
    
    function 
constructor($args)
    {
        
parent::constructor($args);
    
        if (empty(
$this->file_dir))
        {
            
$this->file_dir $this->src_dir;
        }
        if (!(
$realdir makepath($this->file_dir,TRUE)))
        {
            
$private_error 'image: could not find or create path '
                
$this->file_dir
            
;
            
user_error('Error initializing Image class'E_USER_ERROR);
        }
        
$this->file_dir $realdir;
    }

// upload file to file_dir 
    
function upload($fieldname='imagefile'$file=NULL$alt=NULL)
    {
        
$errormsg 'Could not upload image file';
        
$img array_key_value($_FILES$fieldnameNULL);
        if (empty(
$img))
        {
            
$private_error "No entry found in _FILES for field $fieldname";
            
user_error($errormsgE_USER_WARNING);
            return 
FALSE;
        }
        if (
$img['error'])
        {
            switch (
$img['error'])
            {
                case 
UPLOAD_ERR_INI_SIZE:
                    
$private_error 'exceeded upload_max_filesize='
                        
ini_get('upload_max_filesize')
                    ;
                    
$errormsg .= ' : file too large';
                    break;
                case 
UPLOAD_ERR_FORM_SIZE:
                    
$private_error 'exceeded MAX_FILE_SIZE='
                        
array_key_value($_POST,'MAX_FILE_SIZE','NotDefined')
                    ;
                    
$errormsg .= ' : file too large';
                    break;
                case 
UPLOAD_ERR_PARTIAL:
                    
$private_error 'file only partially uploaded';
                    
$errormsg .= ' : file partially uploaded - you may want to try again';
                    break;
                case 
UPLOAD_ERR_PARTIAL:
                    
$private_error 'no file uploaded';
                    
$errormsg .= ' : file not uploaded - check for problems with your image file';
                    break;
                default:
                    
$private_error 'unknown error code';
            }
            
$private_error 'File upload error: '
                
$private_error
                
' img='
                
var_export($imgTRUE)
            ;
            
user_error($errormsgE_USER_WARNING);
            return 
FALSE;
        }
        if (empty(
$file))
        {
            
$this->image $img['name'];
        }
        else
        {
            
$this->image $file;
        }
        
$this->image preg_replace(
            array(
'/[\s]/','/[^a-z0-9\.\-\_]/')
            , array(
'_','')
            , 
strtolower(basename($this->image))
        );
        
$this->file $this->file_dir.DIRECTORY_SEPARATOR.$this->image;
        if (!
move_uploaded_file($img['tmp_name'],$this->file))
        {
            
$private_error 'File upload error: error moving temp file: '
                
' img='
                
var_export($imgTRUE)
                . 
' this->file='
                
$this->file
            
;
            
user_error($errormsgE_USER_WARNING);
            return 
FALSE;
        }
        if (!
$this->getsizes())
        {
            return 
FALSE;
        }
        if (empty(
$alt))
        {
            
$this->alt $this->image;
        }
        else
        {
            
$this->alt $alt;
        }
        return 
TRUE;
    }

    function 
getsizes()
    {
        if (!
$this->file)
            return 
TRUE;


        
$imgsize getimagesize($this->file);
        if (!
$imgsize)
        {
            
$private_error 'Image file error: getimagesize failed: '
                
' this->file='
                
$this->file
            
;
            
$errormsg .= ' Problem with image file - check your original file for errors.';
            
user_error($errormsgE_USER_WARNING);
            return 
FALSE;
        }
        if (!
$this->width && !$this->height)
        {
            if (!
$imgsize[0] || !$imgsize[1])
            {
                
$private_error 'Image error: zero height or width : '
                    
' imgsize='
                    
var_export($imgsizeTRUE)
                    . 
' this->file='
                    
$this->file
                
;
                
$errormsg .= ' Problem with image file - check your original file for errors.';
                
user_error($errormsgE_USER_WARNING);
                return 
FALSE;
            }
            
$this->width $imgsize[0];
            
$this->height $imgsize[1];
        }
        
$this->type $imgsize[2];
        
$this->mimetype $imgsize['mime'];
        return 
TRUE;
    }

    function 
make_thumbnail()
    {
        if (!
$this->check())
        {
            return 
FALSE;
        }
        
$self get_class($this);
        
$this->thumb = new $self(array('width'=>Image_DefaultThumbWidth));
        
$args func_get_args();
        
call_user_func_array(array($this->thumb,'build'),$args);
        if (
$this->width && $this->height 0)
        {
            if (!
$this->thumb->width && $this->thumb->height)
            {
                
$this->thumb->width = (int)$this->thumb->height * ($this->width/$this->height);
            }
            elseif (!
$this->thumb->height && $this->thumb->width)
            {
                
$this->thumb->height = (int)$this->thumb->width * ($this->height/$this->width);
            }
        }
        if (empty(
$this->thumb->image))
        {
            
$this->thumb->image preg_replace(
                
'/(\.[^\.]*)$/'
                
'_thumb\\1'
                
$this->image
            
);
        }
        
$this->thumb->file $this->file_dir.DIRECTORY_SEPARATOR.$this->thumb->image;
        
umask(2);
        
$result TRUE;
        switch (
TRUE)
        {
            
// once one of these cases evaluates to TRUE, the rest are
            // skipped
            
case $this->make_exif_thumbnail():
            case 
$this->make_gd_thumbnail():
            case 
$this->make_dumb_thumbnail():
                break;
            default:
                
user_error('Could not create thumbnail of '.$this->imageE_USER_WARNING);
                
$result FALSE;
        }
        return 
$result;
    }

    function 
make_exif_thumbnail()
    {
        if (!
extension_loaded('exif'))
            return 
FALSE;

        
$type exif_imagetype($this->file);
         if (
$type == IMAGETYPE_JPEG || $type == IMAGETYPE_TIFF_II 
            
|| $type == IMAGETYPE_TIFF_MM
        
)
        {
             
$th exif_thumbnail($this->file);
            if (
$th !== FALSE)
            {
                
$fd fopen($this->thumb->file,'w');
                
fwrite($fd$th);
                
fclose($fd);
                if (
$this->thumb->getsizes())
                {
                    return 
TRUE;
                }
            }
        }
        return 
FALSE;
    }

    function 
make_gd_thumbnail()
    {
        if (!
extension_loaded('gd') || !(imagetypes() & $this->type))
            return 
FALSE;
        
$buf file_get_contents($this->fileTRUE);
        
$img imagecreatefromstring($buf);
        if (!
$img)
        {
            return 
FALSE;
        }
        
$timg imagecreate($this->thumb->width,$this->thumb->height);
        
$src_x 0;
        
$src_y 0;
        
$src_width imagesx($img);
        
$src_height imagesy($img);
        
$dst_x 0;
        
$dst_y 0;
        
$dst_width $this->thumb->width;
        
$dst_height $this->thumb->height;
        
imagecopyresized($timg$img$dst_x$dst_y$src_x$src_y
            
$dst_width$dst_height$src_width$src_height
        
);
        
$this->thumb->image preg_replace(
            
'/(\.[^\.]*)$/'
            
'_thumb.png'
            
$this->image
        
);
        
$this->thumb->file $this->file_dir.DIRECTORY_SEPARATOR.$this->thumb->image;
        if (!
imagepng($timg$this->thumb->file))
        {
            return 
FALSE;
        }
        return 
TRUE;
    }

    function 
make_dumb_thumbnail()
    {
        
$this->thumb->width Image_DefaultThumbWidth;
        
$this->thumb->height = (int)$this->thumb->width * ($this->height/$this->width);
        return 
copy($this->file,$this->thumb->file);
    }

    function 
check()
    {
        if (empty(
$this->image))
        {
            return 
FALSE;
        }
        
$this->file $this->file_dir.DIRECTORY_SEPARATOR.$this->image;
        if (empty(
$this->type))
        {
            if (!
$this->getsizes())
            {
                return 
FALSE;
            }
        }
        
$this->src preg_replace('|//*|','/',$this->src_dir.'/'.$this->image);
        if (empty(
$this->alt))
        {
            
$this->alt $this->image;
        }
        return 
TRUE;
    }

    function 
thumbnail($href=NULL)
    {
        if (empty(
$this->thumb))
        {
            if (!
$this->make_thumbnail())
            {
                
$width $this->width;
                
$height $this->height;
                
$this->width Image_DefaultThumbWidth;
                
$this->height 0;
                
$output $this->tag($href);
                
$this->width $width;
                
$this->height $height;
                return 
$output;
            }
        }
        return 
$this->thumb->tag($href);
    }

    function 
tag($href=NULL)
    {
        if (!
$this->check())
        {
            return 
FALSE;
        }
        
$props = array(
            
'src' => $this->src
            
'border' => 0
        
);
        if (
$this->height) { $props['height'] = $this->height; }
        if (
$this->width) { $props['width'] = $this->width; }
        
$props['alt'] = $href $href $this->alt;
        
$output image_tag($props);
        if (
$href)
        {
            
$output anchor_tag($href,$output);
        }
        return 
$output;
    }
}
?>