<?php
/**
 * Displays an image and allows modifications if required.
 *
 * Copyright 2003 Marko Djukic <marko@oblo.com>
 *
 * See the enclosed file COPYING for license information (GPL). If you did not
 * receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * $Horde: horde/util/img.php,v 1.3 2003/08/20 22:49:11 mdjukic Exp $
 *
 * @author Marko Djukic <marko@oblo.com>
 * @version $Revision: 1.3 $
 */

@define('HORDE_BASE', dirname(__FILE__) . '/..');
require_once HORDE_BASE . '/lib/base.php';

/* Get file info. */
$file = basename(Horde::getFormData('f'));
$type = Horde::getFormData('t');
$source = Horde::getFormData('s', 'tmp');
$name = Horde::getFormData('n', $file);
$action = Horde::getFormData('a');
if (empty($type)) {
    require_once HORDE_BASE . '/lib/MIME/Magic.php';
    $type = MIME_Magic::filenameToMIME($name);
}

switch ($source) {
case 'tmp':
    /* Getting a file from Horde's temp dir. */
    $tmpdir = Horde::getTempDir();
    if (empty($action)) {
        $file_name = $tmpdir . '/' . $file;
    } else {
        $file_name = $tmpdir . '/mod_' . $file;
        if (!file_exists($file_name)) {
            copy($tmpdir . '/' . $file, $file_name);
        }
    }
    $size = filesize($file_name);
    $fp = @fopen($file_name, 'r');
    $file_data = fread($fp, $size);
    fclose($fp);
    break;
}

/* Check if no editing action required and send the image to browser. */
if (empty($action)) {
    $browser->downloadHeaders($name, $type, false, $size);
    echo $file_data;
}

/* Image editing required. */
require_once HORDE_BASE . '/lib/Image.php';
$image = &Horde_Image::singleton('gd');
$image->loadString($file, $file_data);

switch ($action) {
case 'rotate';
    $image->rotate(Horde::getFormData('v'));
    break;
case 'flip';
    $image->flip();
    break;
case 'mirror';
    $image->mirror();
    break;
case 'grayscale';
    $image->grayscale();
    break;
}

/* Write out to the temporary file the image modifications. */
$fp = @fopen($file_name, 'wb');
fwrite($fp, $image->raw());
fclose($fp);

$image->display();
