#! /usr/bin/perl

BEGIN { require "../../perl/lib/Sitedefs.pm"; }

use ErrorLog;
use CGITracker;
use PageTemplate;

use GD;

# This is the directory where we write security "key" files -- the files that
# record the correct security text string.  It should be readable and writable
# by the web server, but outside the document root.
$keydir = "/home/www/www.scienceu.com/contact_keydir";

my $navfile = "$Sitedefs::ROOTPATH/info/navigation.html";

$q   = new CGITracker;
$tpl = new PageTemplate;

my $send    = $q->param("send");
my $name    = $q->param("name");
my $address = $q->param("address");
my $message = $q->param("message");
my $key     = $q->param("key");
my $securitytext = $q->param("securitytext");

my $errors         = ();
my $page_message   = "";

if ($send) {
    if (!is_valid_email_address($address)) {
	push(@errors, "Please give a valid email address");
    }
    if (!$name) {
	push(@errors, "Please type your name in the field next to \"Your Name\"");
    }
    if (!$message) {
	push(@errors, "Please type your message in the space provided");
    }
    if ($securitytext) {
	my $saved_securitytext = get_securitytext($key);
	if (uc($securitytext) ne $saved_securitytext) {
	    push(@errors, "The security text that you entered does not match.  Please try again.");
	}
    } else {
	push(@errors, "Please enter the security text in box below your message");
    }
    remove_keyfile($key);
    if (@errors) {
	$page_message = qq|<font color="#ff0000">
Please fix the following thing(s) and submit your message again:
<ul>| . join("\n", map { "<li>$_" } @errors) . qq|
</ul>
</font>
|;
    } else {
	send_contact_message($name, $address, $message);
	$name = "";
	$address = "";
	$message = "";
	$page_message = qq|<font color="#0000ff">Thank you for your message.</font>|;
    }
}


# First clear out .png files from the "simages" subdir that are more than 5
# minutes old
open(FIND, "find simages -name '*.png' -mmin +5 -print|");
while (<FIND>) {
    chomp;
    unlink($_);
}

# Also clear out .txt files from the $keydir that are more than one
# day old.  These files are also removed whenever a message is sent, so
# this just clears out any old ones left over from page views that weren't
# followed by a successful message send.  The one day delay gives users plenty
# of time to leave a partially-composed message up in their browser before
# sending it.
open(FIND, "find $keydir -name '*.txt' -mmin +1440 -print|");
while (<FIND>) {
    chomp;
    unlink($_);
}

my $w = 59;
my $h = 20;
my $string_x = 7;
my $string_y = 5;


my $img = new GD::Image($w, $h);

$white = $img->colorAllocate(255,255,255);
$red = $img->colorAllocate(255,0,0);
$blue = $img->colorAllocate(0,0,255);
$black = $img->colorAllocate(0,0,0);

$img->fill(0,0,$white);

@possible_chars = qw( 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9 2 3 4 5 6
		      B C D F G H J K L M N P Q R S T V W X Y );

# Note: we omit 1, 0, I, and O, to avoid confusion with each other
# Also omit vowels to that we never spell a word, and include
# as many numbers as letters so they'll appear with equal freqency.

my $securitytext = randchar().randchar().randchar().randchar().randchar();

$img->string(gdGiantFont, $string_x, $string_y, $securitytext, $black);

$key = $$;
$simagename = "simages/$key.png";

open(IMG, ">$simagename");
print IMG $img->png;
close(IMG);

# Write answer in keydir
open(OUT, ">$keydir/$key.txt");
print OUT $securitytext;
close(OUT);

$q->Print($tpl->Header("Contacting Science U"));

open(NAV, "<$navfile");
while (<NAV>) {
    $q->Print($_);
}
close(NAV);

$q->Print($tpl->PreContent());

$q->Print(<<EndOfStuff
<table border="0" width="100%" cellpadding="10" cellspacing="0">
  <tr> 
    <td valign="TOP" bgcolor="#CFCFCF" align="CENTER"><font size="5"><b>
Contacting Science U</b></font></td>
  </tr>
<tr><td>

<B>By post:</B>

<PRE>
    Science U
    c/o Geometry Technologies, LLC
    77 Owenby Cove Road
    Fairview, NC  28730
</PRE>

<B>By telephone:</B>

<PRE>
    1-828-628-0489
</PRE>

<B>By email:</B>
<blockquote>

To send us an email, enter your message in the form below and click
the "Send Message" button below the form.

<p>
$page_message
<center>
<form action="contact.cgi" method="POST">
<input type="hidden" name="key" value="$key">
<table width="90%" border="0">
<tr>
  <td align="right"><font size="-1">Your&nbsp;name:</font></td>
  <td><input type="text" name="name" size="70" value="$name"></td>
</tr>
<tr>
  <td align="right"><font size="-1">Your&nbsp;email&nbsp;address:</font></td>
  <td><input type="text" name="address" size="70" value="$address"></td>
</tr>
<tr>
  <td align="right" valign="top"><font size="-1">Type&nbsp;your<br>message&nbsp;here:</font></td>
  <td><textarea name="message" rows="20" cols="70">$message</textarea></td>
</tr>
<tr>
  <td colspan="2">To verify that you really are a human who wants to contact us, rather than a spambot, enter the following security text string below: <img src="$simagename"></td>
<tr>
  <td align="right" valign="top"><font size="-1">Enter security text here:</font></td>
  <td><input type="text" name="securitytext" size="10"></td>
</tr>
</tr>
</table>
<input type="submit" name="send" value="Send Message">
</form>
</center>
</blockquote>

</td>
</tr>
</table>
EndOfStuff
	  );

$q->Print($tpl->Footer());
$q->EndPrint();

########################################################################

sub randchar {
    return $possible_chars[ int(rand(@possible_chars-0.0001)) ];
}

sub remove_keyfile {
    my $key = shift;
    unlink("$keydir/$key.txt");
}

sub get_securitytext {
    my $key = shift;
    open(KEY, "<$keydir/$key.txt")  || return "";
    my $securitytext = <KEY>;
    close(KEY);
    return $securitytext;
}

sub is_valid_email_address {
    my $address = shift;
    my @parts = split(/\@/, $address);    # split into words on '@'
    if ($#parts != 1)      { return 0; }  # must have exactly two words
    if (!$parts[0])        { return 0; }  # first word must be nonempty
    if ($parts[1] !~ /\./) { return 0; }  # second word must contain a period
    return 1;
}

sub send_contact_message {
    my $name    = shift;
    my $address = shift;
    my $message = shift;
    open(MAIL, "| mail -s 'Science U user contact message' ScienceU-contact\@ScienceU.com");
    print MAIL <<EOF
THIS MESSAGE WAS GENERATED BY THE SCIENCEU CONTACT FORM.  DO NOT REPLY
DIRECTLY TO THIS MESSAGE.  USE THE ADDRESS BELOW FOR REPLIES!

   From: $name
Address: $address

$message
EOF
;
    close(MAIL);
}
