'POST', 'callback' => array( $this, 'handle_request' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'entry' => array( 'required' => true, 'type' => 'string', ), 'rating' => array( 'required' => true, 'type' => 'string', ), 'profile' => array( 'required' => false, 'type' => 'string', ), ), ) ); } /** * Feedback follows the same audience as the chat itself. * * That includes the chat's profile: guests allowed by a profile could chat but not * rate the answers when only the main setting was read here. * * @param WP_REST_Request|null $request Request instance. * @return true|WP_Error */ public function check_permission( $request = null ) { if ( ! AI_Chat_Bedrock_Conversations::enabled() ) { return new WP_Error( 'aicfab_feedback_disabled', __( 'Feedback is not collected on this site.', 'ai-chat-for-amazon-bedrock' ), array( 'status' => 404 ) ); } $profile = $request ? AI_Chat_Bedrock_Profiles::sanitize_key( (string) $request->get_param( 'profile' ) ) : ''; if ( ! AI_Chat_Bedrock_Security::can_use_chat( AI_Chat_Bedrock_Profiles::resolve( $profile ) ) ) { return new WP_Error( 'aicfab_forbidden', __( 'Please sign in to send feedback.', 'ai-chat-for-amazon-bedrock' ), array( 'status' => 401 ) ); } if ( ! AI_Chat_Bedrock_Security::check_rate_limit( 'feedback', self::RATE_LIMIT ) ) { return new WP_Error( 'aicfab_rate_limited', __( 'Too many requests. Please wait a moment.', 'ai-chat-for-amazon-bedrock' ), array( 'status' => 429 ) ); } return true; } /** * Store one rating. * * @param WP_REST_Request $request Request instance. * @return WP_REST_Response|WP_Error */ public function handle_request( $request ) { $entry = (string) $request->get_param( 'entry' ); $rating = strtolower( trim( (string) $request->get_param( 'rating' ) ) ); if ( ! in_array( $rating, array( 'up', 'down' ), true ) ) { return new WP_Error( 'aicfab_invalid_rating', __( 'The rating must be up or down.', 'ai-chat-for-amazon-bedrock' ), array( 'status' => 400 ) ); } $stored = AI_Chat_Bedrock_Conversations::rate( $entry, 'up' === $rating ? 1 : -1 ); if ( ! $stored ) { return new WP_Error( 'aicfab_unknown_entry', __( 'That answer is no longer available for feedback.', 'ai-chat-for-amazon-bedrock' ), array( 'status' => 404 ) ); } return rest_ensure_response( array( 'recorded' => true ) ); } }