100 ) { self::invalid(); } $result = array(); foreach ( $input as $key => $value ) { if ( ! is_string( $key ) || sanitize_key( $key ) !== $key ) { self::invalid(); } $type = '_wp_http_referer' === $key ? 'url' : ( $types[ $key ] ?? 'text' ); $result[ $key ] = self::value( $value, $type, 0 ); } return $result; } /** * Sanitize strings and bounded arrays; keep original scalar types for validation. * * @param mixed $value Unslashed submitted value. * @param string $type Declared field representation. * @param int $depth Current nested-array depth. * @return mixed Sanitized value. */ private static function value( $value, string $type, int $depth ) { if ( is_array( $value ) ) { if ( $depth >= 5 || count( $value ) > 100 ) { self::invalid(); } $result = array(); foreach ( $value as $key => $item ) { if ( ! is_int( $key ) && ( ! is_string( $key ) || sanitize_key( $key ) !== $key ) ) { self::invalid(); } $result[ $key ] = self::value( $item, $type, $depth + 1 ); } return $result; } if ( ! is_string( $value ) || strlen( $value ) > 65536 ) { self::invalid(); } if ( 'json' === $type ) { $decoded = json_decode( $value, true, 16 ); if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $decoded ) ) { self::invalid(); } $encoded = wp_json_encode( $decoded, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); if ( ! is_string( $encoded ) ) { self::invalid(); } return $encoded; } if ( 'textarea' === $type ) { // Browser textareas use CRLF. Preserve lines, allowing only their usual outer whitespace. $value = trim( str_replace( array( "\r\n", "\r" ), "\n", $value ) ); $clean = sanitize_textarea_field( $value ); } elseif ( 'url' === $type ) { $clean = sanitize_url( $value, array( 'http', 'https' ) ); } else { $clean = sanitize_text_field( $value ); } if ( $clean !== $value ) { self::invalid(); } return $clean; } /** Reject invalid input before it can be mistaken for a different valid operation. */ private static function invalid(): void { wp_die( esc_html__( 'The submitted fields contain invalid text. Reload the form and try again.', 'logged-ai' ), '', array( 'response' => 400 ) ); } }