#!/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
#            nexturl  - text      where to go after sending 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 background=\"/icons/background.jpg\"\n";
        print "text=\"#000000\" vlink=\"#0000CC\" link=\"#0000CC\">\n";
        print "<H1>Sorry</H1>\n";
        print "It might be best if you actually sent <em>something</em> ";
        exit;
}

$nexturl = $FORM{'nexturl'};

#  Move recipient list into an array
@users = split(/,/,$FORM{'to'});

print "<Head><Title>Thank you</Title></Head>\n";
print "<Body background=\"/icons/background.jpg\"\n";
print "text=\"#000000\" vlink=\"#0000CC\" link=\"#0000CC\">\n";
print "<H1><IMG SRC=\"/icons/au.gif\"> 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]\@mail.auburn.edu ";
   print FILE "To: $users[$i]\@mail.auburn.edu\n";
   print FILE "From: $FORM{'from'} ";
   print FILE "<$FORM{'username'}>" if $FORM{'username'};
   print FILE "\n";
   print FILE "Subject: $FORM{'sub'}\n";
   print FILE "\n\n";
   print FILE "$FORM{'body'}\n\n";
   close (FILE);
}
print "<HR>\n";
print "<A HREF=\"$nexturl\">Click here to continue</A>\n";
exit;


