Location: PHPKode > projects > VideoDB > videodb/lib/smarty/custom/function.html_image.php
<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 * @author  Andreas Goetz   <hide@address.com>
 */

require_once('./lib/phpthumb/phpthumb.class.php');

/**
 * 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 <hide@address.com>
 * @author credits to Duda <hide@address.com> - 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()
 */

define(THUMB_CACHE_SOURCE, true);
define(THUMB_CACHE_TARGET, true);

function html_image_get_cache($tag, &$width, &$height)
{
    $res    = runSQL("SELECT * FROM ".TBL_CACHE." WHERE tag='".mysql_escape_string($tag)."'");

    if (count($res))
    {
        if (preg_match('/(\d+)x(\d+)/', $res[0]['value'], $m))
        {
            list($foo, $width, $height) = $m;
            return true;
        }
    }

    return false;
}

function html_image_put_cache($tag, $value)
{
    $res    = runSQL("REPLACE INTO ".TBL_CACHE." SET tag='".mysql_escape_string($tag)."', value='".mysql_escape_string($value)."'");
}

/**
 * Thumbnail generation
 */
function generate_thumbnail(&$file, &$width, &$height, $max_width, $max_height, $cache_tag)
{
    global $config;

    $thumb_cache_tag = $cache_tag.'_'.$max_width.'x'.$max_height;

    // the names of the existing or to-be created thumbnail- still missing dimensions
    $thumb_name = './cache/'.CACHE_THUMBS.'/'.
                    (($config['hierarchical']) ? substr($cache_tag, 0, 1).'/' : '').
                    $cache_tag;

    // did we already create this thumbnail?
    if (THUMB_CACHE_TARGET && html_image_get_cache($thumb_cache_tag, $width, $height))
    {
        // get updated filename
        $file        = $thumb_name.'_'.$width.'x'.$height.'.jpg';
        return;
    }

    // thumbnail not created yet
    $scale  = min($max_width/$width, $max_height/$height);
    $width  = round($width * $scale);
    $height = round($height * $scale);

    // really need to scale?
    $thumb_must_scale = (($config['thumbnail_level'] == TUMB_SCALE) ||
                         ($config['thumbnail_level'] == TUMB_REDUCE_ONLY && ($scale < 1)) ||
                         ($config['thumbnail_level'] > 1) && ($config['thumbnail_level'] < @filesize($file)));
#dump("scaling required: ".(int)$thumb_must_scale." filesize: "hide@address.com($file));

    // perform actual scaling
    if ($thumb_must_scale)
    {
        $phpThumb = new phpThumb();

        $phpThumb->sourceFilename = $file;
        $phpThumb->w = $max_width;
        $phpThumb->h = $max_height;
        if ($config['thumbnail_quality']) $phpThumb->q = $config['thumbnail_quality'];

        // set cache filename
        $thumb_name .= '_'.$width.'x'.$height.'.jpg';
#dump("thumbname:$thumb_name");

        // check to see if file already exists in cache, and output it with no processing if it does
        if (is_writable(dirname($thumb_name)) || is_writable($thumb_name))
        {
            if (@filesize($thumb_name) ||
               ($phpThumb->GenerateThumbnail() && $phpThumb->RenderOutput() &&
                file_put_contents($thumb_name, $phpThumb->outputImageData)))
            {
                $file = $thumb_name;
                if (THUMB_CACHE_TARGET) html_image_put_cache($thumb_cache_tag, $width.'x'.$height);
            }
        }

        // free memory
        $phpThumb = null;
    }
}

function smarty_function_html_image($params, &$smarty)
{
    global $config;

    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':
            	// hide@address.com 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;
    }

    $_image_path = (substr($file,0,1) == '/') ? $basedir.$file : $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);
        }
        // hide@address.com checking for non-local images
        elseif (preg_match("/nocover|^(http:|img\.php)/", $_image_path))
        {
            $no_scaling = true;
        }
        else
        {
            // do we already know this image?
            $cache_tag = md5($_image_path);

            if (!(THUMB_CACHE_SOURCE && html_image_get_cache($cache_tag, $width, $height)))
            {
                if ($_image_data = @getimagesize($_image_path)) {
                    if (!isset($params['width'])) $width = $_image_data[0];
                    if (!isset($params['height'])) $height = $_image_data[1];
                    if (THUMB_CACHE_SOURCE) html_image_put_cache($cache_tag, $width.'x'.$height);
#dump("cache commit: $width $height");
                }
                else {
                    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 (empty($width)) $width = $max_width;
        if (empty($height)) $height = $max_height;

        /*
         * Scaling is required if:
         * - scale mode TUMB_SCALE
         * - scale mode TUMB_REDUCE_ONLY and dimensions > target dimensions
         * - scale mode is any other numeric and filesize > scale mode
         */
        if ($max_width && $max_height && !$no_scaling)
        {
            // even if thumbnails are not generated we should get aspect ratio right
            if ($config['thumbnail_level'] == TUMB_NO_SCALE)
            {
                $scale  = min($max_width/$width, $max_height/$height);
                $width  = round($width * $scale);
                $height = round($height * $scale);
            }
            else
            {
                generate_thumbnail($file, $width, $height, $max_width, $max_height, $cache_tag);
            }
        }
    }

    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;
    if (isset($border)) $result    .= '" border="'.$border;
	if ($width) $result     .= '" width="'.$width;
	if ($height) $result    .= '" height="'.$height;
	$result .= '"'.$extra.' />' . $suffix;

	return $result;
}

/* vim: set expandtab: */

?>
Return current item: VideoDB