<?php
/**
 * Ottercomics email form.  Contacts can be changed in the included 
 * contacts.db.php file.  Written by Wolfin <wolfin@wagztail.com>. GPL2/LGPL2
 */

// Load contacts.
require_once "contacts.db.php";

// Check for required form fields.
if (empty($_POST['SendName']) || empty($_POST['SendEmail'])  ||
    empty($_POST['SendTo'])   || empty($_POST['MsgContent'])) {
  // All form fields not filled out.  Options:
  // REDIRECT user -- uncomment this next line:
  # header("Location:form-fail.htm");
  // PRINT error message to screen -- uncomment this next line:
   echo "Some or all fields were not filled out.  Please remember that all fields are REQUIRED.  Press your browsers <b>back</b> button to go back and try again.";
   
   die(); // Ends the script.
}

// Check for a valid "from" address.
$email = '';
if(!isValidEmail(trim($_POST['SendEmail']))) {
  // Email provide is bogus.  Options:
  // REDIRECT user -- uncomment this next line:
  # header("Location:form-fail.htm");
  // PRINT error message to screen -- uncomment this next line:
  echo "The email address you provided does not appear to be valid.  Press your browsers <b>back</b> button to go back and try again.";
   
  die(); // Ends the script.
}

// Check for a valid "to" address.
$email = '';
if(!empty($contact[$_POST['SendTo']])) {
  $email = $contact[$_POST['SendTo']];
} else {
  // Requested email does not exist.  Options:
  // REDIRECT user -- uncomment this next line:
  # header("Location:form-fail.htm");
  // PRINT error message to screen -- uncomment this next line:
  echo "There is no email address on file for the person you requested.  Please ensure you selected a person before submitting the form.  If this error continues, please notify a staff member to correct the issue.";
   
  die(); // Ends the script.
}


// Send the mail!

$to      = $email;
$subject = 'Webform mail from Christian Furry Fellowship';
$message = trim($_POST['MsgContent']) . "\r\n\r\n" 
           . 'Name: ' . $_POST['SendName'] . "\r\n" 
           . 'Email: ' . trim($_POST['SendEmail']);
$headers = 'From: ' . trim($_POST['SendEmail']) . "\r\n" .
           'X-Mailer: PHP/' . phpversion();
$message = htmlspecialchars($message, ENT_QUOTES);
$message = wordwrap($message, 70);
$message = str_replace("\n.", "\n..", $message);

mail($to, $subject, $message, $headers);

// Redirect user to thank you page.
header("Location:form-sent.htm");

die(); // Ensure script terminates.
////////////////// FUNCTIONS //////////////////////
/**
 * PHP validate email
 * http://www.webtoolkit.info/
 */
 function isValidEmail($email){
	return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}
