Created
May 29, 2021 14:46
-
-
Save philbirnie/19a21990aaf63127f60e94411155c62b to your computer and use it in GitHub Desktop.
Gravity Forms Spam Prevention
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 | |
/** | |
* SPAM filtering function | |
* | |
* @param string[] $result Current Result. Contains two keys 'is_valid' and 'message'. | |
* @param mixed $value Field value -could be string or string[]. | |
* @param array $form Form Entity. | |
* @param array $field Field Entity. | |
* | |
* @return array | |
*/ | |
function esch_spam_validation_prevent( array $result, $value, $form, $field ): array { | |
$invalid_triggers = [ | |
'cialis' => [], | |
'viagra' => [], | |
'levitra' => [], | |
'essay' => [], | |
'.ru' => [], | |
'.xyz' => [], | |
'.online' => [], | |
'pharmacy.com' => [], | |
'doxycycline' => [], | |
'д' => [], | |
'.wiki' => [], | |
'google' => [], | |
'me photo' => [], | |
'http' => [ 'name' ], | |
]; | |
/** | |
* Invalid RegEx | |
* | |
* @var $invalid_regexes | |
*/ | |
$invalid_regexes = [ | |
"/^Mel(\W+|$)/" | |
]; | |
/** | |
* First find any NOT specific to any field. | |
*/ | |
$universal_invalid = array_filter( $invalid_triggers, function ( $value ) { | |
return $value == []; | |
} ); | |
str_ireplace( array_keys( $universal_invalid ), '', $value, $count ); | |
/** | |
* Second, check field specific. | |
*/ | |
$field_specific_invalid = array_filter( $invalid_triggers ); | |
foreach ( $field_specific_invalid as $invalid_string => $applicable_fields ) { | |
if ( in_array( $field['type'], $applicable_fields, true ) ) { | |
str_ireplace( $invalid_string, '', $value, $invalid_specific_count ); | |
$count += $invalid_specific_count; | |
} | |
} | |
/** | |
* Finally, check regexes. | |
*/ | |
foreach ( $invalid_regexes as $invalid_regex ) { | |
if ( is_string( $value ) ) { | |
if ( preg_match( $invalid_regex, $value ) ) { | |
$count++; | |
} | |
} else { | |
foreach ( $value as $field_part ) { | |
if ( preg_match( $invalid_regex, $field_part ) ) { | |
$count++; | |
} | |
} | |
} | |
} | |
if ( $count > 0 ) { | |
$result['is_valid'] = false; | |
$result['message'] = sprintf( | |
'This field contains %d word%s associated with SPAM. Please check your submission and try again.', | |
$count, | |
$count !== 1 ? 's' : '', | |
); | |
} | |
return $result; | |
} | |
add_filter( 'gform_field_validation', 'esch_spam_validation_prevent', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment