<?PHP
#
#   FILE:  ViewImage.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2015 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

/**
* Output the bytes of the file to the browser.
* @param string $Path Path to the file.
*/
function OutputFile($Path)
{
    $Handle = @fopen($Path, "rb");

    if (FALSE === $Handle)
    {
        # couldn't open the file, just return to avoid further errors
        return;
    }

    while (!feof($Handle))
    {
        # send the file in 500 KB chunks
        echo fread($Handle, 512000);
        flush();
    }

    fclose($Handle);
}

/**
* Set a 404 header, to be used for errors.
*/
function Set404()
{
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
}

# ----- MAIN -----------------------------------------------------------------

# close the session to avoid serializing image loads
session_write_close();
$GLOBALS["AF"]->SuppressHTMLOutput();

# make sure required parameters are specified
if (!isset($_GET["RI"]) || !isset($_GET["FI"]) ||
    !isset ($_GET["IX"]) || !isset($_GET["T"]))
{
    Set404();
    return;
}

# pull out the requested resource
if (!Resource::ItemExists($_GET["RI"]))
{
    Set404();
    return;
}
$Resource = new Resource($_GET["RI"]);

# pull out the requested field
$Schema = new MetadataSchema($Resource->SchemaId());
$Field = $Schema->GetField($_GET["FI"]);

if ($Field == NULL)
{
    Set404();
    return;
}

# be sure the user can view this image
if (!$Resource->UserCanViewField($GLOBALS["G_User"], $Field))
{
    Set404();
    return;
}

# pull out requested index
$Index = intval($_GET["IX"]);

# retrieve images for this field
$Images = $Resource->Get($Field, TRUE);
if (count($Images) < $Index)
{
    $GLOBALS["AF"]->SetJumpToPage("Home");
    return;
}

# pull out the desired image
$Images = array_slice($Images, $Index, 1);
$Image = current($Images);

# determine which image format we want
if ($_GET["T"]=="t")
{
    $Filepath = $Image->ThumbnailUrl();
    $Size = SPTImage::SIZE_THUMBNAIL;
}
elseif ($_GET["T"]=="p")
{
    $Filepath = $Image->PreviewUrl();
    $Size = SPTImage::SIZE_PREVIEW;
}
else
{
    $Filepath = $Image->Url();
    $Size = SPTImage::SIZE_FULL;
}

if ($GLOBALS["AF"]->HtaccessSupport())
{
    # If we've ended up here, it's because somoene requested an image that
    # they are allowed to see with a CleanURL, but we didn't have a
    # symlink in place to handle that request via .htaccess.  So, call
    # GetImageURLs() to trigger generation of symlinks so that future
    # requests can be handled via .htaccess.

    $Resource->GetImageUrls($Field, $Size);
}

# send file to user, but unbuffered to avoid memory issues
apache_setenv('no-gzip', '1');
header("Content-Type: ".$Image->Mimetype());
$GLOBALS["AF"]->AddUnbufferedCallback('OutputFile', array($Filepath));
