get_option( 'admin_email', '' ), ) ) . ';', 'before' ); if ( file_exists( plugin_dir_path( __FILE__ ) . 'build/blocks/form/index.css' ) ) { wp_enqueue_style( 'spicy-forms-editor-global', plugins_url( 'build/blocks/form/index.css', __FILE__ ), array( 'wp-components', 'wp-block-editor' ), self::VERSION ); } } /** * Register all 6 blocks dynamically from build metadata. * * @return void */ public function register_blocks(): void { $blocks = array( 'form', 'form-field', 'field-input', 'field-option', 'form-submit', 'form-notification', ); foreach ( $blocks as $block ) { $block_dir = plugin_dir_path( __FILE__ ) . 'build/blocks/' . $block; if ( file_exists( $block_dir . '/block.json' ) ) { register_block_type( $block_dir ); } } } /** * Register REST API routes. * * @return void */ public function register_rest_routes(): void { $controller = new Submission_Handler(); $controller->register_routes(); } } /** * Manages form metadata storage in wp_options ('spicy_forms_meta'). * Centralizes form schemas, labels, and validation rules for secure server-side execution. */ final class Form_Metadata_Manager { /** * Option key storing all forms metadata in wp_options. * * @var string */ const OPTION_KEY = 'spicy_forms_meta'; /** * Sanitize a field label attribute to strictly contain only alphanumeric characters, spaces, and underscores. * Strips any HTML tags and special characters. * * @param string $label Raw label text. * @return string Sanitized alphanumeric, space, and underscore label. */ public static function sanitize_field_label( string $label ): string { $label = wp_strip_all_tags( $label ); $label = html_entity_decode( $label, ENT_QUOTES, 'UTF-8' ); $label = preg_replace( '/[^a-zA-Z0-9_ ]/', '', $label ); $label = preg_replace( '/\s+/', ' ', $label ); return trim( (string) $label ); } /** * Retrieve all forms metadata from wp_options. * * @return array */ public static function get_all(): array { $meta = get_option( self::OPTION_KEY, array() ); if ( ! is_array( $meta ) ) { return array(); } // Backfill postIds if any form is missing it. $needs_sync = false; foreach ( $meta as $item ) { if ( ! isset( $item['postIds'] ) ) { $needs_sync = true; break; } } if ( $needs_sync ) { return self::sync_post_ids_for_all_forms(); } return $meta; } /** * Retrieve metadata for a specific form ID. * * @param string $form_id Form UUID. * @return array|null Metadata array or null if not found. */ public static function get( string $form_id ): ?array { if ( empty( $form_id ) ) { return null; } $all = self::get_all(); return $all[ $form_id ] ?? null; } /** * Scan all published/draft/pending posts containing spicy/form blocks and synchronize postIds across all forms. * * @return array Updated forms metadata. */ public static function sync_post_ids_for_all_forms(): array { global $wpdb; $meta = get_option( self::OPTION_KEY, array() ); $all = is_array( $meta ) ? $meta : array(); // Initialize empty postIds for all known forms. foreach ( $all as $fid => &$fdata ) { $fdata['postIds'] = array(); unset( $fdata['post_ids'] ); } unset( $fdata ); // Find all posts containing spicy/form blocks. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( "SELECT ID, post_content FROM {$wpdb->posts} WHERE post_status NOT IN ('trash', 'auto-draft', 'inherit') AND post_content LIKE '%spicy/form%'" ); if ( ! empty( $rows ) ) { foreach ( $rows as $row ) { $pid = (int) $row->ID; $blocks = parse_blocks( $row->post_content ); $fbs = self::find_form_blocks( $blocks ); foreach ( $fbs as $fb ) { $fid = $fb['attrs']['formId'] ?? ''; if ( ! empty( $fid ) ) { if ( ! isset( $all[ $fid ] ) ) { $fmeta = self::build_form_metadata( $fb, $pid ); if ( $fmeta ) { $all[ $fid ] = $fmeta; } } if ( isset( $all[ $fid ] ) ) { if ( ! in_array( $pid, $all[ $fid ]['postIds'], true ) ) { $all[ $fid ]['postIds'][] = $pid; } } } } } } // Sort and clean up postIds. foreach ( $all as $fid => &$fdata ) { unset( $fdata['post_ids'] ); if ( ! empty( $fdata['postIds'] ) ) { $fdata['postIds'] = array_values( array_unique( array_map( 'absint', $fdata['postIds'] ) ) ); sort( $fdata['postIds'] ); } else { $fdata['postIds'] = array(); } } unset( $fdata ); update_option( self::OPTION_KEY, $all ); return $all; } /** * Remove a post ID from a specific form's postIds array. * * @param string $form_id Form UUID. * @param int $post_id Post ID to remove. * @return void */ public static function remove_post_id_from_form( string $form_id, int $post_id ): void { $all = self::get_all(); if ( isset( $all[ $form_id ]['postIds'] ) && in_array( $post_id, $all[ $form_id ]['postIds'], true ) ) { $all[ $form_id ]['postIds'] = array_values( array_diff( $all[ $form_id ]['postIds'], array( $post_id ) ) ); unset( $all[ $form_id ]['post_ids'] ); $all[ $form_id ]['updated_at'] = time(); update_option( self::OPTION_KEY, $all ); } } /** * Remove a post ID from all forms in metadata. * * @param int $post_id Post ID to remove. * @return void */ public static function remove_post_id_from_all_forms( int $post_id ): void { $all = self::get_all(); $changed = false; foreach ( $all as $fid => &$fdata ) { unset( $fdata['post_ids'] ); if ( ! empty( $fdata['postIds'] ) && in_array( $post_id, $fdata['postIds'], true ) ) { $fdata['postIds'] = array_values( array_diff( $fdata['postIds'], array( $post_id ) ) ); $fdata['updated_at'] = time(); $changed = true; } } unset( $fdata ); if ( $changed ) { update_option( self::OPTION_KEY, $all ); } } /** * Save or update metadata for a specific form. * * @param string $form_id Form UUID. * @param array $metadata Form metadata array. * @param int $post_id Optional post ID where the form is saved. * @return bool True on success, false on failure. */ public static function save( string $form_id, array $metadata, int $post_id = 0 ): bool { if ( empty( $form_id ) ) { return false; } $all = self::get_all(); $existing = $all[ $form_id ] ?? array(); $post_ids = ! empty( $metadata['postIds'] ) && is_array( $metadata['postIds'] ) ? array_map( 'absint', $metadata['postIds'] ) : ( ! empty( $existing['postIds'] ) && is_array( $existing['postIds'] ) ? array_map( 'absint', $existing['postIds'] ) : array() ); if ( $post_id > 0 && ! in_array( $post_id, $post_ids, true ) ) { $post_ids[] = $post_id; } sort( $post_ids ); $post_ids = array_values( array_unique( array_filter( $post_ids ) ) ); unset( $metadata['post_ids'] ); $metadata['postIds'] = $post_ids; $metadata['updated_at'] = time(); $all[ $form_id ] = $metadata; return update_option( self::OPTION_KEY, $all ); } /** * Recursively extract all spicy/form blocks from an array of parsed blocks. * * @param array $blocks Array of parsed block structures. * @return array Array of extracted form blocks. */ public static function find_form_blocks( array $blocks ): array { $form_blocks = array(); foreach ( $blocks as $block ) { if ( 'spicy/form' === ( $block['blockName'] ?? '' ) ) { $form_blocks[] = $block; } if ( ! empty( $block['innerBlocks'] ) ) { $nested = self::find_form_blocks( $block['innerBlocks'] ); if ( ! empty( $nested ) ) { $form_blocks = array_merge( $form_blocks, $nested ); } } } return $form_blocks; } /** * Recursively extract all spicy/form-field blocks from an inner blocks array. * * @param array $inner_blocks Array of parsed inner blocks. * @return array Array of spicy/form-field blocks. */ public static function find_field_blocks( array $inner_blocks ): array { $fields = array(); foreach ( $inner_blocks as $block ) { if ( 'spicy/form-field' === ( $block['blockName'] ?? '' ) ) { $fields[] = $block; } if ( ! empty( $block['innerBlocks'] ) ) { $nested = self::find_field_blocks( $block['innerBlocks'] ); if ( ! empty( $nested ) ) { $fields = array_merge( $fields, $nested ); } } } return $fields; } /** * Build structured metadata from a spicy/form block structure. * * @param array $form_block Parsed spicy/form block array. * @param int $post_id Optional post ID where the form is located. * @return array|null */ public static function build_form_metadata( array $form_block, int $post_id = 0 ): ?array { $attrs = $form_block['attrs'] ?? array(); $form_id = ! empty( $attrs['formId'] ) ? sanitize_text_field( $attrs['formId'] ) : ''; if ( empty( $form_id ) ) { return null; } $existing = self::get( $form_id ); $post_ids = array(); if ( ! empty( $existing['postIds'] ) && is_array( $existing['postIds'] ) ) { $post_ids = array_map( 'absint', $existing['postIds'] ); } if ( $post_id > 0 && ! in_array( $post_id, $post_ids, true ) ) { $post_ids[] = $post_id; } sort( $post_ids ); $post_ids = array_values( array_unique( array_filter( $post_ids ) ) ); $form_name = ! empty( $attrs['formName'] ) ? sanitize_text_field( $attrs['formName'] ) : __( 'Contact Form', 'spicy-forms' ); $field_blocks = self::find_field_blocks( $form_block['innerBlocks'] ?? array() ); $fields = array(); $field_labels = array(); foreach ( $field_blocks as $fb ) { $fattrs = $fb['attrs'] ?? array(); $field_name = ! empty( $fattrs['fieldName'] ) ? sanitize_text_field( $fattrs['fieldName'] ) : ''; if ( empty( $field_name ) ) { continue; } // Extract and sanitize label. $raw_label = ! empty( $fattrs['label'] ) ? (string) $fattrs['label'] : ''; if ( empty( $raw_label ) && ! empty( $fb['innerBlocks'] ) ) { foreach ( $fb['innerBlocks'] as $child ) { if ( 'core/paragraph' === ( $child['blockName'] ?? '' ) ) { $c_class = $child['attrs']['className'] ?? ''; if ( false !== strpos( $c_class, 'spicy-field__label' ) || false !== strpos( $c_class, 'spicy-field__consent-label' ) ) { $raw_label = $child['attrs']['content'] ?? ''; break; } } } } $clean_label = self::sanitize_field_label( $raw_label ); if ( '' === $clean_label ) { continue; } $field_type = ! empty( $fattrs['fieldType'] ) ? sanitize_key( $fattrs['fieldType'] ) : 'text'; $required = ! empty( $fattrs['required'] ) || 'consent' === $field_type; $default_value = isset( $fattrs['value'] ) ? sanitize_text_field( (string) $fattrs['value'] ) : ''; $options = ! empty( $fattrs['options'] ) && is_array( $fattrs['options'] ) ? $fattrs['options'] : array(); if ( empty( $options ) && in_array( $field_type, array( 'select', 'radio', 'checkbox' ), true ) ) { $options = array( array( 'label' => 'Option 1', 'value' => 'Option 1', ), array( 'label' => 'Option 2', 'value' => 'Option 2', ), array( 'label' => 'Option 3', 'value' => 'Option 3', ), ); } if ( '' === $default_value && ! empty( $options ) ) { foreach ( $options as $opt ) { if ( ! empty( $opt['default'] ) && isset( $opt['value'] ) ) { $default_value = sanitize_text_field( (string) $opt['value'] ); break; } } } // Build strict, type-specific validation rules. $validation = array(); if ( 'tel' === $field_type ) { $validation['phonePrefix'] = ! empty( $fattrs['phonePrefix'] ) ? sanitize_text_field( (string) $fattrs['phonePrefix'] ) : '+91'; $validation['phoneDigits'] = isset( $fattrs['phoneDigits'] ) && (int) $fattrs['phoneDigits'] >= 0 ? absint( $fattrs['phoneDigits'] ) : 10; } elseif ( 'number' === $field_type || 'range' === $field_type ) { $validation['min'] = isset( $fattrs['min'] ) && '' !== (string) $fattrs['min'] ? (string) $fattrs['min'] : null; $validation['max'] = isset( $fattrs['max'] ) && '' !== (string) $fattrs['max'] ? (string) $fattrs['max'] : null; $validation['step'] = isset( $fattrs['step'] ) && '' !== (string) $fattrs['step'] ? (string) $fattrs['step'] : null; } elseif ( 'text' === $field_type ) { $validation['maxLength'] = isset( $fattrs['maxLength'] ) && (int) $fattrs['maxLength'] > 0 ? absint( $fattrs['maxLength'] ) : 100; } elseif ( 'textarea' === $field_type ) { $validation['maxLength'] = isset( $fattrs['maxLength'] ) && (int) $fattrs['maxLength'] > 0 ? absint( $fattrs['maxLength'] ) : 500; } elseif ( 'email' === $field_type ) { $validation['maxLength'] = isset( $fattrs['maxLength'] ) && (int) $fattrs['maxLength'] > 0 ? absint( $fattrs['maxLength'] ) : 100; } elseif ( 'url' === $field_type ) { $validation['maxLength'] = isset( $fattrs['maxLength'] ) && (int) $fattrs['maxLength'] > 0 ? absint( $fattrs['maxLength'] ) : 100; } elseif ( 'date' === $field_type ) { if ( isset( $fattrs['min'] ) && '' !== (string) $fattrs['min'] ) { $validation['min'] = (string) $fattrs['min']; } if ( isset( $fattrs['max'] ) && '' !== (string) $fattrs['max'] ) { $validation['max'] = (string) $fattrs['max']; } } $field_data = array( 'name' => $field_name, 'label' => $clean_label, 'type' => $field_type, 'required' => $required, 'defaultValue' => $default_value, 'options' => in_array( $field_type, array( 'select', 'radio', 'checkbox' ), true ) ? $options : array(), 'validation' => $validation, ); $fields[] = $field_data; $field_labels[ $field_name ] = $clean_label; } $actions = ! empty( $attrs['actions'] ) && is_array( $attrs['actions'] ) ? $attrs['actions'] : array( 'email' ); $success_action = ! empty( $attrs['successAction'] ) ? sanitize_key( $attrs['successAction'] ) : 'message'; $redirect_url = ! empty( $attrs['redirectUrl'] ) ? esc_url_raw( $attrs['redirectUrl'] ) : ''; $routing = array( 'emailTo' => $attrs['emailTo'] ?? '', 'emailBcc' => $attrs['emailBcc'] ?? '', 'emailFromName' => $attrs['emailFromName'] ?? '', 'emailFromAddress' => $attrs['emailFromAddress'] ?? '', 'emailReplyToField' => $attrs['emailReplyToField'] ?? '', 'emailReplyToNameField' => $attrs['emailReplyToNameField'] ?? '', 'emailSubject' => $attrs['emailSubject'] ?? '', ); return array( 'id' => $form_id, 'name' => $form_name, 'postIds' => $post_ids, 'actions' => $actions, 'successAction' => $success_action, 'redirectUrl' => $redirect_url, 'fields' => $fields, 'fieldLabels' => $field_labels, 'routing' => $routing, ); } /** * Hooked into save_post to automatically compile metadata for all spicy/form blocks. * * @param int $post_id Post ID. * @param \WP_Post $post Post object. * @return void */ public static function on_save_post( $post_id, $post ): void { if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) { return; } $post_id = (int) $post_id; $all = self::get_all(); if ( empty( $post->post_content ) || false === strpos( $post->post_content, 'spicy/form' ) ) { self::remove_post_id_from_all_forms( $post_id ); return; } $blocks = parse_blocks( $post->post_content ); $form_blocks = self::find_form_blocks( $blocks ); $current_form_ids = array(); foreach ( $form_blocks as $fb ) { $meta = self::build_form_metadata( $fb, $post_id ); if ( $meta && ! empty( $meta['id'] ) ) { $current_form_ids[] = $meta['id']; self::save( $meta['id'], $meta, $post_id ); } } // Remove this post ID from any form that was previously in this post but removed. foreach ( $all as $fid => $fdata ) { if ( ! in_array( $fid, $current_form_ids, true ) && ! empty( $fdata['postIds'] ) && in_array( $post_id, $fdata['postIds'], true ) ) { self::remove_post_id_from_form( $fid, $post_id ); } } } /** * Hooked into deleted_post and trashed_post to remove post ID from form metadata. * * @param int $post_id Post ID. * @return void */ public static function on_delete_post( $post_id ): void { self::remove_post_id_from_all_forms( (int) $post_id ); } /** * Hooked into untrashed_post to restore form metadata mapping. * * @param int $post_id Post ID. * @return void */ public static function on_untrash_post( $post_id ): void { $post = get_post( $post_id ); if ( $post ) { self::on_save_post( $post_id, $post ); } } /** * Synchronize metadata on render if missing or incomplete. * * @param array $attributes Block attributes. * @param \WP_Block $block Block instance. * @return void */ public static function sync_from_rendered_block( array $attributes, \WP_Block $block ): void { $form_id = ! empty( $attributes['formId'] ) ? $attributes['formId'] : ''; if ( empty( $form_id ) ) { return; } $post_id = get_the_ID(); $existing = self::get( $form_id ); if ( ! empty( $existing ) && ! empty( $existing['fields'] ) ) { if ( $post_id && ( empty( $existing['postIds'] ) || ! in_array( (int) $post_id, $existing['postIds'], true ) ) ) { self::save( $form_id, $existing, (int) $post_id ); } return; } $parsed_block = array( 'blockName' => 'spicy/form', 'attrs' => $attributes, 'innerBlocks' => array(), ); if ( ! empty( $block->inner_blocks ) ) { $parsed_block['innerBlocks'] = self::convert_wp_blocks_to_parsed( $block->inner_blocks ); } $meta = self::build_form_metadata( $parsed_block, $post_id ? (int) $post_id : 0 ); if ( $meta ) { self::save( $form_id, $meta, $post_id ? (int) $post_id : 0 ); } } /** * Convert an iterable collection of WP_Block instances (array or WP_Block_List) to parsed block structures. * * @param array|\WP_Block_List|iterable $wp_blocks Collection of WP_Block instances. * @return array */ private static function convert_wp_blocks_to_parsed( $wp_blocks ): array { $result = array(); if ( ! is_iterable( $wp_blocks ) ) { return $result; } foreach ( $wp_blocks as $wb ) { if ( ! ( $wb instanceof \WP_Block ) ) { continue; } $item = array( 'blockName' => $wb->name, 'attrs' => $wb->attributes, 'innerBlocks' => array(), ); if ( ! empty( $wb->inner_blocks ) ) { $item['innerBlocks'] = self::convert_wp_blocks_to_parsed( $wb->inner_blocks ); } $result[] = $item; } return $result; } } /** * Handles form submissions, validation, anti-spam, and email delivery. */ final class Submission_Handler { /** * REST route namespace. * * @var string */ const REST_NAMESPACE = 'spicy-forms/v1'; /** * Register REST API routes for form submissions. * * @return void */ public function register_routes(): void { register_rest_route( self::REST_NAMESPACE, '/submit', array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'handle_submission' ), 'permission_callback' => '__return_true', 'args' => array( 'formId' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), 'formName' => array( 'type' => 'string', 'required' => false, 'default' => 'Contact Form', 'sanitize_callback' => 'sanitize_text_field', ), 'startTime' => array( 'type' => 'integer', 'required' => false, 'sanitize_callback' => 'absint', ), 'spicy_hp' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'fields' => array( 'type' => 'object', 'required' => true, ), 'fieldLabels' => array( 'type' => 'object', 'required' => false, ), 'fieldTypes' => array( 'type' => 'object', 'required' => false, ), ), ) ); } /** * Handle incoming submission request. * * @param \WP_REST_Request $request REST request instance. * @return \WP_REST_Response|\WP_Error Response or error. */ public function handle_submission( \WP_REST_Request $request ) { $form_id = sanitize_text_field( (string) $request->get_param( 'formId' ) ); // 1. Verify submission integrity (dynamic stealth verification). if ( ! $this->verify_submission_integrity( $request, $form_id ) ) { return new \WP_REST_Response( array( 'status' => 'success', 'message' => __( 'Thank you! Your message has been sent.', 'spicy-forms' ), ), 200 ); } // 2. Time-check validation (zero-config layer 2: minimum 3 seconds). if ( $this->is_time_check_triggered( $request ) ) { return new \WP_Error( 'spicy_spam_detected', __( 'Submission flagged as automated. Please wait a few seconds before trying again.', 'spicy-forms' ), array( 'status' => 400 ) ); } // 3. Nonce verification. $nonce_error = $this->verify_nonce( $request ); if ( is_wp_error( $nonce_error ) ) { return $nonce_error; } // 4. Data extraction & metadata retrieval. $form_meta = Form_Metadata_Manager::get( $form_id ); $form_name = ! empty( $form_meta['name'] ) ? $form_meta['name'] : sanitize_text_field( (string) ( $request->get_param( 'formName' ) ?: 'Contact Form' ) ); $raw_fields = $request->get_param( 'fields' ); $params = $request->get_json_params(); if ( empty( $raw_fields ) && ! empty( $params['fields'] ) ) { $raw_fields = $params['fields']; } if ( empty( $raw_fields ) || ! is_array( $raw_fields ) ) { return new \WP_Error( 'spicy_missing_fields', __( 'No field data was received.', 'spicy-forms' ), array( 'status' => 400 ) ); } // Strip integrity verification fields from raw payload so they are never saved or emailed. $sec_key = ! empty( $form_id ) ? 'field_' . substr( hash_hmac( 'md5', $form_id, wp_salt( 'nonce' ) ), 0, 8 ) : ''; if ( ! empty( $sec_key ) && isset( $raw_fields[ $sec_key ] ) ) { unset( $raw_fields[ $sec_key ] ); } if ( isset( $raw_fields['spicy_hp'] ) ) { unset( $raw_fields['spicy_hp'] ); } // Fast server-side field validation using stored metadata. if ( ! empty( $form_meta['fields'] ) && is_array( $form_meta['fields'] ) ) { foreach ( $form_meta['fields'] as $meta_field ) { $f_name = $meta_field['name']; $f_label = ! empty( $meta_field['label'] ) ? $meta_field['label'] : __( 'This field', 'spicy-forms' ); $f_required = ! empty( $meta_field['required'] ); $f_type = $meta_field['type'] ?? 'text'; $f_val_rules = $meta_field['validation'] ?? array(); $f_val = $raw_fields[ $f_name ] ?? null; // Required field check. if ( $f_required ) { $is_empty = false; if ( null === $f_val ) { $is_empty = true; } elseif ( is_string( $f_val ) && '' === trim( $f_val ) ) { $is_empty = true; } elseif ( is_array( $f_val ) && empty( $f_val ) ) { $is_empty = true; } if ( $is_empty ) { return new \WP_Error( 'spicy_validation_required', sprintf( /* translators: %s: Field label */ __( '%s is required.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } // Comprehensive type and constraint validation for non-empty fields. if ( ! empty( $f_val ) ) { // 1. Email validation. if ( 'email' === $f_type && is_string( $f_val ) && ! is_email( trim( $f_val ) ) ) { return new \WP_Error( 'spicy_validation_email', sprintf( /* translators: %s: Field label */ __( 'Please enter a valid email address for %s.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } // 2. URL validation (strictly disallowing query parameters). if ( 'url' === $f_type && is_string( $f_val ) ) { $trimmed_url = trim( (string) $f_val ); if ( false !== strpos( $trimmed_url, '?' ) || null !== wp_parse_url( $trimmed_url, PHP_URL_QUERY ) ) { return new \WP_Error( 'spicy_validation_url_query', sprintf( /* translators: %s: Field label */ __( 'Query parameters are not allowed in %s.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } if ( ! wp_http_validate_url( $trimmed_url ) ) { return new \WP_Error( 'spicy_validation_url', sprintf( /* translators: %s: Field label */ __( 'Please enter a valid URL for %s.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } // 3. Phone number validation (ITU-T E.164: 7-15 digits, with optional prefix and exact digit enforcement). if ( 'tel' === $f_type && is_string( $f_val ) ) { $trimmed_phone = trim( (string) $f_val ); $phone_digits = preg_replace( '/\D/', '', $trimmed_phone ); $prefix = ! empty( $f_val_rules['phonePrefix'] ) ? preg_replace( '/\D/', '', (string) $f_val_rules['phonePrefix'] ) : '91'; $exact_digits = isset( $f_val_rules['phoneDigits'] ) ? absint( $f_val_rules['phoneDigits'] ) : 10; if ( $exact_digits > 0 ) { $national_digits = $phone_digits; if ( ! empty( $prefix ) && 0 === strpos( $phone_digits, $prefix ) && strlen( $phone_digits ) > strlen( $prefix ) ) { $national_digits = substr( $phone_digits, strlen( $prefix ) ); } if ( strlen( $national_digits ) !== $exact_digits ) { return new \WP_Error( 'spicy_validation_phone_digits', sprintf( /* translators: 1: Field label, 2: Exact required digit count */ __( '%1$s must contain exactly %2$d digits.', 'spicy-forms' ), $f_label, $exact_digits ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } else { if ( strlen( $phone_digits ) < 7 || strlen( $phone_digits ) > 15 || ! preg_match( '/^[+]?([0-9\s().-]){6,25}$/', $trimmed_phone ) ) { return new \WP_Error( 'spicy_validation_phone', sprintf( /* translators: %s: Field label */ __( 'Please enter a valid phone number for %s.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } } // 4. Number & Range validation (min, max, step). if ( ( 'number' === $f_type || 'range' === $f_type ) ) { if ( ! is_numeric( $f_val ) ) { return new \WP_Error( 'spicy_validation_number', sprintf( /* translators: %s: Field label */ __( 'Please enter a valid number for %s.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } $f_num = floatval( $f_val ); if ( isset( $f_val_rules['min'] ) && '' !== $f_val_rules['min'] && null !== $f_val_rules['min'] ) { $f_min = floatval( $f_val_rules['min'] ); if ( $f_num < $f_min ) { return new \WP_Error( 'spicy_validation_min', sprintf( /* translators: 1: Field label, 2: Minimum value */ __( '%1$s must be at least %2$s.', 'spicy-forms' ), $f_label, $f_min ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } if ( isset( $f_val_rules['max'] ) && '' !== $f_val_rules['max'] && null !== $f_val_rules['max'] ) { $f_max = floatval( $f_val_rules['max'] ); if ( $f_num > $f_max ) { return new \WP_Error( 'spicy_validation_max', sprintf( /* translators: 1: Field label, 2: Maximum value */ __( '%1$s must be at most %2$s.', 'spicy-forms' ), $f_label, $f_max ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } if ( isset( $f_val_rules['step'] ) && '' !== $f_val_rules['step'] && null !== $f_val_rules['step'] && 'any' !== $f_val_rules['step'] ) { $f_step = floatval( $f_val_rules['step'] ); if ( $f_step > 0 ) { $f_base = ( isset( $f_val_rules['min'] ) && '' !== $f_val_rules['min'] && null !== $f_val_rules['min'] ) ? floatval( $f_val_rules['min'] ) : 0.0; $diff = abs( $f_num - $f_base ); $mod = fmod( $diff, $f_step ); if ( $mod > 0.00001 && abs( $mod - $f_step ) > 0.00001 ) { return new \WP_Error( 'spicy_validation_step', sprintf( /* translators: 1: Field label, 2: Step value */ __( '%1$s must be in increments of %2$s.', 'spicy-forms' ), $f_label, $f_step ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } } } // 5. Option validation for choice elements (select, radio, checkbox). if ( in_array( $f_type, array( 'select', 'radio', 'checkbox' ), true ) ) { $allowed_options = array(); if ( ! empty( $meta_field['options'] ) && is_array( $meta_field['options'] ) ) { foreach ( $meta_field['options'] as $opt ) { if ( is_array( $opt ) ) { $val = $opt['value'] ?? ( $opt['label'] ?? '' ); $allowed_options[] = (string) $val; } else { $allowed_options[] = (string) $opt; } } } if ( empty( $allowed_options ) ) { $allowed_options = array( 'Option 1', 'Option 2', 'Option 3' ); } if ( 'checkbox' === $f_type ) { $submitted_items = is_array( $f_val ) ? $f_val : array( $f_val ); foreach ( $submitted_items as $sub_item ) { $sub_str = is_scalar( $sub_item ) ? (string) $sub_item : ''; if ( '' !== $sub_str && ! in_array( $sub_str, $allowed_options, true ) ) { return new \WP_Error( 'spicy_validation_invalid_option', sprintf( /* translators: %s: Field label */ __( 'The selected option for %s is invalid.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } } else { // select or radio. $sub_str = is_scalar( $f_val ) ? (string) $f_val : ''; if ( '' !== $sub_str && ! in_array( $sub_str, $allowed_options, true ) ) { return new \WP_Error( 'spicy_validation_invalid_option', sprintf( /* translators: %s: Field label */ __( 'The selected option for %s is invalid.', 'spicy-forms' ), $f_label ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } } // 6. Max length check for text, textarea, email, and url. if ( in_array( $f_type, array( 'text', 'textarea', 'email', 'url' ), true ) && is_string( $f_val ) ) { $max_len = ! empty( $f_val_rules['maxLength'] ) ? absint( $f_val_rules['maxLength'] ) : ( 'textarea' === $f_type ? 500 : 100 ); if ( $max_len > 0 && mb_strlen( $f_val, 'UTF-8' ) > $max_len ) { return new \WP_Error( 'spicy_validation_maxlength', sprintf( /* translators: 1: Field label, 2: Maximum characters */ __( '%1$s cannot exceed %2$d characters.', 'spicy-forms' ), $f_label, $max_len ), array( 'status' => 400, 'field_key' => $f_name, ) ); } } } } } // Field labels from stored metadata (fast, server-side verified). $field_labels = ! empty( $form_meta['fieldLabels'] ) ? $form_meta['fieldLabels'] : array(); if ( empty( $field_labels ) ) { $raw_labels = $request->get_param( 'fieldLabels' ); if ( empty( $raw_labels ) && ! empty( $params['fieldLabels'] ) && is_array( $params['fieldLabels'] ) ) { $raw_labels = $params['fieldLabels']; } $field_labels = is_array( $raw_labels ) ? array_map( array( Form_Metadata_Manager::class, 'sanitize_field_label' ), $raw_labels ) : array(); } $raw_option_labels = $request->get_param( 'optionLabels' ); if ( empty( $raw_option_labels ) && ! empty( $params['optionLabels'] ) && is_array( $params['optionLabels'] ) ) { $raw_option_labels = $params['optionLabels']; } $option_labels = is_array( $raw_option_labels ) ? array_map( 'sanitize_text_field', $raw_option_labels ) : array(); $raw_field_types = $request->get_param( 'fieldTypes' ); if ( empty( $raw_field_types ) && ! empty( $params['fieldTypes'] ) && is_array( $params['fieldTypes'] ) ) { $raw_field_types = $params['fieldTypes']; } $field_types = is_array( $raw_field_types ) ? array_map( 'sanitize_key', $raw_field_types ) : array(); $parsed = $this->parse_and_sanitize_fields( $raw_fields, $field_labels, $option_labels, $field_types, $form_meta ); $sanitized_fields = $parsed['fields']; $reply_to_email = $parsed['reply_to_email']; $reply_to_name = $parsed['reply_to_name']; // 5. Routing Configuration: Exclusively server-side verified routing from stored form metadata. // Never accept client-supplied routing parameters on an unauthenticated public endpoint. $routing = ( ! empty( $form_meta['routing'] ) && is_array( $form_meta['routing'] ) ) ? $form_meta['routing'] : array(); // Custom reply-to overrides from routing. if ( isset( $routing['emailReplyToField'] ) && 'none' === $routing['emailReplyToField'] ) { $reply_to_email = ''; } elseif ( ! empty( $routing['emailReplyToField'] ) && isset( $sanitized_fields[ $routing['emailReplyToField'] ] ) ) { $val = $sanitized_fields[ $routing['emailReplyToField'] ]['value']; if ( is_email( $val ) ) { $reply_to_email = $val; } } if ( isset( $routing['emailReplyToNameField'] ) && 'none' === $routing['emailReplyToNameField'] ) { $reply_to_name = ''; } elseif ( ! empty( $routing['emailReplyToNameField'] ) && isset( $sanitized_fields[ $routing['emailReplyToNameField'] ] ) ) { $val = $sanitized_fields[ $routing['emailReplyToNameField'] ]['value']; if ( is_string( $val ) ) { $reply_to_name = $val; } } // 6. Build Email. $raw_to = $routing['emailTo'] ?? ''; if ( is_array( $raw_to ) ) { $email_to_list = array_filter( array_map( 'sanitize_email', $raw_to ), 'is_email' ); $email_to = ! empty( $email_to_list ) ? implode( ', ', $email_to_list ) : get_option( 'admin_email' ); } else { $email_to = ! empty( $raw_to ) ? sanitize_email( (string) $raw_to ) : get_option( 'admin_email' ); } if ( ! is_email( $email_to ) && false === strpos( $email_to, ',' ) ) { $email_to = get_option( 'admin_email' ); } $email_from_name = ! empty( $routing['emailFromName'] ) ? sanitize_text_field( $routing['emailFromName'] ) : wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $site_host = wp_parse_url( home_url(), PHP_URL_HOST ); if ( empty( $site_host ) ) { $site_host = 'localhost'; } $email_from_address = ! empty( $routing['emailFromAddress'] ) ? sanitize_email( $routing['emailFromAddress'] ) : 'wordpress@' . preg_replace( '/^www\./', '', $site_host ); $subject = ! empty( $routing['emailSubject'] ) ? sanitize_text_field( $routing['emailSubject'] ) : sprintf( /* translators: %s: Form Name */ __( 'New Submission — %s', 'spicy-forms' ), $form_name ); // Exclude consent field for email notifications. $email_fields = array_filter( $sanitized_fields, static function ( $field_info, $field_key ) use ( $field_types, $form_meta ) { if ( ! empty( $field_info['type'] ) && 'consent' === $field_info['type'] ) { return false; } if ( ! empty( $field_types[ $field_key ] ) && 'consent' === $field_types[ $field_key ] ) { return false; } if ( ! empty( $form_meta['fields'] ) && is_array( $form_meta['fields'] ) ) { foreach ( $form_meta['fields'] as $meta_f ) { if ( isset( $meta_f['name'], $meta_f['type'] ) && $meta_f['name'] === $field_key && 'consent' === $meta_f['type'] ) { return false; } } } return true; }, ARRAY_FILTER_USE_BOTH ); $message = $this->build_email_html( $form_name, $email_fields ); $headers = array(); $headers[] = 'Content-Type: text/html; charset=UTF-8'; $headers[] = sprintf( 'From: %s <%s>', sanitize_text_field( str_replace( array( "\r", "\n" ), '', $email_from_name ) ), sanitize_email( str_replace( array( "\r", "\n" ), '', $email_from_address ) ) ); if ( ! empty( $reply_to_email ) ) { $clean_reply_email = sanitize_email( str_replace( array( "\r", "\n" ), '', $reply_to_email ) ); $clean_reply_name = ! empty( $reply_to_name ) ? sanitize_text_field( str_replace( array( "\r", "\n" ), '', $reply_to_name ) ) : ''; if ( ! empty( $clean_reply_name ) ) { $headers[] = sprintf( 'Reply-To: %s <%s>', $clean_reply_name, $clean_reply_email ); } else { $headers[] = sprintf( 'Reply-To: <%s>', $clean_reply_email ); } } // Allow Pro add-on to inject custom headers (e.g. BCC, CRM routing). $headers = apply_filters( 'spicy_forms_submission_email_headers', $headers, $routing, $sanitized_fields ); // 7. Temporary Queue Buffer (100 cap FIFO). $queue_entry_id = wp_generate_uuid4(); $queue = get_option( 'spicy_forms_queue', array() ); if ( ! is_array( $queue ) ) { $queue = array(); } $queue[] = array( 'id' => $queue_entry_id, 'form_id' => $form_id, 'form_name' => $form_name, 'submitted_at' => current_time( 'mysql' ), 'fields' => $sanitized_fields, 'to' => $email_to, ); if ( count( $queue ) > 100 ) { $queue = array_slice( $queue, -100 ); } update_option( 'spicy_forms_queue', $queue, false ); // 8. Dispatch Email via wp_mail(). $mail_sent = wp_mail( $email_to, $subject, $message, $headers ); if ( $mail_sent ) { $queue = array_values( array_filter( $queue, static function ( $item ) use ( $queue_entry_id ) { return isset( $item['id'] ) && $item['id'] !== $queue_entry_id; } ) ); update_option( 'spicy_forms_queue', $queue, false ); return new \WP_REST_Response( array( 'status' => 'success', 'message' => __( 'Thanks! Your message has been sent.', 'spicy-forms' ), ), 200 ); } return new \WP_Error( 'spicy_mail_failed', __( 'Unable to send email notification at this time. Please try again later.', 'spicy-forms' ), array( 'status' => 500 ) ); } /** * Verify submission integrity and dynamic payload consistency. * * @param \WP_REST_Request $request REST request instance. * @param string $form_id Unique form identifier. * @return bool True if submission passes integrity check, false if compromised. */ private function verify_submission_integrity( \WP_REST_Request $request, string $form_id ): bool { $params = $request->get_json_params() ?: array(); $raw_fields = $request->get_param( 'fields' ); if ( empty( $raw_fields ) && ! empty( $params['fields'] ) ) { $raw_fields = $params['fields']; } $sec_key = ! empty( $form_id ) ? 'field_' . substr( hash_hmac( 'md5', $form_id, wp_salt( 'nonce' ) ), 0, 8 ) : ''; if ( ! empty( $sec_key ) ) { if ( is_array( $raw_fields ) && ! empty( $raw_fields[ $sec_key ] ) ) { return false; } $direct_val = $request->get_param( $sec_key ); if ( ! empty( $direct_val ) || ! empty( $params[ $sec_key ] ) ) { return false; } } // Legacy field check for backwards compatibility. $hp_val = $request->get_param( 'spicy_hp' ); if ( empty( $hp_val ) && ! empty( $params['spicy_hp'] ) ) { $hp_val = $params['spicy_hp']; } if ( empty( $hp_val ) && ! empty( $params['hp']['spicy_hp'] ) ) { $hp_val = $params['hp']['spicy_hp']; } if ( empty( $hp_val ) && is_array( $raw_fields ) && ! empty( $raw_fields['spicy_hp'] ) ) { $hp_val = $raw_fields['spicy_hp']; } return empty( $hp_val ); } /** * Check if the submission was made too fast (bot behavior). * * @param \WP_REST_Request $request REST request instance. * @return bool True if submitted under 3 seconds. */ private function is_time_check_triggered( \WP_REST_Request $request ): bool { $start_time = $request->get_param( 'startTime' ); $params = $request->get_json_params(); if ( empty( $start_time ) && ! empty( $params['startTime'] ) ) { $start_time = absint( $params['startTime'] ); } if ( ! empty( $start_time ) ) { $elapsed = time() - $start_time; return $elapsed < 3; } return false; } /** * Verify REST API nonce if supplied. * * @param \WP_REST_Request $request REST request instance. * @return true|\WP_Error True or error. */ private function verify_nonce( \WP_REST_Request $request ) { $nonce = $request->get_header( 'x_wp_nonce' ); $params = $request->get_json_params(); if ( empty( $nonce ) ) { $nonce = $request->get_param( '_wpnonce' ); } if ( empty( $nonce ) && ! empty( $params['_wpnonce'] ) ) { $nonce = $params['_wpnonce']; } if ( ! empty( $nonce ) ) { $valid = wp_verify_nonce( $nonce, 'wp_rest' ); if ( ! $valid ) { return new \WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid. Please refresh the page and try again.', 'spicy-forms' ), array( 'status' => 403 ) ); } } return true; } /** * Parse and sanitize all submitted form fields. * * @param array $raw_fields Raw fields input array. * @param array $field_labels Optional map of field keys to human-readable labels. * @param array $option_labels Optional map of option value keys to human-readable option labels. * @param array $field_types Optional map of field keys to field types. * @param array $form_meta Optional form metadata. * @return array Parsed fields and reply-to information. */ private function parse_and_sanitize_fields( array $raw_fields, array $field_labels = array(), array $option_labels = array(), array $field_types = array(), array $form_meta = array() ): array { $sanitized_fields = array(); $reply_to_email = ''; $reply_to_name = ''; $meta_fields_by_name = array(); if ( ! empty( $form_meta['fields'] ) && is_array( $form_meta['fields'] ) ) { foreach ( $form_meta['fields'] as $meta_f ) { if ( ! empty( $meta_f['name'] ) ) { $meta_fields_by_name[ sanitize_key( $meta_f['name'] ) ] = $meta_f; } } } $sec_key = ! empty( $form_meta['id'] ) ? 'field_' . substr( hash_hmac( 'md5', $form_meta['id'], wp_salt( 'nonce' ) ), 0, 8 ) : ''; foreach ( $raw_fields as $key => $field_data ) { $clean_key = sanitize_key( $key ); if ( 'spicy_hp' === $clean_key || ( ! empty( $sec_key ) && $clean_key === $sec_key ) ) { continue; } if ( is_array( $field_data ) ) { $label = isset( $field_data['label'] ) ? sanitize_text_field( $field_data['label'] ) : ( ! empty( $field_labels[ $clean_key ] ) ? $field_labels[ $clean_key ] : $clean_key ); $label = wp_strip_all_tags( $label ); $type = isset( $field_data['type'] ) ? sanitize_text_field( $field_data['type'] ) : ( $field_types[ $clean_key ] ?? ( $meta_fields_by_name[ $clean_key ]['type'] ?? 'text' ) ); $value = isset( $field_data['value'] ) ? $field_data['value'] : ''; $clean_value = $this->sanitize_field_value( $value, $type ); // Prepend prefix for phone fields if not already prepended. if ( 'tel' === $type && is_string( $clean_value ) && '' !== trim( $clean_value ) ) { $prefix = ! empty( $meta_fields_by_name[ $clean_key ]['validation']['phonePrefix'] ) ? trim( (string) $meta_fields_by_name[ $clean_key ]['validation']['phonePrefix'] ) : '+91'; $trimmed_val = trim( $clean_value ); if ( 0 !== strpos( $trimmed_val, '+' ) && 0 !== strpos( $trimmed_val, $prefix ) ) { $clean_value = $prefix . ' ' . $trimmed_val; } } $display_value = $clean_value; if ( ! empty( $option_labels ) ) { if ( is_array( $clean_value ) ) { $display_value = array_map( static function ( $v ) use ( $option_labels ) { return is_scalar( $v ) && isset( $option_labels[ (string) $v ] ) ? wp_strip_all_tags( (string) $option_labels[ (string) $v ] ) : wp_strip_all_tags( (string) $v ); }, $clean_value ); } elseif ( is_scalar( $clean_value ) && isset( $option_labels[ (string) $clean_value ] ) ) { $display_value = wp_strip_all_tags( (string) $option_labels[ (string) $clean_value ] ); } } $sanitized_fields[ $clean_key ] = array( 'label' => $label, 'value' => $clean_value, 'display_value' => $display_value, 'type' => $type, ); if ( ( 'email' === $type || is_email( $clean_value ) ) && empty( $reply_to_email ) && is_email( $clean_value ) ) { $reply_to_email = $clean_value; } if ( ( 'name' === $type || false !== stripos( $label, 'name' ) ) && empty( $reply_to_name ) && is_string( $clean_value ) ) { $reply_to_name = $clean_value; } } else { $type = $field_types[ $clean_key ] ?? ( $meta_fields_by_name[ $clean_key ]['type'] ?? 'text' ); $clean_value = $this->sanitize_field_value( $field_data, $type ); // Prepend prefix for phone fields if not already prepended. if ( 'tel' === $type && is_string( $clean_value ) && '' !== trim( $clean_value ) ) { $prefix = ! empty( $meta_fields_by_name[ $clean_key ]['validation']['phonePrefix'] ) ? trim( (string) $meta_fields_by_name[ $clean_key ]['validation']['phonePrefix'] ) : '+91'; $trimmed_val = trim( $clean_value ); if ( 0 !== strpos( $trimmed_val, '+' ) && 0 !== strpos( $trimmed_val, $prefix ) ) { $clean_value = $prefix . ' ' . $trimmed_val; } } $display_value = $clean_value; if ( ! empty( $option_labels ) && isset( $option_labels[ $clean_value ] ) ) { $display_value = wp_strip_all_tags( (string) $option_labels[ $clean_value ] ); } $label = ! empty( $field_labels[ $clean_key ] ) ? $field_labels[ $clean_key ] : ucwords( str_replace( array( '-', '_' ), ' ', $clean_key ) ); $label = wp_strip_all_tags( $label ); $sanitized_fields[ $clean_key ] = array( 'label' => $label, 'value' => $clean_value, 'display_value' => $display_value, 'type' => $type, ); if ( empty( $reply_to_email ) && is_email( $clean_value ) ) { $reply_to_email = $clean_value; } if ( false !== stripos( $label, 'name' ) && empty( $reply_to_name ) && is_string( $clean_value ) ) { $reply_to_name = $clean_value; } } } return array( 'fields' => $sanitized_fields, 'reply_to_email' => $reply_to_email, 'reply_to_name' => $reply_to_name, ); } /** * Sanitize field value based on its type. * Strictly strips all HTML and script tags to ensure zero HTML/script data is processed or stored. * * @param mixed $value Raw field value. * @param string $type Field type. * @return mixed Sanitized value. */ private function sanitize_field_value( $value, string $type ) { if ( is_array( $value ) ) { return array_map( function ( $v ) use ( $type ) { return $this->sanitize_field_value( $v, $type ); }, $value ); } // Ensure all HTML, XML, script and style tags are completely stripped. $clean = wp_strip_all_tags( (string) $value ); switch ( $type ) { case 'email': return sanitize_email( $clean ); case 'url': return esc_url_raw( $clean ); case 'textarea': return sanitize_textarea_field( $clean ); case 'number': case 'range': return is_numeric( $clean ) ? $clean + 0 : 0; case 'consent': return ! empty( $clean ) ? 'Yes' : 'No'; default: return sanitize_text_field( $clean ); } } /** * Build responsive HTML table for email notification. * * @param string $form_name Form name. * @param array $fields Sanitized fields. * @return string HTML email content. */ private function build_email_html( string $form_name, array $fields ): string { $site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $site_url = home_url(); $rows_html = ''; $index = 0; foreach ( $fields as $field ) { $label = ! empty( $field['label'] ) ? esc_html( wp_strip_all_tags( (string) $field['label'] ) ) : esc_html__( 'Field', 'spicy-forms' ); $val = $field['display_value'] ?? $field['value']; $is_textarea = ( 'textarea' === ( $field['type'] ?? '' ) ); $is_tel = ( 'tel' === ( $field['type'] ?? '' ) ); if ( is_array( $val ) ) { $val_display = esc_html( implode( ', ', array_map( 'wp_strip_all_tags', array_map( 'strval', $val ) ) ) ); } elseif ( $is_textarea ) { // Pure plain-text formatting (e.g. poems, addresses): preserve exact spacing and new lines with zero HTML or script tags. $val_display = nl2br( esc_html( wp_strip_all_tags( (string) $val ) ) ); } elseif ( $is_tel && is_string( $val ) && '' !== trim( $val ) && 0 !== strpos( trim( $val ), '+' ) ) { $val_display = esc_html( '+91 ' . wp_strip_all_tags( trim( $val ) ) ); } else { $val_display = esc_html( wp_strip_all_tags( (string) $val ) ); } $val_cell_style = 'padding: 12px 16px; color: #111827; border-bottom: 1px solid #e5e7eb; vertical-align: top;'; if ( $is_textarea ) { $val_cell_style .= ' white-space: pre-wrap; word-break: break-word; font-family: inherit;'; } $bg_color = ( 0 === $index % 2 ) ? '#ffffff' : '#f9fafb'; $rows_html .= sprintf( '