spivurno
8/6/2014 - 9:59 PM

Gravity Wiz // Gravity Forms // Remove or Validate Emojis ✮

Gravity Wiz // Gravity Forms // Remove or Validate Emojis ✮

<?php
/**
 * Gravity Wiz // Gravity Forms // Remove or Validate Emojis ✮
 *
 * Automatically remove or provide a validation error when emojis are submitted via a Gravity Form field.
 *
 * @version	  1.0
 * @author    David Smith <david@gravitywiz.com>
 * @license   GPL-2.0+
 * @link      http://gravitywiz.com/...
 */
class GW_Emoji_Handler {

    public function __construct( $args = array() ) {

        // set our default arguments, parse against the provided arguments, and store for use throughout the class
        $this->_args = wp_parse_args( $args, array(
            'mode'               => 'remove',
            'validation_message' => __( 'Oops! Emojis are not supported.' )
        ) );

        // time for hooks
        add_action( 'gform_validation', array( $this, 'handle_emojis' ), 9 );

    }

    public function handle_emojis( $validation_result ) {

        foreach( $validation_result['form']['fields'] as &$field ) {

            $post_id   = "input_{$field['id']}";
            $value     = rgpost( $post_id );
            $new_value = $this->remove_emoji( $value );

            if( $new_value == $value ) {
                continue;
            }

            if( $this->_args['mode'] == 'remove' ) {
                $_POST[ $post_id ] = $new_value;
            } else {
                $field['failed_validation'] = true;
                $field['validation_message'] = $this->_args['validation_message'];
                $validation_result['is_valid'] = false;
            }

        }

        return $validation_result;
    }

    /*
     * Remove emojis from a given string
     * http://stackoverflow.com/questions/12807176/php-writing-a-simple-removeemoji-function
     */
    public function remove_emoji( $text ) {

        $clean_text = "";

        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace( $regexEmoticons, '', $text );

        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace( $regexSymbols, '', $clean_text );

        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace( $regexTransport, '', $clean_text );

        return $clean_text;
    }

}

# Configuration

//new GW_Emoji_Handler( array(
//    'mode'               => 'validate',
//    'validation_message' => __( 'Oh, poop! Emojis are not supported.' )
//) );

new GW_Emoji_Handler();