'POST', 'callback' => 'stackmime_forms_rest_token', 'permission_callback' => '__return_true', 'args' => array( 'form' => array( 'required' => true, 'sanitize_callback' => 'sanitize_key', ), ), ) ); register_rest_route( 'stackmime-forms/v1', '/submit', array( 'methods' => 'POST', 'callback' => 'stackmime_forms_rest_submit', 'permission_callback' => '__return_true', ) ); } ); /** * HMAC signature for a token. * * @param string $payload Payload. */ function stackmime_forms_sign( $payload ) { return hash_hmac( 'sha256', $payload, wp_salt( 'nonce' ) . '|stackmime-forms' ); } /** * Hashed visitor IP (for rate limiting only). */ function stackmime_forms_ip_hash() { $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; return hash_hmac( 'sha256', $ip, wp_salt( 'auth' ) . '|stackmime-forms-ip' ); } /** * Response that must never be cached. * * @param array $data Body. * @param int $status HTTP status. */ function stackmime_forms_response( $data, $status = 200 ) { do_action( 'litespeed_control_set_nocache', 'stackmime-forms' ); // LiteSpeed Cache: never cache this response. if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); // Other page-cache plugins. } $res = new WP_REST_Response( $data, $status ); $res->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0' ); $res->header( 'X-LiteSpeed-Cache-Control', 'no-cache' ); return $res; } /** * Issue a fresh token. * * @param WP_REST_Request $req Request. */ function stackmime_forms_rest_token( $req ) { $form = $req->get_param( 'form' ); if ( ! stackmime_forms_get( $form ) ) { return stackmime_forms_response( array( 'code' => 'unknown_form' ), 404 ); } $payload = time() . '.' . bin2hex( random_bytes( 8 ) ) . '.' . $form; return stackmime_forms_response( array( 'token' => $payload . '.' . stackmime_forms_sign( $payload ) ) ); } /** * Check a token. Returns '' when valid, otherwise a reason code. * * @param string $token Token. * @param string $form Form ID. */ function stackmime_forms_check_token( $token, $form ) { $parts = explode( '.', (string) $token ); if ( 4 !== count( $parts ) ) { return 'token_invalid'; } list( $ts, $rand, $tform, $sig ) = $parts; $payload = $ts . '.' . $rand . '.' . $tform; if ( $tform !== $form || ! hash_equals( stackmime_forms_sign( $payload ), $sig ) ) { return 'token_invalid'; } $age = time() - (int) $ts; if ( $age > STACKMIME_FORMS_TOKEN_TTL ) { return 'token_expired'; } if ( $age < (int) stackmime_forms_settings()['min_seconds'] ) { return 'too_fast'; } if ( get_transient( 'stackmime_forms_used_' . md5( $sig ) ) ) { return 'token_used'; } return ''; } /** * Validate and clean submitted fields against the form definition. * * @param array $form Form definition. * @param array $input Raw fields. * @return array{0: array, 1: array} Clean values, errors. */ function stackmime_forms_validate( $form, $input ) { $clean = array(); $errors = array(); /** * Fields that apply to this submission. Add-ons can leave out fields their rules hide. * * @param array $fields Form fields. * @param array $form Form definition. * @param array $input Raw submitted values. */ $active = (array) apply_filters( 'stackmime_forms_active_fields', $form['fields'], $form, $input ); foreach ( $active as $key => $field ) { if ( stackmime_forms_is_display_type( $field['type'] ) ) { continue; // Headings and text are never submitted. } $raw = isset( $input[ $key ] ) && is_scalar( $input[ $key ] ) ? (string) $input[ $key ] : ''; $raw = trim( $raw ); switch ( $field['type'] ) { case 'email': $value = sanitize_email( $raw ); if ( '' !== $raw && ! is_email( $value ) ) { $errors[ $key ] = __( 'Please enter a valid email address.', 'stackmime-forms' ); } break; case 'tel': $value = preg_replace( '/[^0-9+()\s.-]/', '', $raw ); if ( '' !== $raw && strlen( preg_replace( '/\D/', '', $value ) ) < 6 ) { $errors[ $key ] = __( 'Please enter a valid phone number.', 'stackmime-forms' ); } break; case 'url': $value = '' === $raw ? '' : esc_url_raw( preg_match( '#^https?://#i', $raw ) ? $raw : 'https://' . $raw, array( 'http', 'https' ) ); if ( '' !== $raw && ( '' === $value || ! wp_parse_url( $value, PHP_URL_HOST ) || false === strpos( (string) wp_parse_url( $value, PHP_URL_HOST ), '.' ) ) ) { $errors[ $key ] = __( 'Please enter a valid web address.', 'stackmime-forms' ); } break; case 'textarea': $value = sanitize_textarea_field( $raw ); break; case 'select': case 'radio': $value = sanitize_text_field( $raw ); if ( '' !== $value && $field['options'] && ! array_key_exists( $value, $field['options'] ) ) { $errors[ $key ] = __( 'Please choose one of the options.', 'stackmime-forms' ); } break; case 'choices': $keys = array_values( array_unique( array_filter( array_map( 'sanitize_key', explode( ',', $raw ) ), 'strlen' ) ) ); $value = implode( ',', $keys ); foreach ( $keys as $k ) { if ( ! array_key_exists( $k, $field['options'] ) ) { $errors[ $key ] = __( 'Please choose from the options.', 'stackmime-forms' ); } } if ( (int) $field['max_choices'] > 0 && count( $keys ) > (int) $field['max_choices'] ) { /* translators: %d: maximum number of choices. */ $errors[ $key ] = sprintf( _n( 'Please choose no more than %d option.', 'Please choose no more than %d options.', (int) $field['max_choices'], 'stackmime-forms' ), (int) $field['max_choices'] ); } break; case 'consent': $value = in_array( strtolower( $raw ), array( '1', 'yes', 'on', 'true' ), true ) ? '1' : ''; if ( $field['required'] && '' === $value ) { $errors[ $key ] = __( 'Please tick this box to continue.', 'stackmime-forms' ); } break; case 'date': $value = sanitize_text_field( $raw ); if ( '' !== $value && ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $value ) ) { $errors[ $key ] = __( 'Please choose a valid date.', 'stackmime-forms' ); } break; case 'number': $num = filter_var( $raw, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); $value = '' === $raw ? '' : ( is_numeric( $num ) ? (string) ( 0 + $num ) : '' ); if ( '' !== $raw && '' === $value ) { $errors[ $key ] = __( 'Please enter a number.', 'stackmime-forms' ); } break; default: $value = sanitize_text_field( $raw ); } if ( mb_strlen( $value ) > (int) $field['max'] ) { $errors[ $key ] = __( 'This is too long.', 'stackmime-forms' ); } if ( $field['required'] && '' === $value && ! isset( $errors[ $key ] ) ) { $errors[ $key ] = __( 'This is required.', 'stackmime-forms' ); } $clean[ $key ] = $value; } return array( $clean, $errors ); } /** * Handle a submission. * * @param WP_REST_Request $req Request. */ function stackmime_forms_rest_submit( $req ) { $body = $req->get_json_params(); $body = is_array( $body ) ? $body : $req->get_body_params(); $form_id = sanitize_key( $body['form'] ?? '' ); $form = stackmime_forms_get( $form_id ); if ( ! $form ) { return stackmime_forms_response( array( 'code' => 'unknown_form', 'message' => stackmime_forms_fail_message(), ), 404 ); } $settings = stackmime_forms_settings(); $fields = isset( $body['fields'] ) && is_array( $body['fields'] ) ? $body['fields'] : array(); $ip_hash = stackmime_forms_ip_hash(); $ok = array( 'success' => true, 'message' => $form['success'], ); // Rate limit per visitor: N submissions per 10 minutes. $rl_key = 'stackmime_forms_rl_' . substr( $ip_hash, 0, 40 ); $count = (int) get_transient( $rl_key ); if ( $count >= max( 1, (int) $settings['rate_limit'] ) ) { return stackmime_forms_response( array( 'code' => 'rate_limited', 'message' => __( 'You\'ve sent a few messages already. Please wait a few minutes and try again.', 'stackmime-forms' ), ), 429 ); } set_transient( $rl_key, $count + 1, 10 * MINUTE_IN_SECONDS ); // Token problems are never treated as spam: a real visitor's browser gets a fresh token and retries // automatically, so a cached, expired or reused token can't lose a lead. Scripts that skip the token get nothing. $token_problem = stackmime_forms_check_token( $body['token'] ?? '', $form_id ); if ( $token_problem && empty( $body['_sm_hp'] ) ) { return stackmime_forms_response( array( 'code' => 'token_retry' ), 409 ); } list( $clean, $errors ) = stackmime_forms_validate( $form, $fields ); // Spam signals. Bots get a normal-looking success so they learn nothing. $spam = ''; if ( ! empty( $body['_sm_hp'] ) ) { $spam = 'honeypot'; } else { $links = 0; foreach ( $clean as $value ) { $links += preg_match_all( '#(https?://|www\.|\[url)#i', (string) $value ); } if ( $links > (int) $settings['max_links'] ) { $spam = 'links'; } } if ( ! $spam && $errors ) { return stackmime_forms_response( array( 'code' => 'invalid', 'message' => __( 'Please check the highlighted fields.', 'stackmime-forms' ), 'errors' => $errors, ), 422 ); } $page = esc_url_raw( (string) ( $body['page'] ?? '' ) ); if ( $page && wp_parse_url( $page, PHP_URL_HOST ) !== wp_parse_url( home_url(), PHP_URL_HOST ) ) { $page = ''; } $ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; if ( $spam ) { if ( ! $errors ) { stackmime_forms_insert( array( 'form_id' => $form_id, 'status' => 'spam', 'data' => $clean, 'page_url' => $page, 'user_agent' => $ua, 'ip_hash' => $ip_hash, 'spam_reason' => $spam, ) ); } return stackmime_forms_response( $ok ); } // One-time token. $sig = substr( (string) ( $body['token'] ?? '' ), strrpos( (string) ( $body['token'] ?? '' ), '.' ) + 1 ); set_transient( 'stackmime_forms_used_' . md5( $sig ), 1, STACKMIME_FORMS_TOKEN_TTL ); $entry_id = stackmime_forms_insert( array( 'form_id' => $form_id, 'status' => 'new', 'data' => $clean, 'page_url' => $page, 'user_agent' => $ua, 'ip_hash' => $ip_hash, ) ); if ( ! $entry_id ) { return stackmime_forms_response( array( 'code' => 'save_failed', 'message' => stackmime_forms_fail_message(), ), 500 ); } // The entry is safe in the database; email problems never lose the lead. stackmime_forms_send_notification( $entry_id ); stackmime_forms_send_autoreply( $entry_id ); do_action( 'stackmime_forms_submitted', $entry_id, $form_id, $clean ); return stackmime_forms_response( $ok ); }