<?php
/*
This file is part of Thomas Bley's moregroupware webmail2/calendar2/admin2 module. (tb-mgw)

More information:
-----------------

Simple Groupware Solutions Thomas Bley
Fichtenstr. 23
Germany, 85640 Putzbrunn

Contact:
--------

info@simple-groupware.de

http://www.simple-groupware.de


Copyright 2002-2003 Thomas Bley
tb-mgw is distributed under the terms of the GNU General Public License 

tb-mgw is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

tb-mgw is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with tb-mgw; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Download
// Moregroupware.org

$myEnv["module"] = "webmail2";
$myEnv["stdsmenu"] = false;
$myEnv["output"] = "html";

session_cache_limiter('private'); 

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$myvars = array("thefilename","msg_id","partno","account","message_id","decrypt");
foreach ($myvars as $thevar) {
  ${$thevar} = (isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "");
}
$MGW = $_SESSION["MGW"];
$user_id = $MGW->userid;

$msg_no = $msg_id;


if ($account == 0) {
  if (!has_read_rights_mail($msg_no,$user_id)) { die("Access denied."); }

  $sql = "select * from mgw_webmail2_messages where message_id=".(int)$msg_no;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();

  $ext = strtolower(substr($thefilename,-strpos(strrev($thefilename),'.')));
  if (isset($mime_types[$ext][0]) and $mime_types[$ext][0]=="img") { $addon = "img/"; } else {$addon = "attachments/";}

  $thenewfilename = CACHE_FOLDER.$addon.getdirnr($msg_id)."/".$row["message_id"]."-".$row["msg_cache"]."-".str_replace(".","_",$partno)."-".$thefilename;
} else {
  $ext = strtolower(substr($thefilename,-strpos(strrev($thefilename),'.')));
  if (isset($mime_types[$ext][0]) and $mime_types[$ext][0]=="img") { $addon = "img/"; } else {$addon = "attachments/";}

  $thenewfilename = CACHE_FOLDER."imap/".$addon.$user_id."-".$message_id."-".str_replace(".","_",$partno)."-".$thefilename;
}

$ext = strtolower(substr($thenewfilename,-strpos(strrev($thenewfilename),'.')));
$gpg = false;

if (isset($MGW->settings["wm2_gpg_use"]) and $MGW->settings["wm2_gpg_use"] and ($ext=="gpg" or $ext=="pgp") and str_replace(".","",PHP_VERSION)>=430 and $decrypt!="no") {
  if (!file_exists($MGW->settings["wm2_gpg_prog"]) or !file_exists($MGW->settings["wm2_gpg_pubring"]) or !file_exists($MGW->settings["wm2_gpg_secring"])) {
    echo "Could not find gpg/pubring/secring.";
	die;
  }

  if (file_exists(substr($thenewfilename,0,-4))) { unlink(substr($thenewfilename,0,-4)); }
  
  $safetmpfname = tempnam ("", "mgw_wm2_checkgpg_");

  $keyserver = ((isset($MGW->settings["wm2_gpg_keyserver"]) and $MGW->settings["wm2_gpg_keyserver"]!="")?" --keyserver ".$MGW->settings["wm2_gpg_keyserver"]:"");
  $passphrase = ((isset($MGW->settings["wm2_gpg_passphrase"]) and $MGW->settings["wm2_gpg_passphrase"]!="")?" --passphrase-fd 0":"");
  
  $output = "";
  $text = "Invalid PHP-Version: < 4.30";

  $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", $safetmpfname, "a"));
  $process = proc_open($MGW->settings["wm2_gpg_prog"].$keyserver." ".$passphrase." --no-default-keyring --secret-keyring ".$MGW->settings["wm2_gpg_secring"]." --keyring ".$MGW->settings["wm2_gpg_pubring"]." --batch --no-tty --no-verbose --textmode --always-trust ".$thenewfilename, $descriptorspec, $pipes);
  if (is_resource($process)) {
    if (isset($MGW->settings["wm2_gpg_passphrase"]) and $MGW->settings["wm2_gpg_passphrase"]!="") {
      fwrite($pipes[0], $MGW->settings["wm2_gpg_passphrase"]);
    }
    fclose($pipes[0]);
    while(!feof($pipes[1])) {
      $output .= fgets($pipes[1], 1024);
    }
    fclose($pipes[1]);
    $return_value = proc_close($process);
  }
  $fp = fopen($safetmpfname, "r");
  $text = fread ($fp, filesize ($safetmpfname));
  fclose($fp);
  unlink($safetmpfname);

  $text = str_replace(array("'","\"","\n","\r"),array("","","\\n","\\n"),$text);

  if (!file_exists(substr($thenewfilename,0,-4)) or strpos(strtolower($text),"bad passphrase")) {
    echo "Decryption failed: ".$text."<br><br><a href=\"download.php?".$_SERVER["QUERY_STRING"]."&decrypt=no\">Download encrypted</a>.";
	die;
  } else {
    $gpg = true;
	$thenewfilename_gpg = $thenewfilename.substr(ereg_replace("/","X",md5(mt_rand(1,6000))),0,12);
	rename(substr($thenewfilename,0,-4),$thenewfilename_gpg);
	$thenewfilename = $thenewfilename_gpg;
	$thefilename = substr($thefilename,0,-4);
  }
}
  
$showlink = true;
if (trim($MGW->settings["wm2_disable_ext"])!="") {
  $myext = explode(",",strtolower(trim($MGW->settings["wm2_disable_ext"])));
  foreach ($myext as $ext2) {
    $ext2 = trim(str_replace(array("\r","\n"),array("",""),$ext2));
    if ($ext2 == $ext) {
      $showlink = false;
      break;
    }
  }
}

if ($showlink and file_exists($thenewfilename)) {
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=".$thefilename);
  header("Accept-Ranges: bytes");
  header("Content-Length: ".filesize($thenewfilename));

  header('Expires: Wed, 11 Nov 1998 11:11:11 GMT');
  header('Cache-Control: no-cache');
  header('Cache-Control: must-revalidate');

  readfile($thenewfilename);

  if ($gpg) unlink($thenewfilename);
} else {
  die("<br>".$hashmap["download_given_attachment_isnt_in_email"]."<br>".$hashmap["download_number_in_db"].$msg_no."<br>partno=".$partno."<br>".$hashmap["download_filename_disabled"]);
}
?>
