# 
# mailme.pl - process form submission and mail results to $mailto.
#
# Ray Miller <raym@herald.ox.ac.uk>
#
# Copyright (C) 2001 University of Oxford
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

my $mailto = "foo\@example.com"; # <-- MODIFY THIS
my $subject = "Web-generated message";

sub form_error {
    my $errors = shift;
    my $body = join ("\n", map { "<p>$_</p>" } @$errors);
    print "Content-type: text/html\n\n";
    print <<"EOT";
<html>
<head>
<title>Form Error</title>
</head>
<body>
<h1>Form Error</h1>
$body
</body>
</html>
EOT
    exit;
}

sub validate_query {
    my $query = shift;
    my @errors;
    foreach (keys %$query) {
        next if /^\*/;
        push (@errors, "Required field $_ not filled")
            unless defined $query->{$_} && length $query->{$_};
    }
    return \@errors;
}

sub send_message {
    my $query = shift;
    my $date = scalar localtime;
    my $message = <<"EOT";
Web-generated message on $date
From: $ENV{REMOTE_HOST} ($ENV{REMOTE_ADDR})
Remote Ident: $ENV{REMOTE_IDENT} (using $ENV{HTTP_USER_AGENT})
Script invoked from: $ENV{HTTP_REFERER}
EOT

    foreach (keys %$query) { $message .= "$_ => $query->{$_}\n" }

    mail ($mailto, $subject, $message)
        or form_error(["An error occurred when processing this form.",
                       "Mail not sent."
                       ]);

    # Let the user know we were successful
    print "Content-type: text/html\n\n";
    print <<'EOT';
<html>
<head>
<title>Message sent</title>
</head>
<body>
<h1>Message sent</h1>
Use the <em>back</em> feature of your browser to return to the previous
page.
<hr>
</body>
</html>
EOT
}

########################################################################
# Main processing
########################################################################

my %query = parsed_query();

if (defined $query{submit}) {
    my $errors = validate_query(\%query);
    form_error($errors) if @$errors;
    send_message(\%query);
}
else {
    form_error(["Invalid form submission!", 
		"Was this form submitted properly?"
		]);
}
