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

// Readmessage-inc
// Moregroupware.org



function smarty_remove_all_links($tpl_source, &$smarty) {
  $tpl_source = preg_replace(array("'<noscript>.*?</noscript>'si"),array(""),$tpl_source);
  $tpl_source = str_replace(array("norefer.php?url=","noimg.php?download=0&url=","noimg.php?download=1&url=","&nbsp;"),"",$tpl_source);
  return $tpl_source;
}

function wm2_unzip($act_name,$filename,$output_file) {
  if ($output_file=="") {
    $safetmpfname = tempnam ("", "mgw_wm2_unzip_");
    $cmd = $_SESSION["MGW"]->settings["wm2_unzip"]." -p ".$act_name." ".$filename." >".$safetmpfname;
    passthru($cmd);

    $fp = fopen($safetmpfname, "r");
    $text = fread ($fp, filesize ($safetmpfname));
    fclose($fp);
    unlink($safetmpfname);

    return $text;
  } else {
    $cmd = $_SESSION["MGW"]->settings["wm2_unzip"]." -p ".$act_name." ".$filename." >".$output_file;
    passthru($cmd);
  }
}

function verify_gpg($body) {
  $safetmpfname = tempnam ("", "mgw_wm2_checkgpg_");

  $keyserver = ((isset($_SESSION["MGW"]->settings["wm2_gpg_keyserver"]) and $_SESSION["MGW"]->settings["wm2_gpg_keyserver"]!="")?" --keyserver ".$_SESSION["MGW"]->settings["wm2_gpg_keyserver"]:"");

  $output = "";
  $text = "Invalid PHP-Version: < 4.30";
  if (str_replace(".","",PHP_VERSION)>=430) {
    $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", $safetmpfname, "a"));
    $process = proc_open($_SESSION["MGW"]->settings["wm2_gpg_prog"].$keyserver." --no-default-keyring --secret-keyring ".$_SESSION["MGW"]->settings["wm2_gpg_secring"]." --keyring ".$_SESSION["MGW"]->settings["wm2_gpg_pubring"]." --batch --no-tty --always-trust --quiet --no-verbose --textmode", $descriptorspec, $pipes);
    if (is_resource($process)) {
      fwrite($pipes[0], $body);
      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 (strpos(strtolower($text),"good signature")) {
    return array(true, $text, $output);
  } else {
    return array(false, $text, $output);
  }
}

function decrypt_gpg($body) {
  $filename = CACHE_FOLDER."gpg/".$_SESSION["MGW"]->userid.".gpg";
  if (file_exists($filename)) { unlink($filename); }

  $fd = fopen($filename, "wb");
  fwrite($fd,$body);
  fclose($fd);
  
  $safetmpfname = tempnam ("", "mgw_wm2_checkgpg_");

  $keyserver = ((isset($_SESSION["MGW"]->settings["wm2_gpg_keyserver"]) and $_SESSION["MGW"]->settings["wm2_gpg_keyserver"]!="")?" --keyserver ".$_SESSION["MGW"]->settings["wm2_gpg_keyserver"]:"");
  $passphrase = ((isset($_SESSION["MGW"]->settings["wm2_gpg_passphrase"]) and $_SESSION["MGW"]->settings["wm2_gpg_passphrase"]!="")?" --passphrase-fd 0":"");
  
  $output = "";
  $text = "Invalid PHP-Version: < 4.30";
  if (str_replace(".","",PHP_VERSION)>=430) {
    $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", $safetmpfname, "a"));
    $process = proc_open($_SESSION["MGW"]->settings["wm2_gpg_prog"].$keyserver." ".$passphrase." --no-default-keyring --secret-keyring ".$_SESSION["MGW"]->settings["wm2_gpg_secring"]." --keyring ".$_SESSION["MGW"]->settings["wm2_gpg_pubring"]." --batch --no-tty --no-verbose --textmode --output - --always-trust ".CACHE_FOLDER."gpg/".$_SESSION["MGW"]->userid.".gpg", $descriptorspec, $pipes);
    if (is_resource($process)) {
      if (isset($_SESSION["MGW"]->settings["wm2_gpg_passphrase"]) and $_SESSION["MGW"]->settings["wm2_gpg_passphrase"]!="") {
  	    fwrite($pipes[0], $_SESSION["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($filename)) { unlink($filename); }
  
  if (strpos(strtolower($text),"bad passphrase")) {
    return array(false, $text, $output);
  } else {
    return array(true, $text, $output);
  }
}

function quotedPrintableDecode($input)
{
  // Remove soft line breaks
  $input = preg_replace("/=\r?\n/", '', $input);

  // Replace encoded characters
  if (preg_match_all('/=[a-f0-9]{2}/i', $input, $matches)) {
    $matches = array_unique($matches[0]);
    foreach ($matches as $value) {
      $input = str_replace($value, chr(hexdec(substr($value,1))), $input);
    }
  }
  return $input;
}

function findboundary2($line,$boundarys) {
$length = strlen($line);
$result = false;
if ($length>10) { //  and $length<81
  if (substr($line,0,2)=="--") {
  	$line = str_replace("\r","",$line);
    foreach ($boundarys as $boundary) {
      if ($boundary!="" and ("--".$boundary==$line or "--".$boundary."--"==$line)) { 
	    $result = true;
		break;
	  }
    }
  }
}
return $result;
}

function make_proto2($line) {
  global $filename;
  if ($line == "") { $line = "@leer@"; }
  echo htmlspecialchars($line);
  if (strlen($line)<8) {
    for ($i=0;$i < strlen($line);$i++) {
      echo ord($line[$i]).",";
    }
  }
  if ($filename != "") {echo " - ".$filename."<br>\n";} else { echo "<br>\n"; }
}        

function add_filename($filename) {
  global $mime_types, $act_name, $protocol, $attachments2, $record, $input, $dir_nr, $msg_no, $msg_cache, $partno, $message, $danger, $hashmap, $account,$user_id, $message_id;
                  
  $record = true;
  if ($protocol) { echo "<font color='#ff0000'>Record true</font><br>\n";}

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

  if ($account == 0) { $act_name = CACHE_FOLDER.$addon.$dir_nr."/".$msg_no."-".$msg_cache."-".$partno."-".$filename; }
    else { $act_name = CACHE_FOLDER."imap/".$addon.$user_id."-".$message_id."-".$partno."-".$filename; }

  if ($protocol) { echo "<font color='#ff0000'>Define actname ".$act_name."</font><br>\n";}
              
  if ((!isset($mime_types[$ext])) or (isset($mime_types[$ext]) and $mime_types[$ext][1]=="danger")) {
    $message[0] = '<br><font color="#ff0000"><b>'.$hashmap["webmail2_func_virus1"].'</b></font>';
    $message[1] = $hashmap["webmail2_func_virus2"];
    $danger = "yes";
  } else {$danger = "no"; $message="";}
                  
  $input .= "\n".$act_name."\n";
}
                
function searchattachments2($line) {
// echo htmlspecialchars($line)."<br>\n";

  global $content_types, $content_type, $boundarys, $content_transfer_encoding, $content_disposition, $filename, $filename2, $protocol,$block_filename;

  $ctline = "";
  $cbline = "";
  $celine = "";
  $cdline = "";
  $cfline = "";
  $filename_int = "";
  $filename2_int = "";
  if (eregi ("^Content-Type:(.*)", $line, $match)) {
    $ctline = trim($match[1]);

   	if(!strpos($ctline,";")) $endpointer = strlen($ctline); else $endpointer = strpos($ctline,";");

    if(eregi("^[".chr(9)."| ]*boundary", $ctline)) $cbline = trim(str_replace("\"","", substr($ctline, 
    	  												strpos($ctline,"=",strpos($ctline,"boundary"))+1,
    	  												strlen($ctline)- strpos($ctline,"=")))." ");
    if(eregi("name", $ctline)) $filename2_int = basename(trim(str_replace(array("\";","\""),array("",""), substr($ctline, 
    	  												strpos($ctline,"=",strpos($ctline,"name"))+1,
    	  												strlen($ctline)- strpos($ctline,"=")))." "));
	if ($filename2_int!="" and strpos($filename2_int,"; ")) {
	  $filename2_int = substr($filename2_int,0,strpos($filename2_int,"; "));
	}
    $ctline = strtolower(trim(substr($ctline,0,$endpointer)));
  }

  if ($cbline=="" and eregi ("[".chr(9)."| ]*boundary=(.*)", $line, $match)) {
    $cbline = trim(str_replace("\"","",$match[1]));
   	if(!strpos($cbline,";")) $endpointer = strlen($cbline); else $endpointer = strpos($cbline,";");
    $cbline = trim(substr($cbline,0,$endpointer));
  }

  if (eregi ("^Content-Transfer-Encoding:(.*)", $line, $match)) {
    $celine = trim($match[1]);

   	if(!strpos($celine,";")) $endpointer = strlen($celine); else $endpointer = strpos($celine,";");
    $celine = strtolower(trim(substr($celine,0,$endpointer)));

	if ($celine=="7bit") {$celine = ""; $content_transfer_encoding=""; }
  }

  if (eregi ("^Content-Disposition:(.*)", $line, $match)) {
	$cdline = trim($match[1]);

   	if(!strpos($cdline,";")) $endpointer = strlen($cdline); else $endpointer = strpos($cdline,";");
    	
    if(eregi("filename", $cdline)) $filename_int = basename(trim(str_replace(array("\";","\""),array("",""), substr($cdline, 
    	  												strpos($cdline,"=",strpos($cdline,"filename"))+1,
    	  												strlen($cdline)- strpos($cdline,"=")))." "));
	$cdline = strtolower(trim(substr($cdline,0,$endpointer)));
  }

  if ($filename_int=="" and eregi ("^[".chr(9)."| ]*filename=(.*)", $line, $match)) {
	$filename_int = trim(str_replace(array("\";","\""),array("",""),$match[1]));
   	if(!strpos($filename_int,";")) $endpointer = strlen($filename_int); else $endpointer = strpos($filename_int,";");
	$filename_int = basename(strtolower(trim(substr($filename_int,0,$endpointer))));
  }

  if ($filename_int=="" and eregi("^[".chr(9)."| ]*name=(.*)", $line, $match) and !strpos($line,">")) {
	$filename2_int = trim(str_replace(array("\";","\""),array("",""),$match[1]));
   	if(!strpos($filename2_int,";")) $endpointer = strlen($filename2_int); else $endpointer = strpos($filename2_int,";");
	$filename2_int = basename(strtolower(trim(substr($filename2_int,0,$endpointer))));
  }

  if ($filename == "" and $filename2 == "" and eregi("^Content-ID:(.*)", $line, $match)) {
    $cfline = trim($match[1]);

   	if(!strpos($cfline,";")) $endpointer = strlen($cfline); else $endpointer = strpos($cfline,";");
    $cfline = strtolower(trim(substr($cfline,0,$endpointer)));
    
    if ($cfline != "") {
      $cfline = str_replace(array(">","<",""),array("","",""),$cfline);
    }
  }

  if ($ctline!="") { 
    $content_types[] = $ctline; $content_type = $ctline;if ($protocol) { echo "<font color='#ff0000'>Found content_type ".$ctline."</font><br>\n";}
	if ($ctline=="text/calendar") {
	  $filename2 = "calendar.ics";
	}
  }
  if ($cbline!="" and !in_array($cbline,$boundarys)) {$boundarys[] = $cbline; if ($protocol) { echo "<font color='#000080'>Found boundary ".$cbline."</font><br>\n";}}

  if ($celine!="") {$content_transfer_encoding = $celine;if ($protocol) { echo "<font color='#ff0000'>Found encoding ".$celine."</font><br>\n";}}
  if ($cdline!="") {$content_disposition = $cdline;if ($protocol) { echo "<font color='#ff0000'>Found disposition ".$cdline."</font><br>\n";}}

  if ($cfline!="" and !$block_filename) {$filename2 = trim(decode_mime_string($cfline)).".gif"; if ($protocol) { echo "<font color='#ff0000'>Found filename content-id ".$filename2."</font><br>\n";}}
  if ($filename_int!="" and !$block_filename) {$filename = urlencode(trim(decode_mime_string($filename_int))); $filename2 = ""; if ($protocol) { echo "<font color='#ff0000'>Found filename ".$filename."</font><br>\n";}}
  if ($filename2_int!="" and !$block_filename) {$filename2 = urlencode(trim(decode_mime_string($filename2_int))); if ($protocol) { echo "<font color='#ff0000'>Found filename2 ".$filename2."</font><br>\n";}}
  if ($content_type=="message/rfc822" and ($filename!="" or $filename2!="")) {$filename = "";$filename2 = ""; if ($protocol) { echo "<font color='#ff0000'>Kill filename (rfc822) ".$filename."</font><br>\n";}}
}



function make_emailbox($thearray) {
global $msg_no,$settings_replyto,$settings_fullname,$print,$hashmap,$emailsourcelink,$inline,$MGW,$webmails2,$mysize,$word_export,$mbox_id,$global_row;

list($from,$betreff,$datum,$cc,$bcc,$to,$replyto,$size,$priority,$mystructure,$attaches3,$attachments2,$gpg_signature,$gpg_decrypt) = $thearray;

global $replied,$replier2,$forwarded,$user_id,$conn,$realattachments,$account,$message_id;

$realattachments = $realattachments+count($attachments2);

if ($to == "") {$to = htmlspecialchars($hashmap["maillist_empty_account"]);}
if ($from == "") {$from = htmlspecialchars($hashmap["maillist_empty_account"]);}

if ($size!=0 and $size!="") {$size = format_filesize($size);}  

/*
if ($nextmessage!="" and $print!="true") {$vor = '<a href="readmessage.php?msg_no='.$nextmessage.'&reload=true&mbox_id='.$mbox_id.'&msg_begin='.$msg_begin.'">'.$hashmap["maillist_next"].'</a>'; $vor2 = '<a href="readmessage.php?msg_no='.$nextmessage.'&reload=true&mbox_id='.$mbox_id.'&msg_begin='.$msg_begin.'"><img src="templates/default/media/arrow_right.gif" alt="" width="10" height="12" border="0"></a>';} else {$vor = ""; $vor2 = "";}
if ($prevmessage!="" and $print!="true") {$back = '<a href="readmessage.php?msg_no='.$prevmessage.'&reload=true&mbox_id='.$mbox_id.'&msg_begin='.$msg_begin.'">'.$hashmap["maillist_previous"].'</a>'; $back2 = '<a href="readmessage.php?msg_no='.$prevmessage.'&reload=true&mbox_id='.$mbox_id.'&msg_begin='.$msg_begin.'"><img src="templates/default/media/arrow_left.gif" alt="" width="10" height="12" border="0"></a>';} else {$back = ""; $back2 = "";}
*/

$from = decode_mime_string(shorten($from));
$to = decode_mime_string(shorten(stripslashes($to)));
$cc = decode_mime_string(shorten(stripslashes($cc)));
$bcc = decode_mime_string(shorten(stripslashes($bcc)));

if ($betreff=="") { $betreff = "(no subject)"; }

if ($priority == 2 or $priority == 1) {$betreff2 = '<font color="#ff0000"><b>'.$betreff.'</b></font>';} else {$betreff2 = $betreff;}
$mystring = "

<table width='100%' border='0' cellspacing='0' cellpadding='0'>
<tr bgcolor='#D1D1D1'><td>
&nbsp;</td><td bgcolor='#D1D1D1'><font color='#4E4E4E'><b> ".$from." - ".$betreff."</b></font>
";

if ($print!="true") {
  $mystring .= "
	&nbsp; <a href='../contact/index.php?mod=contact&obj=person&view=newform&wm2_contact=".$from."&".SID."' target='_blank'><img src='templates/default/media/contacts.gif' alt='' border='0' align='absmiddle'></a>
  ";
}

$mystring .= "
</td></tr></table>

<img src='templates/default/media/spacer.gif' alt='' width='1' height='5' border='0'><br>
<table width='100%' border='0' cellspacing='0' cellpadding='1' bgcolor='#B6B6B6'>
<tr>
  <td>
    <table width='100%' border='0' cellspacing='0' cellpadding='1' bgcolor='#DFDFDF'><tr><td valign='top'>

	  <table width='100%' border='0' cellspacing='0' cellpadding='0'>
";

if ($print=="true") {
$mystring .= "
      <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left' nowrap valign='top'><b><font color='#4E4E4E'>&nbsp;".$hashmap["maillist_subject"]."</font></b></td>
        <td width='2%' align='center' nowrap valign='top'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'>".$betreff2."</td>
      </tr>
      <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left' nowrap><b><font color='#4E4E4E'>&nbsp;".$hashmap["maillist_date"]."</font></b></td>
        <td width='2%' align='center' nowrap><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%' nowrap>".getDateString_full(strtotime($datum))."</td>
      </tr>
";
}

if ($size!=0 and $print=="true") {
$mystring .= "
	  <tr bgcolor='#DFDFDF'>
		<td width='20%' align='left' nowrap><b><font color='#4E4E4E'>&nbsp;".$hashmap["maillist_size"]."</font></b></td>
		<td width='2%' align='center' nowrap><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
		<td width='78%' nowrap>".$size."</td>
	  </tr>
";}

$from2 = Mail_RFC822::parseAddressList(strtolower($from)." (abc)", '', TRUE);

// $from2 = explode(" ",str_replace("&gt;","",str_replace("&lt;","",$from)));

if ((count($settings_replyto)==0 or count($settings_replyto) > 1 or !in_array(strtolower($from2[0]->mailbox."@".$from2[0]->host),$settings_replyto)) and $print=="true") {
$mystring .= "
	  <tr bgcolor='#DFDFDF'>
		<td width='20%' align='left' valign='top'><b><font color='#4E4E4E'>&nbsp;".$hashmap["maillist_from"]."</font></b></td>
		<td width='2%' align='center' valign='top'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
		<td width='78%'>".$from."</td>
	  </tr>
";}

$to1 = str_replace(array("&quot;","&gt;","&lt;"),array("\"",">","<"),$to);
$to2 = Mail_RFC822::parseAddressList(strtolower($to1)." (abc)", '', TRUE);
if (count($settings_replyto) > 1 or count($settings_replyto) < 1 or (count($settings_replyto)==1 and !in_array(strtolower($to2[0]->mailbox."@".$to2[0]->host),$settings_replyto))) {

$mystring .= "
	  <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left' valign='top' nowrap><b><font color='#4E4E4E'>&nbsp;".$hashmap["maillist_to"];

if ($replyto==$to) {$mystring .= " / ".$hashmap["webmail2_func_replyto"];}
$mystring .= "
		</font></b></td>
        <td width='2%' align='center' valign='top'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'>".make_contact_links($to)."</td>
      </tr>
";}

if ($cc!="") {
$mystring .= "
	  <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left' valign='top'><b><font color='#4E4E4E'>&nbsp;".$hashmap["webmail2_func_copyto"]."</font></b></td>
        <td width='2%' align='center' valign='top'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'>".make_contact_links($cc)."</td>
      </tr>
";}

if ($bcc!="") {
$mystring .= "
	  <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left'><b><font color='#4E4E4E'>&nbsp;".$hashmap["webmail2_func_blindcopyto"]."</font></b></td>
        <td width='2%' align='center'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'>".make_contact_links($bcc)."</td>
      </tr>
";}


if ($from!=$replyto and $replyto!="" and $replyto!=$to) {
$mystring .= "
	  <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left'><b><font color='#4E4E4E'>&nbsp;".$hashmap["webmail2_func_replyto"]."</font></b></td>
        <td width='2%' align='center'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'>".make_contact_links($replyto)."</td>
      </tr>
";}

if ($mystructure!="" and $mysize!="" and $print!="true" and !$MGW->settings["wm2_show_size_in_maillist"]) {
$mystring .= "
	  <tr bgcolor='#DFDFDF'>
		<td width='20%' align='left' nowrap><b><font color='#4E4E4E'>&nbsp;".$hashmap["maillist_size"]."</font></b></td>
		<td width='2%' align='center' nowrap><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
		<td width='78%' nowrap>".$mysize."</td>
	  </tr>
";}

if ($attaches3!=0 and count($attachments2) != 0) {
  $mystring .= "
      <tr bgcolor='#DFDFDF'>
        <td width='20%' align='left' nowrap valign='top'><b><font color='#4E4E4E'>&nbsp;".$hashmap["sendmail_attachments"]."</font></b></td>
        <td width='2%' align='center' nowrap valign='top'><b><font color='#4E4E4E'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%' nowrap>
  ";
  foreach ($attachments2 as $attachment) {
  
	if ($MGW->settings["wm2_performvirusscan"]) {
	  $mytarget = "virusscan.php"; 
	  $mytarget2 = "virusscan.php"; 
	  $mytarget3 = "virusscan.php";
    } else {
	  $mytarget = "download.php";
	  $mytarget2 = "download2.php";
	  $mytarget3 = "download3.php";
    }
    if ($attachment[5]=="yes") {
	  if ($MGW->settings["wm2_performvirusscan"]) {
		$alert = "";
	  } else {
	    $alert = 'onclick="alert(\''.$attachment[2][1].'\');"';
	  }
	} else { $alert = ""; }
	if (!isset($attachment[2]) or !is_array($attachment[2])) {$attachment[2][0] = "";}
    $showlink = true;
    $ext = strtolower(substr($attachment[0],-strpos(strrev($attachment[0]),'.')));
    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;
        }
      }
    }
    $long_name = $attachment[0];
    if ($attachment[0]!="" and strlen($attachment[0]) > 40) {
      $ext = strtolower(substr($attachment[0],-strpos(strrev($attachment[0]),'.')));
      if ($ext != "") { $ext = ".".$ext; }
      if (strlen($attachment[0]) > (strlen($ext)+41)) {
  	    $attachment[0] = substr($attachment[0],0,40)." ... ".$ext;
      }
    }
	if ($print=="true") {
      $mystring .= urldecode($attachment[0])." ( ".$attachment[1]." )<br>";
	} elseif ($showlink) {
      $mystring .= "<a ".$alert." target=\"_blank\" href=\"".$mytarget."?account=".$account."&message_id=".rawurlencode($message_id)."&thefilename=".rawurlencode($long_name)."&msg_id=".rawurlencode($msg_no)."&partno=".rawurlencode($attachment[4])."&".SID."\">".urldecode($attachment[0])."</a>&nbsp;&nbsp;( ".$attachment[1]." ) ";
	  if ($ext=="ics" and isModuleInstalled("calendar2")) {
	    $temp = shorten2($global_row["header_from"]);
		if (user_exists($temp)) $_SESSION["calendar2_preview_from"] = $temp;
	      else $_SESSION["calendar2_preview_from"] = get_all_email_addresses(str_replace(array("&lt;","&gt;"),array("<",">"),strtolower($from)));

		$cal2_url = $mytarget3."?save_in=calendar&mbox_id=".$mbox_id."&account=".$account."&message_id=".rawurlencode($message_id)."&thefilename=".rawurlencode($long_name)."&msg_id=".rawurlencode($msg_no)."&partno=".rawurlencode($attachment[4])."&".SID;
		if ((!isset($global_row["cal_accepted"]) or !$global_row["cal_accepted"]) and isset($_SESSION["MGW"]->settings["wm2_enablecal2_popup"]) and $_SESSION["MGW"]->settings["wm2_enablecal2_popup"]) {
		  $mystring .= "<script>setTimeout(\"open_calendar('".$cal2_url."')\",100);</script>";
		  $sql = "update mgw_webmail2_messages set cal_accepted=1 where message_id=".(int)$msg_no;
		  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
		}
	    $mystring .= '<a target="_top" href="#" onclick="open_calendar(\''.$cal2_url.'\');return false;"><img src="templates/default/media/calendar.gif" alt="'.$hashmap["readmessage_copy_to_calendar"].'" width="16" height="15" align="absmiddle" border="0"></a>';
	  } elseif (isModuleInstalled("files")) {
	    $mystring .= '<a '.$alert.' target="_top" href="'.$mytarget2."?save_in=files&account=".$account."&message_id=".rawurlencode($message_id)."&thefilename=".rawurlencode($long_name)."&msg_id=".rawurlencode($msg_no)."&partno=".rawurlencode($attachment[4])."&".SID.'"><img src="templates/default/media/disc.gif" alt="'.$hashmap["readmessage_copy_to_files_module"].'" width="16" height="9" border="0"></a>';
	  }
	  $mystring .=  " ".$attachment[2][0]."<br>";
    } else {
      $mystring .= urldecode($attachment[0])." ( ".$attachment[1]." ) <font color='#FF0000'><b>".$hashmap["readmessage_disabled_ext"]."</b></font><br>";
    }
  }
  $mystring .= "</td></tr>";
}

$replying = "";
if (is_array($replied) and isset($replied[0])) {
  foreach ($replied as $replier) {
	if ($replying!="") {$replying .= "<br>";}
	if (isset($replier[0]) and isset($replier[1]) and is_numeric($replier[0])) {

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

      if ($row["mbox_id"]!="") {
        $replying .= '<a href="maillist.php?mbox_id='.$row["mbox_id"].'&msg_begin=1&markmessage='.$replier[2].'" target="maillist">'.$replier[1]."</a>&nbsp;(".getDateString($replier[0]).")";
      } else {
        $replying .= $replier[1]."&nbsp;(".getDateString($replier[0]).")";
      }

	}
  }
  $mystring .= "
	  <tr><td><img src='templates/default/media/spacer.gif' alt='' width='1' height='10' border='0'></td></tr>
	  <tr bgcolor='#cceecc'>
        <td width='20%' align='left' valign='top'><b><font color='#000080'>&nbsp;".$hashmap["webmail2_funcs_replied"]."</font></b></td>
        <td width='2%' align='center' valign='top'><b><font color='#000080'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'><font color='#000080'>".$replying."</font></td>
      </tr>
  ";
}

$forwarding = "";
if (is_array($forwarded) and isset($forwarded[0])) {
  foreach ($forwarded as $forwarder) {
	if ($forwarding!="") {$forwarding .= "<br>";}
	if (isset($forwarder[0]) and isset($forwarder[1]) and is_numeric($forwarder[0])) {

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

      if ($row["mbox_id"]!="") {
        $forwarding .= '<a href="maillist.php?mbox_id='.$row["mbox_id"].'&msg_begin=1&markmessage='.$forwarder[2].'" target="maillist">'.$forwarder[1].'</a>&nbsp;('.getDateString($forwarder[0]).')';
      } else {
        $forwarding .= $forwarder[1].'&nbsp;('.getDateString($forwarder[0]).')';
      }

	}
  }
  if ($replying=="") {
    $mystring .= '<tr><td><img src="templates/default/media/spacer.gif" alt="" width="1" height="10" border="0"></td></tr>';
  } else {
    $mystring .= '<tr><td><img src="templates/default/media/spacer.gif" alt="" width="1" height="5" border="0"></td></tr>';
  }
  $mystring .= "
	  <tr bgcolor='#cceecc'>
        <td width='20%' align='left' valign='top'><b><font color='#000080'>&nbsp;".$hashmap["webmail2_funcs_forwarded"]."</font></b></td>
        <td width='2%' align='center' valign='top'><b><font color='#000080'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'><font color='#000080'>".$forwarding."</font></td>
      </tr>
  ";
}

if ($replier2 != "" and is_numeric($replier2)) {

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

  $repl_subject = htmlspecialchars(decode_mime_string($row["header_subject"]));
  
  if ($row["mbox_id"]!="") {
    $replying2 = '<a href="maillist.php?mbox_id='.$row["mbox_id"].'&msg_begin=1&markmessage='.$replier2.'" target="maillist">'.$repl_subject.'</a>';
    $mystring .= "
	  <tr><td><img src='templates/default/media/spacer.gif' alt='' width='1' height='10' border='0'></td></tr>
	  <tr bgcolor='#cceecc'>
        <td width='20%' align='left'><b><font color='#000080'>&nbsp;Source</font></b></td>
        <td width='2%' align='center'><b><font color='#000080'>:&nbsp;&nbsp;</font></b></td>
        <td width='78%'><font color='#000080'>".$replying2."</font></td>
      </tr>
    ";
  }
}

if ($print!="true" and count($webmails2)!=0) {
  if ($inline!="false") {
    $myinline = '<a href="readmessage.php?inline=false&msg_no='.$msg_no.'">'.$hashmap["readmessage_disactivate_inline"].'</a>';
  } else {
    $myinline = '<a href="readmessage.php?inline=true&msg_no='.$msg_no.'">'.$hashmap["readmessage_activate_inline"].'</a>';
  }
} else {$myinline = "";}
$mystring .= "</table></td>";

if (count($gpg_signature)>0 and $gpg_signature[0]=="ok" and strpos(strtolower($gpg_signature[1]),strtolower($from2[0]->mailbox."@".$from2[0]->host))) {
  $mystring .= "<td align='right'><a href='#' onclick=\"alert('".$gpg_signature[1]."');\"><img src='".ROOTURL."/modules/webmail2/templates/default/media/sign.gif' border='0'></a></td>";
} else if (count($gpg_signature)>0 and ($gpg_signature[0]=="bad" or $gpg_signature[0]=="ok")) {
  $mystring .= "<td align='right'><a href='#' onclick=\"alert('".$gpg_signature[1]."');\"><img src='".ROOTURL."/modules/webmail2/templates/default/media/unsign.gif' border='0'></a></td>";
}

if (count($gpg_decrypt)>0 and $gpg_decrypt[0]=="ok" and strpos(strtolower($gpg_decrypt[1]),strtolower($from2[0]->mailbox."@".$from2[0]->host))) {
  if (strpos(strtolower($gpg_decrypt[1]),strtolower($from2[0]->mailbox."@".$from2[0]->host)) and strpos(strtolower($gpg_decrypt[1]),"good signature")) {
    $mystring .= "<td align='right'><a href='#' style='text-decoration:none' onclick=\"alert('".$gpg_decrypt[1]."');\"><img src='".ROOTURL."/modules/webmail2/templates/default/media/sign.gif' border='0' align='absmiddle'>&nbsp; <img src='".ROOTURL."/modules/webmail2/templates/default/media/enc.gif' border='0' align='absmiddle'></a></td>";
  } else {
    $mystring .= "<td align='right'><a href='#' onclick=\"alert('".$gpg_decrypt[1]."');\"><img src='".ROOTURL."/modules/webmail2/templates/default/media/enc.gif' border='0'></a></td>";
  }
} else if (count($gpg_decrypt)>0 and ($gpg_decrypt[0]=="bad" or $gpg_decrypt[0]=="ok")) {
  $mystring .= "<td align='right'><a href='#' onclick=\"alert('".$gpg_decrypt[1]."');\"><img src='".ROOTURL."/modules/webmail2/templates/default/media/unsign.gif' border='0'></a></td>";
}

if ($mystructure!="" and $print!="true") {
  $mystring .= "<td bgcolor='#DFDFDF' align='right' valign='top'><font style='font-size: 11px' color='#4E4E4E'>";
  if ($MGW->settings["wm2_enabledownload"] and $MGW->settings["wm2_showstructure"]) {
	if (count($mystructure) < 4) {$thecount = "3";} else {$thecount = "3";}
    $mystring .= $emailsourcelink."<b>".$hashmap["webmail2_func_structure"]."</b></a><br>";
    if (count($mystructure) > 1) {
	  $mystring .= "
	    <select size=\"".$thecount."\" style=\"font-size: 11px; width: 230px; color: #4E4E4E; background-color:'#DFDFDF'\">";
	  foreach ($mystructure as $strucitem) {
	    $mystring .= "<option>".$strucitem;
	  }	
	  $mystring .= "</select>";
	}
  } elseif ($MGW->settings["wm2_enabledownload"]) {
	$mystring .= $emailsourcelink."<b>".$hashmap["webmail2_func_emailsource"]."</b></a>";  
  } elseif ($MGW->settings["wm2_showstructure"]) {
    if (count($mystructure) > 1) {
	  if (count($mystructure) < 4) {$thecount = "3";} else {$thecount = "3";}
      $mystring .= "<!--<b>".$hashmap["webmail2_func_structure"]."</b><br>-->
	    <select size=\"".$thecount."\" style=\"font-size: 11px; width: 150px; color: #4E4E4E; background-color:'#DFDFDF'\">";
	  foreach ($mystructure as $strucitem) {
	    $mystring .= "<option>".$strucitem;
	  }	
	  $mystring .= "</select>";
	}
  }
  if ($myinline!="" and ($MGW->settings["wm2_enabledownload"] or $MGW->settings["wm2_showstructure"])) {$mystring .= "<br><br>";}
  $mystring .= $myinline."</font></td>";
}
$mystring .= "</tr></table></td></tr></table><br>";

if ($print == "true" and $word_export == "true") {
  $mystring = preg_replace(array("'<a[^>]*?>(.*?)</a[^>]*?>'si"),array("\\1"),$mystring);
}

return $mystring;
}

function modify_html($text) {
	
	global $MGW;

//	$text = preg_replace("/(\012\012)/","<br>",$text);
//	$text = preg_replace("/(\012)/","",$text);


	if ($MGW->settings["wm2_securehtmlmails"]) $text = clean_html($text);

// old one
// $pattern = '=(.*)<a.*href\=[\'"](http|https)://([^"]*)[\'"][^>]*>(.*)</a>(.*)=msiU';
// $repl = '\\1<a target="_blank" href="norefer.php?url=\\2://\\3">\\4</a>\\5';


$i = 0;
$start = 0;
$len = strlen($text);

// echo strlen($text)."<br>";

while ($len>=0) {

  $step = 10000;  
  $subtext[$i] = substr($text,$start,$step);
  $start = $start + $step;
  $len = $len - $step;

  $pattern = '=(.*)<a.[^>]*href\=[ ]*[\'"]([^#"]*)[\'"][^>]*>(.*)</a>(.*)=msiU';
  $subtext[$i] = preg_replace_callback($pattern, "modify_my_callback", $subtext[$i]);

  $pattern = '=(.*)<img(.*)src\=[ ]*[\'"]([^"]*)[\'"](.*)>(.*)=msiU';
  $repl = '\\1<img\\2\\4 src="noimg.php?download='.$MGW->settings["wm2_dontdownloadobjects"].'&url=\\3">\\5';

  $subtext[$i] = preg_replace($pattern, $repl, $subtext[$i]);

  $i++;
}

$text = "";
for ($i2=0;$i2<$i;$i2++) {
  $text .= $subtext[$i2];
}
// echo strlen($text)."<br>";
/*
$text = substr($text,0,15000);

$pattern = '=(.*)<a.*href\=[ ]*[\'"]([^#"]*)[\'"][^>]*>(.*)</a>(.*)=msiU';
$repl = '\\1<a target="_blank" href="norefer.php?url=\\2">\\3</a>\\4';
$text = preg_replace_callback($pattern, "modify_my_callback", $text);

$pattern = '=(.*)<img(.*)src\=[ ]*[\'"]([^"]*)[\'"][^>](.*)>(.*)=msiU';
$repl = '\\1<img\\2\\4 src="noimg.php?download='.$MGW->settings["wm2_dontdownloadobjects"].'&url=\\3">\\5';
$text = preg_replace($pattern, $repl, $text);
*/
// eregi-syntax
// $pattern = '(.*)<a.*href\=[ ]*[\'"]([^#"]*)[\'"][^>]*>(.*)</a>(.*)';
// $repl = '\\1<a target="_blank" href="norefer.php?url=\\2">\\3</a>\\4';
// $text = eregi_replace($pattern, $repl, $text);

// echo strlen($text)."<br>";




// $pattern2 = "=[ ]href\=[ ]*[\"']?([^\"'>]+)=msi";
// preg_match_all($pattern2, $text, $out, PREG_SET_ORDER);



// kick all javascript events
// "|[ ](on[^=].*[ ])[^\"'>]+|msi"
// $pattern2 = "=[ ]on[^\=]+([\=][ ]*[\"']?[^\"'>]+[\"'])=msi";
// preg_match_all($pattern2, $text, $out, PREG_SET_ORDER);
// $text = preg_replace($pattern, $repl, $text);

/*
$pattern = '=(.*)<a.*href\=[\'"]mailto:([^"]*)[\'"][^>]*>(.*)</a>(.*)=msi';
$repl = '\\1<a target="_blank" href="sendmail.php?to=\\2">\\3</a>\\4';

$text = preg_replace($pattern, $repl, $text);
*/

/*
	$pattern1  = '=^(.*)<a\\n*(.*)href\="mailto:(.*)"';
	$pattern1 .= '([^>]*)\\n*>(.*)</a\\n*>(.*)$=msi';
	$repl1 = '\\1<a target="blank" href="sendmail.php?to=\\3"\\4>\\5</a>\\6';
*/
/*
	$pattern2  = '=^(.*)<a\\n*(.*)href\="http://(.*)"';
	$pattern2 .= '([^>]*)\\n*>(.*)</a\\n*>(.*)$=msi';

	$repl2 = '\\1<a target="blank" href="norefer.php?url=\\3"\\4>\\5</a>\\6';
*/			
/*
	$pattern5  = '=^(.*)<img\\n*(.*)src\="(.*)://(.*)"';
	$pattern5 .= '([^>]*)\\n*>(.*)$=msi';
	$repl5 = '\\1<img \\2 src="norefer.php?url=\\3'.urlencode("://").'\\4"\\5>\\6</a>\\7';
*/
//	echo "<pre>".htmlspecialchars($text)."</pre>";

//	$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","norefer.php?url=\\0", $text);
//	$text = ereg_replace("[A-Za-z0-9_.\-]+\@[A-Za-z0-9_\-\.]+[.]+[a-zA-Z]+)","sendmail.php?to=\\1",$text);

	return $text;
}

// Taken from http://www.koehntopp.de/php/regexp.html#regexp-lernen
// $webmails[11] = ereg_replace("([-]+){2,}","<hr size=\"1\">",$webmails[11]);
// $webmails[11] = preg_replace($pattern,"\\1<a target=\"_blank\" href=\"norefer.php?url=\\2\\3\"><u>\\2\\3</u></a>\\4",$webmails[11]);
// Taken from de.php.net: eregi_replace
// &lt;mailto:mailing@freecity.de?Subject=unsubscribe&gt;<br>
// $webmails[11] = ereg_replace("([&lt;]+[A-Za-z0-9_.\-]+\@[A-Za-z0-9_\-]+[.]+[a-zA-Z]+)"," <a target='rightframe' href=\"sendmail.php?to=\\1\">\\1</a>",$webmails[11]);
// $webmails[11] = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"norefer.php?url=\\0\">\\0</a>", $webmails[11]);

function modify_my_callback($s) {

  if (strpos("@".$s[2],"mailto:")==1) {
    $repl = $s[1].'<a target="rightframe" href="sendmail.php?to='.str_replace("mailto:","",addslashes(strip_tags($s[2]))).'">'.$s[3].'</a>'.$s[4];
  } else {
    $repl = $s[1].'<a target="_blank" href="norefer.php?url='.addslashes(strip_tags($s[2])).'">'.$s[3].'</a>'.$s[4];
  }
  
  return $repl;
}

function modify_text($text) {
	global $MGW;

	$text = ereg_replace("([_]+){2,}","<hr size=\"1\">",$text);
//	$text = preg_replace("/(\012)/","",$text);
	$text = preg_replace("/(\015\012)|(\015)|(\012)/","<br>\n",$text);
    $text = wordwrap($text,130,"<br>",1);
	$text = str_replace("<<br>br>","<br>",$text);
	$text = str_replace("<b<br>r>","<br>",$text);
	$text = str_replace("<br<br>>","<br>",$text);
	$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a target=\"_blank\" href=\"norefer.php?url=\\0\">\\0</a>", $text);
	$text = ereg_replace("([A-Za-z0-9_.\-]+\@[A-Za-z0-9_\.\-]+[.]+[a-zA-Z]+)","<a target='rightframe' href=\"sendmail.php?to=\\1\">\\1</a>",$text);
//	$text = ereg_replace("([A-Za-z0-9_.\-]+\@[A-Za-z0-9_\-\.]+[.]+[a-zA-Z]+)","<a target='rightframe' href=\"sendmail.php?to=\\1\">\\1</a>",$text);

	if ($MGW->settings["wm2_show_emoticons"]) {
      $text = str_replace(":)",'<img src="templates/default/media/emoti1.gif" alt=":)" width="19" height="19" border="0" align="absmiddle">',$text);
      $text = str_replace(":-)",'<img src="templates/default/media/emoti1.gif" alt=":-)" width="19" height="19" border="0" align="absmiddle">',$text);

      $text = str_replace(":-(",'<img src="templates/default/media/emoti2.gif" alt=":-(" width="19" height="19" border="0" align="absmiddle">',$text);
      $text = str_replace(":(",'<img src="templates/default/media/emoti2.gif" alt=":(" width="19" height="19" border="0" align="absmiddle">',$text);

      $text = str_replace(";-)",'<img src="templates/default/media/emoti3.gif" alt=";-)" width="19" height="19" border="0" align="absmiddle">',$text);
      $text = str_replace(":-P",'<img src="templates/default/media/emoti4.gif" alt=":-P" width="19" height="19" border="0" align="absmiddle">',$text);
      $text = str_replace(":-D",'<img src="templates/default/media/emoti5.gif" alt=":-D" width="19" height="19" border="0" align="absmiddle">',$text);
      $text = str_replace(":-[",'<img src="templates/default/media/emoti6.gif" alt=":-[" width="19" height="19" border="0" align="absmiddle">',$text);
      $text = str_replace(":-\\",'<img src="templates/default/media/emoti7.gif" alt=":-\" width="19" height="19" border="0" align="absmiddle">',$text);
    }
	return $text;
}

function modify_text2($text) {
	global $MGW;

	$text = preg_replace("/(\015\012)|(\015)|(\012)/","<br>\n",$text);
    $text = wordwrap($text,130,"<br>",1);
	$text = str_replace("<<br>br>","<br>",$text);
	$text = str_replace("<b<br>r>","<br>",$text);
	$text = str_replace("<br<br>>","<br>",$text);
	$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a target=\"_blank\" href=\"norefer.php?url=\\0\">\\0</a>", $text);
	$text = ereg_replace("([A-Za-z0-9_.\-]+\@[A-Za-z0-9_\.\-]+[.]+[a-zA-Z]+)","<a target='rightframe' href=\"sendmail.php?to=\\1\">\\1</a>",$text);

	return $text;
}



?>