<?php

set_time_limit(0);

require $_SERVER["DOCUMENT_ROOT"] . "/api/simple_image_class.php";

function smarty_function_images_resize($data)
{
    $content = $data['content'];

    function xreplace($matches)
    {
    	 
        $imgSrcs = array();
        $imgAlts = array();

        foreach ($matches as $img_tag)
        {
            preg_match_all('/(src)=("[^"]*")/i', $img_tag, $imgSrcs[$img_tag]);
            preg_match_all('/(alt)=("[^"]*")/i', $img_tag, $imgAlts[$img_tag]);
        }

        $srcImg = str_replace(array(
            '"',
            "'",
            'http://',
            'http://',
            $_SERVER['HTTP_HOST']), '', $imgSrcs[$img_tag][2][0]);

        $altImg = str_replace(array('"', "'"), '', $imgAlts[$img_tag][2][0]);
        
        $srcImg = str_replace('%20', ' ', $srcImg);

        $rootPath = $_SERVER['DOCUMENT_ROOT'];
        $imgPath = $rootPath . $srcImg;
        $tmbPath = $rootPath . '/thumbs' . $srcImg;
        $imgSize = getimagesize($imgPath);
        $imgWidth = $imgSize[0];
        $imgHeight = $imgSize[1];
        $limitSize = 480; //px

        if ( (substr($srcImg, 0, 1) == '/') and (($imgWidth > $limitSize) or ($imgHeight > $limitSize)) )
        {
            try
            {
                if (!file_exists($tmbPath))
                {
                    $img = new SimpleImage($imgPath);
                    $pathinfo = pathinfo($srcImg);

                    if (!file_exists($rootPath . '/thumbs' . $pathinfo['dirname']))
                    {
                        mkdir($rootPath . '/thumbs' . $pathinfo['dirname'], 0755, true);
                    }

                    $img->best_fit($limitSize, ($limitSize / 4 * 3))->save($tmbPath, 75);
                    $img = null;
                }

                return '<a class="fancybox" data-rel="details" href="' . $srcImg . '"><img src="' . '/thumbs' . $srcImg . '" alt="' . $altImg . '" class="img-thumbnail w"></a>' . "\n";
            }
            catch (exception $e)
            {
                echo '<!-- exception: ', $e->getMessage(), " -->\n";
                return '<img src="' . $srcImg . '" alt="' . $altImg . '" class="img-thumbnail w">' . "\n";
            }

        }
        else
        {
            return '<img src="' . $srcImg . '" alt="' . $altImg . '" class="img-thumbnail w">' . "\n";
        }

    }

    $content = preg_replace_callback('/<img[^>]+>/i', 'xreplace', $content);

    return $content;
}

?>