<?php
	/***************************************************************************\
	* phpGroupWare - FeLaMiMail                                                 *
	* http://www.linux-at-work.de                                               *
	* http://www.phpgw.de                                                       *
	* http://www.phpgroupware.org                                               *
	* Written by : Lars Kneschke [lkneschke@linux-at-work.de]                   *
	* -------------------------------------------------                         *
	* This program 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.                                                *
	\***************************************************************************/
	/* $Id: class.bocompose.inc.php,v 1.1.1.1.2.8 2002/10/27 19:39:32 lkneschke Exp $ */

	class bocompose
	{
		var $public_functions = array
		(
			'addAtachment'	=> True,
			'action'	=> True
		);
		
		var $attachments;	// Array of attachments
		var $preferences;	// the prefenrences(emailserver, username, ...)

		function bocompose($_composeID = '')
		{
			$this->bopreferences	= CreateObject('felamimail.bopreferences');
			$this->preferences = $this->bopreferences->getPreferences();
			
			if (!empty($_composeID))
			{
				$this->composeID = $_composeID;
				$this->restoreSessionData();
			}
		}
		
		function addAttachment($_formData)
		{
			$this->sessionData['to']	= $_formData['to'];
			$this->sessionData['cc']	= $_formData['cc'];
			$this->sessionData['bcc']	= $_formData['bcc'];
			$this->sessionData['reply_to']	= $_formData['reply_to'];
			$this->sessionData['subject']	= $_formData['subject'];
			$this->sessionData['body']	= $_formData['body'];
			$this->sessionData['priority']	= $_formData['priority'];
			$this->sessionData['signature'] = $_formData['signature'];
			
			#while(list($key,$value) = each($GLOBALS['phpgw_info']['user']))
			#{
			#	print "$key: $value<br>";
			#}
			
			if ($_formData['size'] != 0)
			{
				// ensure existance of PHPGROUPWARE temp dir
				// note: this is different from apache temp dir, 
				// and different from any other temp file location set in php.ini
				if (!file_exists($GLOBALS['phpgw_info']['server']['temp_dir']))
				{
					@mkdir($GLOBALS['phpgw_info']['server']['temp_dir'],0700);
				}
				
				// if we were NOT able to create this temp directory, then make an ERROR report
				if (!file_exists($GLOBALS['phpgw_info']['server']['temp_dir']))
				{
					$alert_msg .= 'Error:'.'<br>'
						.'Server is unable to access phpgw tmp directory'.'<br>'
						.$phpgw_info['server']['temp_dir'].'<br>'
						.'Please check your configuration'.'<br>'
						.'<br>';
				}
				
				// sometimes PHP is very clue-less about MIME types, and gives NO file_type
				// rfc default for unknown MIME type is:
				$mime_type_default = 'application/octet-stream';
				// so if PHP did not pass any file_type info, then substitute the rfc default value
				if (trim($_formData['type']) == '')
				{
					$_formData['type'] = $mime_type_default;
				}
				
				$tmpFileName = $GLOBALS['phpgw_info']['server']['temp_dir'].
					SEP.
					$GLOBALS['phpgw_info']['user']['account_id'].
					$this->composeID.
					basename($_formData['file']);
				
				copy($_formData['file'],$tmpFileName);
				
				$this->sessionData['attachments'][]=array
				(
					'name'	=> $_formData['name'],
					'type'	=> $_formData['type'],
					'file'	=> $tmpFileName,
					'size'	=> $_formData['size']
				);
			}
			
			$this->saveSessionData();
		}
		
		function getAttachmentList()
		{
		}
		
		// create a hopefully unique id, to keep track of different compose windows
		// if you do this, you are creating a new email
		function getComposeID()
		{
			mt_srand((float) microtime() * 1000000);
			$this->composeID = mt_rand (100000, 999999);
			
			$this->setDefaults();
			
			return $this->composeID;
		}
		
		function getForwardData($_uid)
		{
			$bofelamimail    = CreateObject('felamimail.bofelamimail');
			$bofelamimail->openConnection();
			
			// get message headers for specified message
			$headers	= $bofelamimail->getMessageHeaders($_uid, ST_UID);
			
			// check for Re: in subject header
			$this->sessionData['subject'] = "[FWD: " . $bofelamimail->decode_header($headers->Subject)."]";

			$structure     = $bofelamimail->getMessageStructure($_uid, ST_UID);
			if(sizeof($structure->parts) > 1)
			{
				$sections = $bofelamimail->parse($structure);
				$attachments = $bofelamimail->get_attachments($sections);
			}
			
			$this->sessionData['body']	 = "                  -----------Originalnachricht-----------\n\n";
			$this->sessionData['body']	.= "Betreff: ".$bofelamimail->decode_header($headers->Subject)."\n";
			$this->sessionData['body']	.= "Von: ".$bofelamimail->decode_header($headers->toaddress)."\n";
			$this->sessionData['body']	.= "An: ".$bofelamimail->decode_header($headers->fromaddress)."\n\n";
			
			// iterate through message parts
			if(is_array($sections))
			{
				for($x=0; $x<sizeof($sections); $x++)
				{
					// if text type, display
					if($sections[$x]["type"] == "text/plain" && $sections[$x]["disposition"] 
						!= "attachment")
					{
						$bodyPart = $bofelamimail->getMessageBody($_uid, $sections[$x]["pid"], ST_UID);
						$this->sessionData['body'] .= quoted_printable_decode($bodyPart);
					}
				}
			}
			else
			{
				$this->sessionData['body']	.= $bofelamimail->getMessageBody($_uid, '', ST_UID);
			}
																
			$this->sessionData['body']	 .= "\n\n                  -----------Originalnachricht-----------\n\n";
					
			$bofelamimail->closeConnection();
			
			$this->saveSessionData();
		}

		// $_mode can be:
		// single: for a reply to one address
		// all: for a reply to all
		function getReplyData($_mode, $_uid)
		{
			$bofelamimail    = CreateObject('felamimail.bofelamimail');
			$bofelamimail->openConnection();
			
			// get message headers for specified message
			$headers	= $bofelamimail->getMessageHeader($_uid);

			$this->sessionData['uid'] = $_uid;
			
			// check for Reply-To: header and use if available
			if($headers->reply_toaddress)
			{
				$this->sessionData['to'] = $bofelamimail->decode_header(trim($headers->reply_toaddress));
			}
			else
			{
				$this->sessionData['to'] = $bofelamimail->decode_header(trim($headers->fromaddress));
			}
			
			if($_mode == 'all')
			{
				#_debug_array($this->preferences);
				// reply to any address which is cc, but not to my self
				$oldCC = $bofelamimail->decode_header(trim($headers->ccaddress));
				$addressParts = imap_rfc822_parse_adrlist($oldCC, '');
				if (count($addressParts)>0)
				{
					while(list($key,$val) = each($addressParts))
					{
						if($val->mailbox.'@'.$val->host == $this->preferences['emailAddress'])
						{
							continue;
						}
						if(!empty($this->sessionData['cc'])) $this->sessionData['cc'] .= ",";
						if(!empty($val->personal))
						{
							$this->sessionData['cc'] .= sprintf('"%s" <%s@%s>',
											$val->personal,
											$val->mailbox,
											$val->host);
						}
						else
						{
							$this->sessionData['cc'] .= sprintf("%s@%s",
											$val->mailbox,
											$val->host);
						}
					}
				}
				
				
				// reply to any address which is to, but not to my self
				$oldTo = $bofelamimail->decode_header(trim($headers->toaddress));
				$addressParts = imap_rfc822_parse_adrlist($oldTo, '');
				if (count($addressParts)>0)
				{
					while(list($key,$val) = each($addressParts))
					{
						if($val->mailbox.'@'.$val->host == $this->preferences['emailAddress'])
						{
							continue;
						}
						#print $val->mailbox.'@'.$val->host."<br>";
						if(!empty($this->sessionData['to'])) $this->sessionData['to'] .= ", ";
						if(!empty($val->personal))
						{
							$this->sessionData['to'] .= sprintf('"%s" <%s@%s>',
											$val->personal,
											$val->mailbox,
											$val->host);
						}
						else
						{
							$this->sessionData['to'] .= sprintf("%s@%s",
											$val->mailbox,
											$val->host);
						}
					}
				}
			}
			
			
			// check for Re: in subject header
			if(strtolower(substr(trim($headers->Subject), 0, 3)) == "re:")
			{
				$this->sessionData['subject'] = $bofelamimail->decode_header($headers->Subject);
			}
			else
			{
				$this->sessionData['subject'] = "Re: " . $bofelamimail->decode_header($headers->Subject);
			}

			$structure = $bofelamimail->getMessageStructure($_uid);
			if(sizeof($structure->parts) > 1)
			{
				$sections = $bofelamimail->parse($structure);
				$attachments = $bofelamimail->get_attachments($sections);
			}
			
			$this->sessionData['body']	= "On " . $headers->Date . ", you wrote: \n>";
			
			// get the body
			$bodyParts = $bofelamimail->getMessageBody($_uid);
			for($i=0; $i<count($bodyParts); $i++)
			{
				$this->sessionData['body']	.= str_replace("\n", "\n>", $bodyParts[$i]);
			}
																
					
			$bofelamimail->closeConnection();
			
			$this->saveSessionData();
		}
		
		function getSessionData()
		{
			return $this->sessionData;
		}

		// get the user name, will will use for the FROM field
		function getUserName()
		{
			$retData = sprintf("%s <%s>",$this->preferences['realname'],$this->preferences['emailAddress']);
			return $retData;
		}
		
		function removeAttachment($_formData)
		{
			$this->sessionData['to']	= $_formData['to'];
			$this->sessionData['cc']	= $_formData['cc'];
			$this->sessionData['bcc']	= $_formData['bcc'];
			$this->sessionData['reply_to']	= $_formData['reply_to'];
			$this->sessionData['subject']	= $_formData['subject'];
			$this->sessionData['body']	= $_formData['body'];
			$this->sessionData['priority']	= $_formData['priority'];
			$this->sessionData['signature']	= $_formData['signature'];

			while(list($key,$value) = each($_formData['removeAttachments']))
			{
				#print "$key: $value<br>";
				unlink($this->sessionData['attachments'][$key]['file']);
				unset($this->sessionData['attachments'][$key]);
			}
			reset($this->sessionData['attachments']);
			
			// if it's empty, clear it totaly
			if (count($this->sessionData['attachments']) == 0) 
			{
				$this->sessionData['attachments'] = '';
			}
			
			$this->saveSessionData();
		}
		
		function restoreSessionData()
		{
			$this->sessionData = $GLOBALS['phpgw']->session->appsession('compose_session_data_'.$this->composeID);
		}
		
		function saveSessionData()
		{
			$GLOBALS['phpgw']->session->appsession('compose_session_data_'.$this->composeID,'',$this->sessionData);
		}

		function send($_formData)
		{
			$this->sessionData['to']	= $_formData['to'];
			$this->sessionData['cc']	= $_formData['cc'];
			$this->sessionData['bcc']	= $_formData['bcc'];
			$this->sessionData['reply_to']	= $_formData['reply_to'];
			$this->sessionData['subject']	= $_formData['subject'];
			$this->sessionData['body']	= $_formData['body'];
			$this->sessionData['priority']	= $_formData['priority'];
			$this->sessionData['signature']	= $_formData['signature'];


			$mail = CreateObject('felamimail.phpmailer');
			
			#print $this->sessionData['uid']."<bR>";
			#print $this->sessionData['folder']."<bR>";
			
			#_debug_array($_formData);
			#exit;
			
			#include(PHPGW_APP_ROOT . "/config/config.php");
				
			$mail->IsSMTP();
			$mail->From 	= $this->preferences['emailAddress'];
			$mail->FromName = $this->preferences['realname'];
			$mail->Host 	= $this->preferences['smtpServerAddress'];
			$mail->Priority = $this->sessionData['priority'];
			$mail->Encoding = '8bit';
			$mail->PluginDir = PHPGW_SERVER_ROOT."/felamimail/inc/";

			if (!empty($this->sessionData['to']))
			{
				$address_array	= imap_rfc822_parse_adrlist($this->sessionData['to'],'');
				if(count($address_array)>0)
				{
					for($i=0;$i<count($address_array);$i++)
					{
						$emailAddress = $address_array[$i]->mailbox."@".$address_array[$i]->host;
						$emailName = $address_array[$i]->personal;
						$mail->AddAddress($emailAddress,$emailName);
					}
				}
			}

			if (!empty($this->sessionData['cc']))
			{
				$address_array	= imap_rfc822_parse_adrlist($this->sessionData['cc'],'');
				if(count($address_array)>0)
				{
					for($i=0;$i<count($address_array);$i++)
					{
						$emailAddress = $address_array[$i]->mailbox."@".$address_array[$i]->host;
						$emailName = $address_array[$i]->personal;
						$mail->AddCC($emailAddress,$emailName);
					}
				}
			}
			
			if (!empty($this->sessionData['bcc']))
			{
				$address_array	= imap_rfc822_parse_adrlist($this->sessionData['bcc'],'');
				if(count($address_array)>0)
				{
					for($i=0;$i<count($address_array);$i++)
					{
						$emailAddress = $address_array[$i]->mailbox."@".$address_array[$i]->host;
						$emailName = $address_array[$i]->personal;
						$mail->AddBCC($emailAddress,$emailName);
					}
				}
			}
			
			if (!empty($this->sessionData['reply_to']))
			{
				$address_array	= imap_rfc822_parse_adrlist($this->sessionData['reply_to'],'');
				if(count($address_array)>0)
				{
					$emailAddress = $address_array[0]->mailbox."@".$address_array[0]->host;
					$emailName = $address_array[0]->personal;
					$mail->AddReplyTo($emailAddress,$emailName);
				}
			}
			
			$mail->WordWrap = 76;
			$mail->Subject = "=?iso-8859-1?Q?".imap_8bit($this->sessionData['subject'])."?=";
			$mail->IsHTML(false);
			$mail->Body    = $this->sessionData['body'];
			if (!empty($this->sessionData['signature']))
			{
				$mail->Body	.= "\r\n--\r\n";
				$mail->Body	.= $this->sessionData['signature'];
			}
			if (is_array($this->sessionData['attachments']))
			{
				while(list($key,$value) = each($this->sessionData['attachments']))
				{
					$mail->AddAttachment
					(
						$value['file'],
						$value['name'],
						'base64',
						$value['type']
					);
				}
			}
			#$mail->AltBody = $this->sessionData['body'];
			
			if(!$mail->Send())
			{
				echo "Message could not be sent. <p>";
				echo "Mailer Error: " . $mail->ErrorInfo;
				exit;
			}

			if ($this->preferences['move_to_sent'] == "true")
			{
				$username 		= $this->preferences['username'];
				$key 			= $this->preferences['key'];
				$imapServerAddress 	= $this->preferences['imapServerAddress'];
				$imapPort 		= $this->preferences['imapPort'];
				$sent_folder		= $this->preferences['sent_folder'];
			
				include(PHPGW_APP_ROOT . "/inc/imap_general.php");
				include(PHPGW_APP_ROOT . "/inc/imap_mailbox.php");
				include(PHPGW_APP_ROOT . "/inc/smtp.php");
			
				$imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
				$sent_folder = trim($sent_folder);
				if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) 
				{
					sqimap_append ($imap_stream, $sent_folder, 
						strlen($mail->create_header())+strlen($mail->create_body()));
					fputs ($imap_stream, $mail->create_header());
					fputs ($imap_stream, $mail->create_body());
					sqimap_append_done ($imap_stream);
				}
				sqimap_logout($imap_stream);
			}
			if(isset($this->sessionData['uid']))
			{
				// mark message as answered
				$bofelamimail = CreateObject('felamimail.bofelamimail',$this->sessionData['folder']);
				$bofelamimail->openConnection();
				$bofelamimail->flagMessages("answered",array('0' => $this->sessionData['uid']));
				$bofelamimail->closeConnection();
			}
			while(list($key,$value) = @each($this->sessionData['attachments']))
			{
				#print "$key: $value<br>";
				unlink($value['file']);
			}
			
			$this->sessionData = '';
			$this->saveSessionData();
		}
		
		function setDefaults()
		{
			$this->sessionData['signature']	= $this->preferences['signature'];
			
			$this->saveSessionData();
		}
		
		function stripSlashes($_string) 
		{
			if (get_magic_quotes_gpc()) 
			{
				return stripslashes($_string);
			}
			else
			{
				return $_string;
			}
		}
                              

}