MDL-31095 quiz editing: only set quiz->grade to 0 if really necessary.
[moodle.git] / mod / quiz / startattempt.php
blob5014fb3afe31154e88884995e6345bab874dbc97
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This script deals with starting a new attempt at a quiz.
20 * Normally, it will end up redirecting to attempt.php - unless a password form is displayed.
22 * This code used to be at the top of attempt.php, if you are looking for CVS history.
24 * @package mod
25 * @subpackage quiz
26 * @copyright 2009 The Open University
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 require_once(dirname(__FILE__) . '/../../config.php');
31 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
33 // Get submitted parameters.
34 $id = required_param('cmid', PARAM_INT); // Course module id
35 $forcenew = optional_param('forcenew', false, PARAM_BOOL); // Used to force a new preview
36 $page = optional_param('page', 0, PARAM_INT); // Page to jump to in the attempt.
38 if (!$cm = get_coursemodule_from_id('quiz', $id)) {
39 print_error('invalidcoursemodule');
41 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
42 print_error("coursemisconf");
44 if (!$quiz = $DB->get_record('quiz', array('id' => $cm->instance))) {
45 print_error('invalidcoursemodule');
48 $quizobj = quiz::create($quiz->id, $USER->id);
49 // This script should only ever be posted to, so set page URL to the view page.
50 $PAGE->set_url($quizobj->view_url());
52 // Check login and sesskey.
53 require_login($quizobj->get_courseid(), false, $quizobj->get_cm());
54 require_sesskey();
55 $PAGE->set_pagelayout('base');
57 // if no questions have been set up yet redirect to edit.php or display an error.
58 if (!$quizobj->has_questions()) {
59 if ($quizobj->has_capability('mod/quiz:manage')) {
60 redirect($quizobj->edit_url());
61 } else {
62 print_error('cannotstartnoquestions', 'quiz', $quizobj->view_url());
66 // Create an object to manage all the other (non-roles) access rules.
67 $accessmanager = $quizobj->get_access_manager(time());
68 if ($quizobj->is_preview_user() && $forcenew) {
69 $accessmanager->clear_password_access();
72 // Check capabilities.
73 if (!$quizobj->is_preview_user()) {
74 $quizobj->require_capability('mod/quiz:attempt');
77 // Check to see if a new preview was requested.
78 if ($quizobj->is_preview_user() && $forcenew) {
79 // To force the creation of a new preview, we set a finish time on the
80 // current attempt (if any). It will then automatically be deleted below
81 $DB->set_field('quiz_attempts', 'timefinish', time(),
82 array('quiz' => $quiz->id, 'userid' => $USER->id));
85 // Look for an existing attempt.
86 $attempts = quiz_get_user_attempts($quiz->id, $USER->id, 'all');
87 $lastattempt = end($attempts);
89 // If an in-progress attempt exists, check password then redirect to it.
90 if ($lastattempt && !$lastattempt->timefinish) {
91 $accessmanager->do_password_check($quizobj->is_preview_user());
92 redirect($quizobj->attempt_url($lastattempt->id, $page));
95 // Get number for the next or unfinished attempt
96 if ($lastattempt && !$lastattempt->preview && !$quizobj->is_preview_user()) {
97 $attemptnumber = $lastattempt->attempt + 1;
98 } else {
99 $lastattempt = false;
100 $attemptnumber = 1;
103 // Check access.
104 $messages = $accessmanager->prevent_access() +
105 $accessmanager->prevent_new_attempt(count($attempts), $lastattempt);
106 if (!$quizobj->is_preview_user() && $messages) {
107 $output = $PAGE->get_renderer('mod_quiz');
108 print_error('attempterror', 'quiz', $quizobj->view_url(),
109 $output->access_messages($messages));
111 $accessmanager->do_password_check($quizobj->is_preview_user());
113 // Delete any previous preview attempts belonging to this user.
114 quiz_delete_previews($quiz, $USER->id);
116 $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
117 $quba->set_preferred_behaviour($quiz->preferredbehaviour);
119 // Create the new attempt and initialize the question sessions
120 $attempt = quiz_create_attempt($quiz, $attemptnumber, $lastattempt, time(),
121 $quizobj->is_preview_user());
123 if (!($quiz->attemptonlast && $lastattempt)) {
124 // Starting a normal, new, quiz attempt.
126 // Fully load all the questions in this quiz.
127 $quizobj->preload_questions();
128 $quizobj->load_questions();
130 // Add them all to the $quba.
131 $idstoslots = array();
132 $questionsinuse = array_keys($quizobj->get_questions());
133 foreach ($quizobj->get_questions() as $i => $questiondata) {
134 if ($questiondata->qtype != 'random') {
135 if (!$quiz->shuffleanswers) {
136 $questiondata->options->shuffleanswers = false;
138 $question = question_bank::make_question($questiondata);
140 } else {
141 $question = question_bank::get_qtype('random')->choose_other_question(
142 $questiondata, $questionsinuse, $quiz->shuffleanswers);
143 if (is_null($question)) {
144 throw new moodle_exception('notenoughrandomquestions', 'quiz',
145 $quizobj->view_url(), $questiondata);
149 $idstoslots[$i] = $quba->add_question($question, $questiondata->maxmark);
150 $questionsinuse[] = $question->id;
153 // Start all the questions.
154 if ($attempt->preview) {
155 $variantoffset = rand(1, 100);
156 } else {
157 $variantoffset = $attemptnumber;
159 $quba->start_all_questions(
160 new question_variant_pseudorandom_no_repeats_strategy($variantoffset),
161 time());
163 // Update attempt layout.
164 $newlayout = array();
165 foreach (explode(',', $attempt->layout) as $qid) {
166 if ($qid != 0) {
167 $newlayout[] = $idstoslots[$qid];
168 } else {
169 $newlayout[] = 0;
172 $attempt->layout = implode(',', $newlayout);
174 } else {
175 // Starting a subsequent attempt in each attempt builds on last mode.
177 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
179 $oldnumberstonew = array();
180 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
181 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
183 $quba->start_question_based_on($newslot, $oldqa);
185 $oldnumberstonew[$oldslot] = $newslot;
188 // Update attempt layout.
189 $newlayout = array();
190 foreach (explode(',', $lastattempt->layout) as $oldslot) {
191 if ($oldslot != 0) {
192 $newlayout[] = $oldnumberstonew[$oldslot];
193 } else {
194 $newlayout[] = 0;
197 $attempt->layout = implode(',', $newlayout);
200 // Save the attempt in the database.
201 $transaction = $DB->start_delegated_transaction();
202 question_engine::save_questions_usage_by_activity($quba);
203 $attempt->uniqueid = $quba->get_id();
204 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
206 // Log the new attempt.
207 if ($attempt->preview) {
208 add_to_log($course->id, 'quiz', 'preview', 'view.php?id=' . $quizobj->get_cmid(),
209 $quizobj->get_quizid(), $quizobj->get_cmid());
210 } else {
211 add_to_log($course->id, 'quiz', 'attempt', 'review.php?attempt=' . $attempt->id,
212 $quizobj->get_quizid(), $quizobj->get_cmid());
215 // Trigger event
216 $eventdata = new stdClass();
217 $eventdata->component = 'mod_quiz';
218 $eventdata->attemptid = $attempt->id;
219 $eventdata->timestart = $attempt->timestart;
220 $eventdata->userid = $attempt->userid;
221 $eventdata->quizid = $quizobj->get_quizid();
222 $eventdata->cmid = $quizobj->get_cmid();
223 $eventdata->courseid = $quizobj->get_courseid();
224 events_trigger('quiz_attempt_started', $eventdata);
226 $transaction->allow_commit();
228 // Redirect to the attempt page.
229 redirect($quizobj->attempt_url($attempt->id, $page));