LLMS_AJAX_Handler::quiz_answer_question( array $request )

AJAX Quiz answer question.


Parameters Parameters

$request

(array) (Required) $_POST data.


Top ↑

Return Return

(WP_Error|string)


Top ↑

Source Source

File: includes/class.llms.ajax.handler.php

			'question_id' => $question_id,
		);
	}

	/**
	 * AJAX Quiz answer question.
	 *
	 * @since 3.9.0
	 * @since 3.27.0 Unknown.
	 * @since 6.4.0 Make sure attempts limit was not reached.
	 *
	 * @param array $request $_POST data.
	 * @return WP_Error|string
	 */
	public static function quiz_answer_question( $request ) {

		$err = new WP_Error();

		$student = llms_get_student();
		if ( ! $student ) {
			$err->add( 400, __( 'You must be logged in to take quizzes.', 'lifterlms' ) );
			return $err;
		}

		$required = array( 'attempt_key', 'question_id', 'question_type' );
		foreach ( $required as $key ) {
			if ( ! isset( $request[ $key ] ) ) {
				$err->add( 400, __( 'Missing required parameters. Could not proceed.', 'lifterlms' ) );
				return $err;
			}
		}

		$attempt_key = sanitize_text_field( $request['attempt_key'] );
		$question_id = absint( $request['question_id'] );
		$answer      = array_map( 'stripslashes_deep', isset( $request['answer'] ) ? $request['answer'] : array() );

		$student_quizzes = $student->quizzes();
		$attempt         = $student_quizzes->get_attempt_by_key( $attempt_key );
		if ( ! $attempt || 'incomplete' !== $attempt->get( 'status' ) || ( $attempt->get_quiz()->can_be_resumed() && ! $attempt->can_be_resumed() ) ) {
			$err->add( 500, __( 'There was an error recording your answer. Please return to the lesson and begin again.', 'lifterlms' ) );
			return $err;
		}

		$access_check = self::verify_quiz_access( $student, $attempt->get( 'lesson_id' ) );
		if ( is_wp_error( $access_check ) ) {
			return $access_check;
		}

		/**
		 * Check limit not reached.
		 *
		 * First check whether the quiz is open (so to leverage the `llms_quiz_is_open` filter ),
		 * if not, check also for remaining attempts.
		 *
		 * At this point the current attempt has already been counted (maybe the last allowed),
		 * so we check that the remaining attempt is just greater than -1.
		 */
		$quiz_id = $attempt->get( 'quiz_id' );
		if ( ! ( new LLMS_Quiz( $quiz_id ) )->is_open() &&
				$student_quizzes->get_attempts_remaining_for_quiz( $quiz_id, true ) < 0 ) {
			$err->add( 400, __( "You've reached the maximum number of attempts for this quiz.", 'lifterlms' ) );
			return $err;
		}

		// record the answer.
		$attempt->answer_question( $question_id, $answer );

		if ( isset( $request['via_previous_question'] ) ) {
			$attempt->set( 'current_question_id', $attempt->get_previous_question( $question_id ) );
			$attempt->save();

			return;
		}


Top ↑

Changelog Changelog

Changelog
Version Description
6.4.0 Make sure attempts limit was not reached.
3.9.0
3.27.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.