I have a simple PHP form with few fields and form details are sent using following code mentioned below..
Even thought i get "Thank you. Your messsage has been received." message but message never comes through.
I tried changed $use_smtp = '0'; still doesn't work
<?php
include('SMTPClass.php');
$use_smtp = '1';
$emailto = 'info#domain.com';
// retrieve from parameters
$emailfrom = isset($_POST["email"]) ? $_POST["email"] : "";
$nocomment = isset($_POST["nocomment"]) ? $_POST["nocomment"] : "";
$subject = 'Email from Website';
$message = '';
$response = 'Thank you for your message. I will be in contact shortly.';
$response_fail = 'There was an error verifying your details.';
// Honeypot captcha
if($nocomment == "") {
$params = $_POST;
foreach ( $params as $key=>$value ){
if(!($key == 'ip' || $key == 'emailsubject' || $key == 'url' || $key == 'emailto' || $key == 'nocomment' || $key == 'v_error' || $key == 'v_email')){
$key = ucwords(str_replace("-", " ", $key));
if ( gettype( $value ) == "array" ){
$message .= "$key: \n";
foreach ( $value as $two_dim_value )
$message .= "...$two_dim_value<br>";
}else {
$message .= $value != '' ? "$key: $value\n" : '';
}
}
}
$response = sendEmail($subject, $message, $emailto, $emailfrom);
} else {
$response = $response_fail;
}
echo $response;
// Run server-side validation
function sendEmail($subject, $content, $emailto, $emailfrom) {
$from = $emailfrom;
$response_sent = 'Thank you. Your messsage has been received.';
$response_error = 'Error. Please try again.';
$subject = filter($subject);
$url = "Origin Page: ".$_SERVER['HTTP_REFERER'];
$ip = "IP Address: ".$_SERVER["REMOTE_ADDR"];
$message = $content."\n$ip\r\n$url";
// Validate return email & inform admin
$emailto = filter($emailto);
// Setup final message
$body = wordwrap($message);
if($use_smtp == '1'){
$SmtpServer = 'smtp.office365.com';
$SmtpPort = '587';
$SmtpUser = 'no-reply#domain.com';
$SmtpPass = 'password';
$to = $emailto;
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
$response = $SMTPChat ? $response_sent : $response_error;
} else {
// Create header
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
// Send email
$mail_sent = #mail($emailto, $subject, $body, $headers);
$response = $mail_sent ? $response_sent : $response_error;
}
return $response;
}
// Remove any un-safe values to prevent email injection
function filter($value) {
$pattern = array("/\n/", "/\r/", "/content-type:/i", "/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
exit;
?>
This example shows settings to use when sending via Google's Gmail servers.
SMTP needs accurate times, and the PHP time zone MUST be set
This should be done in your php.ini, but this is how to do it if you don't have access to that
https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps
Related
I am using the following function to send html mail in cscart.
$value = fn_send_mail($user_data['email'], Registry::get('settings.Company.company_users_department'), 'addons/test/test_subj.tpl', 'addons/test/test_body.tpl');
If i print $value means it only return 1. How do i return html in this function.
I found it :)
To display/retrun html template please use this following code.
$body = Registry::get('view_mail')->display($body, false);
print_r($body);
You have 2 options:
Option 1
You create your on mail sender function which will return the body, and you use this in your add-on. For example:
function custom_send_mail($to, $from, $subj, $body, $attachments = array(), $lang_code = CART_LANGUAGE, $reply_to = '', $is_html = true)
{
fn_disable_translation_mode();
$__from = array();
$__to = array();
fn_init_mailer();
$mailer = & Registry::get('mailer');
$languages = Registry::get('languages');
Registry::get('view_mail')->setLanguage($lang_code);
fn_set_hook('send_mail_pre', $mailer, $to, $from, $subj, $body, $attachments, $lang_code, $reply_to, $is_html);
if (!empty($reply_to)) {
$mailer->ClearReplyTos();
$reply_to = fn_format_emails($reply_to);
foreach ($reply_to as $rep_to) {
$mailer->AddReplyTo($rep_to);
}
}
if (!is_array($from)) {
$__from['email'] = $from;
} else {
$__from = $from;
}
if (empty($__from['email'])) {
$__from['email'] = Registry::get('settings.Company.company_site_administrator');
}
if (empty($__from['name'])) {
$__from['name'] = Registry::get('settings.Company.company_name');
}
$mailer->SetFrom($__from['email'], $__from['name']);
$mailer->IsHTML($is_html);
$mailer->CharSet = CHARSET;
$mailer->Subject = Registry::get('view_mail')->display($subj, false);
$mailer->Subject = trim($mailer->Subject);
$body = Registry::get('view_mail')->display($body, false);
$mailer->Body = fn_attach_images($body, $mailer);
if (!empty($attachments)) {
foreach ($attachments as $name => $file) {
$mailer->AddAttachment($file, $name);
}
}
$__to = fn_format_emails($to);
foreach ($__to as $v) {
$mailer->ClearAddresses();
$mailer->AddAddress($v, '');
$result = $mailer->Send();
if (!$result) {
fn_set_notification('E', fn_get_lang_var('error'), fn_get_lang_var('error_message_not_sent') . ' ' . $mailer->ErrorInfo);
}
fn_set_hook('send_mail', $mailer);
}
return $body;
}
Option 2
You can connect to send_mail_pre hook via your add-on:
function fn_youraddonname_send_mail_pre($mailer, $to, $from, $subj, $body, $attachments, $lang_code, $reply_to, $is_html) {
$rendered_body = Registry::get('view_mail')->display($body, false);
// use your custom code, to do anything you want
// this code will run everytime CS-Cart use the fn_send_mail function
}
I'm getting this error when trying to post from an AngularJS control to a PHP page to process. The object looks fine, but it keeps giving this error:
TypeError: Cannot read property 'protocol' of undefined
at urlIsSameOrigin (angular.js:17714)
at sendReq (angular.js:10225)
at serverRequest (angular.js:9944)
at processQueue (angular.js:14454)
at angular.js:14470
at Scope.$eval (angular.js:15719)
at Scope.$digest (angular.js:15530)
at Scope.$apply (angular.js:15824)
at HTMLFormElement.<anonymous> (jcs-auto-validate.min.js:6)
at HTMLFormElement.eventHandler (angular.js:3247)
Here is the code for the controller:
(function () {
angular
.module('contactApp')
.controller('FormCtrl', FormCtrl);
function FormCtrl ($http) {
/* jshint validthis: true */
var vm = this;
vm.formModel = {};
vm.success = false;
vm.error = false;
vm.onSubmit = function () {
console.log("I'm submitted");
console.log(vm.formModel);
$http({
method : 'POST',
URL : '/formProcess.php',
data : {
'name':vm.formModel.name,
'phoneNumber':vm.formModel.phoneNumber,
'email':vm.formModel.email,
'streetAddress':vm.formModel.streetAddress,
'cityStateZip':vm.formModel.cityStateZip,
'bedrooms':vm.formModel.bedrooms,
'bath':vm.formModel.baths,
'reason':vm.formModel.reason
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data, status, headers, config) {
vm.resultData = data;
alert("Message sent successfully. We'll get in touch with you soon.");
}).error(function(data, status, headers, config) {
vm.resultData = data;
alert("Sending message failed.");
});
/*.success( function(data, status, headers, config) {
if ( data.success ) {
vm.success = true;
console.log('happy');
} else {
vm.error = true;
console.log('sad');
}
});*/
}
}
FormCtrl.$inject = ['$http'];
})();
and for the PHP to send the email:
<?php
// ===========================================
// Define custom variables
// ===========================================
$emailTo = '---.com';
$nameTo = 'test';
$subject = 'test';
// ===========================================
// Validate and send email
// ===========================================
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$response = array( 'success' => false );
$formData = file_get_contents( 'php://input' );
$data = json_decode( $formData );
/*if ( $data->submit ) {*/
$name = $data->name;
$phoneNumber = $data->phoneNumber;
$email = $data->email;
$streetAddress = $data->streetAddress;
$cityStateZip = $data->cityStateZip;
$bedrooms = $data->bedrooms;
$baths = $data->baths;
$reason = $data->reason;
//check if any of the inputs are empty
if ( $name != '' && $phoneNumber != '' && $email != '' && $streetAddress != '' && $cityStateZip != '' && $bedrooms != '' && $baths != '' && $reason != '' ) {
$body = 'From: ' . $name . '\n';
$body .= 'Email: ' . $email . '\n';
$body .= 'Phone Number: ' . $phoneNumber . '\n';
$body .= 'Street Address: ' . $streetAddress . '\n';
$body .= 'City, State and Zip: ' . $cityStateZip . '\n';
$body .= 'Number of Bedrooms: ' . $bedrooms . '\n';
$body .= 'Number of Baths: ' . $baths . '\n';
$body .= 'Reason for Selling:\n ' . $reason . '\n\n';
$headers = 'From: '. $nameTo.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$success = mail($emailTo, $subject, $body, $headers);
if ( $success ) {
$response[ 'success' ] = true;
}
}
/*}*/
}
echo json_encode( $response );
?>
Any thoughts as to what I might be missing here?
Thanks!
I have this form where I wan't people to sign up for receiving free stuff campaign. The form works fine and its send the details to the requested eMail.
Now this form should also write the details to a csv file that we can handle the data more easily.
I use this form:
$value) {
${"".$key} = $value;
}
if (!isset($email)) {
header( "Location: $formurl" );
exit;
}
if ($_POST['services']) {
foreach($_POST['services'] as $value) {
$check_msg .= "- $value\n";
}
}
function is_email($email) {
return ereg("^[^# ]+#[^#]+\.[^# ]+$", $email);
}
function validate_email($email) {
// Create the syntactical validation regular expression
$regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
// Presume that the email is invalid
$valid = 0;
// Validate the syntax
if (eregi($regexp, $email))
{
list($username,$domaintld) = split("#",$email);
// Validate the domain
if (getmxrr($domaintld,$mxrecords))
$valid = 1;
} else {
$valid = 0;
}
return $valid;
}
$formurl = "/sticker/index.php" ;
$errorurl1 = "/sticker/error.php" ;
$errorurl2 = "/sticker/error.php" ;
$thankyouurl = "/sticker/success.php#start" ;
$http_referrer = getenv( "HTTP_REFERER" );
// get POST && GET vars to run with 'register_globals off'
//foreach($_GET AS $key => $value) {
// ${"".$key} = $value;
//}
$messageproper =
"============================================================\n" .
"Sticker Request $firstname $lastname\n" .
"============================================================\n\n" .
"KUNDENDATEN\n\n" .
"Vorname: $firstname\n" .
"Nachname: $lastname\n" .
"Firma: $company\n" .
"Strasse: $street\n" .
"Strasse2: $street2\n" .
"PLZ: $zip\n" .
"City: $city\n" .
"Land: $country\n\n" .
"Telefon: $phone\n" .
"eMail: $email\n" .
"Facebook Name: $fbname\n\n" .
"--------------------------------------\n\n" .
"Bemerkung: $comment\n\n" .
"============================================================\n\n" ;
$myFile = "/sticker/sticker.txt";
$fh = fopen($myFile, 'a');
$stringData = "\r\n";
$x=0;
foreach($_POST AS $key => $value) {
$x!=0?$stringData=",".$stringData:'';
$stringData='"'.$firstname.'";"'.$lastname.'";"'.$company.'";"'.$street.'";"'.$street2.'";"'.$zip.'";"'.$city.'";"'.$country.'";"'.$phone.'";"'.$email.'";"'.$fbname.'";"'.$comment.'"'."\r\n";
$x++;
}
fwrite($fh, $stringData);
fclose($fh);
$mailto = 'email#domain.com' ;
$subject = "Free Sticker Campaign: $company - $firstname $lastname";
mail($mailto, $subject, $messageproper, "From: \"$firstname $lastname\" <$email>\nReply-To: \"$lastname\" <$email>\nX-Mailer: chfeedback.php 2.01" );
header( "Location: $thankyouurl" );
exit;
?>
As I said nothing gets written to the CSV File I declared in $myFile.
Would be great if someone could let me know what to do.
Thanks.
I'm relatively new to WordPress and PHP, however I am trying to create my own shortcode plugin, which I have completed and is working.
However if I add more than 1 on the same page in WP, both forms submit and are not exclusive of each other.
I have search around the web, but can't find out how to easily separate the form id's, below is my plugin code:
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to '
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
If someone can help that would be appreciated.
Thanks,
Steve
I am pretty sure you've forgotten the last attribute in the function shortcode_atts, even if it's optionnal, you need to call it.
Also, is there some code missing ?
edit : you need to id your forms otherwise the function will pick up the datas twice. call the second shortcode giving the value 'second' to teh variable $num_f like so [wptuts_contact_form_sc -your bunch of vars here- num_f="second"]
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"num_f" => 'first'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $num_f == 'second') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
To have more than two forms, you can either do it manually by calling the third block 'trird' and so on, but that's not very good practice to be honest...
If I were you I would change your code at the core, create a function that would return the form with a hidden field like so : <input type"hidden" name="hidden" value=" . $nf . "> and then instead of controling $_SERVER['REQUEST_METHOD'], you'd control the value of $_POST['n'] after checking if it's set ofc.
Here's the code I came up with :
<?php
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"nf" => '1'
), $atts));
if (isset($_POST['hidden'])) {
$hidden = $_POST['hidden'];
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
} else {
$hidden = $_POST['hidden'];
}
for ($i = 1; $i <= $nf; $i++) {
if($result != "" && $i == $hidden) {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="hidden" name="hidden" value="' . $nf . '">
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info . $email_form;
}
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
?>
Let me know if it works, (or does not) I obviously couldnt test it so there might be somehting wrong, in which case I just hope you got the whole idea behind it.
I am trying to add a honeypot field to my form and every thing I have researched I cannot understand where to place the code. Any help would be appreciated. Here is what I have:
<div class="hide">
<label for="spam">What is two plus two?</label>
<input name="spam" type="text" size="4" id="spam">
</div>
Here is the css:
.hide {display: none;}
Here is the .php that I am trying to incorporate in my .php file:
$spa = $_POST["spam"];
if (!empty($spa) && !($spa == "4" || $spa == "four")) {
echo "You failed the bot test!";
exit ();
}
Here is the .php file itself:
<?php
class contactForm{
function contactForm($cfg)
{
$this->cfg['email_address'] = isset($cfg['email_address'])?$cfg['email_address']:'';
// =?UTF-8?B? required to avoid bad character encoding in the From field
// é (keeps utf-8 encoding in the file)
$this->cfg['email_from'] = (isset($cfg['email_from']) && $cfg['email_from'])?'=?UTF-8?B?'.base64_encode($cfg['email_from']).'?=':$this->cfg['email_address'];
$this->cfg['email_address_cc'] = isset($cfg['email_address_cc'])?$cfg['email_address_cc']:'';
$this->cfg['email_address_bcc'] = isset($cfg['email_address_bcc'])?$cfg['email_address_bcc']:'';
$this->cfg['timezone'] = isset($cfg['timezone'])?$cfg['timezone']:'';
$this->cfg['adminnotification_subject'] = isset($cfg['adminnotification_subject'])?$cfg['adminnotification_subject']:'';
$this->cfg['usernotification_insertformdata'] = isset($cfg['usernotification_insertformdata'])?$cfg['usernotification_insertformdata']:'';
$this->cfg['usernotification_inputid'] = isset($cfg['usernotification_inputid'])?$cfg['usernotification_inputid']:'';
$this->cfg['usernotification_subject'] = isset($cfg['usernotification_subject'])?$cfg['usernotification_subject']:'';
$this->cfg['usernotification_message'] = isset($cfg['usernotification_message'])?preg_replace('#<br(\s*)/>|<br(\s*)>#i', "\r\n",$cfg['usernotification_message']):'';
$this->cfg['form_name'] = isset($cfg['form_name'])?$cfg['form_name']:'';
$this->cfg['form_errormessage_captcha'] = isset($cfg['form_errormessage_captcha'])?$cfg['form_errormessage_captcha']:'';
$this->cfg['form_errormessage_emptyfield'] = isset($cfg['form_errormessage_emptyfield'])?$cfg['form_errormessage_emptyfield']:'';
$this->cfg['form_errormessage_invalidemailaddress'] = isset($cfg['form_errormessage_invalidemailaddress'])?$cfg['form_errormessage_invalidemailaddress']:'';
$this->cfg['form_validationmessage'] = isset($cfg['form_validationmessage'])?$cfg['form_validationmessage']:'';
$this->cfg['form_redirecturl'] = isset($cfg['form_redirecturl'])?$cfg['form_redirecturl']:'';
$this->dash_line = '--------------------------------------------------------------';
$this->mail_content_type_format = 'plaintext'; // html
if($this->mail_content_type_format == 'plaintext')
{
$this->mail_content_type_format_charset = 'Content-type: text/plain; charset=utf-8';
$this->mail_line_break = "\r\n";
}
if($this->mail_content_type_format == 'html')
{
$this->mail_content_type_format_charset = 'Content-type: text/html; charset=utf-8';
$this->mail_line_break = "<br />";
}
/**
* USER NOTIFICATION MAIL FORMAT
*/
$this->cfg['usernotification_format'] = isset($cfg['usernotification_format'])?$cfg['usernotification_format']:'';
if($this->cfg['usernotification_format'] == 'plaintext')
{
$this->mail_content_type_format_charset_usernotification = 'Content-type: text/plain; charset=utf-8';
$this->mail_line_break_usernotification = "\r\n";
}
if($this->cfg['usernotification_format'] == 'html')
{
$this->mail_content_type_format_charset_usernotification = 'Content-type: text/html; charset=utf-8';
$this->mail_line_break_usernotification = "<br />";
}
$this->merge_post_index = 0;
$this->demo = 0;
$this->envato_link = '';
}
function sendMail($param)
{
$count_files_to_attach = 0;
// grab and insert the form URL in the notification message
$form_url = (#$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
if($_SERVER['SERVER_PORT'] != '80')
{
$form_url .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].rawurlencode($_SERVER['SCRIPT_NAME']);
}
else
{
$form_url .= $_SERVER['SERVER_NAME'].rawurlencode($_SERVER['SCRIPT_NAME']);
}
$form_url = str_replace('%2F', '/', $form_url);
$form_url_exp = explode('/', $form_url);
// remove contactform/inc/form-validation.php
$pattern_slash = $form_url_exp[count($form_url_exp)-3].'/'.$form_url_exp[count($form_url_exp)-2].'/'.$form_url_exp[count($form_url_exp)-1];
$form_url = str_replace($pattern_slash, '', $form_url);
if($this->cfg['timezone'])
{
date_default_timezone_set($this->cfg['timezone']);
}
// g:i A | 01:37 AM
// G:i | 13:37
$mail_body = $this->cfg['adminnotification_subject'].': '.#date("F jS, Y, G:i")
.$this->mail_line_break.$this->mail_line_break.$this->cfg['form_name']
.$this->mail_line_break.$this->mail_line_break.'Form URL: '
.$this->mail_line_break.$form_url
.$this->mail_line_break.$this->dash_line;
if($this->merge_post)
{
foreach($this->merge_post as $value)
{
if(
isset($value['element_type']) && $value['element_type'] == 'upload'
&& isset($value['filename']) && $value['filename']
)
{
if( isset($value['deletefile']) && ($value['deletefile'] == 1 || $value['deletefile'] == 2) )
{
$count_files_to_attach++;
}
$explode_requesturi = explode('/',$_SERVER['REQUEST_URI']);
//print_r($explode_requesturi);
$explode_requesturi = explode('/',$_SERVER['SCRIPT_NAME']);
//print_r($explode_requesturi);
$inc_form_validation = $explode_requesturi[count($explode_requesturi)-2].'/'.$explode_requesturi[count($explode_requesturi)-1] ;
$install_dir = str_replace($inc_form_validation,'',$_SERVER['SCRIPT_NAME']);
$mail_body .= $this->mail_line_break.$this->mail_line_break.$value['elementlabel_value'].': '.$value['element_value'];
// No file link if we delete the file after the upload
// 1: File Attachment + Download Link
// 2: File Attachment Only
if( isset($value['deletefile']) && ($value['deletefile'] == 1 || $value['deletefile'] == 3) )
{
$mail_body .= $this->mail_line_break
.'http://'.$_SERVER['SERVER_NAME']
.str_replace('%2F', '/', rawurlencode($install_dir.'upload/'.$value['element_value']));
}
}
else{
$mail_body .= $this->mail_line_break.$this->mail_line_break.$value['elementlabel_value'].': '.$value['element_value'];
}
}
}
$mail_body .= $this->mail_line_break.$this->mail_line_break.$this->dash_line;
$mail_body .= $this->mail_line_break.'IP address: '.$_SERVER['REMOTE_ADDR'];
$mail_body .= $this->mail_line_break.'Host: '.gethostbyaddr($_SERVER['REMOTE_ADDR']);
if(preg_match('#html#', $this->mail_content_type_format_charset))
{
$mail_body = nl2br($mail_body);
}
if($this->demo != 1)
{
// for the admin: if the user provides his email address, it will appear in the "from" field
$param['reply_emailaddress'] = (isset($param['reply_emailaddress']) && $param['reply_emailaddress'])?$param['reply_emailaddress']:$this->cfg['email_address'];
// for the admin: if the user provides his email address, it will appear in the "reply-to" field
$replyto_name = $param['reply_emailaddress']?$param['reply_emailaddress']:'';
$replyto_address = $param['reply_emailaddress']?$param['reply_emailaddress']:'';
$mailheaders_options = array(
'from'=>array('name'=>$param['reply_emailaddress'], 'address'=>$param['reply_emailaddress']),
'replyto'=>array('name'=>$replyto_name, 'address'=>$replyto_address),
'cc'=>array('address'=>$this->cfg['email_address_cc']),
'bcc'=>array('address'=>$this->cfg['email_address_bcc'])
);
$mailheaders = $this->getMailHeaders($mailheaders_options);
//if(!isset($param['uploads']) || !$param['uploads'])
if(!$count_files_to_attach)
{
$mailheaders .= $this->mail_content_type_format_charset."\r\n";
$mailmessage = $mail_body;
} else
{
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$mailheaders .= "MIME-Version: 1.0\n"
."Content-Type: multipart/mixed;\n"
." boundary=\"{$mime_boundary}\"";
// multipart boundary
$mailmessage = "This is a multi-part message in MIME format.\n\n"
."--{$mime_boundary}\n"
.$this->mail_content_type_format_charset."\n"
."Content-Transfer-Encoding: 7bit\n\n"
.$mail_body
."\n\n";
$mailmessage .= "--{$mime_boundary}\n";
// preparing attachments
$count_attached_file = 0;
foreach($this->merge_post as $value)
{
if(
isset($value['element_type']) && $value['element_type'] == 'upload'
&& isset($value['filename']) && $value['filename']
&& isset($value['deletefile']) && ($value['deletefile'] == 1 || $value['deletefile'] == 2)
)
{
$count_attached_file++;
$file = fopen('../upload/'.$value['filename'],"rb");
$data = fread($file,filesize('../upload/'.$value['filename']));
fclose($file);
$data = chunk_split(base64_encode($data));
$mailmessage .= 'Content-Type: {"application/octet-stream"};'."\n" . ' name="'.$value['filename'].'"'."\n"
.'Content-Disposition: attachment;'."\n" . ' filename="'.$value['filename'].'"'."\n"
.'Content-Transfer-Encoding: base64'."\n\n" . $data . "\n\n";
// "--" must be added for the last file, or an empty file will be also attached in the message
if($count_attached_file == $count_files_to_attach)
{
$mailmessage .= "--{$mime_boundary}--\n";
} else{
$mailmessage .= "--{$mime_boundary}\n";
}
// delete attached file?
// this is different from deleting the file when the user deletes the file himself in the from: check form-validation.php for this (in form-validation.php because the file must be deleted even if sendMail() is not called - when there are errors for example)
if(isset($value['deletefile']) && $value['deletefile'] == 2)
{
#unlink('../upload/'.$value['filename']);
}
}
} // foreach
} // if(!$count_files_to_attach)
#mail($this->cfg['email_address'], $this->cfg['adminnotification_subject'], $mailmessage, $mailheaders);
}
}
function sendMailReceipt($value)
{
if($this->demo != 1)
{
$mailheaders_options = array(
'from'=>array('name'=>$this->cfg['email_from'], 'address'=>$this->cfg['email_address']),
'replyto'=>array('name'=>$this->cfg['email_from'], 'address'=>$this->cfg['email_address'])
);
$mailheaders = $this->getMailHeaders($mailheaders_options)
.$this->mail_content_type_format_charset_usernotification."\r\n"
;
$mail_body = '';
$mail_body .= $this->cfg['usernotification_message'];
if($this->cfg['usernotification_insertformdata'])
{
$mail_body .= $this->mail_line_break_usernotification."--------------------------------------------------------";
foreach($this->merge_post as $form_data)
{
$mail_body .= $this->mail_line_break_usernotification.$this->mail_line_break_usernotification.$form_data['elementlabel_value'].': '.$form_data['element_value'];
}
}
if(preg_match('#html#', $this->mail_content_type_format_charset_usernotification))
{
$mail_body = nl2br($mail_body);
}
#mail($value['email_address'], $this->cfg['usernotification_subject'], $mail_body, $mailheaders);
}
}
function mergePost($value)
{
$this->merge_post[$this->merge_post_index]['element_id'] = $value['element_id'];
$this->merge_post[$this->merge_post_index]['element_value'] = $this->quote_smart(trim($value['element_value']));
$this->merge_post[$this->merge_post_index]['elementlabel_value'] = $this->quote_smart(trim($value['elementlabel_value']));
$this->merge_post[$this->merge_post_index]['elementlabel_id'] = $this->quote_smart(trim($value['elementlabel_id']));
if(isset($value['element_type']) && $value['element_type'])
{ // if element_type == upload, we add the download link in the mail body message
$this->merge_post[$this->merge_post_index]['element_type'] = trim($value['element_type']);
}
if(isset($value['filename']) && $value['filename'])
{
$this->merge_post[$this->merge_post_index]['filename'] = $this->quote_smart(trim($value['filename']));
}
if(isset($value['deletefile']) && $value['deletefile'])
{
$this->merge_post[$this->merge_post_index]['deletefile'] = trim($value['deletefile']);
}
$this->merge_post_index++;
}
function isEmail($email)
{
$atom = '[-a-z0-9\\_]'; // authorized caracters before #
$domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // authorized caracters after #
$regex = '/^' . $atom . '+' .
'(\.' . $atom . '+)*' .
'#' .
'(' . $domain . '{1,63}\.)+' .
$domain . '{2,63}$/i';
// test de l'adresse e-mail
return preg_match($regex, trim($email)) ? 1 : 0;
}
function quote_smart($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
return $value;
}
function getMailHeaders($mailheaders_options)
{
$mailheaders_options['from']['name'] = isset($mailheaders_options['from']['name'])?$mailheaders_options['from']['name']:$mailheaders_options['from']['address'];
$mailheaders_options['cc']['address'] = isset($mailheaders_options['cc']['address'])?$mailheaders_options['cc']['address']:'';
$mailheaders_options['bcc']['address'] = isset($mailheaders_options['bcc']['address'])?$mailheaders_options['bcc']['address']:'';
$from_name = $mailheaders_options['from']['name']?$mailheaders_options['from']['name']:$mailheaders_options['from']['address'];
if($this->isEmail($from_name))
{
// From: user#domain.com <user#domain.com> is invalid => user#domain.com
$mail_header_from = 'From: '.$from_name."\r\n";
$mail_header_replyto = 'Reply-To: '.$from_name."\r\n";
} else
{
$mail_header_from = 'From: '.$from_name.'<'.$mailheaders_options['from']['address'].'>'."\r\n";
$mail_header_replyto = 'Reply-To: '.$from_name.'<'.$mailheaders_options['from']['address'].'>'."\r\n";
}
$mail_header_cc = '';
if($mailheaders_options['cc']['address'])
{
$explode_email = explode(',', $mailheaders_options['cc']['address']);
$cc = '';
foreach($explode_email as $email_value)
{
$cc .= $email_value.",";
}
$mail_header_cc .= 'Cc: '.substr($cc, 0, -1)."\r\n";
}
$mail_header_bcc = '';
if($mailheaders_options['bcc']['address'])
{
$explode_email = explode(',', $mailheaders_options['bcc']['address']);
$bcc = '';
foreach($explode_email as $email_value)
{
$bcc .= $email_value.",";
}
$mail_header_bcc .= 'Bcc: '.substr($bcc, 0, -1)."\r\n";
}
$mailheaders = $mail_header_from
.$mail_header_cc
.$mail_header_bcc
.$mail_header_replyto
.'MIME-Version: 1.0'."\r\n"
.'X-Mailer: PHP/'.phpversion()."\r\n"
;
/*
Examples of headers that should work would be:
From: user#domain.com will work
From: "user" <user#domain.com>
Examples of headers that will NOT work:
From: "user#domain.com"
From: user # domain.com
From: user#domain.com <user#domain.com>
*/
// echo $mailheaders;
return($mailheaders);
}
}
/**
* NO SPACES AFTER THIS LINE TO PREVENT
* Warning: Cannot modify header information
*/
?>
The idea of a honeypod is that most of the spambots can't execute javascript. So you do the folowwing:
Add a field with a spam question (as you did)
Fill in the correct value with javascript
Hide the field with javascript
Check the answer from the submitted form against the correct answer in the form processing PHP script
So you ensure that someone who has javascript disabled (like a spambot) sees the input field and can insert the answer to your question manually.
All this points implemented could look like this:
<?php
$formErrorMsgs = array();
if(isset($_GET['send'])) {
if(!isset($_POST['byebye_answer']) || $_POST['byebye_answer'] != 'stackoverflow')
$formErrorMsgs[] = 'Please enter the correct answer for the antispam question';
// all the other checks for the form input
if(count($formErrorMsgs) <= 0) {
// do the database insert or whatever here
// redirect to another page or something like that afterwards
}
}
?>
<form method="post" action="?send">
<?php echo (count($formErrorMsgs) > 0)?'<ul><li>' , implode('</li><li>', $formErrorMsgs) , '</li></ul>':null; ?>
<!-- all the regular input fields -->
<dl class="byebye">
<dt><label for="byebye-answer">Type in <b>stackoverflow</b></label></dt>
<dd><input type="text" id="byebye-answer" name="byebye_answer"></dd>
</dl>
</form>
<script>
// if you're using jQuery do this
(function() {
$('#byebye-answer').val('stackoverflow');
$('.byebye').hide();
})();
</script>