Created
November 17, 2017 18:45
-
-
Save agentrickard/671b6ab7c51bdc21472c6e4d0c66e951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Additions to contact form handling. | |
*/ | |
use Drupal\Core\Render\Element; | |
use Symfony\Cmf\Component\Routing\RouteObjectInterface; | |
/** | |
* Implements hook_form_alter(). | |
*/ | |
function antispam_contact_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { | |
if (isset($form['#entity_type']) && $form['#entity_type'] == 'contact_message' && !in_array($form['#form_id'], ['entity_form_display_edit_form', 'entity_view_display_edit_form'])) { | |
// Add our validators. | |
$form['#validate'][] = 'antispam_contact_validate'; | |
} | |
} | |
/** | |
* Validate contact form submissions. | |
*/ | |
function antispam_contact_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) { | |
$values = $form_state->getValues(); | |
// Really simple spam checks. | |
$submission = array(); | |
// @TODO: Make this automated or configurable. | |
$fields = array('field_comments', 'field_email', 'field_name', 'field_organization', 'field_title'); | |
// Look for these strings in the input. | |
// @TODO: Make this configurable. | |
$checks = array( | |
'Xrumer', | |
'michael kors', | |
'hotmail.com', | |
'[email protected]', | |
'air jordans', | |
'air max', | |
'louis vuitton', | |
'thin32.info', | |
'Cheap goods', | |
'Faster and Easier than the SBA', | |
'fundingteam+', | |
'Elsner Technologies', | |
); | |
$errors = array(); | |
foreach ($fields as $field) { | |
if (isset($values[$field][0]['value'])) { | |
$submission[$field] = trim($values[$field][0]['value']); | |
foreach ($checks as $check) { | |
if (stristr($submission[$field], $check)) { | |
$errors[] = $check; | |
} | |
} | |
} | |
} | |
// Some spam is just same name / organization. | |
if (isset($values['field_name'][0]['value']) && isset($values['field_organization'][0]['value'])) { | |
if (trim($values['field_name'][0]['value']) == trim($values['field_organization'][0]['value'])) { | |
$errors[] = 'replication'; | |
} | |
} | |
// Make sure the form isn't all duplicate values. | |
if (count(array_unique($submission)) < 2) { | |
$errors[] = 'duplication'; | |
} | |
if (!empty($errors)) { | |
$form_state->setErrorByName('form_token', 'An illegal form request has been detected. If the problem persists, please give us a call at the number below.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment