protected function reopen_submission_if_required($userid, $submission, $addattempt) {
        $instance = $this->get_instance();
        $maxattemptsreached = !empty($submission) &&
                              $submission->attemptnumber >= ($instance->maxattempts - 1) &&
                              $instance->maxattempts != ASSIGN_UNLIMITED_ATTEMPTS;
        $shouldreopen = false;
        if ($instance->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS) {
            // Check the gradetopass from the gradebook.
            $gradeitem = $this->get_grade_item();
            if ($gradeitem) {
                $gradegrade = grade_grade::fetch(array('userid' => $userid, 'itemid' => $gradeitem->id));

                // Do not reopen if is_passed returns null, e.g. if there is no pass criterion set.
                if ($gradegrade && ($gradegrade->is_passed() === false)) {
                    $shouldreopen = true;
                }
            }
        }
        if ($instance->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL &&
                !empty($addattempt)) {
            $shouldreopen = true;
        }
        if ($shouldreopen && !$maxattemptsreached) {
            $this->add_attempt($userid);
            return true;
        }
        return false;
    }