<?php

/*
 
 File: compose.php3
 $Author: rkrusty $
 $Revision: 1.158 $
 $Date: 1999/04/14 04:02:01 $
 
 IMP: Copyright 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.
 
 */


/* format a from: address correctly based on all relevant factors... */
function get_from($user, $server) {
   global $default, $from;
   
   if ($default->user_change_fullname) {
      $name = imp_get_fullname($user, $server);
   }
   if (!isset($name) || !$name) $name = '';
   
   if (!isset($from) || !$from || !$default->user_change_from) { 
      $from = '';
      if ($name) {
	 $from  = $name;
	 $from .= ' <';
      }
      $from .= get_barefrom($user, $server);
      if ($name) {
	 $from .= '>'; 
      }
   }
   
   return $from;
}

/* 
 * Replace %ENV_NAME% in string with the respective environmental 
 * variable 
 */
function set_env_in_string($text) {
  while(ereg("%([A-Za-z_]+)%", $text, $regs)) {
    $text = ereg_replace( "%([A-Za-z_]+)%", getenv($regs[1]), $text );
  }
  return $text;
}

/* obtain the -0400 or whatever it is for your offset for the date header */
function gm_offset() {
   $offset = ((date("H") - gmdate("H")));
   if ($offset >= 0) { return sprintf("+%02d", $offset) . "00"; }
   else { return sprintf("-%02d", -$offset) . "00"; }
}

/* function that interfaces to sendmail, so from address and all headers
 * are set correctly
 */

function mailfrom($to, $from, $barefrom, $subject, $hdrs, $mesg) {
   global $default;
   
   $hdrs .= "Sender: $barefrom\n";
   if ($default->append_header) {
     $header_array = @file('./config/header.txt');
     for($j = 0; $j < count($header_array); $j++) {
	 $hdrs .= set_env_in_string($header_array[$j]);
     }
   }


   if (is_executable($default->path_to_sendmail)) {
      $mail = popen("$default->path_to_sendmail -t -i -f '$barefrom'", 'w');
      
      $result  = fputs($mail, "From: $from\n");
      $result += fputs($mail, "To: $to\n");
      $result += fputs($mail, $hdrs);
      $result += fputs($mail, "Subject: $subject\n\n");
      $result += fputs($mail, $mesg);
      
      if (pclose($mail) != 0) $result = 0;
      
   } else {
      
      $hdrs = "From: $from\n" . $hdrs;
      
      if (mail($to, $subject, $mesg, $hdrs)) { $result = 1; }
      else { $result = 0; }
   }
   
   if ($result > 0) { return 1; }
   else { return 0; }
}

$need_horde_db = 1;
$db_lib_loaded = 0;
if (!defined("HORDE_LIB")) include ('../lib/horde.lib');
require ('./lib/imp.lib');                   /* IMPlib is the IMP function library  */
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');

require ('../lib/mime.lib');                  /* Mime lib for composing mime messages */
$language = select_lang();
require ("./locale/$language/compose.lang");
require ("./locale/local/compose.lang");
$help_file = 'compose.help';
require ("./locale/defines/$help_file");

/* Setup the this_client object */
$this_client = new WebClient;

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

/* send headers to ensure that the page will reload correctly. */
/* 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();
if (!isset($mailbox)) { $mailbox = 'INBOX'; }
$get_sig = true;

/* login */
$mbox = validate_login($server, $port, $mailbox, $user, $pass, OP_READONLY);

/* array to translate string actions into the appropriate integer ID */
if (!$this_client->lynx) {
   $actions[$lang->button_send]          = SEND_MESSAGE;
} else {
   $actions['[ ' . $lang->button_send . ' ]']          = SEND_MESSAGE;
}
$actions[$lang->button_attach]        = ADD_ATTACHMENT;
$actions[$lang->button_delete_attach] = DELETE_ATTACHMENT;
$actions[$lang->button_bounce]        = BOUNCE_MESSAGE;

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

/* Run through action handlers */

if (isset($actionID)) {
   /* translate non-int values into the correct int */
   if (strcspn($actionID, '0123456789')) { $actionID = $actions[$actionID]; }
   
   switch ($actionID) {
    case NO_ACTION:
      /* don't want it to hit the IMAP server here - nuke the refresh */
      unset($default->refresh_delay);
      status($lang->status_composition);
      $ACTION_TEXT = $lang->status_composition;
      break;
      
    case MAILTO:
      if ($mailbox && $index && $bodypart) {
	 if (!isset($to)) {
	    $h = @imap_header($mbox, imap_msgno($mbox, $index));
	    if ($h->reply_toaddress)
	      $to = chop(htmlspecialchars($h->reply_toaddress));
	    else
	      $to = chop(htmlspecialchars($h->fromaddress )); 
	 }
	 $ACTION_TEXT = $lang->action_compose;
      }
      break;
      
    case REPLY:
      if ($mailbox && $index && $bodypart) {
	 $h = imap_header($mbox, imap_msgno($mbox, $index));
	 
	 /* Set the message_id and references headers */
	 if (isset($h->message_id)) {
	     $in_reply_to = chop(htmlspecialchars($h->message_id));
	     if(isset($h->references)) {
		 $references = chop(htmlspecialchars($h->references)) . " " . $in_reply_to;
	     } else {
		 $references = $in_reply_to;
	     }
	 } else {
	     $in_reply_to = '';
	     $references = '';
	 }
	 
	 if (isset($h->reply_toaddress)) { $to = chop(htmlspecialchars($h->reply_toaddress)); }
	 elseif (isset($h->fromaddress)) { $to = chop(htmlspecialchars($h->fromaddress )); }
	 else $to = '';
	 
	 if (isset($h->fromaddress)) $qfrom = chop(htmlspecialchars($h->fromaddress));
	 else $qfrom = '&lt;&gt;';
	 
	 $msg  = $lang->quoting_string . ' ' . $qfrom . ":\n\n&gt; ";
	 $msg .= htmlspecialchars(wrap_message(imap_fetchbody($mbox, $index, $bodypart, FT_UID), 75, "\n> "));
	 $msg .= "\n";
	 
	 if (isset($h->subject) && (strtolower(substr($h->subject, 0, 3)) != 're:')) $subject = 'Re: ' . chop(htmlspecialchars($h->subject));
	 elseif (isset($h->subject)) $subject = chop(htmlspecialchars($h->subject));
	 else $subject = 'Re: ';
	 
	 $ACTION_TEXT = $lang->action_reply . ' ' . chop(htmlspecialchars($subject));
      }
      break;
      
    case REPLY_ALL:
      if ($mailbox && $index && $bodypart) {
	 $h = imap_header($mbox, imap_msgno($mbox, $index));

	 /* Set the message_id and references headers */
	 if (isset($h->message_id)) {
	     $in_reply_to = chop(htmlspecialchars($h->message_id));
	     if(isset($h->references)) {
		 $references = chop(htmlspecialchars($h->references)) . " " . $in_reply_to;
	     } else {
		 $references = $in_reply_to;
	     }
	 } else {
	     $in_reply_to = '';
	     $references = '';
	 }
	 
	 if ($h->reply_toaddress) { $reply = chop(htmlspecialchars($h->reply_toaddress)); }
	 else { $reply = chop(htmlspecialchars($h->fromaddress )); }
	 
	 /* build up the reply to all addresses */
	 if ($reply != chop(htmlspecialchars($h->fromaddress ))) { $to = $reply . ',' . chop(htmlspecialchars($h->fromaddress )); }
	 else { $to = $reply; }
	 if ( $reply != chop(htmlspecialchars($h->toaddress )) ) { $to .= "," . chop(htmlspecialchars($h->toaddress )); }
	 if (isset($h->ccaddress)) { $to .= ',' . chop(htmlspecialchars($h->ccaddress )); }
	 if (isset($h->bccaddress)) { $to .= ',' . chop(htmlspecialchars($h->bccaddress )); }

	 $msg  = $lang->quoting_string . ' ' . chop(htmlspecialchars($h->fromaddress)) . ":\n\n&gt; ";
	 $msg .= htmlspecialchars(wrap_message(imap_fetchbody($mbox, $index, $bodypart, FT_UID), 75, "\n> "));
	 $msg .= "\n";
	 
	 if (strtolower(substr($h->subject, 0, 3)) != 're:') $subject = 'Re: ' . chop(htmlspecialchars($h->subject));
	 else $subject = chop(htmlspecialchars($h->subject));
	 
	 $ACTION_TEXT = $lang->action_reply_all . ' ' . chop( htmlspecialchars( $h->subject ) );
	 
      }
      break;
      
    case FORWARD:
      if ($mailbox && $index && $bodypart) {
	 $h = imap_header($mbox, imap_msgno($mbox, $index));
	 $message_source = chop(htmlspecialchars($h->fromaddress));
	 $barefrom = get_barefrom($user, $server);
	 $from = get_from($user, $server);
	 
	 $msg  = "\n" . $lang->forwarded_from($message_source) . "\n";
	 
	 if ($h->date) { $msg .= 'Date: ' . chop(htmlspecialchars($h->date)) . "\n"; }
	 if ($h->fromaddress) { $msg .= 'From: ' . chop(htmlspecialchars($h->fromaddress)) . "\n"; }
	 if ($h->reply_toaddress) { $msg .= 'Reply-To: ' . chop(htmlspecialchars($h->reply_toaddress)) . "\n"; }
	 if ($h->subject) { $msg .= 'Subject: ' . chop(htmlspecialchars($h->subject)) . "\n"; }
	 if ($h->toaddress) { $msg .= 'To: ' . chop(htmlspecialchars($h->toaddress)) . "\n"; }
	 $msg .= "\n";
	 $msg .= htmlspecialchars(wrap_message(imap_fetchbody($mbox, $index, $bodypart, FT_UID)));
	 $msg .= "\n----- " . $lang->forward_end_string . " -----\n";
	 
	 $subject = $lang->fwd_string . ' ' . chop(htmlspecialchars($h->subject));
	 $ACTION_TEXT = $lang->action_forward . ' ' . chop( htmlspecialchars( $h->subject ) );
      }
      break;
      
    case BOUNCE_MESSAGE:
      if ($mailbox && $index && $to) {
	 
	 $h = imap_header($mbox, imap_msgno($mbox, $index));
	 $barefrom = get_barefrom($user, $server);
	 
	 if (isset($h->fromaddress)) { $from = $h->fromaddress;
	 } else $from = '';
	 if (isset($h->subject)) { $subject = $h->subject;
	 } else $subject = '';
	 
	 $msg = imap_body($mbox, $index, FT_UID);
	 $hdrs = '';
	 
	 if (mailfrom($to, $from, $barefrom, $subject, $hdrs, $msg)) {
	    status($lang->status_bounce_success);
	    
	    if ($default->save_sent_mail) {
	       $fcc  = 'Date: ' . date("D, d M H:i:s Y ") . gm_offset() . "\n";
	       $fcc .= 'To: ' . $to . "\n";
	       $fcc .= "From: $from\n";
	       $fcc .= 'Subject: ' . $subject . "\n";
	       $fcc .= $hdrs;
	       $fcc .= "\n";
	       $fcc .= $msg;
	    }
	    
	    if (!$this_client->lynx) {
	       echo '<script language="JavaScript">self.close();</script></body></html>';
	    } else {
	       include('./mailbox.php3');
	    }
	    exit;
	 }
	 
	 unset($to);
	 unset($subject);
	 unset($msg);
	 unset($from);
	 unset($barefrom);
	 unset($hdrs);
	 unset($h);
      }
      break;
      
    case SEND_MESSAGE:
      
      if (isset($is_reply) && isset($index) && isset($mailbox) && $is_reply) {
	 imap_reopen($mbox, "{$server:$port}$folders$mailbox");
	 imap_setflag_full($mbox, $index, '\\ANSWERED', SE_UID);
	 imap_reopen($mbox, "{$server:$port}$folders$mailbox", OP_READONLY);
      }
      
      if (isset($attachments_name) && !is_array($attachments_name)) { $attachments = array($attachments_name); }
      if (isset($attachments_size) && !is_array($attachments_size)) { $attachments = array($attachments_size); }
      if (isset($attachments_file) && !is_array($attachments_file)) { $attachments = array($attachments_file); }
      if (isset($attachments_type) && !is_array($attachments_type)) { $attachments = array($attachments_type); }
      
      if ($to && $message) {
	 /* somehow need to verify email addresses */
	 
	 // move these checks into javascript expand function
	 if (!strstr($to, '@')) $to .= "@$server";
	 if ((strlen($cc) > 0) && !strstr($cc, '@')) { $cc .= "@$server"; }
	 if ((strlen($bcc) > 0) && !strstr($bcc, '@')) { $bcc .= "@$server"; }
	 
	 $mime = new mime_message;
	 $mime->init($message);
	 
	 $text_part = new mime_part;
	 $text_part->type = 'text';
	 $text_part->subtype = 'plain';
	 $text_part->contents = $message;
         /* add footer to text_part */
         if ($default->append_trailer) {
	    $config_trailer = "\n" . implode(@file('./config/trailer.txt'), '');
	    $config_trailer = set_env_in_string($config_trailer);
	    $text_part->contents .= $config_trailer;
         }
	 
	 $mime->add_begin_part($text_part);
	 
	 if (count($attachments_name) > 0) {
	    for ($i = 0; $i < count ($attachments_name) - 1; $i++) {
	       $fd = fopen ($attachments_file[$i], 'r');
	       $contents = fread($fd, $attachments_size[$i]);
	       fclose($fd); 
	       unlink($attachments_file[$i]);
	       
	       $file_part = new mime_part;
	       
	       /* some browsers do not send mime type */
	       if (strcmp($attachments_type[$i], '')) { 
		  $file_part->parse_full_type($attachments_type[$i]);
	       } else { 
		  $file_part->parse_full_type('application/octet-stream');
	       }
	       
	       $file_part->transfer_encoding = 'base64';
	       $file_part->name = $attachments_name[$i];
	       $file_part->contents = chunk_split(base64_encode($contents), 73, "\n") . "\n";
	       
	       $mime->add_middle_part($file_part);
	    }
	    
	    $i = count ($attachments_name) - 1;
	    
	    $fd = fopen($attachments_file[$i], 'r');
	    $contents = fread($fd, $attachments_size[$i]);
	    fclose($fd); 
	    unlink($attachments_file[$i]);
	    
	    $file_part = new mime_part;
	    
	    /* some browsers do not send mime type */
	    if (strcmp($attachments_type[$i], '')) { 
	       $file_part->parse_full_type($attachments_type[$i]);
	    } else { 
	       $file_part->parse_full_type('application/octet-stream');
	    }
	    
	    $file_part->transfer_encoding = "base64";
	    $file_part->name = $attachments_name[$i];
	    $file_part->contents = chunk_split(base64_encode($contents)) . "\n";
	    $mime->add_end_part($file_part);
	 }
	 
	 $msg = $mime->generate();
	 $barefrom = get_barefrom($user, $server);
	 $from = get_from($user, $server);

	 $hdrs  = "Errors-To: $barefrom\n";
	 $hdrs .= "Reply-To: $from\n";
	 if ($cc != '') { $hdrs .= "Cc: $cc\n"; }
         if ($bcc != '') { $hdrs .= "Bcc: $bcc\n"; }

	 if (isset($references)) { $hdrs .= "References: $references\n"; }
	 if (isset($in_reply_to)) { $hdrs .= "In-Reply-To: $in_reply_to\n"; }
	 
	 $hdrs .= $mime->header();
	 
	 $hdrs .= 'X-Mailer: IMP/PHP3 Imap webMail Program ' . IMP_VERSION;
	 $hdrs .= "\n";
	 
	 if (mailfrom($to, $from, $barefrom, $subject, $hdrs, $msg)) {
	    status($lang->status_send_success);
	    
	    if ($default->save_sent_mail) {
	       $fcc  = 'Date: ' . date("D, d M H:i:s Y ") . gm_offset() . "\n";
	       $fcc .= 'To: ' . $to . "\n";
	       $fcc .= "From: $from\n";
	       $fcc .= 'Subject: ' . $subject . "\n";
	       $fcc .= $hdrs;
	       $fcc .= "\n";
	       $fcc .= $msg;
	       
	       $preamble = $folders.$default->personal_folders;
	       
	       if (!imap_listmailbox($mbox, "{$server:$port}", "$preamble$default->sent_mail")) {
		  imap_createmailbox($mbox, "{$server:$port}$preamble$default->sent_mail");
		  if ($default->use_imap_subscribe) {
		     imap_subscribe($mbox, "{$server:$port}$preamble$default->sent_mail");
		  }
		  imp_reload_frame('impfolder', 'select.php3');
	       }
	       $fcc = str_replace("\n", "\r\n", $fcc);
	       if (!(imap_append($mbox, "{$server:$port}$preamble"."$default->sent_mail", $fcc))) {
		  status($lang->status_send_save_error . $default->sent_mail);
	       }
	    }
	    
	    if (!$this_client->lynx) {
	       echo '<script language="JavaScript">self.close();</script></body></html>';
	    } else {
	       include('./mailbox.php3');
	    }
	    
	    exit;
	 }
      }
      break;
      
    case ADD_ATTACHMENT:
      
      if (isset($attachments_name) && !is_array($attachments_name)) { $attachments_name = array($attachments_name); }
      if (isset($attachments_size) && !is_array($attachments_size)) { $attachments_size = array($attachments_size); }
      if (isset($attachments_file) && !is_array($attachments_file)) { $attachments_file = array($attachments_file); }
      if (isset($attachments_type) && !is_array($attachments_type)) { $attachments = array($attachments_type); }
      
      if ($file_upload_size > 0) {
	 $attachments_name[] = $file_upload_name;
	 $attachments_size[] = $file_upload_size;
	 $attachments_file[] = $file_upload . '.att';
	 
	 if (isset ($file_upload_type)) {
	    $attachments_type[] = $file_upload_type;
	 } else {
	    $attachments_type[] = '';
	 }
	 
	 $total_size = 0;
	 
	 for ($i = 0; $i < count($attachments_size); $i++) {
	    $total_size += $attachments_size[$i];
	 }
	 
	 rename ($file_upload, $file_upload . '.att');
	 
	 $msg = $message;
      }
      
      $ACTION_TEXT = $lang->action_add_attach;
      $get_sig = false;
      break;
      
    case DELETE_ATTACHMENT:
      
      if (isset($attachments_name) && !is_array($attachments_name)) { $attachments = array($attachments_name); }
      if (isset($attachments_size) && !is_array($attachments_size)) { $attachments = array($attachments_size); }
      if (isset($attachments_file) && !is_array($attachments_file)) { $attachments = array($attachments_file); }
      if (isset($attachments_type) && !is_array($attachments_type)) { $attachments = array($attachments_type); }
      if (isset($delattachments) && !is_array($delattachments)) { $indices = array($delattachments); }
      
      if ($delattachments) {
	 for ($i = 0; $i < count ($delattachments); $i++) {
	    for ($j = 0; $j < count ($attachments_file); $j++) {
	       if (strcmp($delattachments[$i], $attachments_file[$j]) == 0) {
		  unlink ($attachments_file[$j]);
		  $attachments_name[$j] = "";
		  $attachments_size[$j] = "";
		  $attachments_file[$j] = "";
		  $attachments_type[$i] = "";
	       }
	    }
	 }
      }
      
      $new_name = array ();
      $new_file = array ();
      $new_size = array ();
      $new_type = array ();
      
      for ($i = 0; $i < count ($attachments_file); $i++) {
	 if (strcmp($attachments_file[$i], "")) {
	    $new_name[] = $attachments_name[$i];
	    $new_file[] = $attachments_file[$i];
	    $new_size[] = $attachments_size[$i];
	    $new_type[] = $attachments_type[$i];
	 }
      }
      
      $attachments_name = array ();
      $attachments_file = array ();
      $attachments_size = array ();
      $attachments_type = array ();
      
      $total_size = 0;
      
      for ($i = 0; $i < count ($new_name); $i++) {
	 $attachments_name[] = $new_name[$i];
	 $attachments_file[] = $new_file[$i]; 
	 $attachments_size[] = $new_size[$i]; 
	 $attachments_type[] = $new_type[$i]; 
	 $total_size += $attachments_size[$i];
      }
      
      $msg = $message;
      $ACTION_TEXT = $lang->action_del_attach;
      $get_sig = false;
      break;
      
      
    case BOUNCE_COMPOSE:
      $ACTION_TEXT = $lang->action_bounce;
      break;
      
    default:
      $ACTION_TEXT = $lang->action_compose;
      break;
      
   }
}
if (!isset($ACTION_TEXT)) $ACTION_TEXT = $lang->action_compose;
if (!isset($status_sent)) status($lang->status_composition);

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

$barefrom = get_barefrom($user, $server);
$from = get_from($user, $server);
if (!isset($msg)) { $msg = ''; }
if (!isset($to)) { $to = ''; }
if (!isset($cc)) { $cc = ''; }
if (!isset($bcc)) { $bcc = ''; }
if (!isset($subject)) { $subject = ''; }
if ($get_sig && $sig = imp_get_signature($user, $server)) $msg .= "\n\n\n" . $sig;

if (!$this_client->lynx) {
    $addresses = imp_get_addresses($user, $server);
}

if (isset($actionID) && ($actionID == BOUNCE_COMPOSE)) {
   if (!$this_client->lynx) {
      include("$default->include_dir/compose/bounce.inc");
   } else {
      include("$default->include_dir/compose/lynx_bounce.inc");
   }
} else {
   if (!$this_client->lynx) {
      include("$default->include_dir/compose/compose.inc");
   } else {
      include("$default->include_dir/compose/lynx_compose.inc");
   }
}
require("$default->include_dir/generic-footer.inc");
if (!$this_client->lynx) {
   include("$default->include_dir/compose/javascript.inc");   
   include("./lib/js/open_contacts.js");
}

?>
