MDL-35868: quiz: Use correct attemptnumber when a last attempt exists.
[moodle.git] / mod / quiz / startattempt.php
CommitLineData
83192608 1<?php
7c5bd5bf
TH
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.
13//
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/>.
16
78e7a3dd 17/**
7c5bd5bf 18 * This script deals with starting a new attempt at a quiz.
78e7a3dd 19 *
20 * Normally, it will end up redirecting to attempt.php - unless a password form is displayed.
21 *
ccc45155 22 * This code used to be at the top of attempt.php, if you are looking for CVS history.
23 *
34b7d838
TH
24 * @package mod_quiz
25 * @copyright 2009 The Open University
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
78e7a3dd 27 */
28
29require_once(dirname(__FILE__) . '/../../config.php');
30require_once($CFG->dirroot . '/mod/quiz/locallib.php');
31
7c5bd5bf 32// Get submitted parameters.
da729916 33$id = required_param('cmid', PARAM_INT); // Course module id
78e7a3dd 34$forcenew = optional_param('forcenew', false, PARAM_BOOL); // Used to force a new preview
5db82949 35$page = optional_param('page', -1, PARAM_INT); // Page to jump to in the attempt.
78e7a3dd 36
37if (!$cm = get_coursemodule_from_id('quiz', $id)) {
38 print_error('invalidcoursemodule');
39}
40if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
41 print_error("coursemisconf");
42}
78e7a3dd 43
dd70d561 44$quizobj = quiz::create($cm->instance, $USER->id);
a88ba570
TH
45// This script should only ever be posted to, so set page URL to the view page.
46$PAGE->set_url($quizobj->view_url());
78e7a3dd 47
7c5bd5bf 48// Check login and sesskey.
cdbea7ee 49require_login($quizobj->get_course(), false, $quizobj->get_cm());
88f0eb15 50require_sesskey();
78e7a3dd 51
9e83f3d1 52// If no questions have been set up yet redirect to edit.php or display an error.
18dff757
TH
53if (!$quizobj->has_questions()) {
54 if ($quizobj->has_capability('mod/quiz:manage')) {
55 redirect($quizobj->edit_url());
56 } else {
57 print_error('cannotstartnoquestions', 'quiz', $quizobj->view_url());
58 }
78e7a3dd 59}
60
7c5bd5bf 61// Create an object to manage all the other (non-roles) access rules.
34b7d838
TH
62$timenow = time();
63$accessmanager = $quizobj->get_access_manager($timenow);
78e7a3dd 64if ($quizobj->is_preview_user() && $forcenew) {
987c2d49 65 $accessmanager->current_attempt_finished();
78e7a3dd 66}
67
7c5bd5bf 68// Check capabilities.
78e7a3dd 69if (!$quizobj->is_preview_user()) {
70 $quizobj->require_capability('mod/quiz:attempt');
71}
72
7c5bd5bf 73// Check to see if a new preview was requested.
78e7a3dd 74if ($quizobj->is_preview_user() && $forcenew) {
34b7d838 75 // To force the creation of a new preview, we mark the current attempt (if any)
9e83f3d1 76 // as finished. It will then automatically be deleted below.
34b7d838 77 $DB->set_field('quiz_attempts', 'state', quiz_attempt::FINISHED,
dd70d561 78 array('quiz' => $quizobj->get_quizid(), 'userid' => $USER->id));
78e7a3dd 79}
80
7c5bd5bf 81// Look for an existing attempt.
987c2d49 82$attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id, 'all', true);
3461dbad 83$lastattempt = end($attempts);
78e7a3dd 84
3461dbad 85// If an in-progress attempt exists, check password then redirect to it.
34b7d838
TH
86if ($lastattempt && ($lastattempt->state == quiz_attempt::IN_PROGRESS ||
87 $lastattempt->state == quiz_attempt::OVERDUE)) {
987c2d49
TH
88 $currentattemptid = $lastattempt->id;
89 $messages = $accessmanager->prevent_access();
c5fd1682 90
34b7d838 91 // If the attempt is now overdue, deal with that.
a403bce0 92 $quizobj->create_attempt_object($lastattempt)->handle_if_time_expired($timenow, true);
34b7d838
TH
93
94 // And, if the attempt is now no longer in progress, redirect to the appropriate place.
95 if ($lastattempt->state == quiz_attempt::OVERDUE) {
96 redirect($quizobj->summary_url($lastattempt->id));
97 } else if ($lastattempt->state != quiz_attempt::IN_PROGRESS) {
98 redirect($quizobj->review_url($lastattempt->id));
99 }
100
101 // If the page number was not explicitly in the URL, go to the current page.
5db82949
CF
102 if ($page == -1) {
103 $page = $lastattempt->currentpage;
104 }
78e7a3dd 105
78e7a3dd 106} else {
9e83f3d1 107 // Get number for the next or unfinished attempt.
be47011d 108 if ($lastattempt) {
987c2d49
TH
109 $attemptnumber = $lastattempt->attempt + 1;
110 } else {
111 $lastattempt = false;
112 $attemptnumber = 1;
113 }
114 $currentattemptid = null;
115
116 $messages = $accessmanager->prevent_access() +
117 $accessmanager->prevent_new_attempt(count($attempts), $lastattempt);
5db82949
CF
118
119 if ($page == -1) {
c5fd1682 120 $page = 0;
5db82949 121 }
78e7a3dd 122}
123
7c5bd5bf 124// Check access.
987c2d49 125$output = $PAGE->get_renderer('mod_quiz');
78e7a3dd 126if (!$quizobj->is_preview_user() && $messages) {
127 print_error('attempterror', 'quiz', $quizobj->view_url(),
7238cd2e 128 $output->access_messages($messages));
78e7a3dd 129}
d755b0f5 130
987c2d49
TH
131if ($accessmanager->is_preflight_check_required($currentattemptid)) {
132 // Need to do some checks before allowing the user to continue.
133 $mform = $accessmanager->get_preflight_check_form(
134 $quizobj->start_attempt_url($page), $currentattemptid);
135
136 if ($mform->is_cancelled()) {
137 $accessmanager->back_to_view_page($output);
138
139 } else if (!$mform->get_data()) {
140
141 // Form not submitted successfully, re-display it and stop.
142 $PAGE->set_url($quizobj->start_attempt_url($page));
143 $PAGE->set_title(format_string($quizobj->get_quiz_name()));
144 $accessmanager->setup_attempt_page($PAGE);
145 if (empty($quizobj->get_quiz()->showblocks)) {
146 $PAGE->blocks->show_only_fake_blocks();
147 }
148
149 echo $output->start_attempt_page($quizobj, $mform);
150 die();
151 }
152
153 // Pre-flight check passed.
154 $accessmanager->notify_preflight_check_passed($currentattemptid);
155}
156if ($currentattemptid) {
157 redirect($quizobj->attempt_url($currentattemptid, $page));
158}
78e7a3dd 159
7c5bd5bf 160// Delete any previous preview attempts belonging to this user.
dd70d561 161quiz_delete_previews($quizobj->get_quiz(), $USER->id);
78e7a3dd 162
7c5bd5bf 163$quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
dd70d561 164$quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
7c5bd5bf
TH
165
166// Create the new attempt and initialize the question sessions
34b7d838 167$timenow = time(); // Update time now, in case the server is running really slowly.
8e771aed 168$attempt = quiz_create_attempt($quizobj, $attemptnumber, $lastattempt, $timenow,
55ca80ed 169 $quizobj->is_preview_user());
78e7a3dd 170
dd70d561 171if (!($quizobj->get_quiz()->attemptonlast && $lastattempt)) {
7c5bd5bf
TH
172 // Starting a normal, new, quiz attempt.
173
174 // Fully load all the questions in this quiz.
175 $quizobj->preload_questions();
176 $quizobj->load_questions();
177
178 // Add them all to the $quba.
179 $idstoslots = array();
180 $questionsinuse = array_keys($quizobj->get_questions());
181 foreach ($quizobj->get_questions() as $i => $questiondata) {
182 if ($questiondata->qtype != 'random') {
dd70d561 183 if (!$quizobj->get_quiz()->shuffleanswers) {
7c5bd5bf
TH
184 $questiondata->options->shuffleanswers = false;
185 }
186 $question = question_bank::make_question($questiondata);
187
188 } else {
189 $question = question_bank::get_qtype('random')->choose_other_question(
dd70d561 190 $questiondata, $questionsinuse, $quizobj->get_quiz()->shuffleanswers);
7c5bd5bf
TH
191 if (is_null($question)) {
192 throw new moodle_exception('notenoughrandomquestions', 'quiz',
193 $quizobj->view_url(), $questiondata);
194 }
195 }
196
197 $idstoslots[$i] = $quba->add_question($question, $questiondata->maxmark);
198 $questionsinuse[] = $question->id;
199 }
200
c014b989
TH
201 // Start all the questions.
202 if ($attempt->preview) {
203 $variantoffset = rand(1, 100);
204 } else {
205 $variantoffset = $attemptnumber;
206 }
207 $quba->start_all_questions(
34b7d838 208 new question_variant_pseudorandom_no_repeats_strategy($variantoffset), $timenow);
7c5bd5bf
TH
209
210 // Update attempt layout.
211 $newlayout = array();
212 foreach (explode(',', $attempt->layout) as $qid) {
213 if ($qid != 0) {
214 $newlayout[] = $idstoslots[$qid];
215 } else {
216 $newlayout[] = 0;
217 }
218 }
219 $attempt->layout = implode(',', $newlayout);
220
221} else {
222 // Starting a subsequent attempt in each attempt builds on last mode.
223
224 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
225
226 $oldnumberstonew = array();
227 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
228 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
229
230 $quba->start_question_based_on($newslot, $oldqa);
78e7a3dd 231
7c5bd5bf
TH
232 $oldnumberstonew[$oldslot] = $newslot;
233 }
234
235 // Update attempt layout.
236 $newlayout = array();
237 foreach (explode(',', $lastattempt->layout) as $oldslot) {
238 if ($oldslot != 0) {
239 $newlayout[] = $oldnumberstonew[$oldslot];
240 } else {
241 $newlayout[] = 0;
242 }
243 }
244 $attempt->layout = implode(',', $newlayout);
245}
246
247// Save the attempt in the database.
a1eb3a44 248$transaction = $DB->start_delegated_transaction();
7c5bd5bf
TH
249question_engine::save_questions_usage_by_activity($quba);
250$attempt->uniqueid = $quba->get_id();
88f0eb15 251$attempt->id = $DB->insert_record('quiz_attempts', $attempt);
7c5bd5bf
TH
252
253// Log the new attempt.
78e7a3dd 254if ($attempt->preview) {
b1103f2b 255 add_to_log($course->id, 'quiz', 'preview', 'view.php?id=' . $quizobj->get_cmid(),
256 $quizobj->get_quizid(), $quizobj->get_cmid());
78e7a3dd 257} else {
b1103f2b 258 add_to_log($course->id, 'quiz', 'attempt', 'review.php?attempt=' . $attempt->id,
259 $quizobj->get_quizid(), $quizobj->get_cmid());
78e7a3dd 260}
261
9e83f3d1 262// Trigger event.
39790bd8 263$eventdata = new stdClass();
cbb8b55c
TH
264$eventdata->component = 'mod_quiz';
265$eventdata->attemptid = $attempt->id;
266$eventdata->timestart = $attempt->timestart;
a403bce0 267$eventdata->timestamp = $attempt->timestart;
cbb8b55c
TH
268$eventdata->userid = $attempt->userid;
269$eventdata->quizid = $quizobj->get_quizid();
270$eventdata->cmid = $quizobj->get_cmid();
271$eventdata->courseid = $quizobj->get_courseid();
9df209c1 272events_trigger('quiz_attempt_started', $eventdata);
78e7a3dd 273
a1eb3a44 274$transaction->allow_commit();
7c5bd5bf
TH
275
276// Redirect to the attempt page.
da729916 277redirect($quizobj->attempt_url($attempt->id, $page));