<?php

/*
 
 File: message.php3
 $Author: chuck $
 $Revision: 1.107 $
 $Date: 1999/04/13 16:14:11 $
 
 IMP: Copyright 1998, 1999 Charles J. Hagenbuch <chuck@horde.org>
 
 You should have received a copy of the GNU Public
 License along with this package; if not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 
 */


function add_attachment ($mime, $ref) {
   global $atc, $mailbox, $index, $default, $lang;
   if ($mime->name == '') { $mime->name = $lang->attachment . ' ' . $ref; }
   if ($mime->size != 0) {
      if (!isset($atc)) $atc = '';
      $atc .= $mime->display();
   }
}

function parse_attachement ($part, $ref, $msg) {
   global $bodypart, $mailbox, $mbox,  $index, $default, $lang, $textpart, $server, $port, $user, $pass;
   $j = 0;
   
   $num_parts = count($part->parts);
   while ($j < $num_parts) {
      if (strlen($ref) == 0)
	$aref="".($j+1);
      else
	$aref=$ref.".".($j+1);
      if (isset($part->parts[$j])) {
	 $p = $part->parts[$j];
	 if (isset($p->parts[0]))
	   $msg = parse_attachement($p,$aref,$msg);
      }
      else {
	 $p = $part;
      }
      $mime = new mime_part_data;
      $mime->set_imap_data($mailbox, $index, $aref);
      $mime->parse($p);
      // we only display the first text part (we can change it to display all
      // textual parts, separated by <HR>) 
      // We do not display text/plain parts with base64 or binary or unknown
      // encoding
      if ($mime->type == 1 && $mime->subtype == 'plain'  && $mime->size > 0 &&
	  ($mime->encoding == 0 || $mime->encoding == 1 || $mime->encoding ==4) &&
	  ($textpart == 0 || $default->text_parts_inline)) {

	 /* Safe to display, it is text */
	 /* get and format the main body part */
	 $tmsg = @imap_fetchbody($mbox, $index, $aref , FT_UID);
	 
	 /* some balky IMAP servers don't get it right at first... */
	 while(!is_string($tmsg) || !imap_ping($mbox)) {
	     $mbox = imap_open("{$server:$port}$mailbox", $user, $pass);
	     $tmsg = @imap_fetchbody($mbox, $index, $aref , FT_UID);
	 }

	 /* If its a quoted-printable document, translate it into the right charset */
	 if ($mime->encoding == 4) {
	     $tmsg = imap_qprint($tmsg);
	 }

	 $tmsg = wrap_message($tmsg, 85);
	 $tmsg = wrap($tmsg, 85);
	 $tmsg = eregi_replace("(http|https|ftp)://([[:alnum:]/\n+-=%&:_.~?@]+[#[:alnum:]+]*)",
	 		       "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>", $tmsg);
	 $tmsg = htmlspecialchars($tmsg);
	 $tmsg = str_replace('&lt;a href=&quot;', '<a href="', $tmsg);
	 $tmsg = str_replace('&quot; target=&quot;_blank&quot;&gt;', '" target="_blank">', $tmsg);
	 $tmsg = str_replace('&lt;/a&gt;', '</a>', $tmsg);
	 $charset = $mime->charset;
	 if ($textpart > 0) {
	    $msg = $msg . "<br><br><hr width=\"50%\" size=9 align=\"center\"><br><br>" . $tmsg;
	    add_attachment(&$mime,$aref);
	 } else {
	    $msg = $tmsg;
	    if (!isset($bodypart))
	      $bodypart = $aref;
	 }
	 $textpart++;

      /* It may not be text directly, but if its configured to be displayed inline, inline it */
      } else if(isset($mime->action["view"]) && isset($mime->action["inline"]) &&
		$mime->action["view"] == true && $mime->action["inline"] == true &&
		isset($mime->action["view_function"])) {

	  if ($textpart > 0) {

	      /* If this MIME-type is configured to override other things for display, do it */
	      if(isset($mime->action["override_text"]) && $mime->action["override_text"] == true) {
		  $msg = '';
	      } else {
		  $msg = $msg . "<br><br><hr width=\"50%\" size=9 align=\"center\"><br><br>";
	      }
	      
	      eval( '$mime_part =  '.$mime->action["view_function"].'($mime);' );
	      $msg = $msg . $mime_part;
	  } else {
	      eval( '$mime_part =  '.$mime->action["view_function"].'($mime);' );
	      $msg = $msg . $mime_part;
	      if (!isset($bodypart))
		  $bodypart = $aref;
	  }
	  $textpart++;
	  
	  /* add it as an attachment link to download if this type is downloadable */
	  if(isset($mime->action["download"]) &&
	     $mime->action["download"] == true) {
	      add_attachment(&$mime, $aref);
	  }
      } else {
	  add_attachment(&$mime, $aref);
      }
      $j++;
   }
   return $msg;
}


function wrap ($text, $wrap = 80, $break = "\n") {
   $paras = explode("\n", $text);
   
   $result = array();
   $i = 0;
   while ($i < count($paras)) {
      if (strlen($paras[$i]) <= $wrap) {
	 $result[] = $paras[$i];
	 $i++;
      } else {
	 $result[] = substr($paras[$i], 0, $wrap);
	 $new = trim(substr($paras[$i], $wrap, strlen($paras[$i]) - $wrap));
	 if ($new != '') $paras[$i] = $new;
	 else $i++;
      }
   }
   return implode($break, $result);
}


$need_horde_db = 0;
$db_lib_loaded = 0;
if (!defined("HORDE_LIB")) include ('../lib/horde.lib');
require('./lib/imp.lib');           /* IMPlib is the IMP function library */
require('./lib/mimetypes.lib');     /* Mime handling routes */
require('./config/defaults.php3');  /* Defaults configuration file */

/* Html styles configuration */
require('./config/html.php3');
/* Mailbox configuration */
require('./config/mailbox.php3');
/* include mime and language configuration */
require('./config/mime.php3');
require('./config/lang.php3');
$language = select_lang();
require ("./locale/$language/message.lang");
require ("./locale/local/message.lang");

error_reporting($default->error_level);  /* set error level from imp.lib   */
caching_headers();

$session = create_session_object();
$user    = $session->get_user();
$pass    = $session->get_password();
$server  = $session->get_server();
$port    = $session->get_port();
$folders = $session->get_folder();
$sorted  = $session->get_msgl();
if (!$mailbox) $mailbox = 'INBOX';
$current_mbox = str_replace("{$server}$folders", '', $mailbox);

if (strlen($default->personal_folders) > 0) $current_mbox = str_replace("$default->personal_folders", '', $current_mbox);

$mbox = validate_login($server, $port, $mailbox, $user, $pass);

/* doctype */
require("$default->include_dir/doctype.inc");

/* Run through action handlers */

if (isset($actionID)) {
   switch ($actionID) {
    case NO_ACTION:
      break;
      
    case DELETE_MESSAGES:
      if ($index && $mailbox) {
	 if (!(@imap_delete($mbox, imap_msgno($mbox, $index)))) {
	    $errormsg = $lang->delete_error;
	 }
	 $array_index++;
	 $index = $sorted[$array_index];
      }
      break;

   case MOVE_MESSAGES:
       if (isset($index) && isset($targetMbox) && $index && $targetMbox) {
	   if(!(@imap_mail_copy($mbox, $index, $targetMbox, CP_UID|CP_MOVE))) {
	       $status_string = $lang->move_error;
	       $status_color = 'red';
	   } else {
	       $plural = false;
	       $status_string = $lang->success2($current_mbox, $targetMbox, 'moved', 1, $plural);
	       $status_color = 'green';
	       $array_index++;
	       $index = $sorted[$array_index];
	   }
       }
       if(!isset($status_string)) {
	   $plural = false;
	   $status_string = $lang->move_error;
	   $status_color = 'red';
       }  
       break;

   case COPY_MESSAGES:
       if (isset($index) && isset($targetMbox) && $targetMbox && $index) {
	   if(!@imap_mail_copy($mbox, $index, $targetMbox, CP_UID)) {
	       $status_string = $lang->copy_error;
	       $status_color = 'red';
	   } else {
	       $plural = false;
	       $status_string = $lang->success2($current_mbox, $targetMbox, 'copied', 1, $plural);
	       $status_color = 'green';
	       $array_index++;
	       $index = $sorted[$array_index];
	   }
       }
       if(!isset($status_string)) {
	   $plural = false;
	   $status_string = $lang->copy_error;
	   $status_color = 'red';
       }
       break;
   }
}

$options = mailbox_list($mailbox, true);

/* parse MIME header info */

$structure = @imap_fetchstructure($mbox, imap_msgno($mbox, $index));

/* some balky IMAP servers don't get it right at first... */
while(!is_object($structure) || !imap_ping($mbox)) {
    $mbox = imap_open("{$server:$port}$mailbox", $user, $pass);
    $structure = @imap_fetchstructure($mbox, imap_msgno($mbox, $index));
}

$num_parts = count($structure->parts);

$textpart = 0;
$num = 0;
$msg = "&nbsp;";
$msg = parse_attachement($structure,"",$msg);

if ($default->view_message_source) {
   if (!isset($atc)) $atc = "";
   $mime = new mime_part_data;
   $mime->set_type_full( "mail/source" );
   $atc .= "<a target=\"_blank\" href=\"$default->root_url/view.php3?mailbox=" . urlencode($mailbox) . "&index=$index&bodypart=$bodypart&actionID=" . VIEW_SOURCE . '">' . $mime->img_tag() . ' ' . $lang->source . '</a><br>';
}


$h = @imap_header($mbox, imap_msgno($mbox, $index));

/* some balky IMAP servers don't get it right at first... */
while(!is_object($h) || !imap_ping($mbox)) {
    $mbox = imap_open("{$server:$port}$mailbox", $user, $pass);
    $h = @imap_header($mbox,imap_msgno($mbox, $index));
}
   

if (isset($h->date))            { $dat = htmlspecialchars(chop($h->date)); }
if (isset($h->toaddress))       { $to  = htmlspecialchars(decode_mime_string(chop($h->toaddress))); }
if (isset($h->fromaddress))     { $frm = htmlspecialchars(decode_mime_string(chop($h->fromaddress))); }
if (isset($h->ccaddress))       { $cc  = htmlspecialchars(decode_mime_string(chop($h->ccaddress))); }
if (isset($h->bccaddress))      { $bcc  = htmlspecialchars(decode_mime_string(chop($h->bccaddress))); }
if (isset($h->reply_toaddress)) { $rep = htmlspecialchars(decode_mime_string(chop($h->reply_toaddress))); }
if ((isset($h->subject)) && (strlen($h->subject) != 0)) {
   $sub = htmlspecialchars(decode_mime_string(chop($h->subject)));
} else {
   $sub = $lang->no_subject;
}

// try and add some space in order to break really long header lines
if (isset($to)) $to = str_replace(',', ', ', $to);
if (isset($cc)) $cc = str_replace(',', ', ', $cc);
if (isset($frm)) $frm = str_replace(',', ', ', $frm);
if (isset($bcc)) $bcc = str_replace(',', ', ', $bcc);
if (isset($rep)) $rep = str_replace(',', ', ', $rep);

$msg_index = $array_index + 1;
$num_msgs = imap_num_msg($mbox);

$title = "$mailbox: $sub";

$sidebar = false;
require("$default->include_dir/generic-header.inc");

$prev_index = $array_index - 1;
$next_index = $array_index + 1;

if (isset($sorted[$prev_index])) $prev = $sorted[$prev_index];
else $prev = -1;

if (isset($sorted[$next_index])) $next = $sorted[$next_index];
else $next = -1;

if ($msg_index != count($sorted)) {
   $del_target = 'message.php3';
   $del_ident  = 'index';
} else {
   $del_target = 'mailbox.php3';
   $del_ident  = 'indices';
}

require('./lib/js/open_compose_win.js');
require('./lib/js/open_contacts.js');
require("$default->include_dir/message/navbar_aux_top.inc");
require("$default->include_dir/message/navbar.inc");
require("$default->include_dir/message/headers.inc");
require("$default->include_dir/message/message.inc");
require("$default->include_dir/message/navbar.inc");
require("$default->include_dir/message/navbar_aux_bottom.inc");
require("$default->include_dir/message/javascript.inc");

if(isset($status_string)) {
   status($status_string, $status_color);
}

require("$default->include_dir/generic-footer.inc");
?>
