MDL-37961 webservice: PARAM_BOOL with PARAM_DEFAULT accepts boolean default
[moodle.git] / mod / quiz / startattempt.php
blob374db3fc7f46b577dd866223f86d40066e34ccba
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_quiz
25 * @copyright 2009 The Open University
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 require_once(dirname(__FILE__) . '/../../config.php');
30 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
32 // Get submitted parameters.
33 $id = required_param('cmid', PARAM_INT); // Course module id
34 $forcenew = optional_param('forcenew', false, PARAM_BOOL); // Used to force a new preview
35 $page = optional_param('page', -1, PARAM_INT); // Page to jump to in the attempt.
37 if (!$cm = get_coursemodule_from_id('quiz', $id)) {
38 print_error('invalidcoursemodule');
40 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
41 print_error("coursemisconf");
44 $quizobj = quiz::create($cm->instance, $USER->id);
45 // This script should only ever be posted to, so set page URL to the view page.
46 $PAGE->set_url($quizobj->view_url());
48 // Check login and sesskey.
49 require_login($quizobj->get_course(), false, $quizobj->get_cm());
50 require_sesskey();
52 // If no questions have been set up yet redirect to edit.php or display an error.
53 if (!$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());
61 // Create an object to manage all the other (non-roles) access rules.
62 $timenow = time();
63 $accessmanager = $quizobj->get_access_manager($timenow);
64 if ($quizobj->is_preview_user() && $forcenew) {
65 $accessmanager->current_attempt_finished();
68 // Check capabilities.
69 if (!$quizobj->is_preview_user()) {
70 $quizobj->require_capability('mod/quiz:attempt');
73 // Check to see if a new preview was requested.
74 if ($quizobj->is_preview_user() && $forcenew) {
75 // To force the creation of a new preview, we mark the current attempt (if any)
76 // as finished. It will then automatically be deleted below.
77 $DB->set_field('quiz_attempts', 'state', quiz_attempt::FINISHED,
78 array('quiz' => $quizobj->get_quizid(), 'userid' => $USER->id));
81 // Look for an existing attempt.
82 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id, 'all', true);
83 $lastattempt = end($attempts);
85 // If an in-progress attempt exists, check password then redirect to it.
86 if ($lastattempt && ($lastattempt->state == quiz_attempt::IN_PROGRESS ||
87 $lastattempt->state == quiz_attempt::OVERDUE)) {
88 $currentattemptid = $lastattempt->id;
89 $messages = $accessmanager->prevent_access();
91 // If the attempt is now overdue, deal with that.
92 $quizobj->create_attempt_object($lastattempt)->handle_if_time_expired($timenow, true);
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));
101 // If the page number was not explicitly in the URL, go to the current page.
102 if ($page == -1) {
103 $page = $lastattempt->currentpage;
106 } else {
107 // Get number for the next or unfinished attempt.
108 if ($lastattempt && !$lastattempt->preview && !$quizobj->is_preview_user()) {
109 $attemptnumber = $lastattempt->attempt + 1;
110 } else {
111 $lastattempt = false;
112 $attemptnumber = 1;
114 $currentattemptid = null;
116 $messages = $accessmanager->prevent_access() +
117 $accessmanager->prevent_new_attempt(count($attempts), $lastattempt);
119 if ($page == -1) {
120 $page = 0;
124 // Check access.
125 $output = $PAGE->get_renderer('mod_quiz');
126 if (!$quizobj->is_preview_user() && $messages) {
127 print_error('attempterror', 'quiz', $quizobj->view_url(),
128 $output->access_messages($messages));
131 if ($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);
136 if ($mform->is_cancelled()) {
137 $accessmanager->back_to_view_page($output);
139 } else if (!$mform->get_data()) {
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();
149 echo $output->start_attempt_page($quizobj, $mform);
150 die();
153 // Pre-flight check passed.
154 $accessmanager->notify_preflight_check_passed($currentattemptid);
156 if ($currentattemptid) {
157 redirect($quizobj->attempt_url($currentattemptid, $page));
160 // Delete any previous preview attempts belonging to this user.
161 quiz_delete_previews($quizobj->get_quiz(), $USER->id);
163 $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
164 $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
166 // Create the new attempt and initialize the question sessions
167 $timenow = time(); // Update time now, in case the server is running really slowly.
168 $attempt = quiz_create_attempt($quizobj, $attemptnumber, $lastattempt, $timenow,
169 $quizobj->is_preview_user());
171 if (!($quizobj->get_quiz()->attemptonlast && $lastattempt)) {
172 // Starting a normal, new, quiz attempt.
174 // Fully load all the questions in this quiz.
175 $quizobj->preload_questions();
176 $quizobj->load_questions();
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') {
183 if (!$quizobj->get_quiz()->shuffleanswers) {
184 $questiondata->options->shuffleanswers = false;
186 $question = question_bank::make_question($questiondata);
188 } else {
189 $question = question_bank::get_qtype('random')->choose_other_question(
190 $questiondata, $questionsinuse, $quizobj->get_quiz()->shuffleanswers);
191 if (is_null($question)) {
192 throw new moodle_exception('notenoughrandomquestions', 'quiz',
193 $quizobj->view_url(), $questiondata);
197 $idstoslots[$i] = $quba->add_question($question, $questiondata->maxmark);
198 $questionsinuse[] = $question->id;
201 // Start all the questions.
202 if ($attempt->preview) {
203 $variantoffset = rand(1, 100);
204 } else {
205 $variantoffset = $attemptnumber;
207 $quba->start_all_questions(
208 new question_variant_pseudorandom_no_repeats_strategy($variantoffset), $timenow);
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;
219 $attempt->layout = implode(',', $newlayout);
221 } else {
222 // Starting a subsequent attempt in each attempt builds on last mode.
224 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
226 $oldnumberstonew = array();
227 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
228 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
230 $quba->start_question_based_on($newslot, $oldqa);
232 $oldnumberstonew[$oldslot] = $newslot;
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;
244 $attempt->layout = implode(',', $newlayout);
247 // Save the attempt in the database.
248 $transaction = $DB->start_delegated_transaction();
249 question_engine::save_questions_usage_by_activity($quba);
250 $attempt->uniqueid = $quba->get_id();
251 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
253 // Log the new attempt.
254 if ($attempt->preview) {
255 add_to_log($course->id, 'quiz', 'preview', 'view.php?id=' . $quizobj->get_cmid(),
256 $quizobj->get_quizid(), $quizobj->get_cmid());
257 } else {
258 add_to_log($course->id, 'quiz', 'attempt', 'review.php?attempt=' . $attempt->id,
259 $quizobj->get_quizid(), $quizobj->get_cmid());
262 // Trigger event.
263 $eventdata = new stdClass();
264 $eventdata->component = 'mod_quiz';
265 $eventdata->attemptid = $attempt->id;
266 $eventdata->timestart = $attempt->timestart;
267 $eventdata->timestamp = $attempt->timestart;
268 $eventdata->userid = $attempt->userid;
269 $eventdata->quizid = $quizobj->get_quizid();
270 $eventdata->cmid = $quizobj->get_cmid();
271 $eventdata->courseid = $quizobj->get_courseid();
272 events_trigger('quiz_attempt_started', $eventdata);
274 $transaction->allow_commit();
276 // Redirect to the attempt page.
277 redirect($quizobj->attempt_url($attempt->id, $page));