<?PHP
#
#   FILE:  DownloadFile.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012 Internet Scout Project
#   http://scout.wisc.edu/
#

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

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);
}

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

$Id = GetArrayValue($_GET, "ID", GetArrayValue($_GET, "Id"));

# if file ID was supplied
if (!is_null($Id))
{
    $FileId = intval($Id);
    $File = new File($FileId);

    # if file info was loaded successfully
    if ($File->Status() == File::FILESTAT_OK)
    {
        $Schema = new MetadataSchema();
        $Field = $Schema->GetField($File->FieldId());
        $Resource = new Resource($File->ResourceId());

        # if user can view file
        if ($Resource->UserCanViewField($User, $Field))
        {
            $Filepath = $File->GetNameOfStoredFile();
            $Filename = addslashes($File->Name());
            $Mimetype = $File->GetMimeType();

            # set headers to download file
            header("Content-Disposition: attachment; filename=\"".$Filename."\"");
            header("Content-Type: ".$Mimetype);
            header("Content-Length: ".$File->GetLength());

            # send file to user, but unbuffered to avoid memory issues
            $AF->AddUnbufferedCallback('OutputFile', array($Filepath));

            $AF->SuppressHTMLOutput();
        }

        else
        {
            CheckAuthorization(-1);
        }
    }
}

# if a file was not found, the HTML template will be loaded instead
