#!/opt/perl/bin/perl
#
# Sends mail to a list of users
#
# Form fields:
#            to       - text      list of recipients GIDs
#            from     - text      sender's email address
#            username - text      sender's real name
#            sub      - text      subject line
#            body     - textarea  email message
#
# Author: Gene Stewart     - stewagb@mail.auburn.edu
# ----------------------------------------------------------------------------

# Define constants
local(%FORM);
$CRLF="\r\n";
$SENDMAIL="/usr/lib/sendmail -t";

if ($ENV{'REQUEST_METHOD'} ne 'POST') {
   exit;
}

# Print out what we need
print "Content-type: text/html$CRLF$CRLF";

# Get the input
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

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

foreach $pair (@pairs)
{
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    # Stop people from using subshells to execute commands
    $value =~ s/~!/ ~!/g;

    # Uncomment for debugging purposes
    # print "Setting $name to $value<P>";

    $FORM{$name} = $value;
}

# Sanity check
$FORM{'to'}= "postmaster"  if ! $FORM{'to'};
if (! $FORM{'body'}) {
   print "<Head><Title>Missing Text of Message</Title></Head>\n";
   print "<BODY TEXT=\"#000066\" BGCOLOR=\"#FFFFFF\" LINK=\"#3300ff\" VLINK=\"#666699\">\n";
   print "<A HREF=\"http://www.auburn.edu/cgi-bin/imagemap/map/header.map\">\n";
   print "<IMG SRC=\"http://www.auburn.edu/map/header.gif\" ISMAP border=0\n";
   print "height=25 width=589></A>\n";
   print "<H1>Sorry</H1>\n";
   print "It might be best if you actually sent <em>something</em> ";
   exit;
}
#  Move recipient list into an array
@users = split(/,/,$FORM{'to'});

print "<Head><Title>Thank you</Title></Head>\n";
print "<BODY TEXT=\"#000066\" BGCOLOR=\"#FFFFFF\" LINK=\"#3300ff\" VLINK=\"#666699\">\n";
print "<A HREF=\"http://www.auburn.edu/cgi-bin/imagemap/map/header.map\">\n";
print "<IMG SRC=\"http://www.auburn.edu/map/header.gif\" ISMAP border=0\n";
print "height=25 width=589></A>\n";
print "<H1>Have a nice day</H1><HR>\n";
print "Your message has been sent to:<P>\n";

# Send message to each recipient
foreach $i (0 .. $#users) {
   open (FILE, "| $SENDMAIL") || die "Can't open pipe to sendmail $SENDMAIL!\n";
   print "$users[$i] ";
   print FILE "To: $users[$i]\n";
   print FILE "From: $FORM{'from'}\n";
   print FILE "Subject: $FORM{'sub'}\n";
   print FILE "\n\n";
   print FILE "$FORM{'username'} writes:\n\n" if $FORM{'username'};
   print FILE "$FORM{'body'}\n";
   print FILE "\n";
   print FILE "WARNING FROM THE WEBMASTER:\n\n";
   print FILE "This mail message was generated by an Auburn University\n";
   print FILE "Web user and may contain a false or erroneous return\n";
   print FILE "address.  If you reply to this message please verify\n";
   print FILE "that you are replying to a valid email address.\n\n";
   close (FILE);
}

exit;


