Esempio n. 1
0
 /**
  * Return access information for a given quiz.
  *
  * @param int $quizid quiz instance id
  * @return array of warnings and the access information
  * @since Moodle 3.1
  * @throws  moodle_quiz_exception
  */
 public static function get_quiz_access_information($quizid)
 {
     global $DB, $USER;
     $warnings = array();
     $params = array('quizid' => $quizid);
     $params = self::validate_parameters(self::get_quiz_access_information_parameters(), $params);
     list($quiz, $course, $cm, $context) = self::validate_quiz($params['quizid']);
     $result = array();
     // Capabilities first.
     $result['canattempt'] = has_capability('mod/quiz:attempt', $context);
     $result['canmanage'] = has_capability('mod/quiz:manage', $context);
     $result['canpreview'] = has_capability('mod/quiz:preview', $context);
     $result['canreviewmyattempts'] = has_capability('mod/quiz:reviewmyattempts', $context);
     $result['canviewreports'] = has_capability('mod/quiz:viewreports', $context);
     // Access manager now.
     $quizobj = quiz::create($cm->instance, $USER->id);
     $ignoretimelimits = has_capability('mod/quiz:ignoretimelimits', $context, null, false);
     $timenow = time();
     $accessmanager = new quiz_access_manager($quizobj, $timenow, $ignoretimelimits);
     $result['accessrules'] = $accessmanager->describe_rules();
     $result['activerulenames'] = $accessmanager->get_active_rule_names();
     $result['preventaccessreasons'] = $accessmanager->prevent_access();
     $result['warnings'] = $warnings;
     return $result;
 }
Esempio n. 2
0
                } else {
                    $buttontext = get_string('reattemptquiz', 'quiz');
                }
            }
        } else {
            if ($canpreview) {
                $buttontext = get_string('previewquiznow', 'quiz');
            }
        }
    }
    // If, so far, we think a button should be printed, so check if they will be allowed to access it.
    if ($buttontext) {
        if (!$moreattempts) {
            $buttontext = '';
        } else {
            if ($canattempt && ($messages = $accessmanager->prevent_access())) {
                $accessmanager->print_messages($messages);
                $buttontext = '';
            }
        }
    }
}
/// Now actually print the appropriate button.
if ($buttontext) {
    $accessmanager->print_start_attempt_button($canpreview, $buttontext, $unfinished);
} else {
    echo $OUTPUT->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id);
}
echo $OUTPUT->box_end();
// Mark module as viewed (note, we do this here and not in finish_page,
// otherwise the 'not enrolled' error conditions would result in marking
function prepareQuizAttempt($q)
{
    global $DB;
    if ($id) {
        if (!($cm = get_coursemodule_from_id('quiz', $id))) {
            print_error('invalidcoursemodule');
        }
        if (!($course = $DB->get_record('course', array('id' => $cm->course)))) {
            print_error('coursemisconf');
        }
        if (!($quiz = $DB->get_record('quiz', array('id' => $cm->instance)))) {
            print_error('invalidcoursemodule');
        }
    } else {
        if (!($quiz = $DB->get_record('quiz', array('id' => $q)))) {
            print_error('invalidquizid', 'quiz');
        }
        if (!($course = $DB->get_record('course', array('id' => $quiz->course)))) {
            print_error('invalidcourseid');
        }
        if (!($cm = get_coursemodule_from_instance("quiz", $quiz->id, $course->id))) {
            print_error('invalidcoursemodule');
        }
    }
    /// Check login and get context.
    require_login($course->id, false, $cm);
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    require_capability('mod/quiz:view', $context);
    /// Cache some other capabilites we use several times.
    $canattempt = has_capability('mod/quiz:attempt', $context);
    $canreviewmine = has_capability('mod/quiz:reviewmyattempts', $context);
    $canpreview = has_capability('mod/quiz:preview', $context);
    /// Create an object to manage all the other (non-roles) access rules.
    $timenow = time();
    $accessmanager = new quiz_access_manager(new quiz($quiz, $cm, $course), $timenow, has_capability('mod/quiz:ignoretimelimits', $context, NULL, false));
    /// Print information about the student's best score for this quiz if possible.
    $moreattempts = $unfinished || !$accessmanager->is_finished($numattempts, $lastfinishedattempt);
    /// Determine if we should be showing a start/continue attempt button,
    /// or a button to go back to the course page.
    print_box_start('quizattempt');
    $buttontext = '';
    // This will be set something if as start/continue attempt button should appear.
    if (!$quiz->questions) {
        print_heading(get_string("noquestions", "quiz"));
    } else {
        if ($unfinished) {
            if ($canattempt) {
                $buttontext = get_string('continueattemptquiz', 'quiz');
            } else {
                if ($canpreview) {
                    $buttontext = get_string('continuepreview', 'quiz');
                }
            }
        } else {
            if ($canattempt) {
                $messages = $accessmanager->prevent_new_attempt($numattempts, $lastfinishedattempt);
                if ($messages) {
                    $accessmanager->print_messages($messages);
                } else {
                    if ($numattempts == 0) {
                        $buttontext = get_string('attemptquiznow', 'quiz');
                    } else {
                        $buttontext = get_string('reattemptquiz', 'quiz');
                    }
                }
            } else {
                if ($canpreview) {
                    $buttontext = get_string('previewquiznow', 'quiz');
                }
            }
        }
        // If, so far, we think a button should be printed, so check if they will be allowed to access it.
        if ($buttontext) {
            if (!$moreattempts) {
                $buttontext = '';
            } else {
                if ($canattempt && ($messages = $accessmanager->prevent_access())) {
                    $accessmanager->print_messages($messages);
                    $buttontext = '';
                }
            }
        }
    }
    /// Now actually print the appropriate button.
    if ($buttontext) {
        $accessmanager->print_start_attempt_button($canpreview, $buttontext, $unfinished);
    } else {
        print_continue($CFG->wwwroot . '/course/view.php?id=' . $course->id);
    }
    print_box_end();
}
Esempio n. 4
0
 /**
  * Returns a list of quizzes in a provided list of courses,
  * if no list is provided all quizzes that the user can view will be returned.
  *
  * @param array $courseids Array of course ids
  * @return array of quizzes details
  * @since Moodle 3.1
  */
 public static function get_quizzes_by_courses($courseids = array())
 {
     global $USER;
     $warnings = array();
     $returnedquizzes = array();
     $params = array('courseids' => $courseids);
     $params = self::validate_parameters(self::get_quizzes_by_courses_parameters(), $params);
     $mycourses = array();
     if (empty($params['courseids'])) {
         $mycourses = enrol_get_my_courses();
         $params['courseids'] = array_keys($mycourses);
     }
     // Ensure there are courseids to loop through.
     if (!empty($params['courseids'])) {
         list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses);
         // Get the quizzes in this course, this function checks users visibility permissions.
         // We can avoid then additional validate_context calls.
         $quizzes = get_all_instances_in_courses("quiz", $courses);
         foreach ($quizzes as $quiz) {
             $context = context_module::instance($quiz->coursemodule);
             // Update quiz with override information.
             $quiz = quiz_update_effective_access($quiz, $USER->id);
             // Entry to return.
             $quizdetails = array();
             // First, we return information that any user can see in the web interface.
             $quizdetails['id'] = $quiz->id;
             $quizdetails['coursemodule'] = $quiz->coursemodule;
             $quizdetails['course'] = $quiz->course;
             $quizdetails['name'] = external_format_string($quiz->name, $context->id);
             if (has_capability('mod/quiz:view', $context)) {
                 // Format intro.
                 list($quizdetails['intro'], $quizdetails['introformat']) = external_format_text($quiz->intro, $quiz->introformat, $context->id, 'mod_quiz', 'intro', null);
                 $viewablefields = array('timeopen', 'timeclose', 'grademethod', 'section', 'visible', 'groupmode', 'groupingid');
                 $timenow = time();
                 $quizobj = quiz::create($quiz->id, $USER->id);
                 $accessmanager = new quiz_access_manager($quizobj, $timenow, has_capability('mod/quiz:ignoretimelimits', $context, null, false));
                 // Fields the user could see if have access to the quiz.
                 if (!$accessmanager->prevent_access()) {
                     // Some times this function returns just empty.
                     $hasfeedback = quiz_has_feedback($quiz);
                     $quizdetails['hasfeedback'] = !empty($hasfeedback) ? 1 : 0;
                     $quizdetails['hasquestions'] = (int) $quizobj->has_questions();
                     $quizdetails['autosaveperiod'] = get_config('quiz', 'autosaveperiod');
                     $additionalfields = array('timelimit', 'attempts', 'attemptonlast', 'grademethod', 'decimalpoints', 'questiondecimalpoints', 'reviewattempt', 'reviewcorrectness', 'reviewmarks', 'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer', 'reviewoverallfeedback', 'questionsperpage', 'navmethod', 'sumgrades', 'grade', 'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks', 'completionattemptsexhausted', 'completionpass', 'overduehandling', 'graceperiod', 'preferredbehaviour', 'canredoquestions');
                     $viewablefields = array_merge($viewablefields, $additionalfields);
                 }
                 // Fields only for managers.
                 if (has_capability('moodle/course:manageactivities', $context)) {
                     $additionalfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
                     $viewablefields = array_merge($viewablefields, $additionalfields);
                 }
                 foreach ($viewablefields as $field) {
                     $quizdetails[$field] = $quiz->{$field};
                 }
             }
             $returnedquizzes[] = $quizdetails;
         }
     }
     $result = array();
     $result['quizzes'] = $returnedquizzes;
     $result['warnings'] = $warnings;
     return $result;
 }
Esempio n. 5
0
/**
 * Validate permissions for creating a new attempt and start a new preview attempt if required.
 *
 * @param  quiz $quizobj quiz object
 * @param  quiz_access_manager $accessmanager quiz access manager
 * @param  bool $forcenew whether was required to start a new preview attempt
 * @param  int $page page to jump to in the attempt
 * @param  bool $redirect whether to redirect or throw exceptions (for web or ws usage)
 * @return array an array containing the attempt information, access error messages and the page to jump to in the attempt
 * @throws moodle_quiz_exception
 * @since Moodle 3.1
 */
function quiz_validate_new_attempt(quiz $quizobj, quiz_access_manager $accessmanager, $forcenew, $page, $redirect)
{
    global $DB, $USER;
    $timenow = time();
    if ($quizobj->is_preview_user() && $forcenew) {
        $accessmanager->current_attempt_finished();
    }
    // Check capabilities.
    if (!$quizobj->is_preview_user()) {
        $quizobj->require_capability('mod/quiz:attempt');
    }
    // Check to see if a new preview was requested.
    if ($quizobj->is_preview_user() && $forcenew) {
        // To force the creation of a new preview, we mark the current attempt (if any)
        // as finished. It will then automatically be deleted below.
        $DB->set_field('quiz_attempts', 'state', quiz_attempt::FINISHED, array('quiz' => $quizobj->get_quizid(), 'userid' => $USER->id));
    }
    // Look for an existing attempt.
    $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id, 'all', true);
    $lastattempt = end($attempts);
    $attemptnumber = null;
    // If an in-progress attempt exists, check password then redirect to it.
    if ($lastattempt && ($lastattempt->state == quiz_attempt::IN_PROGRESS || $lastattempt->state == quiz_attempt::OVERDUE)) {
        $currentattemptid = $lastattempt->id;
        $messages = $accessmanager->prevent_access();
        // If the attempt is now overdue, deal with that.
        $quizobj->create_attempt_object($lastattempt)->handle_if_time_expired($timenow, true);
        // And, if the attempt is now no longer in progress, redirect to the appropriate place.
        if ($lastattempt->state == quiz_attempt::ABANDONED || $lastattempt->state == quiz_attempt::FINISHED) {
            if ($redirect) {
                redirect($quizobj->review_url($lastattempt->id));
            } else {
                throw new moodle_quiz_exception($quizobj, 'attemptalreadyclosed');
            }
        }
        // If the page number was not explicitly in the URL, go to the current page.
        if ($page == -1) {
            $page = $lastattempt->currentpage;
        }
    } else {
        while ($lastattempt && $lastattempt->preview) {
            $lastattempt = array_pop($attempts);
        }
        // Get number for the next or unfinished attempt.
        if ($lastattempt) {
            $attemptnumber = $lastattempt->attempt + 1;
        } else {
            $lastattempt = false;
            $attemptnumber = 1;
        }
        $currentattemptid = null;
        $messages = $accessmanager->prevent_access() + $accessmanager->prevent_new_attempt(count($attempts), $lastattempt);
        if ($page == -1) {
            $page = 0;
        }
    }
    return array($currentattemptid, $attemptnumber, $lastattempt, $messages, $page);
}