Desde estas últimas semanas estamos notando un aumento de envios de correos desde Rusia (eso lo supongo porque las letras son mu mu raras 😉 ), muy importante el origen son los formularios de contacto de nuestros Prestashop.
La solución ha sido muy sencilla y rápida, nos hemos dado de alta en Google reCAPTCHA :
Esta herramienta de Google, fuerza que un humano, sea el que envie correos desde nuestro formulario de contacto. Para ello le añade un campo a nuestro prestashop, el cual os mostraremos como añadirlo. Utensilios y herramientas para realizar los cambios:
- Cliente FTP(Filezilla, Win SCP)
- Paciencia y un poco de Té o Café, si es de nuestro amigo Mario mejor.
- Copia de seguridad
- Tocar tres ficheros.
- Darse de alta en Google reCAPTCHA
Vamos al lio nos conectamos por ftp a nuestro servidor y realizamos copia de seguridad de los siguientes ficheros.
- themes/nuestroTema/header.tpl
- themes/nuestroTema/contact-from.tpl
Y vamos a ello:
- En nuestro header.tpl que ya hemos realizado copia de seguridad le añadimos lo siguiente sobre la linea 66:
<script src='https://www.google.com/recaptcha/api.js'></script>
- En nuestro contact-form.tpl le añadimos sobre la linea 141, le añadimos lo siguente:
<div class="form-group"> <div class="g-recaptcha" data-sitekey="TUCODIGOGENERADO"></div> </div>
- Una vez que ya hemos realizado estos dos cambios solo nos queda el comprobar que se haya marcado correctamente el captcha para enviarlos para ello tenemos dos formas de hacerlo, la buena y la mala, primero os contamos la mala, la cual nosotros no haremos nunca:
- Editamos el fichero /controllers/front/ContactController.php, y sobre la linea 54 a continuación del parentesis:
if (Tools::isSubmit('submitMessage')) { $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg'); $file_attachment = Tools::fileAttachment('fileUpload'); $message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags. if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) { $this->errors[] = Tools::displayError('Invalid email address.'); } elseif (!$message) { $this->errors[] = Tools::displayError('The message cannot be blank.'); } elseif (!Validate::isCleanHtml($message)) { $this->errors[] = Tools::displayError('Invalid message'); } elseif (!($id_contact = (int)Tools::getValue('id_contact')) || !(Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id)))) { $this->errors[] = Tools::displayError('Please select a subject from the list provided. '); } elseif (!empty($file_attachment['name']) && $file_attachment['error'] != 0) { $this->errors[] = Tools::displayError('An error occurred during the file-upload process.'); } elseif (!empty($file_attachment['name']) && !in_array(Tools::strtolower(substr($file_attachment['name'], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment['name'], -5)), $extension)) { $this->errors[] = Tools::displayError('Bad file extension'); } else { $customer = $this->context->customer; if (!$customer->id) { $customer->getByEmail($from); }
Deberia quedar tal que así:
if (Tools::isSubmit('submitMessage')) { $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg'); $fileAttachment = Tools::fileAttachment('fileUpload'); $message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags. if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) $this->errors[] = Tools::displayError('Invalid email address.'); else if (!$message) $this->errors[] = Tools::displayError('The message cannot be blank.'); else if (!Validate::isCleanHtml($message)) $this->errors[] = Tools::displayError('Invalid message'); else if (!($id_contact = (int)(Tools::getValue('id_contact'))) || !(Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id)))) $this->errors[] = Tools::displayError('Please select a subject from the list provided. '); else if (!empty($fileAttachment['name']) && $fileAttachment['error'] != 0) $this->errors[] = Tools::displayError('An error occurred during the file-upload process.'); else if (!empty($fileAttachment['name']) && !in_array( Tools::strtolower(substr($fileAttachment['name'], -4)), $extension) && !in_array( Tools::strtolower(substr($fileAttachment['name'], -5)), $extension)) $this->errors[] = Tools::displayError('Bad file extension'); else if (!($gcaptcha = (int)(Tools::getValue('g-recaptcha-response')))) $this->errors[] = Tools::displayError('Captcha no verificado'); else {
- Creamos en la carpeta override/controllers/front/ContactController.php, de esta forma podreis actualizar vuestra plataforma sin problemas;-)
?php /* * 2007-2014 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2014 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class ContactController extends ContactControllerCore { public $php_self = 'contact'; public $ssl = true; /** * Start forms process * @see FrontController::postProcess() */ public function postProcess() { if (Tools::isSubmit('submitMessage')) { $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg'); $fileAttachment = Tools::fileAttachment('fileUpload'); $message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags. if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) $this->errors[] = Tools::displayError('Invalid email address.'); else if (!$message) $this->errors[] = Tools::displayError('The message cannot be blank.'); else if (!Validate::isCleanHtml($message)) $this->errors[] = Tools::displayError('Invalid message'); else if (!($id_contact = (int)(Tools::getValue('id_contact'))) || !(Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id)))) $this->errors[] = Tools::displayError('Please select a subject from the list provided. '); else if (!empty($fileAttachment['name']) && $fileAttachment['error'] != 0) $this->errors[] = Tools::displayError('An error occurred during the file-upload process.'); else if (!empty($fileAttachment['name']) && !in_array( Tools::strtolower(substr($fileAttachment['name'], -4)), $extension) && !in_array( Tools::strtolower(substr($fileAttachment['name'], -5)), $extension)) $this->errors[] = Tools::displayError('Bad file extension'); else if (!($gcaptcha = (int)(Tools::getValue('g-recaptcha-response')))) $this->errors[] = Tools::displayError('Captcha no verificado'); else { $customer = $this->context->customer; if (!$customer->id) $customer->getByEmail($from); $contact = new Contact($id_contact, $this->context->language->id); $id_order = (int)$this->getOrder(); if (!(( ($id_customer_thread = (int)Tools::getValue('id_customer_thread')) && (int)Db::getInstance()->getValue(' SELECT cm.id_customer_thread FROM '._DB_PREFIX_.'customer_thread cm WHERE cm.id_customer_thread = '.(int)$id_customer_thread.' AND cm.id_shop = '.(int)$this->context->shop->id.' AND token = \''.pSQL(Tools::getValue('token')).'\'') ) || ( $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, $id_order) ))) { $fields = Db::getInstance()->executeS(' SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email FROM '._DB_PREFIX_.'customer_thread cm WHERE email = \''.pSQL($from).'\' AND cm.id_shop = '.(int)$this->context->shop->id.' AND ('. ($customer->id ? 'id_customer = '.(int)($customer->id).' OR ' : '').' id_order = '.(int)$id_order.')'); $score = 0; foreach ($fields as $key => $row) { $tmp = 0; if ((int)$row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from) continue; if ($row['id_order'] != 0 && $id_order != $row['id_order']) continue; if ($row['email'] == $from) $tmp += 4; if ($row['id_contact'] == $id_contact) $tmp++; if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product')) $tmp += 2; if ($tmp >= 5 && $tmp >= $score) { $score = $tmp; $id_customer_thread = $row['id_customer_thread']; } } } $old_message = Db::getInstance()->getValue(' SELECT cm.message FROM '._DB_PREFIX_.'customer_message cm LEFT JOIN '._DB_PREFIX_.'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread) WHERE cc.id_customer_thread = '.(int)($id_customer_thread).' AND cc.id_shop = '.(int)$this->context->shop->id.' ORDER BY cm.date_add DESC'); if ($old_message == $message) { $this->context->smarty->assign('alreadySent', 1); $contact->email = ''; $contact->customer_service = 0; } if ($contact->customer_service) { if ((int)$id_customer_thread) { $ct = new CustomerThread($id_customer_thread); $ct->status = 'open'; $ct->id_lang = (int)$this->context->language->id; $ct->id_contact = (int)($id_contact); $ct->id_order = (int)$id_order; if ($id_product = (int)Tools::getValue('id_product')) $ct->id_product = $id_product; $ct->update(); } else { $ct = new CustomerThread(); if (isset($customer->id)) $ct->id_customer = (int)($customer->id); $ct->id_shop = (int)$this->context->shop->id; $ct->id_order = (int)$id_order; if ($id_product = (int)Tools::getValue('id_product')) $ct->id_product = $id_product; $ct->id_contact = (int)($id_contact); $ct->id_lang = (int)$this->context->language->id; $ct->email = $from; $ct->status = 'open'; $ct->token = Tools::passwdGen(12); $ct->add(); } if ($ct->id) { $cm = new CustomerMessage(); $cm->id_customer_thread = $ct->id; $cm->message = $message; if (isset($fileAttachment['rename']) && !empty($fileAttachment['rename']) && rename($fileAttachment['tmp_name'], _PS_UPLOAD_DIR_.basename($fileAttachment['rename']))) { $cm->file_name = $fileAttachment['rename']; @chmod(_PS_UPLOAD_DIR_.basename($fileAttachment['rename']), 0664); } $cm->ip_address = ip2long(Tools::getRemoteAddr()); $cm->user_agent = $_SERVER['HTTP_USER_AGENT']; if (!$cm->add()) $this->errors[] = Tools::displayError('An error occurred while sending the message.'); } else $this->errors[] = Tools::displayError('An error occurred while sending the message.'); } if (!count($this->errors)) { $var_list = array( '{order_name}' => '-', '{attached_file}' => '-', '{message}' => Tools::nl2br(stripslashes($message)), '{email}' => $from, '{product_name}' => '', ); if (isset($fileAttachment['name'])) $var_list['{attached_file}'] = $fileAttachment['name']; $id_product = (int)Tools::getValue('id_product'); if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order) { $order = new Order((int)$ct->id_order); $var_list['{order_name}'] = $order->getUniqReference(); $var_list['{id_order}'] = (int)$order->id; } if ($id_product) { $product = new Product((int)$id_product); if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id])) $var_list['{product_name}'] = $product->name[Context::getContext()->language->id]; } if (empty($contact->email)) Mail::Send($this->context->language->id, 'contact_form', ((isset($ct) && Validate::isLoadedObject($ct)) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent')), $var_list, $from, null, null, null, $fileAttachment); else { if (!Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form').' [no_sync]', $var_list, $contact->email, $contact->name, $from, ($customer->id ? $customer->firstname.' '.$customer->lastname : ''), $fileAttachment) || !Mail::Send($this->context->language->id, 'contact_form', ((isset($ct) && Validate::isLoadedObject($ct)) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent')), $var_list, $from, null, $contact->email, $contact->name, $fileAttachment)) $this->errors[] = Tools::displayError('An error occurred while sending the message.'); } } if (count($this->errors) > 1) array_unique($this->errors); else $this->context->smarty->assign('confirmation', 1); } } } }
- Editamos el fichero /controllers/front/ContactController.php, y sobre la linea 54 a continuación del parentesis:
Y con esto que no deberia llevar más de 5 minutos, ya podeis decir adios a los Rusos y a los bots que estan todo el dia enviando correos desde el formulario de contacta. Simple, rápido y seguro. Un saludo y disfrutarlo.
PD: Añado mejora de Victor Ródenas, el gran Nadie en Prestashop, nos pasa un enlace un módulo para 1.6 y 1.7, nosotros no lo hemos probado pero si Nadie habla de ese módulo yo me fio:
https://github.com/nenes25/eicaptcha