<?php

# FormMail.php V1.0.1 Copyright (c) 2001, 2002 Internet Express, Inc.


$conffile './FormMail.cfg';

# Copyright string included at the bottom of all status pages.  You must
# keep this copyright notice intact in all generated HTML output.
$copyright '<span style="text-align : center; font-size : 10pt"><a href="http://www.netexpress.net/scripting/">FormMail</a>
V1.0 &copy; 2001 <a href="http://www.netexpress.net/">Internet Express, Inc.</a></span><br>'
;

# Generic US-style date string
$date strftime("%A, %B %d, %Y at %H:%M:%S");

# List of options used by the script.
$options = array('recipient','subject','email','realname','redirect','bgcolor',
                 
'background','link_color','vlink_color','text_color',
                 
'alink_color','title','sort','print_config','required',
                 
'env_report','return_link_title','return_link_url',
                 
'print_blank_fields','missing_fields_redirect');


# Read in the config file settings.
$config read_config($conffile);

# If a referring URL was specified, make sure it matches one of the 
# domains in our referer list.

$check_referer false;

if (
$HTTP_SERVER_VARS['HTTP_REFERER']) {
    if (!
is_array($config['referers'])) {
        
$config['referers'] = array($config['referers']);
    }
    foreach (
$config['referers'] as $referer) {
        if (
eregi("^https?://([^/]*)$referer",
                  
$HTTP_SERVER_VARS['HTTP_REFERER']))
        {
            
$check_referer true;
            break;
        }
    }
} else {
    
$check_referer true;
}

# If the HTTP_REFERER was invalid, send back an error.
if (!$check_referer) { local_error('bad_referer'); }


if (
$HTTP_SERVER_VARS['REQUEST_METHOD'] !== 'POST'
    
&& $HTTP_SERVER_VARS['REQUEST_METHOD'] !== 'GET') {
    
local_error('request_method');
}

# Know which variables we're pulling from.
if ($HTTP_SERVER_VARS['REQUEST_METHOD'] === 'POST') {
    
$user_vars $HTTP_POST_VARS;
} else {
    
$user_vars $HTTP_GET_VARS;
}

$Field_Order = array();
$errors = array();

foreach (
$user_vars as $name => $value) {

    if (
in_array($name,$options,true)) {
        
$config[$name] = $value;
    } else {
            if (
$output[$name] && $value) {
            
$output[$name] = $output[$name] . ', ' $value;
        } else if (
$value) {
            
array_push($Field_Order,$name);
            
$output[$name] = $value;
        }

        
$output[$name] = $value;
    }
}

# These three settings are lists of variable names.  Turn them into
# arrays.
if (!is_array($config['required'])) {
    
$config['required'] = parse_array($config['required']);
}
if (!
is_array($config['env_report'])) {
    
$config['env_report'] = parse_array($config['env_report']);
}
if (!
is_array($config['print_config'])) {
    
$config['print_config'] = parse_array($config['print_config']);
}


if (!
$config['recipient']) {
    if (
count($output) === 0) {
        
local_error('bad_referer');
    } else {
        
local_error('no_recipient');
    }
}


foreach (
$config['required'] as $required) {
    
# If the required field is the email field, the syntax of the email
    # address if checked to make sure it passes a valid syntax.
    
if ($required === 'email' && !check_email($config[$required])) {
        
array_push($errors,$required);
    }

    
# Otherwise, if the required field is a configuration field and it
    # has no value or has been filled in with a space, send an error.
        
else if (in_array($required,$options,true)) {
        if (!
$config[$required]) {
            
array_push($errors,$required);
        }
    }

    
# If it is a regular form field which has not been filled in or
    # filled in with a space, flag it as an error field.
    
else if (!$output[$required]) {
        
array_push($errors,$required);
    }
}

# If any error fields have been found, send error message to the user.
if (count($errors)) {
    
local_error('missing_fields'$errors);
}

if (
is_array($config['recipient'])) {
    
$config['recipient'] = implode(", "$config['recipient']);
}

# If redirect option is used, print the redirectional location header.
if ($config['redirect']) {
    
Header("Location: " $config['redirect']);
} else {

    
# Otherwise, begin printing the response page.
    
?>
<html>
 <head>
<?php

    
# Print out title of page
    
if ($config['title']) {
        
?><title><?= $config['title'?></title><?php
    
} else {
        
?><title>Thank You</title><?php
    
}
    
?>
</head>
<body<?php
        
# Get Body Tag Attributes
        
body_attributes();
?>>
 <center><?php

    
# Print custom or generic title.
    
if ($config['title']) {
        
?>
   <h1><?= $config['title'?></h1>
<?php
    
} else {
        
?>
   <h1>Thank You For Filling Out This Form</h1>
<?php
    
}
    
?></center>
Below is what you submitted to <?= $config['recipient'?> on <?= $date ?>
<p><hr size="1" width="75%">
<p>
<?php

    
# Sort alphabetically if specified:
    
if ($config['sort'] === 'alphabetic') {
        
$keys array_keys($output);
        
sort($keys);
        foreach (
$keys as $field) {

            
# If the field has a value or the print blank fields
            # option is turned on, print out the form field and
            # value.
            
if ($config['print_blank_fields'] || $output[$field])
            {
                
?><b><?= field ?>:</b> <?= $output[$field?>
<p>
<?php
            
}
        }
    }
    
# If a sort order is specified, sort the form fields based on that.
    
else if (ereg('^order:.*,.*'$config['sort'])
             || 
is_array($config['sort']))
    {

        if (!
is_array($config['sort'])) {
            
$sort_order parse_array($config['sort']);
        } else {
            
$sort_order $config['sort'];
        }

        
$sort_order[0] = preg_replace("/order:/","",$sort_order[0]);

        
# For each sorted field, if it has a value or the print blank
        # fields option is turned on print the form field and value.
        
foreach ($sort_order as $sorted_field) {
            if (
$config['print_blank_fields']
                || 
$output[$sorted_field])
            {
                
?><b><?= $sorted_field ?></b> 
<?= $output[$sorted_field?><p>
<?php
            
}
        }
    }
    
# Otherwise, default to the order in which the fields were sent.
    
else {

        
# For each form field, if it has a value or the print blank
        # fields option is turned on print the form field and value.
        
foreach ($Field_Order as $field) {
            if (
$config['print_blank_fields'] || $output[$field])
            {
                
?>
<b><?= $field ?>:</b> <?= $output[$field?><p>
<?php
            
}
        }
    }
    
?>
<p><hr size="1" width="75%">
<p><?php

    
# Check for a Return Link and print one if found.
        
if ($config['return_link_url'] && $config['return_link_title'])
    {
        
?><ul>
<li><a href="<?= $config['return_link_url'?>"><?= $config['return_link_title'?></a>
</ul>
<?php
    
}

    
?>
<hr size="1" width="75%">
<p><?= $copyright?>
</body>
</html>
<?php

}


# Start with an empty body for the mail message
$body '';

# Build up some nice From/Reply Headers, as well as headers showing where the form was.
$headers 'From: ' $config['email'] . ' (' $config['realname'] . ")\r\n";
$headers .= 'Reply-To: ' $config['email'] . "\r\n";
$headers .= 'X-Sent-From-Form: ' $_SERVER['HTTP_REFERER'] . "\r\n";
$headers .= 'X-Sent-From-Domain: ' $_SERVER['SERVER_NAME'] . "\r\n";


$body .= "Below is the result of your feedback form.  It was submitted by\r\n";
$body .= $config['realname'] . " (" $config['email'] . ") on $date\r\n";
$body .= str_repeat('-'75) . "\r\n\r\n";

if (
count($config['print_config'])) {
    foreach (
$config['print_config'] as $print_config) {
        if (
$config[$print_config]) {
            
$body .= "$print_config: " $config[$print_config]
                     . 
"\r\n\r\n";
        }
    }
}


# Sort alphabetically if specified:
if ($config['sort'] === 'alphabetic') {
    
$keys array_keys($output);
    
sort($keys);
    foreach (
$keys as $field) {

        
# If the field has a value or the print blank fields option
        # is turned on, print out the form field and value.
        
if ($config['print_blank_fields'] || $output[$field])
        {
            
$body .= "$field: " $output[$field] . "\r\n\r\n";
        }
    }
}
# If a sort order is specified, sort the form fields based on that.
else if (ereg('^order:.*,.*'$config['sort']) || is_array($config['sort']))
{

    if (!
is_array($config['sort'])) {
        
$sort_order parse_array($config['sort']);
    } else {
        
$sort_order $config['sort'];
    }

    
$sort_order[0] = preg_replace("/order:/","",$sort_order[0]);

    
# For each sorted field, if it has a value or the print blank
    # fields option is turned on print the form field and value.
    
foreach ($sort_order as $sorted_field) {
        if (
$config['print_blank_fields'] || $output[$sorted_field])
        {
            
$body .= "$sorted_field: " $output[$sorted_field]
                     . 
"\r\n\r\n";
            
        }
    }
}
# Otherwise, default to the order in which the fields were sent.
else {

    
# For each form field, if it has a value or the print blank
    # fields option is turned on print the form field and value.
    
foreach ($Field_Order as $field) {
        if (
$config['print_blank_fields'] || $output[$field])
        {
            
$body .= "$field: " $output[$field] . "\r\n\r\n";
        }
    }
}

$body .= str_repeat('-'75) . "\r\n\r\n";


# Send any specified Environment Variables to recipient.
foreach ($config['env_report'] as $env_report) {
    if (
$HTTP_ENV_VARS[$env_report]) {
        
$body .= "$env_report: " $HTTP_ENV_VARS[$env_report] . "\r\n";
    }
}


# Set a default message subject if none was provided.
if (!$config['subject']) {
    
$config['subject'] = 'WWW Form Submission';
}

$success mail($config['recipient'], $config['subject'], $body$headers);

exit;


function 
parse_array($string) {
    
$output = array();

    while (
preg_match('/^(([^\\\,]*(\\\,)*(\\\)*)+),(.*)$/'$string$matches)) {
        
array_push($output,trim($matches[1]));
        
$string $matches[5];
    }
    if (
$string) {
        
array_push($output,trim($string));
    }
    return 
$output;
}


function 
read_config($filename) {
    
$set = array();
    
$fd fopen($filename,'r');
    while (
$line fgets($fd1024)) {
        if (
ereg('^#',$line)) {
            continue;
        }

        
preg_match('/^\s*([^=]*)\s*=\s*(.*)\s*$/',$line,$matches);
        
$name trim($matches[1]);
        
$val  trim($matches[2]);

        
# Skip lines w/ empty lhs.
        
if ($name === '') {
            continue;
        }
        if (
ereg("[^\\],",$val)) {
            
$val parse_array($val);
        }
        
$set[$name] = $val;
    }
    return 
$set;
}


function 
check_email($address)
{
    if (
preg_match("/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/",$address)
        || !
preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/",$address))
    {
        return 
false;
    }

    
# Return a true value, e-mail verification passed.
    
return true;
}


function 
body_attributes() {
    global 
$config;

    
# Check for Background Color

    
if ($config['bgcolor']) {
        
?> bgcolor="<?= $config['bgcolor'?>"<?php
    
}

    
# Check for Background Image
    
if ($config['background']) {
        
?> background="<?= $config['background'?>"<?php
    
}

    
# Check for Link Color
    
if ($config['link_color']) {
        
?> link="<?= $config['link_color'?>"<?php
    
}

    
# Check for Visited Link Color
    
if ($config['vlink_color']) {
        
?> vlink="<?= $config['vlink_color'?>"<?php
    
}

    
# Check for Active Link Color
    
if ($config['alink_color']) {
        
?> alink="<?= $config['alink_color'?>"<?php
    
}

    
# Check for Body Text Color
    
if ($config['text_color']) {
        
?> text="<?= $config['text_color'?>"<?php
    
}
}

function 
local_error($error,$error_fields = array()) { 
    global 
$HTTP_SERVER_VARS$copyright$config;

    if (
$error === 'bad_referer') {
        
$server $HTTP_SERVER_VARS['HTTP_REFERER'];
        if (
preg_match("/^https?:\/\/([\w\.]+)/i",
                       
$server$matches))
        {
            
$host $matches[1];
            
?>
<html>
 <head>
  <title>Bad Referrer - Access Denied</title>
 </head>
 <body bgcolor=#FFFFFF text=#000000>
  <center>
   <table border=0 width=600 bgcolor=#9C9C9C>
    <tr><th><span style="font-size : 16pt;">Bad Referrer - Access Denied</span></th></tr>
   </table>
   <table border=0 width=600 bgcolor=#CFCFCF>
    <tr><td>The form attempting to use
     <a href="http://www.netexpress.net/scripting/">FormMail</a> resides
     at <tt><?= $server ?></tt>, which is not allowed to access this cgi script.

   <p>If you are attempting to configure FormMail to run with this form,
     you need to add the following to referers list, explained in detail
     in the README file.
   <p>Add <tt>'<?= $host ?>'</tt> to your <tt><b>referers</b></tt> list.
   <hr size=1>
     <?= $copyright ?>
    </td></tr>
   </table>
  </center>
 </body>
</html>
<?php
        
} else {
            
?>
<html>
 <head>
  <title>Internet Express FormMail v1.0</title>
 </head>
 <body bgcolor=#FFFFFF text=#000000>
  <center>
   <table border=0 width=600 bgcolor=#9C9C9C>
    <tr><th><span style="font-size : 16pt;">FormMail</span></th></tr>
   </table>
   <table border=0 width=600 bgcolor=#CFCFCF>
    <tr><th><tt><?= $copyright ?>
        Licensed for use by Internet Express customers.</tt></th></tr>
   </table>
  </center>
 </body>
</html>
<?php
        
}
    } else if (
$error === 'request_method') {
        
?>
<html>
 <head>
  <title>Error: Request Method</title>
 </head>
 <body bgcolor=#FFFFFF text=#000000>
  <center>
   <table border=0 width=600 bgcolor=#9C9C9C>
    <tr><th><span style="font-size : 16pt;">Error: Request Method</span></th></tr>
   </table>
   <table border=0 width=600 bgcolor=#CFCFCF>
    <tr><td>The Request Method of the Form you submitted did not match
     either <tt>GET</tt> or <tt>POST</tt>.  Please check the form and make sure the
     <tt>method=</tt> statement is in upper case and matches <tt>GET</tt> or <tt>POST</tt>.<p>

     <?= $copyright ?>
    </td></tr>
   </table>
  </center>
 </body>
</html>
<?php
    
} else if ($error === 'no_recipient') {
        
?>
<html>
 <head>
  <title>Error: No Recipient</title>
 </head>
 <body bgcolor=#FFFFFF text=#000000>
  <center>
   <table border=0 width=600 bgcolor=#9C9C9C>
    <tr><th><span style="font-size : 16pt;">Error: No Recipient</span></th></tr>
   </table>
   <table border=0 width=600 bgcolor=#CFCFCF>
    <tr><td>No Recipient was specified in the data sent to FormMail.  Please
     make sure you have filled in the 'recipient' form field with an e-mail
     address.  More information on filling in recipient form fields can be
     found in the README file.<hr size=1>

     <?= $copyright ?>
    </td></tr>
   </table>
  </center>
 </body>
</html>
<?php
    
} else if ($error === 'missing_fields') {
        if (
$config['missing_fields_redirect']) {
            
Header("Location: " $config['missing_fields_redirect']);
        } else {
            foreach (
$error_fields as $missing_field) {
                
$missing_field_list .= "      <li>$missing_field\n";
        }
        
?>
<html>
 <head>
  <title>Error: Blank Fields</title>
 </head>
  <center>
   <table border=0 width=600 bgcolor=#9C9C9C>
    <tr><th><span style="font-size : 16pt;">Error: Blank Fields</span></th></tr>
   </table>
   <table border=0 width=600 bgcolor=#CFCFCF>
    <tr><td>The following fields were left blank in your submission form:<p>
     <ul>
<?= $missing_field_list ?>
     </ul><br>

     These fields must be filled in before you can successfully submit the form.<p>
     Please use your browser's back button to return to the form and try again.<hr size=1>
     <?= $copyright ?>
    </td></tr>
   </table>
  </center>
 </body>
</html>
<?php
        
}
    }
    exit;
}

?>