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