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

# ----- 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 -----------------------------------------------------------------

# if file secret was supplied and is valid
if (array_key_exists("FS", $_GET))
{
    # if file secret is valid
    $Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
    $FileInfo = $Plugin->GetExportedFileInfo($_GET["FS"]);
    if ($FileInfo !== NULL)
    {
        # if current user is the one who created the file and file exists
        if (($GLOBALS["G_User"]->Id() == $FileInfo["ExporterId"])
                && (is_readable($FileInfo["LocalFileName"])))
        {
            # set headers to download file
            $FileName = $FileInfo["LocalFileName"];
            header("Content-Type: ".GetMimeType($FileName));
            header("Content-Length: ".filesize($FileName));
            header('Content-Disposition: attachment; filename="'
                    .basename($FileInfo["FileName"]).'"');

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

            # turn off display of HTML template
            $AF->SuppressHTMLOutput();
        }
    }
}

# (if a download was not successfully set up, the HTML template will be loaded instead)

