I've an HTML onepage website.
I want insert google recaptcha 2.0 system but something go wrong with js.
When i click on submit button no success message is shown and no message is sent.
The button Send remains clicked and no further actions happen.
WIth the original php file on bottom the form works. But i've to insert recaptcha, too much spam.
Could someone help?
Thank you
Scipio
HTML CODE
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form name="frmcontact" action="php/send.php" class="contact-frm" method="post">
<input type="text" required placeholder="Nome" name="txtname">
<p class="twocolumn">
<input type="email" required placeholder="Email" name="txtemail">
<input type="tel" placeholder="Phone" name="txtphone">
</p>
<div class="g-recaptcha" data-sitekey="xxx"></div>
<textarea placeholder="Testo del Messaggio" name="txtmessage"></textarea>
<input type="submit" class="button" value="SEND" name="btnsend">
PHP CODE THAT I WANT TO INSERT:
<?php
if(isset($_POST['btnsend']) && !empty($_POST['btnsend'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha- response'])):
//your site secret key
$secret = 'XXX';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//contact form submission code
$name = !empty($_POST['txtname'])?$_POST['txtname']:'';
$email = !empty($_POST['txtemail'])?$_POST['txtemail']:'';
$email = !empty($_POST['txtphone'])?$_POST['txtphone']:'';
$message = !empty($_POST['txtmessage'])?$_POST['txtmessage']:'';
$to = 'XXX';
$subject = 'New contact form have been submitted';
$htmlContent = "
<h1>Contact request details</h1>
<p><b>Name: </b>".$name."</p>
<p><b>Email: </b>".$email."</p>
<p><b>Phone: </b>".$phone."</p>
<p><b>Message: </b>".$message."</p>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
//send email
#mail($to,$subject,$htmlContent,$headers);
$succMsg = 'Your contact request have submitted successfully.';
else:
$errMsg = 'Robot verification failed, please try again.';
endif;
else:
$errMsg = 'Please click on the reCAPTCHA box.';
endif;
else:
$errMsg = '';
$succMsg = '';
endif;
?>
JS CODE:
$('form[name="frmcontact"]').submit(function () {
var This = $(this);
if($(This).valid()) {
var action = $(This).attr('action');
var data_value = unescape($(This).serialize());
$.ajax({
type: "POST",
url:action,
data: data_value,
error: function (xhr, status, error) {
confirm('The page save failed.');
},
success: function (response) {
$('#ajax_contact_msg').html(response);
$('#ajax_contact_msg').slideDown('slow');
if (response.match('success') != null) $(This).slideUp('slow');
}
});
}
return false;
});
ORIGINAL PHP CODE:
<?php
if(!$_POST) exit;
$to = 'gopal#iamdesigning.com'; #Replace your email id...
$name = $_POST['txtname'];
$email = $_POST['txtemail'];
$phone = $_POST['txtphone'];
$subject = 'Support';
$comment = $_POST['txtmessage'];
if(get_magic_quotes_gpc()) { $comment = stripslashes($comment); }
$e_subject = 'You\'ve been contacted by ' . $name . '.';
$msg = "You have been contacted by $name with regards to $subject.\r\n\n";
$msg .= "$comment\r\n\n";
$msg .= "You can contact $name via email, $email.\r\n\n";
$msg .= "-------------------------------------------------------------------------------------------\r\n";
if(#mail($to, $e_subject, $msg, "From: $email\r\nReturn-Path: $email\r\n"))
{
echo "<span class='success-msg'>Thanks for Contacting Us, We will call back to you soon.</span>";
}
else
{
echo "<span class='error-msg'>Sorry your message not sent, Try again Later.</span>";
}
?>
Related
In Ajax code I have action = 'contact';, contact is used in route file:
Route::post('contact', array('uses' => 'FormsController#send', 'as' => 'post_form'));
In route file I have FormsController#send it is file php to send email:
$name = Input::get('name');
$getSubject = "Subject of my email";
$myEmail = 'myEmail#gmail.com';
$uid = md5(uniqid(time()));
$eol = "\r\n";
// header
$header = "From: " . $name . " <" . $email . ">\r\n";
$header .= "MIME-Version: 1.0" . $eol;
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"" . $eol;
$header .= "Content-Transfer-Encoding: 7bit" . $eol;
$header .= "This is a MIME encoded message." . $eol;
// message & attachment
$nmessage = "--" . $uid . "\r\n";
$nmessage .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$nmessage .= "Content-Transfer-Encoding: 8bit" . $eol;
if($name != ''){$nmessage .= "Name: " . $name . "\r\n\r\n";}
// $nmessage .= "Wiadomość:\r\n" . $getMessage . "\r\n\r\n";
$nmessage .= "--" . $uid . "\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "--" . $uid . "--";
$send = mail($myEmail, $getSubject, $nmessage, $header);
Ajax directs to the controller file and bypasses the form, so the controller file does not download any data from the form, and the mail can not be sent. I have no idea how to pass data from the form to the controller file.
My Ajax:
const sendForm = function () {
action = 'contact';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('post', action, true);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
const getMessageSend = document.querySelector("#messageSend");
getMessageSend.innerText = "Thank you for sending an email. You will receive an answer shortly.";
} else {
const getMessageSendError = document.querySelector("#messageSendError");
getMessageSendError.innerText = "An error occurred and the email was not sent.";
}
};
// xmlhttp.open("post", action, true);
// xmlhttp.send();
const token = document.querySelector('meta[name="csrf-token"]').content;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xmlhttp.setRequestHeader('X-CSRF-TOKEN', token);
xmlhttp.send();
};
const sendMail = function() {
options.form.addEventListener('submit', function (e) {
e.preventDefault();
let validate = true;
const elementsRequired = document.querySelectorAll(":scope [formHr]");
[].forEach.call(elementsRequired, function(element) {
const type = element.type.toUpperCase();
if (type === 'TEXT') {
if (!validateText(element)) {validate = false;}
}
});
if (validate) {
sendForm();
// this.submit();
} else {
return false;
}
});
};
My form:
{!! Form::open(['action'=>['FormsController#send'], 'method' => 'post', 'class' => 'form', 'novalidate' => 'novalidate', 'files' => true]) !!}
<input type="text" name="name" placeholder="Name" formHr>
{!! Form::submit('Send', ['class' => 'submit-btn']); !!}
{!! Form::close() !!}
I found a solution. Help me this theme Submit form laravel using AJAX
I just add data to my code:
$.ajax({
type: "POST",
url: 'contact',
data: $(this).serialize(),
success: function () {
$("#messageSend").addClass("message-send");
$("#messageSend").text("Thank you for sending an email. You will receive an answer shortly.");
}
});
Remember to use full version Jquery!
Am working on a Password reset system whereby the user who forgot his password can request for password reset link by submitting his email used in registration. I successfully create the email, it sent the link and I test the link by clicking on it. The link went through and load the reset page but my problem is how to make the system recognise the user who click through and get all the details including Name, Token, email with which the system will confirm that the user is the user who requested the link.
The following is what I have done so far:
Controller
public function preset(){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_error_delimiters("<div class='alert alert-warning'><span type='button' class='close' data-dismiss='alert'>×</span>","</div>");
if($this->form_validation->run() == false){
$this->load->view('passwordrecovery.php', $data);
}
else{
$eMail = $this->input->post('email');
$this->db->where("email = '$eMail'");
$this->db->from("useraccount");
$countResult = $this->db->count_all_results();
if($countResult >=1){
// $data['firstName'] = '';
// $data['lastName'] = '';
$this->db->where("email = '$eMail'");
$getUserData =$this->db->get("useraccount")->result();
foreach($getUserData as $userD){
$data['firstName'] = $userD->firstname;
$data['lastName'] = $userD->lastname;
}
$sender_email = 'xxx#gmail.com';
$user_password = 'xxxxxx';
$token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 50);
$subject = 'Password Reset';
$message = '';
$message .= "<h2>You are receiving this message in response to your request for password reset</h2>"
. "<p>Follow this link to reset your password <a href='".site_url()."/authenticate/resetpassword/.$token' >Reset Password</a> </p>"
. "<p>If You did not make this request kindly ignore!</p>"
. "<P class='pj'><h2>Kind Regard: Votemate</h2></p>"
. "<style>"
. ".pj{"
. "color:green;"
. "}"
. "</style>"
. "";
// Configure email library
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $user_password;
$config['mailtype'] = 'html';
// Load email library and passing configured values to email library
$this->load->library('email', $config);
//$this->email->set_newline("rn");
$this->email->set_mailtype("html");
// Sender email address
$this->email->from($sender_email);
// Receiver email address
$this->email->to($eMail);
// Subject of email
$this->email->subject($subject);
// Message in email
$this->email->message($message);
if ($this->email->send()) {
$eMail = $this->input->post('email');
$ipadd = $this->input->ip_address();
$insert = array(
'email' => $eMail,
'ipaddress' => $ipadd,
'token' => $token
);
$this->db->insert('passwordreset', $insert);
$mail = $this->session->set_userdata('email');
$data['success'] = 'Email Successfully Send !';
$this->load->view('linksent.php', $data);
} else {
$data['error'] = '<p class="error_msg">Invalid Gmail Account or Password !
</p>';
}
$this->load->view('passwordrecovery.php', $data);
}
if($countResult <= 0){
//user already registered
$data['error'] = "<div class='alert alert-warning'> Invalid
email address<span type='button' class='close' data-
dismiss='alert'>×</span></div>";
$this->load->view('passwordrecovery.php',$data);
}
}
}
View
<div>
<h1>Password Recovery</h1>
<h3>Enter your email to receive the password reset link in
your Inbox</h3>
<br/>
<?php echo form_open('authenticate/preset');?>
<?php echo $error;?>
<div class="form-group">
<input type="text" name="email" required="required">
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn-success
btn" >
</div>
<?php echo form_close()?>
<br/><br/><br/>
</div>
Database: The following is database where I store the info:
CREATE TABLE `passwordreset` (
`resetid` int(11) NOT NULL,
`email` varchar(150) NOT NULL,
`ipaddress` varchar(25) NOT NULL,
`token` varchar(512) NOT NULL
) ENGINE
The help I need is how to get the details (Name, email, token) of the user who click the link from his email and use it to validate and also use it to update his password. Thanks
pass user email or token in url or in hidden field when user click on verify link and check in controller method.
<a href="<?=site_url('user_verification?user_email=' . $user_email . '&user_code=' . $user_code);?> Click To Verifiy Email </a>
user_verification controller
public function user_verification_get()
{
$user_email = $this->input->get('user_email');
$user_code = $this->input->get('user_code');
$data=$this->admin_model->user_verification($user_email,$user_code);
if($data)
{
$data['message'] = 'Success.';
}
else
{
$data['message'] = 'Not Valid User.';
}
$this->load->template('verify', $data);
}
Model
public function user_verification($user_email,$user_code){
$this->db->select('user_email');
$this->db->where('user_email',$user_email);
$this->db->where('user_code',$user_code);
$query = $this->db->get('users');
if($query->row_array() > 0)
{
$data['user_isactive'] = true;
$this->db->where('user_email',$user_email);
$this->db->update('users',$data);
return $query->row_array();
}
return false;
}
You have to create a database table to store the tokens. Before sending the email, You must generate a unique token and add it into a separate table. The password reset link must contain encoded token and userID. Once the password reset link is clicked, you must check the encoded token and UserID in the link matches to the entry in database? If yes, then show the change password page, If not, you must show a message "Link is expired" or whatever.
Here is the hint of code from my project.
$act_code = md5(rand(0,1000).'uniquefrasehere');
$activate['UserID'] $USERID;
$activate['TokenNumber'] = $act_code;
$activate['UserEmail'] = $email;
$activate['TokenTime'] = time();
$str_tmp = $this->db->insert_string('forgetpasswordtoken', $activate);
$query_tmp = $this->db->query($str_tmp);
Once the link is clicked, You must check using the following code:
$record = $this->user_model->checkforgot($uid[0], base64_decode($uid[1]));
if($record == true){
$data['uid'] = $uid[1];
}
else
{
$msg = "You have already changed your password or your link was expired.!";
}
And What the checkforgotpassword function does? Here is below:
function checkforgot($token, $id)
{
$qry = $this->db->query("SELECT * FROM forgetpasswordtoken WHERE TokenNumber = '".$token."' AND UserID = $id");
$num_row = $qry->num_rows();
if($num_row!=0)
{
$del = $this->db->delete('forgetpasswordtoken', array('TokenNumber' => $token, 'UserID' => $id));
return true;
}
else
{
return false;
}
}
You can further add the time limit of few hours before the link expires.
Let me know after adding this in your project.
Thanks,
WP_MAIL functionality is not working in my ajax function in functions.php file.
Please have an look on the code and help me out !!
Do i need to load any files for the working of wp_mail function ??
function et_contact_form() { ?>
<script type="text/javascript" >
jQuery('#contact_modal').on('submit', function (e) {
e.preventDefault();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var name = jQuery("#name").val();
var data = {
'action':'et_contact_modal',
'name' : name
};
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
});
</script> <?php
}
add_action( 'wp_footer', 'et_contact_form' );
function et_contact_modal() {
global $wpdb;
$headers .= "Reply-To: test#gmail.com \r\n";
//$headers .= "CC: test#gmail.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$subject = 'New Enquiry From ';
$message .= '<p>' . $_POST['name'] . '</p>';
$message .= '<p></p>';
$mailResult = false;
$mailResult = wp_mail( 'test#gmail.com',$subject,$message, $headers );
echo $mailResult;
}
add_action( 'wp_ajax_et_contact_modal', 'et_contact_modal' );
Sorry people's!!
The code was correct , it was just server issue !!
Thank you.
It's the First time that I use SP Page Builder component with Joomla. I want to use their contact form, but it doesn't support Google ReCaptcha.
I'm good enough with coding to thought that I could manually add it into : /com_sppagebuilder/addons/ajax_contact/site.php and get it to work.
I did add : <div class="g-recaptcha" data-sitekey="My_Key"></div>;
And the Joomla ReCaptcha plugin is activated.
I didn't know if I had to, but I added <script src='https://www.google.com/recaptcha/api.js'></script> into the head tag.
With this the ReCaptcha is showing fine.
My problem is with the validation.
I did try to add some validation code in the site.php but I believe SP Page Builder uses JFactory::getMailer(); to get the email ready and send it, and I don't know anything about that.
Thus, I do not know where I can add my ReCaptcha validation code, and as I did find few versions of that code online, I really don't know which one to use.
I've been searching everywhere for some answers to how to do this verification... and I tried many things, but it's still not working.
Can anyone help me through this one ?
Thank you very much !
EDIT
I think my question is not clear enough :
I want to add Recaptcha, that is already working fine in other forms on my website (so it's not a configuration with Joomla problem). I want to use the following SP Page Builder contact form and not a RSFormPro as on the rest of the Website. The validation process should be done around this section, but I tried to add the Google validation code, and I tried a few versions of it I found around the Internet, and it's not working at all :
public static function getAjax() {
$input = JFactory::getApplication()->input;
$mail = JFactory::getMailer();
//inputs
$inputs = $input->get('data', array(), 'ARRAY');
foreach ($inputs as $input) {
if( $input['name'] == 'recipient' ) {
$recipient = base64_decode($input['value']);
}
if( $input['name'] == 'email' ) {
$email = $input['value'];
}
if( $input['name'] == 'name' ) {
$name = $input['value'];
}
if( $input['name'] == 'subject' ) {
$subject = $input['value'];
}
if( $input['name'] == 'message' ) {
$message = nl2br( $input['value'] );
}
}
/*Try at the validation*/
$captcha_plugin = JFactory::getConfig()->get('captcha');
if ($captcha_plugin != '0') {
$captcha = JCaptcha::getInstance($captcha_plugin);
$field_id = 'google-recaptcha';
print $captcha->display($field_id, $field_id, 'g-recaptcha');
}
$sender = array($email, $name);
$mail->setSender($sender);
$mail->addRecipient($recipient);
$mail->setSubject($subject);
$mail->isHTML(true);
$mail->Encoding = 'base64';
$mail->setBody($message);
if ($mail->Send()) {
return '<span class="sppb-text-success">'. JText::_('COM_SPPAGEBUILDER_ADDON_AJAX_CONTACT_SUCCESS') .'</span>';
} else {
return '<span class="sppb-text-danger">'. JText::_('COM_SPPAGEBUILDER_ADDON_AJAX_CONTACT_FAILED') .'</span>';
}
}
Any suggestions ?
Thank you !
I have successfully added captcha to the Ajax contact form. Although the code still needs some improvements, Here is what I did:
See that I am using the n3tseznamcaptcha captcha plugin, I still need to implement the changes for other captchas to work (recaptcha,etc) but you can adapt it to your needs.
An SP Pagebuilder addon consists of two files, admin, and site. In the admin site I removed the default captcha, which lacks many security measures. Then in the site part I added the following:
function ajax_contact_addon($atts)
{
global $formcaptcha;
(...)
if($formcaptcha)
{
// TODO: Add Joomla's captcha:
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
// This will put the code to load CAPTCHA's JavaScript file into your <head>
$dispatcher->trigger('onInit', 'dynamic_captcha_1');
// This will return the array of HTML code.
$captcha = $dispatcher->trigger('onDisplay', array(null, 'dynamic_captcha_1', 'class=""'));
// I have only 1 recaptcha plugin enabled so the HTML is at 0 index, this will be improved in next version, following the contact component
$output .= (isset($captcha[0])) ? $captcha[0] : '';
$output .= '<div class="clearfix"></div><p></p>';
}
(...)
}
function ajax_contact_get_ajax()
{
global $formcaptcha;
$jinput = JFactory::getApplication()->input;
$mail = JFactory::getMailer();
$config = JFactory::getConfig();
// TODO: CHECK CAPTCHA and add a Helper Class to get the captchas fields
$captchaset = 'n3tseznamcaptcha';
if ($captchaset === 'n3tseznamcaptcha')
{
$captcha_field_hash = 'n3t_seznam_captcha_hash';
$captcha_field_answer = 'n3t_seznam_captcha';
}
//inputs
$inputs = $jinput->get('data', array(), 'ARRAY');
foreach ($inputs as $input)
{
if( $input['name'] == 'title' )
{
$title = $input['value'];
}
if( $input['name'] == 'recipient' )
{
$recipient = base64_decode($input['value']);
}
if( $input['name'] == 'email' )
{
$email = $input['value'];
}
(...)
if( $input['name'] == $captcha_field_hash )
{
$captcha_hash = $input['value'];
}
if( $input['name'] == $captcha_field_answer )
{
$captcha_answer = $input['value'];
}
}
if($formcaptcha)
{
// get the plugin
JPluginHelper::importPlugin('captcha');
$dispatcher = JEventDispatcher::getInstance();
// In order the plugin can check the code, we have to insert it into the request data:
$jinput->set('n3t_seznam_captcha_hash', $captcha_hash);
$jinput->set('n3t_seznam_captcha', $captcha_answer);
// Here we check for the code:
$res = $dispatcher->trigger('onCheckAnswer', $captcha_answer);
if(!$res[0])
{
// There is a problem with pagebuilder cache and captchas, so we need to clean the cache, to renew the captcha code:
$cache = JFactory::getCache('page');
$cache->clean();
return '<span class="pb-text-danger">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_FORM_WRONG_CAPTCHA') .'</span>';
}
}
}
I think that's all. Hope it helps you to find out.
So here you have the complete solution. Note that I changed a few things in the admin side too. This version will display and validate the default captcha selected in Joomla config, but it will only work for recaptcha and n3tsezam.. other should be added manually. The reason is that this addon does not add the challenge and response fields in the request, which the captcha plugins use for validation, therefor we need to retrieve it and write to the jinput within our ajax function (ajax_contact_get_ajax), and what complicates the whole thing is that every captcha plugin use different fields. Anyway.. if you need any other captcha plugin just can add it to the switch and you should be done.
function ajax_contact_addon($atts)
{
extract(AddonAtts(array(
"title" => '',
"show_title" => '',
"heading_selector" => 'h3',
"title_fontsize" => '',
"title_fontweight" => '',
"title_text_color" => '',
"title_margin_top" => '',
"title_margin_bottom" => '',
"recipient_email" => '',
"formcaptcha" => '',
"class" => '',
), $atts));
JHtml::script('media/com_pagebuilder/js/ajax-contact.js');
// There is a problem with pagebuilder cache and captchas
$cache = JFactory::getCache('page');
$cache->clean();
$output = '<div class="pb-addon pb-addon-ajax-contact ' . $class . '">';
if(boolval($show_title) && $title)
{
$title_style = '';
if($title_margin_top !='') $title_style .= 'margin-top:' . (int) $title_margin_top . 'px;';
if($title_margin_bottom !='') $title_style .= 'margin-bottom:' . (int) $title_margin_bottom . 'px;';
if($title_text_color) $title_style .= 'color:' . $title_text_color . ';';
if($title_fontsize) $title_style .= 'font-size:'.$title_fontsize.'px;line-height:'.$title_fontsize.'px;';
if($title_fontweight) $title_style .= 'font-weight:'.$title_fontweight.';';
$output .= '<'.$heading_selector.' class="pb-addon-title" style="' . $title_style . '">' . $title . '</'.$heading_selector.'>';
}
$output .= '<div class="pb-addon-content">';
$output .= '<form class="pb-ajax-contact-form">';
$output .= '<div class="pb-form-group">';
$output .= '<input type="text" name="name" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_NAME') .'" required="required">';
$output .= '</div>';
$output .= '<div class="pb-form-group">';
$output .= '<input type="email" name="email" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_EMAIL') .'" required="required">';
$output .= '</div>';
$output .= '<div class="pb-form-group">';
$output .= '<input type="text" name="subject" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_SUBJECT') .'" required="required">';
$output .= '</div>';
$output .= '<div class="pb-form-group">';
$output .= '<textarea type="text" name="message" rows="5" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_MESSAGE') .'" required="required"></textarea>';
$output .= '</div>';
if($formcaptcha)
{
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$dispatcher->trigger('onInit', 'dynamic_captcha_1');
$captchas = $dispatcher->trigger('onDisplay', array(null, 'dynamic_captcha_1', 'class=""'));
$index = 0;
foreach (JPluginHelper::getPlugin('captcha') as $plugin)
{
if (JFactory::getApplication()->get('captcha', '0') === $plugin->name)
{
$captcha = $captchas[$index];
break;
}
$index++;
}
$output .= (isset($captcha)) ? $captcha : '';
$output .= '<div class="clearfix"></div><p></p>';
}
$output .= '<input type="hidden" name="recipient" value="'. base64_encode($recipient_email) .'">';
$output .= '<input type="hidden" name="title" value="'. $title .'">';
$output .= '<button type="submit" class="btn btn-default"><i class="fa"></i> '. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_SEND') .'</button>';
$output .= '</form>';
$output .= '<div style="display:none;margin-top:10px;" class="pb-ajax-contact-status"></div>';
$output .= '</div>';
$output .= '</div>';
return $output;
}
function ajax_contact_get_ajax()
{
$config = JFactory::getConfig();
$jinput = JFactory::getApplication()->input;
//inputs
$inputs = $jinput->get('data', array(), 'ARRAY');
$mail = JFactory::getMailer();
// TODO: Find the way to check if captcha is enabled in the addon
$formcaptcha = true;
$message = "";
// TODO: CHECK CAPTCHA and add a Helper Class to get the captchas
switch (JFactory::getApplication()->get('captcha', '0'))
{
case 'recaptcha':
// v.1:
//$captcha_challenge_field = 'recaptcha_challenge_field';
//$captcha_answer_field = 'recaptcha_response_field';
// v.2:
$captcha_challenge_field = '';
$captcha_answer_field = 'g-recaptcha-response';
break;
case 'n3tseznamcaptcha':
$captcha_challenge_field = 'n3t_seznam_captcha_hash';
$captcha_answer_field = 'n3t_seznam_captcha';
break;
default:
// disable captcha as we could not find the right fields
$formcaptcha = false;
}
foreach ($inputs as $input)
{
if( $input['name'] == 'title' )
{
$title = $input['value'];
}
if( $input['name'] == 'recipient' )
{
$recipient = base64_decode($input['value']);
}
if( $input['name'] == 'email' )
{
$email = $input['value'];
}
if( $input['name'] == 'name' )
{
$name = $input['value'];
}
if( $input['name'] == 'subject' )
{
$subject = $input['value'];
}
if( $input['name'] == 'message' )
{
$message = nl2br( $input['value'] );
}
if( $input['name'] == $captcha_challenge_field )
{
$captcha_challenge = $input['value'];
}
if( $input['name'] == $captcha_answer_field )
{
$captcha_answer = $input['value'];
}
}
$valid_captcha = true;
if($formcaptcha)
{
// get the plugin
JPluginHelper::importPlugin('captcha');
$dispatcher = JEventDispatcher::getInstance();
$jinput->set($captcha_challenge_field, $captcha_challenge);
$jinput->set($captcha_answer_field, $captcha_answer);
$res = $dispatcher->trigger('onCheckAnswer', $captcha_answer);
$index = 0;
foreach (JPluginHelper::getPlugin('captcha') as $plugin)
{
if (JFactory::getApplication()->get('captcha', '0') === $plugin->name)
{
$valid_captcha = $res[$index];
break;
}
$index++;
}
if(!$valid_captcha)
{
$msg = '<span class="pb-text-danger">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_FORM_WRONG_CAPTCHA') .'</span>';
}
}
if ($valid_captcha)
{
// We do not want to send the email as a fake user, it may cause spam problems
$sender = array(
$config->get( 'mailfrom' ),
$config->get( 'fromname' )
);
$subject = (($title)? '['.$title.'] ' : '') . $subject;
$message .= JText::sprintf('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_EMAIL_SIGNATURE', JUri::getInstance()->toString(), JUri::getInstance());
$mail->setSender($sender);
$mail->addRecipient($recipient);
$mail->setSubject($subject);
$mail->AddReplyTo($email);
$mail->isHTML(true);
$mail->Encoding = 'base64';
$mail->setBody($message);
if ($mail->Send())
{
$msg = '<span class="pb-text-success">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_SUCCESS') .'</span>';
} else {
$msg = '<span class="pb-text-danger">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_FAILED') .'</span>';
}
}
// There is a problem with pagebuilder cache and captchas
$cache = JFactory::getCache('page');
$cache->clean();
return $msg;
}
That functionality is now integrated into SP Page Builder Contact Form Addon.
1) Grab the reCaptcha API keys from the console: https://www.google.com/recaptcha/admin
2) Enable reCaptcha plugin in Joomla's backend:
Joomla Control Panel and navigate to Extensions > Plugins > captcha - reCaptcha
3) Enable reCaptcha in your Joomla configuration:
Go to System > Global Configuration > Site Settings > Default Captcha
4) Go to your Contact Form (or create a new one) and enable captcha. Then choose "CAPTCHA - reCAPTCHA" in Captcha type selector.
After completing the above steps, if you don't see a reCAPTCHA box on the contact form frontend, it means that your template uses the old contact addon code. In most cases, you can safely take a backup and then delete the (bold) folder: templates\YOUR-TEMPLATE-NAME\sppagebuilder\addons\ajax_contact
All the info you need is available in this article: https://www.joomshaper.com/blog/google-recaptcha-joomla-contact-forms-integration
My website is built using Codeigniter, and there's an area for users to modify their information. This area allows users to choose a profile picture, and when editing it, the selected picture is previewed. In case they don't choose a new one, there's a hidden field storing its name, which is passed to the controller to specify the same image name, but if the user decides to change it, the new name is passed to the controller.
public function edit($id)
{
$this->input->post('tipo_usuario') === 'F' ? $validator = 'editar_pessoa_fisica' : $validator = 'editar_pessoa_juridica';
if ($this->form_validation->run($validator)) {
$data = array();
$data['nome_razao_social'] = $this->input->post('nome_razao_social');
$data['nome_responsavel'] = $this->input->post('nome_responsavel');
$data['nome_fantasia'] = $this->input->post('nome_fantasia');
$data['cpf_cnpj'] = $this->input->post('cpf_cnpj');
$data['telefone'] = $this->input->post('telefone');
$data['telefone_2'] = $this->input->post('telefone_2');
$data['email'] = $this->input->post('email');
$data['novo_email'] = $this->input->post('novo_email');
$data['senha'] = md5($this->input->post('senha'));
$data['cep'] = $this->input->post('cep');
$data['logradouro'] = $this->input->post('logradouro');
$data['id_cidade'] = $this->input->post('id_cidade');
$data['id_estado'] = $this->input->post('id_estado');
$data['numero'] = $this->input->post('numero');
$data['complemento'] = $this->input->post('complemento');
$data['tipo_usuario'] = $this->input->post('tipo_usuario');
/*
HERE IS IN CASE THE USER DOES NOT CHANGE HIS PROFILE PICTURE
*/
$data['imagem'] = $this->input->post('imagem_old');
$data['url'] = $this->input->post('url');
// Nova senha?
if ($this->input->post('novasenha') !== '') {
$data['senha'] = md5($this->input->post('novasenha'));
} else {
$data['senha'] = $this->input->post('senha');
}
/*
HERE IS IN CASE THE USER CHANGES HIS PROFILE PICTURE
*/
// Nova imagem?
if ($_FILES['imagem']['name'] !== '') {
$data['imagem'] = $_FILES['imagem']['name'];
}
// Novo e-mail?
if ($this->input->post('email') !== $this->input->post('novoemail')) {
$data['novo_email'] = $this->input->post('novoemail');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->input->post('novo_novo_email') !== $this->input->post('novo_email')) {
$data['novo_email'] = $this->input->post('novo_novo_email');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->Usuarios_model->update($data, $id)) {
$this->upload->do_upload('imagem');
$this->session->set_flashdata('message', 'Dados alterados');
echo json_encode(array(
'redirect' => '/usuario/painel'
));
}
} else {
echo json_encode(array(
'type' => 'validation',
'message' => validation_errors(),
));
}
}
This is the HTML:
<form action="/auto/usuario/edit/<?php echo $id_usuario; ?>" method="POST" class="formulario" enctype="multipart/form-data">
<input type="hidden" name="tipo_usuario" value="F"/>
<div class="p100">
<span class="titulo">Foto de Perfil</span>
<div class="imagem_destaque img_perfil image-trigger">
<div class="file-upload-trigger">
<input type="file" name="imagem" class="none file-chooser"/>
<img src="/uploads/perfil/<?php echo $u['imagem'] ?>" class="preview more"/>
</div>
</div>
<input type="hidden" name="imagem_old" value="<?php echo $u['imagem']; ?>"/>
</div>
With Google Chrome, it works fine, but in Firefox 45, if I do not choose a new image, an error is thrown:
Severity: Notice
Message: Undefined index: imagem
Filename: controllers/Usuario.php
Line Number: 362
It only works locally.
If you do not upload a new image, your $_FILES[] is undefined, as the error says. To check if the user has changed his image you should do:
if ( isset($_FILES['imagem']['name']) ) {
$data['imagem'] = $_FILES['imagem']['name'];
}