reCAPTCHA and Dropzone JS - recaptcha

Is it possible to combine Google's incredible reCAPTCHA and Matias Meno's incredible dropzone.js, to prevent attacks and deter spam bots?

Using wordpress.
This is what I came up with following a few tutorials:
SO answer
codeforgeek
And some others I dont remember
// Dropzone.autoDiscover = false; //I use Autodiscover
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
previewsContainer: '.fileupload',
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// myDropzone.processQueue();
var valid = true;
$('[data-required]').each(function(i,ele){
if(ele.value == ''){
$(this).parent().parent().addClass('alert');
valid = false;
}
});
if (!valid){
e.preventDefault();
scrollTop();
return false;
}
// Get the recaptcha input
var cap_input = grecaptcha.getResponse();
$.ajax({
url: homeUrl+'/wp-admin/admin-ajax.php',
type: "POST",
dataType: "JSON",
data: {
"action": "verifyReCaptcha",
"g-recaptcha-response": cap_input
},
success: function(response){
console.log(response);
if(response == 'Good captcha'){
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
}
else {
// Upload anyway without files
if (wantToUpload == 'unknown') {
$('#noFiles').modal();
e.preventDefault();
return false;
}
else if (wantToUpload == false) {
myDropzone.uploadFiles([ ]);
}
else {
myDropzone.uploadFiles([ ]);
}
}
}
else{
console.log('Spammer go away');
$('.g-recaptcha').addClass('alert');
}
}
});
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
console.log('sending');
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
console.log('success');
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
console.log('error');
});
}
}
And some html/php
<form name="" action="<?=get_permalink();?>" method="post" id="my-awesome-dropzone" class="dropzone" enctype="multipart/form-data">
<label class="label" for="text-435">
<?=__('Name*','gt_domain');?>
</label>
<input type="text" name="client-name" value="" size="40" class="input__field--manami" id="text-435" data-required="true">
<!-- Lots of input fields -->
<div class="col-md-8 col-xs-12 fileupload dropzone-previews dz-message">
<h2 class="text-center" id="fileuploadtext">
<?=__('Click or drag and drop your file here <br>(Max 60mb)','gt_domain');?>
</h2>
</div>
<div class="g-recaptcha" data-sitekey="MY_PUBLIC_KEY"></div>
<input class="dangerzone-submit" type="submit" value="<?=__('Request quote','gt_domain');?>" name="dangerzone-submit">
</form>
And for ajax validation before submitting the form:
function verifyReCaptcha(){
$email;
$comment;
$captcha = false;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo json_encode('Please check the the captcha form.');
exit;
}
$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MY_SUPER_SECRET_GOOGLE_RECAPTCHA_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false){
echo json_encode('You are spammer ! Get the #$%K out');
}
else{
echo json_encode('Good captcha');
}
exit;
}
add_action( 'wp_ajax_nopriv_verifyReCaptcha', 'verifyReCaptcha' );
add_action( 'wp_ajax_verifyReCaptcha', 'verifyReCaptcha' );
And finnaly recieve form inputs and images:
<?php
if (isset($_POST['dangerzone-submit'])) {
// print_r($_POST);
$client = $_POST['client-name'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
// print_r($array);
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK && $_FILES[$file]['error'][0] !== 0) {
echo "upload error : \n";
print_r($_FILES[$file]['error']);
print_r($_FILES);
die();
}
$uploads_dir = ABSPATH . 'wp-content/uploads/dropzone/';
$external_link = get_home_url().'/wp-content/uploads/dropzone/';
foreach ($array['name'] as $key => $val) {
print_r($key);
$name = $array['name'][$key];
$tmp_name = $array['tmp_name'][$key];
$newfilename = wp_unique_filename( $uploads_dir, $name );
$movefile = move_uploaded_file($tmp_name, $uploads_dir.$newfilename);
$uploaded_files[] = $external_link.$newfilename;
}
}
}
sendMail( //My func for sending mail
$client,
$email,
$company,
$phone,
$comments,
$uploaded_files
);
}
?>

Related

Problem not displaying success message for each registration with Ajax

I want to do this after the user registers, shows a successful message and the text boxes are empty again and ready for the next registration, but the registration success message is only displayed for the first registration, but I want to Display each registration
public IActionResult submitSingelControlItem(int Projectid,String calender, String ProjectName,String ProjectManagementName, String ajaxControlItem,String ajaxFraindName,int SingelControlState)
{
Hesabrsee hesabrsee = new Hesabrsee();
hesabrsee.ControlDate = ConvertDateTime.ConvertShamsiToMiladi(calender);
hesabrsee.SabtDate = DateTime.Now;
hesabrsee.Projectid = Projectid;
hesabrsee.ProjectName = ProjectName;
hesabrsee.ProjectManagementName = ProjectManagementName;
hesabrsee.FaraindName = ajaxFraindName;
hesabrsee.Deiscreption = ajaxControlItem;
hesabrsee.ControlState = SingelControlState;
_context.Add(hesabrsee);
_context.SaveChanges();
return Json(new { status = "ok" });
}
<script>
$("#btn").on('click', function () {
var ajaxFraindName = $("#ajaxFraindName").val();
var ajaxControlItem = $("#ajaxControlItem").val();
var calender = $("#calender").val();
var SingelControlState = $("#SingelControlState").val();
if (ajaxFraindName == '' || ajaxControlItem == '' || calender == '' || SingelControlState == '') {
alert("لطفا ورودی ها را پر کنید");
}
else {
$.ajax({
type: "Post",
url: '#Url.Action("submitSingelControlItem", "Hasabrsee")',
data: {
'ajaxControlItem': $("#ajaxControlItem").val(),
'ajaxFraindName': $("#ajaxFraindName").val(),
'Projectid': $("#Projectid").val(),
'ProjectName': $("#ProjectName").val(),
'ProjectManagementName': $("#ProjectManagementName").val(),
'calender': $("#calender").val(),
'SingelControlState': $("#SingelControlState").val(),
}
}).done(function (res) {
if (res.status == 'ok') {
$("#ohsnap").removeClass('d-none').removeClass('alert-danger').addClass('alert-success').html('مورد کنترلی با موفقیت ثبت شد');
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
}
setTimeout(function () {
$('#ohsnap').fadeOut('fast');
}, 2000)
});
}
});
</script>
<div id="ohsnap" class="col-md-4 col-xs-12 alert d-none" style="text-align:center;"></div>
Of course, it displays the message only once because you are removing the class from the $("#ohsnap") div and then you are not restoring it.
Try using Toastr to display the popup alert. It is easier to do.
From the Toastr documentation:
Download the CSS and JS files and add them to your project.
Reference the css <link href="toastr.css" rel="stylesheet"/>
Reference the script <script src="toastr.js"></script>
in your .done() function call toastr;
.done(function (res) {
if (res.status == 'ok') {
toastr.success('title-here', 'مورد کنترلی با موفقیت ثبت شد', {
timeOut: 2000,
closeButton: true,
});
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
});

Multiple Insert Image Laravel, Vue, Axios

this is the first time for me to make multiple upload files for vue js laravel. I managed to create multiple images in laravel but only one stored in the database is not the same as the requested image that was entered. something like this is my code.
in my controller laravel.
public function storeProduct()
{
$data = $this->request->all();
$query['gallery'] = new ProductGallery;
if ($this->request->hasFile('images')) {
if (count($this->request->images) > 1) {
foreach($this->request->file('images') as $file){
//filename to store
$query['gallery']->product_id = 2;
$filename = md5($file . time()) . '.jpg';
Storage::disk('public')->put($filename, file_get_contents($file));
$path = public_path('storage/article-image/'.$filename);
Image::make($file)->save($path);
$query['gallery']->file_path = 'article-image/'.$filename;
$query['gallery']->save();
}
}else {
return "not array";
}
}
return "Success";
}
in Vue Js Template.
<template>
<div class="file-input">
<label for="file">Select a File</label>
<input type="file" id="file" #change="onInputChange" multiple>
</div>
</template>
data() {
return {
files: [],
images: [],
}
},
methods: {
onInputChange(e) {
const files = e.target.files;
Array.from(files).forEach(file => this.addImage(file));
},
addImage(file) {
if (!file.type.match('image.*')) {
this.$toastr.e(`${file.name} is not an image`);
return;
}
this.files.push(file);
const img = new Image(),
reader = new FileReader();
reader.onload = (e) => this.images.push(e.target.result);
reader.readAsDataURL(file);
},
upload() {
const formData = new FormData();
this.files.forEach(file => {
formData.append('images[]', file, file.name);
});
axios.post('http://localhost.pro/api/v1/product-store', formData)
.then(response => {
console.log(response);
})
}
}
please help, sorry my english is passive. Thank you

How to send an ajax contact form with to a recipient email address

I've currently got this:
$.ajax({
url: '/some/url',
dataType: 'json',
type: 'POST',
data: formData,
success: function(data) {
if (window.confirm('Thank you for your message. Can I erase the form?')) {
document.querySelector('.form-input').val('');
}
},
error: function(xhr, status, err) {
console.error(status, err.toString());
alert('There was some problem with sending your message.');
}
});
Instead of it going to a URL, how can I change it to send directly to a specific email address? I am using this contact form with a React app I've created.
So react component, class based.
class Foo extends Component {
popupQuestion() {
// implement method
}
sendEmail() = () => {
axios.post('/some/url', {
subject: 'mail',
to: 'someone#example.com',
body: 'something',
name: 'name'
})
.then(function (response) {
popupQuestion();
})
.catch(function (error) {
console.log(error);
return 'Error occurred. Please refresh page and try again.';
});
}
render() {
return(
<form onSubmit={this.sendEmail}>
// ...
</form>
);
}
}
And php method that will be executed on some/url
public function sendEmailAction(): bool
{
$request = // get request;
$subject = $request->get('subject');
$to = $request->get('to');
$body = $request->get('body');
$name = $request->get('name');
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($subject))
->setFrom(['mymail#exmaple.com' => 'me'])
->setTo([$to => $name])
->setBody($body);
$sent = $mailer->send($message);
return $sent ? true : false;
}

dropzone.zs Rename All files before / when uploading

I have this problem using dropzone.js for uploading files with drag&drop.
Lets say i have this form:
<form action=""<?php echo $_SERVER['PHP_SELF'];?>"" enctype=""multipart/form-data"" class=""dropzone"" id=""dropzone1"">
<input type=""text"" name=""somevalue"" id=""somevalue"" value=""somevalue"" />
<div class=""fallback"">
<input type=""file"" name=""file-image"" />
</div>
</form>
The javascript for the dropzone call is :
<script type=""text/javascript"">
$(document).ready(function() {
Dropzone.autoDiscover = false;
var fileList = new Array;
var i =0;
$(""#dropzone1"").dropzone({
init: function() {
var $this = this;
$(""#submit-all-1"").click(function() {
$this.processQueue();
});
var totalFiles = 0,completeFiles = 0;
this.on(""addedfile"", function (file) {
totalFiles += 1;
var numQueued=this.getQueuedFiles().length;
});
this.on(""success"", function(file, serverFileName) {
fileList[i] = {""serverFileName"" : serverFileName, ""fileName"" : file.name,""fileId"" : i };
i++;
});
this.on(""removed file"", function (file) {
totalFiles -= 1;
});
this.on(""complete"", function (file) {
completeFiles += 1;
if (completeFiles === totalFiles) {
// Do something
}
});
},
paramName: 'file-image',
acceptedFiles:'image/*',
autoProcessQueue:false,
addRemoveLinks: true,
parallelUploads: 10
});
/////////////////////////////////
});
</script>
And in php section:
<?php
if (!empty($_FILES)) {
$somevalue=$_POST['somevalue'];
$counter=1;
$image=$_FILES['file-image']['name']);
$picture_in = ""/PicsUrl/"".$somevalues.$counter.$image;
move_uploaded_file($_FILES['file-image']['tmp_name'], $picture_in);
$counter++;
}
?>
I want to do this :
With the $somevalue posted, all the files that i upload simultanously,
to be renamed like that:
$somevalue_1_imagefilename,$somevalue_2_imagefilename,$somevalue_3_imagefilename
etc....
Any help ?
Try changing your PHP script like the below :
<?php
if (!empty($_FILES)) {
$somevalue=$_POST['somevalue'];
$counter=1;
$image=$_FILES['file-image']['name']);
$picture_in = ""/PicsUrl/"".$somevalue.$counter++.$image;
move_uploaded_file($_FILES['file-image']['tmp_name'], $picture_in);
}
?>

How to send ajax request to check session timeout and render relogin message in grails?

I want to display a message to the user saying, "you're logged out re-login please!" when session is timed-out, sending an ajax request each time. If session timer ends i want to send final ajax request displaying above message. But the problem here is i don't know where should i have to keep my ajax and jquery codes and since i don't have much knowledge about ajax request, can anyone explain this process with codes. In siple my requirement is like of what facebook shows on session time out, or when any one tab in case of multiople tabs are logged out. I'm working on grails project.
Do your ajax request like this
$.ajax({
url:url,
type:"POST", // or get
data:parameters,
success: function(data) {
// do procedure if success
}
error : function(xhr, type, error){
// do procedure if fail
// may be send a message to the server side to display a message that shows session timeout
}
});
Handle your session timeout in the error function
I did it myself and this is the js code for it "gracefulSession.js" and call this javascript at the page where you are going to embed your html code..
function checkSessionStatus() {
var lStorage = getLocalStorage();
if (lStorage) {
//lStorage.setItem('poleTime',new Date());
var poleTime = lStorage.getItem("poleTime");
var parsedTime;
try {
parsedTime = new Date(poleTime);
} catch (e) {}
//alert(new Date()-parsedTime)
//alert(new Date())
//alert(parsedTime)
//3900000 = 1H5M
if (parsedTime && (new Date() - parsedTime) < 3900000) {
//alert('NCATCH'+parsedTime);
} else {
//alert('POINT');
poleSessionStatus();
}
}
}
function setlatestPoleTIme() {
//alert("SETTING POLE TIME");
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('poleTime', new Date());
}
}
function setCheckSessionTimer() {
var lStorage = getLocalStorage();
var isLoggedOut = false;
if (lStorage) {
if (lStorage.getItem('isLoggedOut') == 'true') {
isLoggedOut = true;
}
}
//console.log('checkingIfLoggedOut');
if (!isLoggedOut) {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("NOPT LO");
$('#LoggedoutMessage').hide();
checkSessionStatus();
} else {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("KO");
//alert("You're Logged Out from other tab");
$('#LoggedoutMessage').show();
}
}
function logout() {
//alert("LOGGIN OUT")
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('isLoggedOut', 'true');
}
}
function resetLoggedOutFLag() {
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.removeItem('isLoggedOut');
}
}
function getLocalStorage() {
var storage, fail, uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (e) {}
return storage
}
Now, HTML code to embed ,
<div id="LoggedoutMessage" style="display:none;position:absolute;background:black;height: 200%;width:100%;top: 0;z-index: 10000;opacity: 0.9;">
<div id="login_box" style="position:fixed;left:38%;top:30%; padding:10px; width: 365px;margin: 0 auto;border: 0px solid #CCC;margin-top: 35px;height: 150px;background: white; border-radius:3px;">
<div id="login_title">
<h1>You have been logged out.</h1>
</div>
<div id="reLogin">
<p>Please login to continue.</p>
<g:link controller="dashBoard" action="index" target="_blank" onclick="logout();">Login</g:link>
</div>
</div>
</div>
Finally where you keep your html,keep this javascript code at top of it embedding script tag:
function poleSessionStatus() {
jQuery.ajax({
type: 'POST',
data: '',
url: '<g:createLink action="ajaxCheckSession" controller="dashBoard"/>',
success: function (data, textStatus) {
//setTimeout ( "checkSession();", 5000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#LoggedoutMessage').show();
},
complete: function (XMLHttpRequest, textStatus) {
$.unblockUI();
}
});
}

Resources