#!/usr/local/bin/perl

print "Content-type: text/html", "\n\n"  ;

require ChatSign ;
require TimeUtilities ;
$data_basedir=&ChatSign::data_basedir ;
$URLdir_executables=&ChatSign::URLdir_executables ;

$request_method=$ENV{'REQUEST_METHOD'} ;

if ($request_method eq "GET") {
	$query_string=$ENV{'QUERY_STRING'} ;
	exit (1) ;
} else {
	$size_of_form=$ENV{'CONTENT_LENGTH'} ;
	read(STDIN, $query_string, $size_of_form) ;
}

# Split the name-value pairs
@pairs = split(/&/, $query_string);

foreach $pair (@pairs) {
	($name, $value) = split(/=/, $pair);
	# Un-Webify plus signs and %-encoding
	$value =~ tr/+/ /;
	# Get rid of all non-alpha/numeric stuff esp " ' ,
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	# $value =~ s/['|"|`|,]//g;
	# Stop people from using subshells to execute commands
	# when using UCB mail (aka mailx).
	$value =~ s/~!/ ~!/g;
	$FORM{$name}=$value ;
}


$email_address=$FORM{email_to} ;
unless  ($email_address=~ /\@/) { &invalid_email_address ; }
unless  ($email_address=~ /(.*)\@(.*)\.(.*)/) { &invalid_email_address ; }
if  ($email_address=~ /![A-Za-z0-9_+-.]/) { &invalid_email_address ; }
if  ($email_address=~ / /) { &invalid_email_address ; }
unless  ($email_address) { &invalid_email_address ; }


$now=time ;

$chat_datafile="$data_basedir/$FORM{domain}/chats/$FORM{requestor}" ;

open (ADDTOCONVERSATION,">> $chat_datafile") || die "Can't add to $chat_datafile
" ;
print ADDTOCONVERSATION "$FORM{email_to}^$now^$FORM{requestor} was emailled a copy of this chat with $FORM{domain}\n" ;
close (ADDTOCONVERSATION) ;

print <<ENUF;
<HTML>
<HEAD>
<TITLE>
ChatSign - Email Chat to $FORM{email_to}
</TITLE>
</HEAD>
<BODY>
<font face=\"Arial, Helvetica, sans-serif\" size=\"2\">
<CENTER>
<H3>Hello $FORM{requestor}</H3>

A copy of your chat with $FORM{domain} has been
emailled to you at $FORM{email_to}.

</BODY>
</HTML>
ENUF

($pretty_date, $pretty_time)=&TimeUtilities::make_unixtime_readable($now) ;

$mailprog = '/usr/lib/sendmail';

$recipient=$FORM{email_to} ;
open (MAIL, "|$mailprog $recipient") || die "Can't open $mailprog!\n";
print MAIL <<ENUF ;
From: chat\@chatsign.com (ChatSign Chats)
To: $recipient 
Subject: A copy of your chat with $FORM{domain}

ENUF

open (CHAT,$chat_datafile) || die "Cannot open $chat_datafile\n" ;
while (<CHAT>) {
	($who,$when,$what)=split(/\^/) ;
	($pretty_date, $pretty_time)=&TimeUtilities::make_unixtime_readable($when) ;
	print MAIL "$who - $pretty_date $pretty_time - $what\n" ;
}


print <<ENUF;


<FONT SIZE=2>
<P>Regards
<P><A TARGET="_blank" HREF="http://www.chatsign.com">www.ChatSign.com</A>


ENUF
close (MAIL) ;

exit (0) ;

sub invalid_email_address {
print "<HTML><SCRIPT Language=\"JavaScript\"></SCRIPT><HEAD><TITLE>Invalid Email Address</TITLE></HEAD><BODY><CENTER><H3>Invalid Email Address</H3>$email_address does not appear to be a valid email address. <P><A onMouseOver=\"window.back()\" HREF=nowhere>Back $referer</A></BODY></HTML>" ;
 exit (1) ;
}
