<?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
*/

// Sendmail_post
// Moregroupware.org

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

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(WM2_INC_DIR.'class.smtp.php');
include(WM2_INC_DIR.'class.html.mime.mail.php');
include(WM2_INC_DIR.'sendmail_post_inc.php');
include(WM2_INC_DIR."imap/date.php");

define('CRLF', "\n", TRUE);

require_once(INCLUDEPATH . "crypt.inc.php");
$myC = new Crypto();

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$myvars = array("to","subject","inreplyto","msg_no","date");
foreach ($myvars as $thevar) {
  ${$thevar} = stripcslashes(myquote((isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "")));
}

$MGW = $_SESSION["MGW"];
$user_id = $MGW->userid;
$username = $MGW->username;

$smarty->assign("username", ucfirst($username));
$webmail_sendmail_temp_dir = CACHE_FOLDER."sendmail/";
checkdir($webmail_sendmail_temp_dir,true);

$mbox_id = getboxid("sent",0,$user_id);

$users = getallusers2();
$users2 = getallusers3();

$tolocalarr = array();
$toarr = array();

$inreplyto = htmlnonspecialchars($inreplyto);

if (isset($users2[$to])) $tolocalarr=array(array_search($to,$users)=>$to);
  else $toarr = array($to);
  
$sql = "select * from mgw_webmail2_accounts where user_id=".(int)$user_id." and id=".(int)$_SESSION["MGW"]->settings["wm2_default_account"];
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
$row = $res->FetchRow();

if (!isset($row["id"]) or $_SESSION["MGW"]->settings["wm2_default_account"]==0) die("Invalid account.");

$txtbody = $hashmap["notify_text"]."\n\n".$hashmap["maillist_to"].":   ".addslashes($to)."\n".$hashmap["maillist_subject"].":   ".$subject."\n".$hashmap["webmail2_func_sent"].":   ".getDateString_full($date)."\n\n".$hashmap["notify_text2"]." ".getDateString_full(time())."\n";

if ($row["password"]!="") {$password = $myC->decrypt($username, $row["password"]);} else {$password = "";}
if ($row["smtppassword"]!="") {$thesmtppassword = $myC->decrypt($username, $row["smtppassword"]);} else {$thesmtppassword = "";}

if ($row["smtpauth"]=="checked") {
  $smtpauth = true;
  if ($row["smtpusepopuser"]=="checked") {
    $smtpusername = $row["username"];
    $smtppassword = $password;
  } else {
    $smtpusername = $row["smtpusername"];
    $smtppassword = $thesmtppassword;
  }
} else {
  $smtpusername = "";
  $smtppassword = "";
  $smtpauth = false;
}

check_pop_sendmail($row,"",count($toarr));

$mail = new html_mime_mail(array('X-Mailer: Moregroupware Webmail2'));
$mail->add_text(wordwrap($txtbody,72,"\n",1));

$mail->add_attachment("Final-Recipient: rfc822; ".$row["replyto"]."\nOriginal-Message-ID: ".$inreplyto."\nDisposition: manual-action/MDN-sent-automatically; displayed\n", '', 'message/disposition-notification', '7bit','inline');
$mail->add_attachment("Subject: ".$subject."\nDate: ".date("r",$date)."", '', 'text/rfc822-headers', '7bit','inline');

if(!$mail->build_message()) { show_webmail_error($back_button."Error building message.",""); } else {
  $mail->output = str_replace("\r\n","\n",$mail->output);
}
$mail_attachments = array();

$mydate = date("D, d M Y H:i:s O");

$send_params = array(
  'from'			=> $row["replyto"],
  'recipients'	=> $toarr
);

$subject = $hashmap["notify_text3"].": ".$subject;

$send_params['headers'] = array(
		'From: '.$row["fullname"]." <".$row["replyto"].">",
		'To: '.$to,
		'Subject: '.$subject,
		'Date: '.$mydate
);

$headers = str_replace(CRLF.'.', CRLF.'..', trim(implode(CRLF, $mail->headers)).CRLF.trim(implode(CRLF, $send_params["headers"])));
$headers = str_replace("\r\n","\n",$headers);

$body = $mail->output;
$body = $body[0] == '.' ? '.'.$body : $body;
$body = CRLF.CRLF.$body;

mt_srand((double)microtime()*10000);

$msg_id = mgw_genID('mgw__seq_messages');
$dir_nr = getdirnr($msg_id);
checkdir(STORE_FOLDER.$dir_nr."/",false);
$act_name = STORE_FOLDER.$dir_nr."/" . $msg_id . "-" .date("dmY-His")."-". ereg_replace("/","X",md5(mt_rand(1,6000))).".eml";
$msg_cache = ereg_replace("/","X",md5(mt_rand(1,6000)));

$uid = "<".date("YmdHi").".".substr(ereg_replace("/","X",md5(mt_rand(1,6000))),0,12)."@".$_SERVER["SERVER_NAME"].">";

$attaches = 0;

  if (count($tolocalarr) != 0) {
    foreach ($tolocalarr as $key=>$key2) {
      if (!isset($act_name2)) {
        $msg_id2 = $msg_id;
        $msg_id = "";
        $msg_cache2 = $msg_cache;
        $uid2 = $uid;
        $act_name2 = $act_name;
      }
      $the_user_id = $key;
      
      if (!boxexist2("inbox",0,$the_user_id)) {
        create_boxes(array(array("inbox",0,$the_user_id)));
      }
      $the_mbox_id = getboxid("inbox",0,$key);
      
      if ($msg_id2 == "") { $msg_id2 = mgw_genID('mgw__seq_messages'); }
      $myids[] = $msg_id2;
    
      $sql = "INSERT INTO mgw_webmail2_messages (cal_accepted,notified,attachbit,msg_cache,message_id,account_name,uid,type,mbox_id,header_from,header_to,header_cc,header_bcc,header_replyto,header_date,header_subject,header_inreplyto,msg_body,recentbit,readbit,replybit,draftbit,flaggedbit,forwardbit,replied2,labelbit) VALUES".
      "('0','0','".$attaches."','".$msg_cache2."',".(int)$msg_id2.",'".$row["username"]."@".$row["pophost"]."','".$uid2."','eml',".(int)$the_mbox_id.",".$conn->Quote($row["fullname"]." (".$_SESSION["MGW"]->username.") <".$row["replyto"].">").",".$conn->Quote($to).",'','','','".time()."',".$conn->Quote($subject).",'".$inreplyto."','".$act_name2."','1','1','0','0','3','0',0,'0')";
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

      $msg_id2 = "";
    }
  }
  
  if (count($toarr) != 0) {
      if ($row["enable_ssl_smtp"]=="checked") {
        $port = "465";
        $hostname = "ssl://".$row["smtphost"];
      } else {
        $port = "25";
        $hostname = $row["smtphost"];
      }

      $smtp =& smtp::connect(array('host'=>$hostname,'port'=>$port,'helo'=>$_SERVER["SERVER_NAME"],'auth'=>$smtpauth,'user'=>$smtpusername,'pass'=>$smtppassword));
      if (!$mail->smtp_send($smtp, $send_params)) {
	    show_webmail_error($back_button.$hashmap["sendmail_post_error"],$smtp->errors);
      }
  }

if ($msg_id == "") { $msg_id = mgw_genID('mgw__seq_messages'); }

$myids[] = $msg_id;
$sql = "INSERT INTO mgw_webmail2_messages (cal_accepted,notified,attachbit,msg_cache,message_id,account_name,uid,type,mbox_id,header_from,header_to,header_cc,header_bcc,header_replyto,header_date,header_subject,header_inreplyto,msg_body,recentbit,readbit,replybit,draftbit,flaggedbit,forwardbit,replied2,labelbit) VALUES('1','1','".$attaches."','".$msg_cache."',".(int)$msg_id.",'".$row["username"]."@".$row["pophost"]."','".$uid."','eml',".(int)$mbox_id.",".$conn->Quote($row["fullname"]." <".$row["replyto"].">").",".$conn->Quote($to).",'','','','".time()."',".$conn->Quote($subject).",'".$inreplyto."','".$act_name."','1','0','0','0','3','0',0,'0')";
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

writetofile_sendmail($act_name,$headers.str_replace("\r\n","\n",$body));

if (file_exists($act_name)) {
  foreach ($myids as $myid) {
    $sql = "update mgw_webmail2_messages set header_size=".(int)filesize($act_name)." where message_id=".(int)$myid;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  }
}

$sql = "update mgw_webmail2_messages set notified=1 where message_id=".(int)$msg_no;
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

echo "<script>window.close();</script>";
?>
