# $Id: Send.pm,v 1.5 2002/05/11 09:55:50 muhri Exp $
# -*- perl -*-
package Pronto::Send;
use SelfLoader;
use vars qw( $inter $called_from_send);
use strict;
use Pronto::Data::Message;
1;
__DATA__

sub send 
{
	if ($called_from_send == 1 and $inter ==1)
	{
		use Gtk;
		init Gtk;
	}	
  
	#touch lock file
	open(TMP,">$main::prefs{'MailDir'}/prontosend.running");
	print TMP "$$\n";
	close(TMP);

	use IO::Socket;
	use Sys::Hostname;
	use Text::ParseWords;


	my ($sql, $query, @row, $sql2, $query2, $smtp, @test, $tmp, @body, $sender, $msg, $mailline);
	my $crlf="\r\n";


	$sql = "select id, accountid, sentto, sentfrom, subject, replyto, cc, bcc from messages where boxid = ?";
	$query = $main::conn->prepare($sql);
	$query->execute(2);
	while (@row=$query->fetchrow_array()) {
		my ($msgid, $acctid, $to, $from, $subj, $reply, $cc, $bcc) = @row;
		my $port;
		$sql2 = "select smtp from accounts where id = ?";
		$query2=$main::conn->prepare($sql2);
		$query2->execute($acctid);
		($smtp) = $query2->fetchrow_array();
		($smtp, $port) = split(/:/, $smtp);
		if (!$port || $port eq "") { $port = 25; };
	        if (!$main::prefs{'use_http_proxy'}) {
		    @test = gethostbyname($smtp);# or next;
		    if (!@test) { 
			#       if ($inter == 1) {
			#		&main::err_dialog("SMTP error: Could not resolve hostname $smtp","y");
			#	}
			print(_("SMTP error: Could not resolve hostname ")."$smtp\n");
			next;
		    }
		}
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		#get the body
		@body = &Pronto::Data::Message::get_source($msgid);
		# open connection to the smtp server
	    if (!$main::prefs{'use_http_proxy'}) {
		$sender=IO::Socket::INET->new( PeerAddr => $smtp,
 						PeerPort => $port,
						Proto => 'tcp',
		        			Timeout=>60);
	    } else {
		$sender = IO::Socket::INET->new( PeerAddr => $main::prefs{'Proxy'},
						PeerPort=> $main::prefs{'ProxyPort'},
						Proto => "tcp",
						Type => SOCK_STREAM);
		print $sender "connect $smtp:$port http/1.0\r\n\r\n";
		my $string = <$sender>;
		chomp($string);
		my ($proxy_status) = (split (/ /, $string))[1];
		if (int ($proxy_status /100) != 2) {
		    if ($inter == 1) {
			&main::err_dialog("recieved bad status code \"$proxy_status\" from http-proxy while connecting to $smtp","y");
		    } else {
			print("recieved bad status code \"$proxy_status\" from http-proxy while connecting to $smtp\n");
		    }
		    next;
		}
		my $test_int=0;
		while (!$test_int) {
		    $string=<$sender>;
		    if ($string eq "\n") { $test_int=1; }
		}
	    }
		
		
		$msg=$sender->getline() if ($sender);
		if (!$msg) {  
			if ($inter == 1) {
				&main::err_dialog(_("FATAL: An error occured while connecting to ")."$smtp","y");
			}
			print(_("FATAL: An error occured while connecting to ")."$smtp\n");
			last;
		}	
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		if($msg=~/^[45](.*)/){
			if ($inter == 1) { 
				&main::err_dialog("$smtp error: smtp error $1","y") 
			}
			print "$smtp error: smtp error $1\n";
			next;
		}
 
		# send helo
		$sender->send("helo ".hostname().$crlf);
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		$msg=$sender->getline();
		if($msg=~/^[45](.*)/){
			if ($inter == 1) { 
				&main::err_dialog("$smtp error: smtp error $1","y") 
		       	}
			print "$smtp error: smtp error $1\n";
			next;
		}
 
		# send mail from
		$_=$from;
		if (/\<(.*)\>/){
			$from="<$1>";
		} else {
			$from="<".$from.">";
		}
		$from=~s/ //g;

		$sender->send("mail from: ".$from.$crlf);
		$msg=$sender->getline();
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		if($msg=~/^[45](.*)/){
			if ($inter == 1) { 
				&main::err_dialog("$smtp error: smtp error $1","y") 
		       	}
	 		print "$smtp error: smtp error $1\n";
			next;
		}
	 # send rcpt to for each mail adress
		foreach (quotewords(", ", 1, $to), quotewords(", ", 1, $cc), quotewords(", ", 1, $bcc)){
		#pull <blah@foo.org> from address, or assume address is in blah@foo.org format and just <> it (ie: if you set address as "Kordik, Steven" <stevek@voila.net> this will pull the <stevek@voila.net> out.. if you set address as stevek@voila.net it will just use that, wrapping it in <>) Obviously, this breaks if the To: line contains invalid addresses... but hey.. we should check for that in pronto send function and popup an &&main::err_dialog() to warn... 
			if (/\<(.*)\>/){
				$_="<$1>";
			} else {
				$_="<$_>";
			}
			s/ //g;
			$sender->send("rcpt to: ".$_.$crlf);
 			$msg=$sender->getline();
	 		if ($called_from_send == 0) {
				while (Gtk->events_pending) { Gtk->main_iteration }
			}
			if($msg=~/^[45](.*)/){
				if ($inter == 1) { 
					&main::err_dialog("$smtp error: smtp error $1","y") 
			       	}
	 			print "$smtp error: smtp error $1\n";
				next;
 			}
		}

		# print beginning of data
		$sender->send("data".$crlf);
		$msg=$sender->getline();
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		if($msg=~/^[45](.*)/){
			if ($inter == 1) { 
				&main::err_dialog("$smtp error: smtp error $1","y") 
		       	}
	 		print "$smtp error: smtp error $1\n";
			next;
		}
 
 
	 # send the body
		foreach $mailline (@body){
 			 $mailline=~s/\n/$crlf/g;
			 $sender->send($mailline);
			if ($called_from_send == 0) {
				while (Gtk->events_pending) { Gtk->main_iteration }
			}
		}
 
		# print data end (a dot)
		$sender->send($crlf.".".$crlf);
		$msg=$sender->getline();
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		if($msg=~/^[45](.*)/){
			if ($inter == 1) { 
				&main::err_dialog("$smtp error: smtp error $1","y") 
			}
		 	print "$smtp error: smtp error $1\n";
			next;
		}

		$sender->send("quit".$crlf);
		if ($called_from_send == 0) {
			while (Gtk->events_pending) { Gtk->main_iteration }
		}
		$sender->close();
		$sql2 = "update messages set boxid=3 where id = ?";
		$query2=$main::conn->prepare($sql2);
		$query2->execute($msgid);
	}
	
	if(open(TMP,"<$main::prefs{'MailDir'}/pronto.running")) {
		my $proc = <TMP>;
        	close(TMP);
        	if(kill(0,$proc)) {
        		kill('USR2',$proc);
        	}
	}
	unlink("$main::prefs{'MailDir'}/prontosend.running");
	if ($query) {$query->finish;}
	if ($query2) {$query2->finish;}

	if ($called_from_send) {
		$main::conn->disconnect;
	}


}

1;
