<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 * @author  Andreas Goetz   <cpuidle@gmx.de>
 */


/**
 * Smarty {html_image} function plugin
 *
 * Type:     function<br>
 * Name:     html_image<br>
 * Date:     Feb 24, 2003<br>
 * Purpose:  format HTML tags for the image<br>
 * Input:<br>
 *         - file = file (and path) of image (required)
 *         - border = border width (optional, default 0)
 *         - height = image height (optional, default actual height)
 *         - image =image width (optional, default actual width)
 *         - basedir = base directory for absolute paths, default
 *                     is environment variable DOCUMENT_ROOT
 *
 * Examples: {html_image file="images/masthead.gif"}
 * Output:   <img src="images/masthead.gif" border=0 width=400 height=23>
 * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image}
 *      (Smarty online manual)
 * @author   Monte Ohrt <monte@ispi.net>
 * @author credits to Duda <duda@big.hu> - wrote first image function
 *           in repository, helped with lots of functionality
 * @version  1.0
 * @param array
 * @param Smarty
 * @return string
 * @uses smarty_function_escape_special_chars()
 */
function smarty_function_html_image($params, &$smarty)
{
    require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
    
    $alt = '';
    $file = '';
    $border = 0;
    $height = '';
    $width = '';
    $extra = '';
    $prefix = '';
    $suffix = '';
    $server_vars = ($smarty->request_use_auto_globals) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
    $basedir = isset($server_vars['DOCUMENT_ROOT']) ? $server_vars['DOCUMENT_ROOT'] : '';
    foreach($params as $_key => $_val) {
        switch($_key) {
            case 'file':
            case 'border':
            case 'height':
            case 'width':
            case 'dpi':
            case 'basedir':
            case 'max_width':
            case 'max_height':
                $$_key = $_val;
                break;

            case 'alt':
                if(!is_array($_val)) {
                    $$_key = smarty_function_escape_special_chars($_val);
                } else {
                    $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;

            case 'link':
            case 'href':
            	// cpuidle@gmx.de suppress hrefs without link
            	if (!empty($_val)) {
                $prefix = '<a href="' . $_val . '">';
                $suffix = '</a>';
				}
                break;

            default:
                if(!is_array($_val)) {
                    $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
                } else {
                    $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;
        }
    }

    if (empty($file)) {
        $smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
        return;
    }

    if (substr($file,0,1) == '/') {
        $_image_path = $basedir . $file;
    } else {
        $_image_path = $file;
    }

    if(!isset($params['width']) || !isset($params['height'])) {
        if ($smarty->security &&
            ($_params = array('resource_type' => 'file', 'resource_name' => $_image_path)) &&
            (require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.is_secure.php')) &&
            (!smarty_core_is_secure($_params, $smarty)) ) {
            $smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE);

        } 
        // cpuidle@gmx.de checking for non-local images
        elseif (!preg_match("/^(http:|img\.php)/", $_image_path)) {
        	if (!$_image_data = @getimagesize($_image_path)) {
	            if(!file_exists($_image_path)) {
	                $smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
	                return;
	            } else if(!is_readable($_image_path)) {
	                $smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
	                return;
	            } else {
	                $smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
	                return;
	            }
        	}
        }

        if (!isset($params['width'])) {
            $width = $_image_data[0];
        }
        if (!isset($params['height'])) {
            $height = $_image_data[1];
        }
        
        // cpuidle@gmx.de add scaling
        if ($max_width && $max_height)
        {
           	// cpuidle@gmx.de scale images correctly
        	if (!(empty($width) || empty($height)))
        	{
				// nothing should be 0 now
				if ($width > $max_width) {
					$height = round($height * $max_width / $width);
					$width = $max_width;
				} 
                if ($height > $max_height) {
					$width = round($width * $max_height / $height);
					$height = $max_height;
				}

                // created cached thumbnail
                $config = $GLOBALS['config'];
                if (!empty($config['thumbnail_module']))
                {
                    $cache_directory = './cache/thumbs';
                    
                    // always create thumbnails?
                    $thumb_must_scale = ($config['thumbnail_level'] === -1);
                    
                    // check if filesize demands thumbnail
                    if (!empty($config['thumbnail_level']) &! $thumb_must_scale)
                    {
                        $size = @filesize($file);
                        $thumb_must_scale = $size > $config['thumbnail_level'];
                    }

                    // perform actual scale
                    if (($thumb_must_scale || $width < $_image_data[0] || $height < $_image_data[1]) && 
                         include_once($config['thumbnail_module'].'phpthumb.class.php'))
                    {
                        $phpThumb = new phpThumb();
                        $phpThumb->config_cache_directory = $cache_directory;
                        $phpThumb->sourceFilename = $file;

                        // extract md5 hash from cache file name to ensure unique thumbnail identifiers are created
                        $filepath = preg_split("/\/|\./", $file);
                        $phpThumb->src = $filepath[count($filepath)-2];

                        $phpThumb->w = $width;
                        $phpThumb->h = $height;
                        if (!empty($config['thumbnail_quality'])) 
                        {
                            $phpThumb->q = $config['thumbnail_quality'];
                        }

                        // get nice cache filename
                        $phpThumb->SetCacheFilename();
                        $phpThumb->cache_filename .= '.jpg';

                        // check to see if file already exists in cache, and output it with no processing if it does
                        if (is_file($phpThumb->cache_filename)) 
                        {
                            $file = $phpThumb->cache_filename;
                        }
                        elseif ((file_exists($phpThumb->cache_filename) && is_writable($phpThumb->cache_filename)) || is_writable(dirname($phpThumb->cache_filename)))
                        {
                            $phpThumb->GenerateThumbnail();
                            $phpThumb->RenderToFile($phpThumb->cache_filename);
                            $file = $phpThumb->cache_filename;
                        }

                        // work around phpThumb's funny name creation (fixes FireFox issue)
                        $file = str_replace('\\', '/', $file);

                        // added for phpThumb 1.5 to translate local path into document root
                        $file = $cache_directory.'/'.preg_replace('/^.*\/(.*)/', '$1', $file);
                        
                        // free memory
                        $phpThumb = null;
                    }
                }
	        } else {
	        	if (empty($width)) $width = $max_width;
	        	if (empty($height)) $height = $max_height;
	        }
        }

    }

    if(isset($params['dpi'])) {
        if(strstr($server_vars['HTTP_USER_AGENT'], 'Mac')) {
            $dpi_default = 72;
        } else {
            $dpi_default = 96;
        }
        $_resize = $dpi_default/$params['dpi'];
        $width = round($width * $_resize);
        $height = round($height * $_resize);
    }

	$result = $prefix . '<img src="'.$file.'" alt="'.$alt.'" border="'.$border;
	if (isset($width)) $result .='" width="'.$width;
	if (isset($height)) $result .= '" height="'.$height;
	$result .= '"'.$extra.' />' . $suffix;
	return $result;
}

/* vim: set expandtab: */

?>
