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

// Readmessages
// Moregroupware.org

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

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(WM2_INC_DIR."imap/date.php");
include(WM2_INC_DIR.'readmessage_inc.php');

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$myvars = array("msg_no","print","inline","print2","account","mbox_id","word_export","show_headers");
foreach ($myvars as $thevar) {
  ${$thevar} = (isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "");
}
$MGW = $_SESSION["MGW"];
$user_id = $MGW->userid;
$username = $MGW->username;

if ($print=="true") { $print2="onload=\"print();\""; }

$message_id = "";
$this_recache = false;

store_webmail_readmessage($msg_no);

if ($account!=0 and $mbox_id != "" and is_numeric($mbox_id)) {

  if ($email = connect_my_imap($account,$mbox_id,true)) {

	checkdir(CACHE_FOLDER."imap/eml/",true);

    $header = my_imap_header($email,$email,"int",$msg_no);
    if (isset($header->Size)) {$size = $header->Size;} else {$size = "0";}

    $oversize = false;
    if (isset($MGW->settings["wm2_fetch_limit"]) and $MGW->settings["wm2_fetch_limit"] != "" and is_numeric($MGW->settings["wm2_fetch_limit"]) and $MGW->settings["wm2_fetch_limit"]!=0 and ($MGW->settings["wm2_fetch_limit"]*1024) < $header->Size) {
      die("mail is too big.");
    }
    $message_id = str_replace(array(".","<",">","/"),"",getmessage_id($header));
        
    $act_name = CACHE_FOLDER."imap/eml/".$user_id."-".$message_id.".eml";
    $emailsource = $act_name;
    $emailsource_mini = CACHE_FOLDER."imap/readmessage/".$user_id."-".$message_id.".php";
    $emailsource_mini2 = CACHE_FOLDER."imap/readmessage/".$user_id."-".$message_id."-2.php";
        
    if (!file_exists($act_name)) {
	  $actname_temp = CACHE_FOLDER ."imap/eml/temp-".$user_id.$username.".eml";

	  @set_time_limit(0);

	  my_imap_get_message($email,$email,"ing",$msg_no,$actname_temp);
	  if (!file_exists($actname_temp)) {die("The E-Mail could not be fetched !!");}

      if (file_exists($act_name)) {unlink($act_name);}
      rename($actname_temp,$act_name);
    }
    sqimap_messages_add_flag ($email, $msg_no, $msg_no, "\\Seen");
    sqimap_logout($email);

    $row2 = array();
    $row2["header_bcc"] = "";
    $row2["attachbit"] = "";
    $row2["notified"] = "";
    $row2["header_from"] = decode_mime_string(trim(isset($header->fromaddress)?$header->fromaddress:""));
    $row2["header_to"] = decode_mime_string(trim(isset($header->toaddress)?$header->toaddress:""));
    $row2["header_cc"] = decode_mime_string(trim(isset($header->ccaddress)?$header->ccaddress:""));
    $row2["header_replyto"] = decode_mime_string(isset($header->reply_toaddress)?$header->reply_toaddress:"");
    $row2["header_subject"] = decode_mime_string(isset($header->subject)?$header->subject:"");
    $row2["header_date"] = (isset($header->date)?$header->date:"");
    $row2["uid"] = (isset($header->message_id)?$header->message_id:"");
    $row2["flaggedbit"] = (isset($header->priority)?$header->priority:"");
        
  } else {
    $msg_no="";
  }
}    

if ($msg_no!="" and ($account!=0 or has_write_rights_mail($msg_no,$user_id))) {
  $settings_replyto = array();
  $settings_fullname = array();
  $sql = "select replyto, fullname from mgw_webmail2_accounts where user_id=".(int)$user_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  while($row = $res->FetchRow()) {
    $settings_replyto[] = strtolower($row["replyto"]);
    $settings_fullname[] = $row["fullname"];
  }

  $replied = array();
  $forwarded = array();
  $replier2 = "";
  
  if ($account == 0) {
    $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();
  
    if ($row["header_size"]!=0) {$mysize=format_filesize($row["header_size"]);} else {$mysize="";}
  
    $msg_cache = $row["msg_cache"];

    if ($msg_cache=="") {
      $msg_cache = ereg_replace("/","X",md5(mt_rand(1,6000)));
      $sql = "update mgw_webmail2_messages set msg_cache='".$msg_cache."' where message_id=".(int)$msg_no;
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    }
    if ($msg_no%10000==0) { $dir_nr = $msg_no/10000; } else {$dir_nr = 0;}

    checkdir(CACHE_FOLDER."img/".$dir_nr."/",false);
    checkdir(CACHE_FOLDER."attachments/".$dir_nr."/",false);
    checkdir(CACHE_FOLDER."readmessage/".$dir_nr."/",false);
  
    if ($row["replybit"]==1 and $row["replied"]!="") {
      $repliers = explode(";@;",$row["replied"]);
	  foreach ($repliers as $replier) {
        if ($replier !="") {
    	  $replied[] = explode(";#;",$replier);
	    }
      }
    }
  
    if ($row["replied2"]!="") {
      $replier2 = $row["replied2"];
    }
  
    if ($row["forwardbit"]==1 and $row["forwarded"]!="") {
      $forwarders = explode(";@;",$row["forwarded"]);
	  foreach ($forwarders as $forwarder) {
        if ($forwarder !="") {
	      $forwarded[] = explode(";#;",$forwarder);
        }
	  }
    }
  
    if ($row["readbit"]==1) {
      $this_recache = true;
      $sql = "update mgw_webmail2_messages set readbit=0 where message_id=".(int)$msg_no;
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    }
  
    $emailsource = $row["msg_body"];
    $emailsource_mini = CACHE_FOLDER."readmessage/".$dir_nr."/".basename($row["msg_body"]).".php";
    $emailsource_mini2 = CACHE_FOLDER."readmessage/".$dir_nr."/".basename($row["msg_body"])."-2.php";

  } else {
    if ($size!=0) {$mysize=format_filesize($size);} else {$mysize="";}
  
    $row = $row2;
  
    checkdir(CACHE_FOLDER."imap/img/",false);
    checkdir(CACHE_FOLDER."imap/attachments/",true);
    checkdir(CACHE_FOLDER."imap/readmessage/",true);
  }
  $global_row = $row;

  $emailsourcelink = '<a target="_blank" href="'.$emailsource.'" onclick="return confirm(\''.$hashmap["readmessage_email_source_warning"].'\');">';

  include WM2_INC_DIR."mimedecode.php";
  require_once(WM2_INC_DIR."rfc822.php");
  
	$attachments2 = array();
	$boundarys = array();
	$content_types = array();
  
	$content_type = ""; $content_transfer_encoding = ""; $content_disposition = "";
	$filename = "";	$filename2 = "";
	$cont2 = ""; $input = "";
	$inline2 = "";
	
    $rfc = false;
    
	$record = false; $write_attach = false;
	$firsttime = true;
    $block_filename = false;	
    
    $partno = 0;
    $attaches4 = 0;
    $realattachments = 0;
		
	$cache_version_now = "2.1";
	$cache_version_now2 = "2.3";
	
  $recache = true;

  @set_time_limit(0);

  if (file_exists($emailsource_mini)) {
    include $emailsource_mini;

    if (!isset($cache_version)) {$cache_version = "0";}
    if ($cache_version == $cache_version_now) { $recache = false; }
  }
  if ($MGW->settings["wm2_always_recache"] or $this_recache) {
    $recache = true;
  }
  if ($recache) {
    $protocol = false;
    $input = "";
	$attachments2 = array();
	if (!file_exists($emailsource) or !$fp=@fopen($emailsource,"rb")) {
      die("<br>".$hashmap["readmessage_email_not_found"]."<br>".$hashmap["readmessage_number_in_db"].$msg_no."<br>".$hashmap["readmessage_filename_disabled"]);} // .$emailsource

    while(!feof($fp)) {
        $cont = $cont2.fread($fp,1024*8);

		if ($firsttime) {
		  $firsttime = false;
		  if (strpos(substr($cont,0,100), "\r\n") === false) {
		    $crlf = "\n";
		  } else {$crlf = "\r\n";}
		}

		$cont2 = substr($cont,strrpos($cont,$crlf)+1);
		$cont = substr($cont,0,strrpos($cont,$crlf));

		$lines = explode($crlf,$cont);
        
		foreach ($lines as $key=>$line) {
          $line = str_replace("\n","",$line);

          if ($protocol and !$record) { make_proto2($line); }
          //  and $content_type!="text/html" and $content_type!="text/plain"
		  if (!$block_filename) searchattachments2($line);

          if (!$record and ($line=="" or ord($line)==13 or (strlen($line)>1 and ord($line[0])==10 and ord($line[1])==13))) {
            if (!$block_filename and $content_type!="message/rfc822") {
              $block_filename = true;
              if ($protocol) { echo "<font color='#000080'>Block filename</font><br>\n";}
            }
            
  		    if ($filename!="" or $filename2!="") {

 			  if ($filename2!="") {$filename=$filename2;}
              add_filename($filename);
                
			  if ($filename2=="") { $attaches4++; }

			  $dont_write = false;
              $ext = strtolower(substr($filename,-strpos(strrev($filename),'.')));
              if (trim($MGW->settings["wm2_disable_ext"])!="") {
                $ext = strtolower(substr($filename,-strpos(strrev($filename),'.')));
                $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) {
                    $dont_write = true;
                    break;
                  }
                }
              }
			  
              if ((!file_exists($act_name) and !$dont_write) or $protocol) {
                if ($protocol) { echo "<font color='#ff0000'>Open ".$act_name."</font><br>\n";}
			    $write_attach = true;
			    $fd = fopen($act_name.".tmp", "wb");
	          }
            }
          }

		  if (findboundary2($line,$boundarys)) {
            if ($protocol) { echo "<font color='#000080'>Found boundary</font><br>\n";}
            if ($block_filename) { $block_filename = false; if ($protocol) { echo "<font color='#000080'>Unblock filename</font><br>\n";}}
            if ($record) {

              $att_size = 0;

              if ($write_attach) {
                if ($protocol) { echo "<font color='#ff0000'>Close ".$act_name."</font><br>\n";}
			    if ($content_transfer_encoding != "base64") { //  and $content_transfer_encoding != "quoted-printable"
			      ftruncate($fd,ftell($fd)-2);
			    }
			    fclose($fd);
                if (file_exists($act_name)) {unlink($act_name);}
			    rename($act_name.".tmp",$act_name);
                
                $att_size = filesize($act_name);
                
                if ($protocol) { echo "<font color='#ff0000'>Rename ".$act_name." -> $act_name</font><br>\n";}
              }
              
              if ($att_size==0 and file_exists($act_name)) { $att_size = filesize($act_name); }
              
              if ($protocol and $record) { echo "<font color='#ff0000'>Record false</font><br>\n";}
              $attachments2[] = array($filename,format_filesize($att_size),$message,$msg_no,$partno,$danger);

			  $content_type = ""; $content_transfer_encoding = ""; $content_disposition = "";
			  $filename = "";	$filename2 = "";
			  $record = false; $write_attach = false; $partno++;
            }
          }
          if ($record and $write_attach) {
			if ($content_transfer_encoding == "quoted-printable") $line = quoted_printable_decode($line.$crlf);
              elseif ($content_transfer_encoding == "base64") { $line = base64_decode($line); }
              else { $line = $line."\r\n";}
            fwrite($fd, $line);
          }
		  if (!$record) { $input .= $line."\n";}
		}
    }
    fclose($fp);

    if ($record and $protocol) {
      echo "<font color='#FF0000'>End of mail: record is true</font>";
    }
    
	if ($record and $write_attach) {
      if ($protocol) { echo "<font color='#FF0000'>End of mail: file still open, closing ...</font>"; }
      if ($content_transfer_encoding != "base64" and $content_transfer_encoding != "quoted-printable") {
	    ftruncate($fd,ftell($fd)-2);
	  }
      fclose($fd);
      if (file_exists($act_name)) {unlink($act_name);}
	  rename($act_name.".tmp",$act_name);
    }
    if ($record) {
      $attachments2[] = array($filename,format_filesize(filesize($act_name)),$message,$msg_no,$partno,$danger);
    }
    
	if ($input!="") { //  and $crlf == "\r\n"
	  $input = str_replace("\r\n","\n",$input);
	}

	$fp = fopen($emailsource_mini, "w");

	fwrite($fp,"<?php\n");

	fwrite($fp,"\$cache_version=\"".$cache_version_now."\";\n");

	fwrite($fp,"\$input=\"");
	fwrite($fp,addcslashes($input,"\$\\\""));
	fwrite($fp,"\";\n");

	if (count($attachments2)!=0) {
	  fwrite($fp,"\$attachments2=");
	  fwrite($fp, draw_array($attachments2,true));
	} else {
	  fwrite($fp,"\$attachments2=array();\n");
	}
	fwrite($fp,"?>\n");
    fclose($fp);
  }	
	
  $recache = true;
  if (file_exists($emailsource_mini2)) {
    include $emailsource_mini2;
    
    if ($MGW->settings["wm2_enableinline"]) { $wm2_enableinline = "checked"; } else { $wm2_enableinline = ""; }
    if ($MGW->settings["wm2_securehtmlmails"]) { $wm2_securehtmlmails = "checked"; } else { $wm2_securehtmlmails = ""; }
    if (!isset($cache_version)) {$cache_version = "0";}
    if ($cache_version2 == $cache_version_now2
	  and $inline2 == $wm2_enableinline
	  and $secure2 == $wm2_securehtmlmails
	) { $recache = false; }
  }
  
  if ($MGW->settings["wm2_always_recache"]) {
    $recache = true;
  }
  if ($recache) {
    $body_show = array();
	$body_plain = "";
	$emailbox = array();
    $msg_id = $msg_no;  
    $params = array(
	'input'          => $input,
	'crlf'           => "\r\n",
	'include_bodies' => TRUE,
	'decode_headers' => TRUE,
	'decode_bodies'  => TRUE
    );

  $webmails = "";
  $webmails2 = array();
  $emailbox = "";
  $body_plain = "";
  $related = array();
  $notify = false;

  $structure = Mail_mimeDecode::decode($params, 0 , FALSE, FALSE, "no");

  if (isset($emailbox) and is_array($emailbox)) { $emailbox = array_reverse($emailbox);} else {
    $emailbox = array(0);
//    die($emailsource."<br>".$hashmap["readmessage_corrupted_message_fetch_again"]." If you fetch it again and it's still corrupted, feel free to mail this .eml-file as a bug report. (If the mail doesn't contain any secure content)");
  }

	if (isset($body_show) and is_array($body_show)) {

	  if (count($related)!=0) {
        foreach ($body_show as $key=>$key2) {
          if ($body_show[$key][0]=="text" or $body_show[$key][0]=="html") {
    	    foreach($related as $relative) {
              if (isset($emailbox[$key]) and isset($emailbox[$key][11]) and is_array($emailbox[$key][11])) {
                foreach ($emailbox[$key][11] as $ekey => $ekey2) {
                  if ($ekey2[0] == $relative["filename"]) {
                    if ($emailbox[$key][10] > 0) { $emailbox[$key][10]--; }
                    unset($emailbox[$key][11][$ekey]);
                  }
                }
              }
	          $body_show[$key][1] = str_replace(array("cid:".$relative["c_id"]."'","cid:".$relative["c_id"]."\""),array($relative["act_name"]."'",$relative["act_name"]."\""),$body_show[$key][1]);
	        }
		  }
	    }
	  }
    }
    // } else {
  	//	$webmails .= $body_plain."<br>";

	$fp = fopen($emailsource_mini2, "w");

	fwrite($fp,"<?php\n");
    
	fwrite($fp,"\$cache_version2=\"".$cache_version_now2."\";\n");

    if ($MGW->settings["wm2_enableinline"]) { $wm2_enableinline = "checked"; } else { $wm2_enableinline = ""; }
    if ($MGW->settings["wm2_securehtmlmails"]) { $wm2_securehtmlmails = "checked"; } else { $wm2_securehtmlmails = ""; }

	$from2 = shorten2($row["header_from"]);
	fwrite($fp,"\n\$cache_from=\"".addcslashes((user_exists($from2)?$from2:$row["header_from"]),"\$\\\"")."\";\n");
	fwrite($fp,"\$cache_to=\"".addcslashes($row["header_to"],"\$\\\"")."\";\n");
	fwrite($fp,"\$cache_cc=\"".addcslashes($row["header_cc"],"\$\\\"")."\";\n");
	fwrite($fp,"\$cache_bcc=\"".addcslashes($row["header_bcc"],"\$\\\"")."\";\n");
	fwrite($fp,"\$cache_replyto=\"".addcslashes($row["header_replyto"],"\$\\\"")."\";\n");
	fwrite($fp,"\$cache_uid=\"".addcslashes($row["uid"],"\$\\\"")."\";\n");
	fwrite($fp,"\$cache_date=\"".$row["header_date"]."\";\n");
	fwrite($fp,"\$cache_flaggedbit=\"".$row["flaggedbit"]."\";\n");
	fwrite($fp,"\$cache_subject=\"".addcslashes(htmlnonspecialchars($row["header_subject"]),"\$\\\"")."\";\n\n");

	fwrite($fp,"\$inline2=\"".$wm2_enableinline."\";\n");
	fwrite($fp,"\$secure2=\"".$wm2_securehtmlmails."\";\n");

        $body_plain = str_replace("&quot;","\"",$body_plain);
    
	fwrite($fp,"\$body_plain=\"");
	fwrite($fp,addcslashes($body_plain,"\$\\\""));
	fwrite($fp,"\";\n");
	
	if (count($emailbox)!=0) {
	  fwrite($fp,"\$emailbox=");
	  fwrite($fp, draw_array($emailbox,true));
  } else {
	  fwrite($fp,"\$emailbox=array();\n");
  }
  
	if (count($body_show)!=0) {
	  fwrite($fp,"\$body_show=");
	  fwrite($fp, draw_array($body_show,true));
	} else {
	  fwrite($fp,"\$body_show=array();\n");
    }

	fwrite($fp,"?>\n");
    fclose($fp);
  }

  $webmails = "";
  while (count($body_show) < count($emailbox)) {
    $body_show[count($body_show)][0] = "text";
    $body_show[count($body_show)-1][1] = "";
  }

  if (isset($body_show) and is_array($body_show)) {
    foreach ($body_show as $key=>$key2) {
	  if ($key!=0) {$webmails .= "<br>";}
	  if ($key!=0 and isset($emailbox[$key])) {
	    $webmails .= make_emailbox( $emailbox[$key] );
	  }
	  if ($show_headers=="true") {
	    $webmails .= nl2br(htmlspecialchars(substr($input,0,strpos($input,"\n\n"))))."<br><br>";
	  }

      if ($body_show[$key][0]!="text" and $body_show[$key][0]!="html") {
	    $webmails .= $body_show[$key][0];
	  }
	  $webmails .= $body_show[$key][1];
  }
}
  

$smarty->assign("emailbox", make_emailbox($emailbox[0]));
  
$smarty->assign("msg_no", $msg_no);
$smarty->assign("account", $account);
$smarty->assign("mbox_id", $mbox_id);
$smarty->assign("webmails", $webmails);

if ($realattachments != 0 and $account==0 and $row["readbit"]==0) {
  $sql = "update mgw_webmail2_messages set attachbit=1 where message_id=".(int)$msg_no;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
} else if ($realattachments == 0 and $row["attachbit"]==1) {
  $sql = "update mgw_webmail2_messages set attachbit=0 where message_id=".(int)$msg_no;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
}

} // msgno!=""

if ($print == "true" and $word_export == "true") {
  header("Content-type: application/msword"); // application/vnd.ms-powerpoint
  header("Content-Disposition: attachment; filename=".$row["message_id"].".doc");

  $smarty->register_outputfilter("smarty_remove_all_links");
  $print2 = "";
}

$smarty->assign("print", $print);
$smarty->assign("print2", $print2);

if ($notify and !$row["notified"] and isset($_SESSION["MGW"]->settings["wm2_accept_receipt"]) and $_SESSION["MGW"]->settings["wm2_accept_receipt"]!="") {
  $smarty->assign("notify", $notify);
  $temp = shorten2($row["header_from"]);
  if (!user_exists($temp)) $temp = get_all_email_addresses($row["header_from"]);
  $smarty->assign("notify_url", "sendmail_notify.php?to=".strtolower($temp)."&subject=".urlencode($row["header_subject"])."&inreplyto=".htmlspecialchars($row["uid"])."&date=".$row["header_date"]."&msg_no=".$msg_no."&".SID);
}

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