<?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');
require_once(WM2_INC_DIR."rfc822.php");
include(WM2_INC_DIR.'sendmail_post_inc.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("von","to","cc","bcc","subject","signit","sendplain","notification","msgbody","replyto","priority","saveto","function","slcsil","forward","editmail","inreplyto");
foreach ($myvars as $thevar) {
  ${$thevar} = stripcslashes(myquote((isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "")));
  // echo $thevar.": ".${$thevar}."<br>";
}

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

$mysession_vars = array("msgbody","subject","von","to","cc","bcc","priority","signit","sendplain","notification","forward","editmail","replyto","inreplyto");
foreach ($mysession_vars as $thevar) {
  if (${$thevar}!="<empty>") {
    $_SESSION["webmail2_compose_array"][$thevar] = htmlspecialchars(${$thevar});
  }
}

if ($to=="") {Header("Location: sendmail.php?sendplain2=yes&signit2=yes&notification2=yes&".SID); die;}

$back_button = '
      <form method="post" action="sendmail.php">
        <input type="hidden" name="signit2" value="yes">
        <input type="hidden" name="sendplain2" value="yes">
        <input type="hidden" name="notification2" value="yes">
		<input type="hidden" name="'.session_name().'" value="'.session_id().'">			
        <input type="submit" class="submit" value="'.$hashmap["attachments_go_back"].'">
      </form>
';

$myvars = array("von","to","cc","bcc","signit","sendplain","notification","msgbody","replyto","priority","saveto","function","slcsil","forward","editmail");
foreach ($myvars as $thevar) {
  ${$thevar} = myquote((isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : ""));
}

if ($saveto=="draft") {
  $mbox_id = getboxid("draft",0,$user_id);
} else {
  $mbox_id = getboxid("sent",0,$user_id);
}


$to = stripslashes($to);
$cc = stripslashes($cc);
$bcc = stripslashes($bcc);

$users = getallusers2();
$users2 = getallusers3();
$groups = getallgroups2();
$groups_contacts = getallgroups2_contacts();

$toarr = make_array_adr($to);
$ccarr = make_array_adr($cc);
$bccarr = make_array_adr($bcc);

$tolocalarr = array();
$tolocalarrgroup = array();
$togroup_contacts = array();

add_adr_to_arr($toarr);
$togroup_contacts2 = $togroup_contacts;
$togroup_contacts = array();

add_adr_to_arr($ccarr);
$ccgroup_contacts = $togroup_contacts;
$togroup_contacts = array();

add_adr_to_arr($bccarr);
$bccgroup_contacts = $togroup_contacts;
$togroup_contacts = array();

assign_rec_arrays("tolocalarrgroup","tolocalarr");

assign_rec_arrays_contacts("togroup_contacts2","toarr");
assign_rec_arrays_contacts("ccgroup_contacts","ccarr");
assign_rec_arrays_contacts("bccgroup_contacts","bccarr");

$sendto = make_str_from_arr_adr($toarr);
$sendcc = make_str_from_arr_adr($ccarr);
$sendbcc = make_str_from_arr_adr($bccarr);
$sendlocal = make_str_from_arr_adr($tolocalarr);

if ($sendlocal=="" and $sendcc=="" and $sendto=="") {Header("Location: sendmail.php?sendplain2=yes&signit2=yes&notification2=yes&".SID); die;}

/*
show_print_r($sendto);
show_print_r($sendcc);
show_print_r($sendbcc);

show_print_r($toarr);
show_print_r($ccarr);
show_print_r($bccarr);
die;
*/

$sql = "select * from mgw_webmail2_accounts where user_id=".(int)$user_id." and id=".(int)$von;
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
$row = $res->FetchRow();


$msgbody = stripslashes($msgbody);
$txtbody = str_replace(array("\n","<br />","<br>","<p>","</p>"),array("","\n","\n","\n","\n\n"),$msgbody);

if ($signit=="checked" and $row["signature_html"]!="") {
  if (!strpos($msgbody,"<signature />")) {
    $msgbody .= "<br><br>-- <br>".$row["signature_html"];
  } else {
    $msgbody = str_replace("<signature />","<br>-- <br>".$row["signature_html"]."<br><br><br>",$msgbody);
  }
}

if ($signit=="checked" and $row["signature"]!="") {
  if (!strpos($txtbody,"<signature />")) {
    $txtbody .= "\n\n-- \n".$row["signature"];
  } else {
    $txtbody = str_replace("<signature />","\n-- \n".$row["signature"]."\n\n\n",$txtbody);
  }
}

$txtbody = strip_tags($txtbody);
$msgbody = str_replace("\r\n","\n",$msgbody);
$txtbody = str_replace("\r\n","\n",$txtbody);

$txtbody = my_decodeHTML($txtbody);


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,$saveto,(count($toarr)+count($ccarr)+count($bccarr)));

$mail = new html_mime_mail(array('X-Mailer: Moregroupware Webmail2'));

if ($sendplain) {
  $mail->add_text(wordwrap($txtbody,72,"\n",1));
} else {
  if ($msgbody=="") $msgbody = " ";
  $mail->add_html($msgbody,wordwrap($txtbody,72,"\n",1));
}
add_attachments_sendmail();

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();
if (isset($mail->attachments) and count($mail->attachments)!=0) {
  foreach ($mail->attachments as $att) {
    $mail_attachments[] = $att['body'];
  }
}


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

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

$my_headers = array(
		'From: '.$row["fullname"]." <".$row["replyto"].">",
		'To: '.$to,
		'Cc: '.$cc,
		'Subject: '.$subject,
		'Date: '.$mydate,
		'X-Priority: '.$priority, 'References: '.$inreplyto, 'In-Reply-To: '.$inreplyto
);

$my_headers2 = array(
		'From: '.$row["fullname"]." <".$row["replyto"].">",
		'Date: '.$mydate,
		'X-Priority: '.$priority, 'References: '.$inreplyto, 'In-Reply-To: '.$inreplyto
);

if ($notification) {
  $send_params['headers'] = array_merge(array('Disposition-Notification-To: "'.$row["fullname"].'" <'.$row["replyto"].'>'),$my_headers);
} else {
  $send_params['headers'] = $my_headers;
}

if ($bcc!="") {
  $headers2 = str_replace(CRLF.'.', CRLF.'..', trim(implode(CRLF, $mail->headers)).CRLF.trim(implode(CRLF, array_merge($send_params["headers"],array('Bcc: '.$bcc)))));
  $headers2 = str_replace("\r\n","\n",$headers2);
}

$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 = str_replace(CRLF.'.', CRLF.'..', $mail->output);
$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";

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

if ($attaches!=0) {$attaches = 1;}

$to2 = $sendto;
if ($sendcc != "") {
  if ($to2 != "") {$to2 .= ", "; }
  $to2 .= $sendcc;
}
if ($sendbcc != "") {
  if ($to2 != "") {$to2 .= ", "; }
  $to2 .= $sendbcc;
}
if ($sendlocal != "") {
  if ($to2 != "") {$to2 .= ", "; }
  $to2 .= $sendlocal;
}

$to2 = htmlspecialchars($to2);
$to22 = $to2;

if ($saveto!="draft") {

  if ($bcc!="" and count($tolocalarr) != 0) {

    $msg_id2 = mgw_genID('mgw__seq_messages');
    $dir_nr2 = getdirnr($msg_id2);
    checkdir(STORE_FOLDER.$dir_nr2."/",false);
    $act_name2 = STORE_FOLDER.$dir_nr2."/" . $msg_id2 . "-" .date("dmY-His")."-". ereg_replace("/","X",md5(mt_rand(1,6000))).".eml";

    $uid2 = "<".date("YmdHi").".".substr(ereg_replace("/","X",md5(mt_rand(1,6000))),0,12)."@".$_SERVER["SERVER_NAME"].">";
  } 
  if (count($tolocalarr) != 0) {
    foreach ($tolocalarr as $key=>$key2) {
    
      if (!isset($act_name2)) {
        $msg_id2 = $msg_id;
        $msg_id = "";
        $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."','".ereg_replace("/","X",md5(mt_rand(1,6000)))."',".(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).",".$conn->Quote($cc).",'','','".time()."',".$conn->Quote($subject).",'".$inreplyto."','".$act_name."','1','1','0','0','".$priority."','0',0,'0')";
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

      $msg_id2 = "";
    }
  }
  
  if (count($toarr)+count($ccarr)+count($bccarr) != 0) {
  
    /*
    if ($row["usemailfunction"]=="checked") {
      if ($sendcc != "") {$kommacc = ", ".$sendcc;} else {$kommacc = "";}
      if (!$mail->send("", $sendto.$kommacc, $row["fullname"], $row["replyto"],$subject,$send_params["headers"])) {
  	    show_webmail_error($back_button.$hashmap["sendmail_post_error"],"");
      }

      if (count($bccarr) != 0) {
        foreach ($bccarr as $thatbcc) {
	      if (!$mail->send("", $thatbcc, $row["fullname"], $row["replyto"],$subject,$send_params["headers"])) {
		    show_webmail_error($back_button.$hashmap["sendmail_post_error"],"");
  	      }
        }
      }
  
    } else {
    */
      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);
      }
    // }
  }
  $message = $hashmap["sendmail_post_successfully_sent"];

  $to2 = $to2."<br>";
} else {
  $message = $hashmap["sendmail_post_email_was_saved"];
  $to2 = "";
}

if (!isset($act_name2)) $act_name2 = $act_name;

if ($msg_id == "") { $msg_id = mgw_genID('mgw__seq_messages'); }
if ($replyto == "") { $replyto = 0; }
$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."','".ereg_replace("/","X",md5(mt_rand(1,6000)))."',".(int)$msg_id.",'".$row["username"]."@".$row["pophost"]."','".$uid."','eml',".(int)$mbox_id.",".$conn->Quote($row["fullname"]." (".$_SESSION["MGW"]->username.") <".$row["replyto"].">").",".$conn->Quote($to).",".$conn->Quote($cc).",".$conn->Quote($bcc).",'','".time()."',".$conn->Quote($subject).",'".$inreplyto."','".$act_name2."','1','0','0','0','".$priority."','0',".(int)$replyto.",'0')";
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

$body = str_replace("\r\n","\n",$body);
writetofile_sendmail($act_name,$headers.$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__));
  }
}
  
if ($bcc!="" and count($tolocalarr) != 0) {
  writetofile_sendmail($act_name2,$headers2.$body);
}

delete_open_attachments($webmail_sendmail_temp_dir);

$_SESSION["webmail2_compose_array"] = array();
unset($_SESSION["webmail2_compose_array"]);

if ($replyto!="" and $saveto!="draft") {
  if (has_write_rights_mail($replyto,$user_id)) { add_to_replied($replyto,$msg_id,$to22); }
} elseif ($saveto=="draft" and $replyto!="") {
  if (has_write_rights_mail($replyto,$user_id)) {
    $sql = "update mgw_webmail2_messages set reply_draft=".(int)$replyto." where message_id=".(int)$msg_id;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  }
}

if ($forward!="" and $saveto!="draft") {
  if (has_write_rights_mail($forward,$user_id)) { add_to_forwarded($forward,$msg_id,$to22); }
} elseif ($saveto=="draft" and $forward!="") {
  $sql = "update mgw_webmail2_messages set forward_draft=".(int)$forward." where message_id=".(int)$msg_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
}

if ($editmail!="" and has_write_rights_mail($editmail,$user_id)) {
  $folderto = getboxid("trash",0,$user_id);
  $folderfrom = getboxid("draft",0,$user_id);

  $sql = "update mgw_webmail2_messages set mbox_id=".(int)$folderto." where mbox_id=".(int)$folderfrom." and message_id=".(int)$editmail;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
}

$smarty->assign("waittime", $MGW->settings["wm2_waittime"]);
$smarty->assign("message", $message);
$smarty->assign("to2", $to2);
$smarty->assign("saveto", $saveto);

$smarty->display("sendmail_post.tpl");
?>
