Skip to content

Instantly share code, notes, and snippets.

@kagg-design
Last active May 10, 2025 11:49
Show Gist options
  • Save kagg-design/fde657626b92070fe50b0e0784a44539 to your computer and use it in GitHub Desktop.
Save kagg-design/fde657626b92070fe50b0e0784a44539 to your computer and use it in GitHub Desktop.
Akismet check for Quform
/**
* Check Quform data with Akismet.
*
* @param array|mixed $result Result.
* @param Quform_Form $form Form.
*
* @return array
* @noinspection PhpUndefinedFunctionInspection
* @noinspection PhpPossiblePolymorphicInvocationInspection
*/
public function akismet_check( array $result, Quform_Form $form ): array {
$result = (array) $result;
$success = empty( $result ) || 'success' === ( $result['type'] ?? '' );
if ( ! $success ) {
return $result;
}
if ( ! function_exists( 'akismet_http_post' ) ) {
return $result;
}
// Collect all values into one content line.
$values = $form->getValues();
$content = '';
// Add form data.
foreach ( $values as $key => $value ) {
$element = $form->getElement( $key );
if ( ! $element ) {
continue;
}
$label = trim( $element->config()['label'] ?? '' );
if ( ! $label ) {
continue;
}
// Do not check fields having any validators except required.
if ( array_diff( array_keys( $element->getValidators() ), [ 'Quform_Validator_Required' ] ) ) {
continue;
}
$content .= $label . ': ' . $value . "\n";
}
$user_agent = isset( $_SERVER['HTTP_USER_AGENT'] )
? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) )
: '';
$referrer = isset( $_SERVER['HTTP_REFERER'] )
? sanitize_url( wp_unslash( $_SERVER['HTTP_REFERER'] ) )
: '';
// Preparing Akismet data.
$akismet_data = [
'user_ip' => $this->get_user_ip(),
'user_agent' => $user_agent,
'referrer' => $referrer,
'blog' => get_option( 'home' ),
'blog_lang' => get_locale(),
'blog_charset' => get_bloginfo( 'charset' ),
'permalink' => get_permalink(),
'comment_type' => 'contact-form',
'comment_content' => trim( $content ),
];
// Check data with Akismet.
$response = Akismet::http_post( Akismet::build_query( $akismet_data ), 'comment-check' );
if ( isset( $response[1] ) && trim( $response[1] ) === 'true' ) {
// Spam found - do not save/submit data.
return $this->error( __( 'Spam found', 'wtei' ) );
}
return [];
}
add_action( 'quform_post_process', [ $this, 'akismet_check' ], 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment