<?php
/**
 * $Horde: imp/attachment.php,v 2.5.10.1 2005/01/03 12:25:30 jan Exp $
 *
 * Copyright 2004-2005 Andrew Coleman <mercury@appisolutions.net>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * This file should be the basis for serving hosted attachments.  It
 * should fetch the file from the VFS and funnel it to the client
 * wishing to download the attachment. This will allow for the
 * exchange of massive attachments without causing mail server havoc.
 */

// Set up initial includes.
//
// This does *not* include IMP's base.php because we do not need to be
// authenticated to get the file. Most users won't send linked
// attachments just to other IMP users.
if (!defined('HORDE_BASE')) {
    @define('HORDE_BASE', dirname(__FILE__) . '/..');
}
require_once HORDE_BASE . '/lib/core.php';
require_once 'VFS.php';
require_once 'Horde/MIME/Magic.php';
$registry = &Registry::singleton();
$registry->importConfig('imp');

$_self_url = Horde::selfURL(false, true, true);

// Lets see if we are even able to send the user an attachment.
if (!$conf['compose']['link_attachments']) {
    Horde::fatal(_("Linked attachments are forbidden."), $_self_url, __LINE__);
}

// Gather required form variables.
$mail_user = Util::getFormData('u');
$time_stamp = Util::getFormData('t');
$file_name = Util::getFormData('f');
if (!isset($mail_user) || !isset($time_stamp) || !isset($file_name) ||
    $mail_user == '' || $time_stamp == '' || $file_name == '') {
    Horde::fatal(_("The attachment was not found."),
        $_self_url, __LINE__);
}

// Initialize the VFS.
$vfsroot = &VFS::singleton($conf['vfs']['type'], Horde::getDriverConfig('vfs', $conf['vfs']['type']));
if (is_a($vfsroot, 'PEAR_Error')) {
    Horde::fatal(sprintf(_("Could not create the VFS backend: %s"), $vfsroot->getMessage()), $_self_url, __LINE__);
}

// Check if the file exists.
$mail_user = basename($mail_user);
$time_stamp = basename($time_stamp);
$file_name = basename($file_name);
$full_path = sprintf(".horde/imp/attachments/%s/%d", $mail_user, $time_stamp);
if (!$vfsroot->exists($full_path, $file_name)) {
    Horde::fatal(_("The specified file does not exist."), $_self_url, __LINE__);
}

// Find the file's mime-type.
$file_data = $vfsroot->read($full_path, $file_name);
$mime_type = MIME_Magic::analyzeData($file_data);
if (!$mime_type) {
    $mime_type = 'application/octet-stream';
}

// Send the client the file.
$browser->downloadHeaders($file_name, $mime_type, false, strlen($file_data));
echo $file_data;
