All pastes #523205 Raw Edit

Untitled

public text v1 · immutable
#523205 ·published 2007-05-30 18:22 UTC
rendered paste body
<?
/**
* aFormMail script - sending mail via form
*
*     Author: Alex Scott
*      Email: alex@cgi-central.net
*        Web: http://www.cgi-central.net
*    Details: The installation file
*    FileName $RCSfile: mini-app.php,v $
*    Release: 1.1 ($Revision: 1.6 $)
*
* Please direct bug reports,suggestions or feedback to the cgi-central forums.
* http://www.cgi-central.net/forum/
*                                                                          
* aMember is free for both commercial and non-commercial use.
* Re-distribution of this script without prior consent is strictly prohibited.
*                                                                                 
*/

/*****************************************************************************
 *                                                                           *
 *                C  O  N  F  I  G  U  R  A  T  I  O  N                      *
 *                                                                           *
 *****************************************************************************/

// email for send submitted forms //////////////////////////////////////////
// if empty, use value from form ('send_to' field)

$send_to = "www.BuyersHelpline.com <gethelp@buyershelpline.com>";

// set $send_cc address if you need copy of mail to other addresses
// for example: $send_cc = array('friend1@ccc.cc', 'friend2@ccc.cc'); 

$send_cc = array("www.BuyersHelpline.com <buyershelpline@yahoo.com>");

// Subject. if empty, use value from form ('subject' field)

$subject = "Buyers Help Request!";

// Allowed Referrers. Should be empty or list of domains

$referrers = array('buyershelpline.com','www.buyershelpline.com'); 

// Attachments

$attachment_enabled = 1;

////// Database - write CSV file with data of submitted forms //////////////

$database_enabled = 1;
$database_file = '../../list/free-help-requests.csv';

// Fields to collect
// $database_fields = '*' - mean all fields, as in form
// $database_fields = array('from', 'subject') - only 'from', 'subject' fields

$database_fields = array('Buyer', 'Co-Buyer', 'Buyer_Email', 'phone', 'home_phone', 'work_phone', 'cell_phone', 'company', 'address_from', 'city_from', 'state_from', 'message'); 

////// Redirect user after submitting form

$redirect_url = 'http://www.buyershelpline.com/success';

////// Auto-Responder
////// You can substitute any form fields in response by using
////// %field_name% in response text.

$autoresponder_enabled = 1;
$autoresponder_from = $send_to;
$autoresponder_subject = "Here's your FREE Buyers Resource Guide...";
$autoresponder_message = <<<MSG

Hi %Buyer%, %Co-Buyer%

Thank you for using our Buyers Help Request form...

You've made an excellent decision to get free help buying real estate!

Your FREE Buyers Resource Guide (PDF) is attached to this email. If you have
any trouble retreiving the attachment, just use this download link here:

   http://www.buyershelpline.com/Buyers-Resource-Guide.pdf

(Make sure you right-click on the link and then select "Save target as...")

Hey %Buyer% - Don't miss this...

You're now also entitled to a NO-OBLIGATION PRE-QUALIFICATION
plus a 100% FREE COPY of your Credit Report w/FICO by mail!

Request your PRE-QUALIFICATION & FREE CREDIT REPORT by calling here:

 -------------------------
      Buyers Helpline
      1-800-997-5307
 -------------------------

You'll be hearing from our local Real Estate Experts soon
to help you explore some of your many homebuying options.

And remember, whenever you have questions about buying real estate...
just pick up the phone & call the Buyers Helpline toll-free!

Thanks again for using the Buyers Helpline!

 http://www.BuyersHelpline.com


The Buyers Helpline is a Free Real Estate Referral Service of
Jonathan Keller, a licensed agent in the State of California.
Jonathan Keller is an agent of: CA DRE #01353675

CPS Santa Rosa West
3806 Sebastopol Road
Santa Rosa, CA 95407

http://www.BuyersHelpline.com - http://www.SellersHelpline.com - http://www.RefinanceHelpline.com


MSG;

// Attachment to send along with autoresponder.
$autoresponder_attach_path = '../../brg/Buyers-Resource-Guide.pdf';
$autoresponder_attach_name = 'Buyers-Resource-Guide.pdf';
$autoresponder_attach_type = 'application/pdf';

/***************************************************************************/

function do_formmail(){
    global $autoresponder_enabled, $database_enabled;
    $form      = get_form_data();
    $errors    = check_form($form);
    if ($errors) {
        display_errors($errors);
        return;
    }
    send_mail($form);
    if ($autoresponder_enabled) 
        auto_respond($form);
    if ($database_enabled)
        save_form($form);
    redirect();
}

function redirect(){
    global $redirect_url;
    header("Location: $redirect_url");
    exit();
}


function save_form($vars){
    global $database_file, $database_fields;
    $f = fopen($database_file, 'a');
    if (!$f){
        die("Cannot open db file for save");
    }
    foreach ($vars as $k=>$v) {
        $vars[$k] = str_replace(array("|", "\r","\n"), array('_',' ',' '), $v);
    }
    if (is_array($database_fields)) {
        $vars_orig = $vars; 
        $vars = array();
        foreach ($database_fields as $k)
            $vars[$k] = $vars_orig[$k];
    }
    $str = join('|', $vars);
    fwrite($f, $str."\n");
    fclose($f);
}

function auto_respond($vars){
    global $autoresponder_from, $autoresponder_message, $autoresponder_subject,
           $autoresponder_attach_path, $autoresponder_attach_name, $autoresponder_attach_type;

    $mime_delimiter = md5(time());

    /// replace all vars in message
    $msg = <<<MSG
This is a MIME-encapsulated message
    
--$mime_delimiter
Content-type: text/plain
Content-Transfer-Encoding: 8bit

MSG;

    $msg .= $autoresponder_message;
    
    /// replace all vars in message
    preg_match_all('/%(.+?)%/', $msg, $out);
    $s_vars = $out[1]; //field list to substitute
    foreach ($s_vars as $k)
        $msg = str_replace("%$k%", $vars[$k], $msg);
    
    // attach file to document
    $file_name     = $autoresponder_attach_name;
    $file_type     = $autoresponder_attach_type;
    $file_path     = $autoresponder_attach_path;
    $file_cnt = "";
    $f=@fopen($file_path, "rb");
    if ($f) { 
        while($f && !feof($f))
            $file_cnt .= fread($f, 4096);
        fclose($f);
        if (!strlen($file_type)) $file_type="applicaton/octet-stream";
        if ($file_type == 'application/x-msdownload')
            $file_type = "applicaton/octet-stream";

        $msg .= "\n--$mime_delimiter\n";
        $msg .= "Content-type: $file_type\n";
        $msg .= "Content-Disposition: attachment; filename=\"$file_name\"\n";
        $msg .= "Content-Transfer-Encoding: base64\n\n";
        $msg .= chunk_split(base64_encode($file_cnt));
    }
    $msg .= "\n--$mime_delimiter--";

    
    /// replace all vars in subject
    $subj = $autoresponder_subject;
    preg_match_all('/%(.+?)%/', $subj, $out);
    $s_vars = $out[1]; //field list to substitute
    foreach ($s_vars as $k)
        $subj = str_replace("%$k%", $vars[$k], $subj);
    //
    $_send_to = "$vars[Buyer] <".$vars[Buyer_Email].">";
    $_send_from = $autoresponder_from;

    mail($_send_to, $subj, $msg,
    "Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");
}

function _build_fields($vars){
    $skip_fields = array(
        'email_to', 
        'name_to', 
        'subject',
        'submit', 
	'image');

    // order by numeric begin, if it exists
    $is_ordered = 0;
    foreach ($vars as $k=>$v) 
        if (in_array($k, $skip_fields)) unset($vars[$k]);

    $new_vars = array();
    foreach ($vars as $k=>$v){
        // remove _num, _reqnum, _req from end of field names
        $k = preg_replace('/_(req|num|reqnum)$/', '', $k);
        // check if the fields is ordered
        if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;
        //remove number from begin of fields
        $k = preg_replace('/^\d+[ \:_-]/', '', $k);
        $new_vars[$k] = $v;
    }
    $vars = $new_vars;

    $max_length = 10; // max length of key field 
    foreach ($vars as $k=>$v) {
        $klen = strlen($k);
        if (($klen > $max_length) && ($klen < 40))
            $max_length = $klen;
    }

    if ($is_ordered)
        ksort($vars);

    // make output text
    $out = "";
    foreach ($vars as $k=>$v){
        $k = str_replace('_', ' ', $k);
        $k = ucfirst($k);
        $len_diff = $max_length - strlen($k);
        if ($len_diff > 0) 
            $fill = str_repeat('.', $len_diff);
        else 
            $fill = '';
        $out .= $k."$fill...: $v\n";
    }
    return $out;
}


function send_mail($vars){
    global $send_to, $send_cc;
    global $subject;
    global $attachment_enabled;
    global $REMOTE_ADDR;

    global $HTTP_POST_FILES;
    $files = array(); //files (field names) to attach in mail
    if (count($HTTP_POST_FILES) && $attachment_enabled){
        $files = array_keys($HTTP_POST_FILES);
    }

    // build mail
    $date_time = date('Y-m-d H:i:s');
    $mime_delimiter = md5(time());
    $fields = _build_fields($vars);
    $mail = <<<EOF
This is a MIME-encapsulated message
    
--$mime_delimiter
Content-type: text/plain
Content-Transfer-Encoding: 8bit

------------------
Buyer Information:
------------------

$fields

-------------------------------------
 DATE/TIME : $date_time
 REMOTE IP : $REMOTE_ADDR
-------------------------------------
EOF;

    if (count($files)){
        foreach ($files as $file){
            $file_name     = $HTTP_POST_FILES[$file]['name'];
            $file_type     = $HTTP_POST_FILES[$file]['type'];
            $file_tmp_name = $HTTP_POST_FILES[$file]['tmp_name'];
            $file_cnt = "";
            $f=@fopen($file_tmp_name, "rb");
            if (!$f) 
                continue;
            while($f && !feof($f))
                $file_cnt .= fread($f, 4096);
            fclose($f);
            if (!strlen($file_type)) $file_type="applicaton/octet-stream";
            if ($file_type == 'application/x-msdownload')
                $file_type = "applicaton/octet-stream";

            $mail .= "\n--$mime_delimiter\n";
            $mail .= "Content-type: $file_type\n";
            $mail .= "Content-Disposition: attachment; filename=\"$file_name\"\n";
            $mail .= "Content-Transfer-Encoding: base64\n\n";
            $mail .= chunk_split(base64_encode($file_cnt));
        }
    }
    $mail .= "\n--$mime_delimiter--";


    //send to
    $_send_to = $send_to ? $send_to : "$vars[Buyer] <".$vars[Buyer_Email].">";
    $_send_from = "$vars[Buyer_Email] <".$vars[Buyer_Email].">";
    $_subject = $subject ? $subject : $vars['subject'];

    mail($_send_to, $_subject, $mail, 
    "Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");

    foreach ($send_cc as $v){
      mail($v, $_subject, $mail, 
      "Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");
    }

}

function get_form_data(){
    global $REQUEST_METHOD;
    global $HTTP_POST_VARS;
    global $HTTP_GET_VARS;
    
    $vars = ($REQUEST_METHOD == 'GET') ? $HTTP_GET_VARS : $HTTP_POST_VARS;
    //strip spaces from all fields
    foreach ($vars as $k=>$v) $vars[$k] = trim($v);
    return $vars;
}

function check_form($vars){
    global $referrers;
    global $send_to;
    global $subject;
    global $HTTP_REFERER;

    $errors = array();

    // check from email set
    if (!strlen($vars[Buyer_Email])){
        $errors[] = "<b>Primary Email</b> empty";
    } else if (!check_email($vars[Buyer_Email])){
        $errors[] = "<b>Primary Email</b> incorrect";        
    }                 
    if (!strlen($send_to) && !strlen($vars[$send_to])){
        $errors[] = "<b>To Email</b> address empty (possible configuration error)";
    } else if (!strlen($send_to) && !check_email($vars[$send_to])){
        //if to email specified in form, check it and display error
        $errors[] = "<b>To Email address</b> incorrect";        
    }
    if (!strlen($vars['subject']) && !strlen($subject)){
        $errors[] = "<b>Subject</b> empty (possible configuration error)";
    }
    foreach ($vars as $k=>$v){
        // check for required fields (end with _req)
        if (preg_match('/^(.+?)_req$/i', $k, $m) && !strlen($v)){
            $field_name = ucfirst($m[1]);
            $errors[] = "Required field <b>$field_name</b> empty";
        }
        // check for number fields (end with _num)
        if (preg_match('/^(.+?)_num$/i', $k, $m) && strlen($v) && !is_numeric($v)){
            $field_name = ucfirst($m[1]);
            $errors[] = "Field <b>$field_name</b> must contain only digits or be empty";
        }
        // check for number & required fields (end with _reqnum)
        if (preg_match('/^(.+?)_reqnum$/i', $k, $m) && !is_numeric($v)){
            $field_name = ucfirst($m[1]);
            $errors[] = "Field <b>$field_name</b> must contain digits and only digits";
        }
    }

    //check referrer
    if (is_array($referrers) && count($referrers)){
        $ref = parse_url($HTTP_REFERER);
        $host = $ref['host'];
        $host_found = 0;
        foreach ($referrers as $r){
            if (strstr($host, $r)) 
                $host_found++;
        }
        if (!$host_found){
            $errors[] = "Unknown Referrer: <b>$host</b>";
        }
    }
    return $errors;
}

function display_errors($errors){
$errors = '<li>' . join('<li>', $errors);
print <<<EOF

<html>
<head>
<title>Buyers Helpline - There was an Error...</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style>
<!-- A {TEXT-DECORATION: none} A:hover{TEXT-DECORATION: underline} //-->
</style>
</head>
<body bgcolor="#EEEBD8" link="#003366" vlink="#003366" alink="#003366" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" height="202" border="0" cellpadding="0" cellspacing="0" background="../images/bg.jpg">
  <tr>
    <td valign="middle"><div id="Layer1" style="position:absolute; width:100%; height:100%; z-index:1; left: 0px; top: 0px;">
        <div align="center"> 
          <table border="0" cellpadding="0" cellspacing="0" width="627">
            <!-- fwtable fwsrc="buyers_helpline_new.png" fwbase="buyers_helpline_new.jpg" fwstyle="Dreamweaver" fwdocid = "742308039" fwnested="0" -->
            <tr> 
              <td><img src="../images/spacer.gif" width="627" height="1" border="0" alt=""></td>
              <td><img src="../images/spacer.gif" width="1" height="1" border="0" alt=""></td>
            </tr>
            <tr> 
              <td><a href="javascript: history.back(-1)"><img name="buyers_helpline_new_r1_c1" src="../images/buyers_helpline_new_r1_c1.jpg" width="627" height="200" border="0" alt=""></a></td>
              <td><img src="../images/spacer.gif" width="1" height="200" border="0" alt=""></td>
            </tr>
            <tr> 
              <td rowspan="2" background="../images/buyers_helpline_new_r3_c1.jpg"><div align="center"> 
                  <p><br>
                    <a href="javascript: history.back(-1)"><img src="../images/buyers_toll_free_blue.gif" width="431" height="77" border="0"></a> 
                  <p align="center"><font color="#993300" size="5" face="Arial, Helvetica, sans-serif"><a href="javascript: history.back(-1)">Oops! There 
                    was an error<br>
                    with your Help Request Form:</a></font></p>
                  <p align=center> <font face="Arial" size="3" color="#555555">$errors</font> <br>
                    <br>
                    <font size="4" face="Arial, Helvetica, sans-serif"><strong><a href="javascript: history.back(-1)">Click 
                    Here to Return and Fix the Error(s)</a></font><br>
                    <br>
                    <a href="javascript: history.back(-1)"><img src="../images/buyers.gif" width="438" height="190" border="0"></a> 
                    <br><br>
					<a href="javascript: history.back(-1)"><img src="../images/buyers_text_blue_2.gif" alt="Click to Get Help Now!" width="420" height="90" border="0"></a>
                    </p>
                    </p>
                </div></td>
              <td><img src="../images/spacer.gif" width="1" height="280" border="0" alt=""></td>
            </tr>
            <tr> 
              <td height="7"><img src="../images/spacer.gif" width="1" height="7" border="0" alt=""></td>
            </tr>
            <tr> 
              <td><img name="buyers_helpline_new_r4_c1" src="../images/buyers_helpline_new_r4_c1.jpg" width="627" height="49" border="0" alt=""></td>
              <td><img src="../images/spacer.gif" width="1" height="49" border="0" alt=""></td>
            </tr>
          </table>
          <p align="center"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><a href="http://www.SellersHelpline.com"><strong><font size="3" face="Arial, Helvetica, sans-serif">Sellers 
              Helpline</font> </strong></a>-  
              <a href="http://www.BuyersHelpline.com"><strong><font size="3" face="Arial, Helvetica, sans-serif">Buyers Helpline</font></strong></a> 
              - <a href="http://www.RefinanceHelpline.com"><strong><font size="3" face="Arial, Helvetica, sans-serif">Refinance 
              Helpline</font><br>
              <br>
              </strong></a></font><font color="#777777" size="1" face="Verdana, Arial, Helvetica, sans-serif">Copyright 
              &copy;2006-2007 - Buyers Helpline - All Rights Reserved.</font></p>
            <p>&nbsp;</p>
          </div>
</div>
      </div></td>
  </tr>
</table>
</body>
</html>

EOF;
}


/**
* Check email using regexes
* @param string email
* @return bool true if email valid, false if not
*/
function check_email($email) {
    #characters allowed on name: 0-9a-Z-._ on host: 0-9a-Z-. on between: @
    if (!preg_match('/^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/', $email))
        return false;

    #must start or end with alpha or num
    if ( preg_match('/^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/', $email))
        return false;

    #name must end with alpha or num
    if (!preg_match('/([0-9a-zA-Z_]{1})\@./',$email) )                    
        return false;

    #host must start with alpha or num
    if (!preg_match('/.\@([0-9a-zA-Z_]{1})/',$email) )                    
        return false;

    #pair .- or -. or -- or .. not allowed
    if ( preg_match('/.\.\-.|.\-\..|.\.\..|.\-\-./',$email) )
        return false;

    #pair ._ or -_ or _. or _- or __ not allowed
    if ( preg_match('/.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./',$email) )
        return false;

    #host must end with '.' plus 2-5 alpha for TopLevelDomain
    if (!preg_match('/\.([a-zA-Z]{2,5})$/',$email) )
        return false;

    return true;
}

do_formmail();
?>