<?php
/*
    Simple Mailer Script v1.4
    
    Copyright 2009-2011 Jamie Knight. All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are
    permitted provided that the following conditions are met:

       1. Redistributions of source code must retain the above copyright notice, this list of
          conditions and the following disclaimer.

       2. Redistributions in binary form must reproduce the above copyright notice, this list
          of conditions and the following disclaimer in the documentation and/or other materials
          provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY JAMIE KNIGHT ''AS IS'' AND ANY EXPRESS OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    The views and conclusions contained in the software and documentation are those of the
    authors and should not be interpreted as representing official policies, either expressed
    or implied, of Jamie Knight.
    
    Note:    You don't have to credit me on your website. But if you do (even if its
            just in the source code) I will be grateful. Thanks.
    
    Instructions for use:
    1.    Set the options below for your needs
    2.    Create a HTML form and set 'method' to 'post' and 'action' to 'mailerscript.php' (or
        whatever you have called this file).
    3.    Add the various inputs you need. If a 'subject' input is given it will become the
        subject of the email. If an 'email' input is given, it will optionally be DNS tested
        and become the reply-to address.
    4.    Sit back and relax, you're done!
*/

//
// 1. Set the options before use
//

// Email settings
$options['admin_email']        = 'me@example.com';                        // Your email address
$options['subject_prefix']    = 'Website Message: ';                    // The prefix to/content of the email subject

// Pages which the user get redirected to
$options['send_success']    = 'http://www.example.com/success.html';    // For when it works
$options['send_failure']    = 'http://www.example.com/fail.html';        // For when it doesn't

// Optional DNS check if an 'email' parameter is given. It works by scanning for valid MX records of the
// email host given, elimating at least some spambots. In rare cases, depending on your server configuration, 
// it will always fail, even when valid records exist.
$options['email_dns_check'] = true;                                    

// Debugging mode - only change it if you know what it means :P
$options['debug']            = false;

//
// YOU CAN STOP EDITING HERE!
//

// If you wish to specify a valid email address to send from,
// here is where you set it. This isn't needed in most cases.
$options['sender_email']    = 'mailer-noreply@'.$_SERVER['SERVER_NAME'];

//
// 2. Lets get ready to rumble...
//

// Set error reporting
if($options['debug']) {
    
error_reporting(E_ALL);
    
debug_message("Setting up the script... ");
}
else {
    
error_reporting(0);
}

date_default_timezone_set('Europe/London');

// Page redirects
function page_redirect($url) {
    
header('Location: '.$url);
    exit();
}

// Sanitation Function
function var_clean($var$is_email false) { 
    if(
$is_email) {
        if(
function_exists('filter_var')) {
            
$var    filter_var($varFILTER_SANITIZE_EMAIL);
        }
        else {
            
$var    ereg_replace("[^A-Za-z0-9@\._-]"""$var); 
        }
    }
    else {
        
// $var    = filter_var($var, FILTER_SANITIZE_STRING);
        
$var    ereg_replace("[^A-Za-z0-9 ?!\n\r()@\.,_-]"""$var); 
    }
    if(
$var == false) {
        
$var    null;
    }
    return 
$var;    
}

// Debug messages
function debug_message($msg$fatal false) {
    global 
$options;
    if(
$options['debug']) {
        if(
$fatal) {
            
// Abandon all hope 
            
exit('<span style="font-weight: bold;">Error: </span> '.$msg.' - script execution stopped.');
        }
        else {
            echo(
$msg "\n <br /> \n");
        }
    }
    elseif(
$fatal) {
        
page_redirect($options['send_failure']);
    }
}

// Gets the variable sent to the form
function get_post_variables() {
    
// Get all the variables sent to the script
    
if(empty($_POST)) {
        
// No data
        
debug_message('No data was sent to the script'true);
    }
    
$vars = array();
    
$is_data false;
    foreach(
$_POST as $var => $value) {
        
// Clean both variables
        
$var    var_clean($var);
        if (
$var == 'email') {
            
// Special treatment
            
$value    var_clean($valuetrue);
        }
        else {
            
$value    var_clean($value);
        }
        
// Get the end of the var name
        
$var_end null;
        if(
strlen($var) > 5) { $var_end substr($varstrlen($var) - 5); } // 
        
if($var != null && $value != null && $var_end != '_hide') {
            
// There is still someting worth sending
            
$vars[$var] = $value;
            
$is_data true;
        }
    }
    
// Check that we still have data to send
    
if(!$is_data) {
        
debug_message('No valid data was sent to the script'true);
    }
    if(!isset(
$vars['subject']) || $vars['subject'] == null) {
        
// Just put a blank subject in
        
$vars['subject'] = " ";
    }
    return 
$vars;
}

//
// 3. Prepare to sent the message
//
debug_message("Preparing to send the message...");

// Get the data sent to the script
$vars                    get_post_variables();

debug_message("Got variables - sorting them out.");

// Take known variables and use them
$email['to']        = $options['admin_email'];
$email['from']        = $options['sender_email'];
if(!empty(
$vars['email'])) {
    if(
$options['email_dns_check'] && !checkdnsrr(substr($vars['email'], strpos($vars['email'], '@') + 1), 'MX')) {
        
debug_message('Email DNS check failed. "'.$vars['email'].'" does not have a valid MX record.'true);
    }
    else {
        
$email['reply-to']        = $vars['email'];
    }
}
$email['subject']    = $options['subject_prefix'].$vars['subject'];
unset(
$vars['subject']);

$content null;
foreach(
$vars as $var => $value) {
    
$content    .= ucwords(strtolower($var)).": ".$value."\n\r";
}
// Add the IP Address and date
$content    .= "\n\rSent from the IP Address: ".$_SERVER['REMOTE_ADDR']." on ".date("D jS M Y @ H:i")."\n\r";
$content    .= "Their email address is: ".$email['from'];

$email['content']    = $content;

//
// 4. Send the message
//

debug_message("About to send the message...");

debug_message("Message variables:");
debug_message("To: ".$email['to']);
debug_message("From: ".$email['from']);
debug_message("Reply-To: ".(isset($email['reply-to']) ? $email['reply-to'] : "Unset"));
debug_message("Subject: ".$email['subject']);
debug_message("Email Content: ".$email['content']);

debug_message("Sending the message NOW!");

// Dev Reference:    mail( string $to  , string $subject  , string $message  [, string $additional_headers  [, string $additional_parameters  ]] )
$mail_thread    mail($email['to'], $email['subject'], $email['content'], "From: ".$email['from'].(isset($email['reply-to']) ? "\r\nReply-To: ".$email['reply-to'] : ""));

if(!
$mail_thread) {
    
// Couldn't send the message! All that hard work...
    
debug_message('unable to send the message - mail() function error'true);
}

debug_message("Message Sent.");

// 
//    5. All done!
//
if($options['debug']) {
    
debug_message("Script Finished");
    exit();
}
else {
    
page_redirect($options['send_success']);
}

?>