MDL-69716 mod_quiz: No timestamp for in progress attempts
[moodle.git] / mod / quiz / lib.php
CommitLineData
8cc86111 1<?php
8cc86111 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/>.
84e628a0 16
ee1fb969 17/**
84e628a0 18 * Library of functions for the quiz module.
19 *
20 * This contains functions that are called also from outside the quiz module
21 * Functions that are only called by the quiz module itself are in {@link locallib.php}
22 *
01773a6d 23 * @package mod_quiz
ba643847
TH
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
84e628a0 26 */
730fd187 27
25302dee 28
a17b297d
TH
29defined('MOODLE_INTERNAL') || die();
30
f81a8247 31require_once($CFG->dirroot . '/calendar/lib.php');
8966a111 32
75cd257b 33
e2249afe 34/**#@+
25302dee 35 * Option controlling what options are offered on the quiz settings form.
e2249afe 36 */
84e628a0 37define('QUIZ_MAX_ATTEMPT_OPTION', 10);
38define('QUIZ_MAX_QPP_OPTION', 50);
39define('QUIZ_MAX_DECIMAL_OPTION', 5);
40define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
75cd257b 41/**#@-*/
42
4344c5d5
TH
43/**#@+
44 * Options determining how the grades from individual attempts are combined to give
45 * the overall grade for a user
46 */
47define('QUIZ_GRADEHIGHEST', '1');
48define('QUIZ_GRADEAVERAGE', '2');
49define('QUIZ_ATTEMPTFIRST', '3');
50define('QUIZ_ATTEMPTLAST', '4');
51/**#@-*/
52
75cd257b 53/**
9e83f3d1 54 * @var int If start and end date for the quiz are more than this many seconds apart
75cd257b 55 * they will be represented by two separate events in the calendar
56 */
9e83f3d1 57define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
ee1fb969 58
33c8d37b
CF
59/**#@+
60 * Options for navigation method within quizzes.
61 */
62define('QUIZ_NAVMETHOD_FREE', 'free');
63define('QUIZ_NAVMETHOD_SEQ', 'sequential');
64/**#@-*/
65
b3d7d175
MN
66/**
67 * Event types.
68 */
69define('QUIZ_EVENT_TYPE_OPEN', 'open');
70define('QUIZ_EVENT_TYPE_CLOSE', 'close');
71
920b93d1 72/**
73 * Given an object containing all the necessary data,
7cac0c4b 74 * (defined by the form in mod_form.php) this function
920b93d1 75 * will create a new instance and return the id number
76 * of the new instance.
a23f0aaf 77 *
920b93d1 78 * @param object $quiz the data that came from the form.
212b7b8c 79 * @return mixed the id of the new instance on success,
80 * false or a string error message on failure.
920b93d1 81 */
730fd187 82function quiz_add_instance($quiz) {
c18269c7 83 global $DB;
fe6ce234 84 $cmid = $quiz->coursemodule;
730fd187 85
920b93d1 86 // Process the options from the form.
380534b0 87 $quiz->timecreated = time();
212b7b8c 88 $result = quiz_process_options($quiz);
89 if ($result && is_string($result)) {
90 return $result;
91 }
6f797013 92
920b93d1 93 // Try to store it in the database.
eeab18f0 94 $quiz->id = $DB->insert_record('quiz', $quiz);
7bd1aa1d 95
5d949702
K
96 // Create the first section for this quiz.
97 $DB->insert_record('quiz_sections', array('quizid' => $quiz->id,
98 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0));
99
920b93d1 100 // Do the processing required after an add or an update.
101 quiz_after_add_or_update($quiz);
a23f0aaf 102
7bd1aa1d 103 return $quiz->id;
730fd187 104}
105
920b93d1 106/**
107 * Given an object containing all the necessary data,
7cac0c4b 108 * (defined by the form in mod_form.php) this function
920b93d1 109 * will update an existing instance with new data.
a23f0aaf 110 *
920b93d1 111 * @param object $quiz the data that came from the form.
212b7b8c 112 * @return mixed true on success, false or a string error message on failure.
920b93d1 113 */
eeab18f0 114function quiz_update_instance($quiz, $mform) {
115 global $CFG, $DB;
475225a1 116 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
730fd187 117
920b93d1 118 // Process the options from the form.
212b7b8c 119 $result = quiz_process_options($quiz);
120 if ($result && is_string($result)) {
121 return $result;
122 }
ee1fb969 123
475225a1 124 // Get the current value, so we can see what changed.
f2557823 125 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
25302dee 126
475225a1
TH
127 // We need two values from the existing DB record that are not in the form,
128 // in some of the function calls below.
129 $quiz->sumgrades = $oldquiz->sumgrades;
130 $quiz->grade = $oldquiz->grade;
131
920b93d1 132 // Update the database.
730fd187 133 $quiz->id = $quiz->instance;
eeab18f0 134 $DB->update_record('quiz', $quiz);
730fd187 135
920b93d1 136 // Do the processing required after an add or an update.
137 quiz_after_add_or_update($quiz);
ee1fb969 138
25302dee 139 if ($oldquiz->grademethod != $quiz->grademethod) {
25302dee
TH
140 quiz_update_all_final_grades($quiz);
141 quiz_update_grades($quiz);
142 }
143
475225a1
TH
144 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
145 || $oldquiz->timeclose != $quiz->timeclose
146 || $oldquiz->graceperiod != $quiz->graceperiod;
147 if ($quizdateschanged) {
148 quiz_update_open_attempts(array('quizid' => $quiz->id));
8e771aed
MP
149 }
150
9e83f3d1 151 // Delete any previous preview attempts.
53004e48 152 quiz_delete_previews($quiz);
d2f308c0 153
ccba5b88 154 // Repaginate, if asked to.
5d949702 155 if (!empty($quiz->repaginatenow)) {
ccba5b88
TH
156 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
157 }
158
7bd1aa1d 159 return true;
730fd187 160}
161
8cc86111 162/**
163 * Given an ID of an instance of this module,
164 * this function will permanently delete the instance
165 * and any data that depends on it.
166 *
25302dee 167 * @param int $id the id of the quiz to delete.
f7970e3c 168 * @return bool success or failure.
8cc86111 169 */
730fd187 170function quiz_delete_instance($id) {
c18269c7 171 global $DB;
730fd187 172
25302dee 173 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
730fd187 174
53004e48 175 quiz_delete_all_attempts($quiz);
990650f9 176 quiz_delete_all_overrides($quiz);
730fd187 177
828a4e9f
EM
178 // Look for random questions that may no longer be used when this quiz is gone.
179 $sql = "SELECT q.id
180 FROM {quiz_slots} slot
181 JOIN {question} q ON q.id = slot.questionid
182 WHERE slot.quizid = ? AND q.qtype = ?";
183 $questionids = $DB->get_fieldset_sql($sql, array($quiz->id, 'random'));
184
3090719d
SR
185 // We need to do the following deletes before we try and delete randoms, otherwise they would still be 'in use'.
186 $quizslots = $DB->get_fieldset_select('quiz_slots', 'id', 'quizid = ?', array($quiz->id));
187 $DB->delete_records_list('quiz_slot_tags', 'slotid', $quizslots);
ccba5b88 188 $DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
5d949702 189 $DB->delete_records('quiz_sections', array('quizid' => $quiz->id));
828a4e9f
EM
190
191 foreach ($questionids as $questionid) {
192 question_delete_question($questionid);
193 }
194
53004e48 195 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
730fd187 196
35cbe84b
TH
197 quiz_access_manager::delete_settings($quiz);
198
53004e48 199 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
25a03faa 200 foreach ($events as $event) {
f81a8247
SH
201 $event = calendar_event::load($event);
202 $event->delete();
b2a3cd2d 203 }
204
d6dd2108 205 quiz_grade_item_delete($quiz);
40fe1538 206 // We must delete the module record after we delete the grade item.
53004e48 207 $DB->delete_records('quiz', array('id' => $quiz->id));
d6dd2108 208
53004e48 209 return true;
210}
211
990650f9
TH
212/**
213 * Deletes a quiz override from the database and clears any corresponding calendar events
214 *
215 * @param object $quiz The quiz object.
f7970e3c 216 * @param int $overrideid The id of the override being deleted
4c729982 217 * @param bool $log Whether to trigger logs.
990650f9
TH
218 * @return bool true on success
219 */
4c729982 220function quiz_delete_override($quiz, $overrideid, $log = true) {
990650f9
TH
221 global $DB;
222
92089e0e
MN
223 if (!isset($quiz->cmid)) {
224 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
225 $quiz->cmid = $cm->id;
226 }
227
25302dee 228 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
990650f9 229
9e83f3d1 230 // Delete the events.
99618f89
LB
231 if (isset($override->groupid)) {
232 // Create the search array for a group override.
233 $eventsearcharray = array('modulename' => 'quiz',
234 'instance' => $quiz->id, 'groupid' => (int)$override->groupid);
235 } else {
236 // Create the search array for a user override.
237 $eventsearcharray = array('modulename' => 'quiz',
238 'instance' => $quiz->id, 'userid' => (int)$override->userid);
239 }
240 $events = $DB->get_records('event', $eventsearcharray);
25302dee 241 foreach ($events as $event) {
990650f9
TH
242 $eventold = calendar_event::load($event);
243 $eventold->delete();
244 }
245
246 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
8de2eb35 247
4c729982
AN
248 if ($log) {
249 // Set the common parameters for one of the events we will be triggering.
250 $params = array(
251 'objectid' => $override->id,
252 'context' => context_module::instance($quiz->cmid),
253 'other' => array(
254 'quizid' => $override->quiz
255 )
256 );
257 // Determine which override deleted event to fire.
258 if (!empty($override->userid)) {
259 $params['relateduserid'] = $override->userid;
260 $event = \mod_quiz\event\user_override_deleted::create($params);
261 } else {
262 $params['other']['groupid'] = $override->groupid;
263 $event = \mod_quiz\event\group_override_deleted::create($params);
264 }
8de2eb35 265
4c729982
AN
266 // Trigger the override deleted event.
267 $event->add_record_snapshot('quiz_overrides', $override);
268 $event->trigger();
269 }
8de2eb35 270
990650f9
TH
271 return true;
272}
273
274/**
275 * Deletes all quiz overrides from the database and clears any corresponding calendar events
276 *
277 * @param object $quiz The quiz object.
4c729982 278 * @param bool $log Whether to trigger logs.
990650f9 279 */
4c729982 280function quiz_delete_all_overrides($quiz, $log = true) {
990650f9
TH
281 global $DB;
282
283 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
284 foreach ($overrides as $override) {
4c729982 285 quiz_delete_override($quiz, $override->id, $log);
990650f9
TH
286 }
287}
288
289/**
290 * Updates a quiz object with override information for a user.
291 *
292 * Algorithm: For each quiz setting, if there is a matching user-specific override,
293 * then use that otherwise, if there are group-specific overrides, return the most
294 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
295 *
296 * Special case: if there is more than one password that applies to the user, then
297 * quiz->extrapasswords will contain an array of strings giving the remaining
298 * passwords.
299 *
300 * @param object $quiz The quiz object.
f7970e3c 301 * @param int $userid The userid.
990650f9
TH
302 * @return object $quiz The updated quiz object.
303 */
304function quiz_update_effective_access($quiz, $userid) {
305 global $DB;
306
9e83f3d1 307 // Check for user override.
990650f9
TH
308 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
309
310 if (!$override) {
6bdfef5d 311 $override = new stdClass();
990650f9
TH
312 $override->timeopen = null;
313 $override->timeclose = null;
314 $override->timelimit = null;
315 $override->attempts = null;
316 $override->password = null;
317 }
318
9e83f3d1 319 // Check for group overrides.
990650f9 320 $groupings = groups_get_user_groups($quiz->course, $userid);
990650f9 321
7bc488dc 322 if (!empty($groupings[0])) {
9e83f3d1 323 // Select all overrides that apply to the User's groups.
7bc488dc 324 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
990650f9
TH
325 $sql = "SELECT * FROM {quiz_overrides}
326 WHERE groupid $extra AND quiz = ?";
ac250ad5 327 $params[] = $quiz->id;
990650f9
TH
328 $records = $DB->get_records_sql($sql, $params);
329
9e83f3d1 330 // Combine the overrides.
990650f9
TH
331 $opens = array();
332 $closes = array();
333 $limits = array();
334 $attempts = array();
335 $passwords = array();
336
337 foreach ($records as $gpoverride) {
338 if (isset($gpoverride->timeopen)) {
339 $opens[] = $gpoverride->timeopen;
340 }
341 if (isset($gpoverride->timeclose)) {
342 $closes[] = $gpoverride->timeclose;
343 }
344 if (isset($gpoverride->timelimit)) {
345 $limits[] = $gpoverride->timelimit;
346 }
347 if (isset($gpoverride->attempts)) {
348 $attempts[] = $gpoverride->attempts;
349 }
350 if (isset($gpoverride->password)) {
351 $passwords[] = $gpoverride->password;
352 }
353 }
9e83f3d1 354 // If there is a user override for a setting, ignore the group override.
990650f9 355 if (is_null($override->timeopen) && count($opens)) {
25302dee 356 $override->timeopen = min($opens);
990650f9
TH
357 }
358 if (is_null($override->timeclose) && count($closes)) {
8e771aed
MP
359 if (in_array(0, $closes)) {
360 $override->timeclose = 0;
361 } else {
362 $override->timeclose = max($closes);
363 }
990650f9
TH
364 }
365 if (is_null($override->timelimit) && count($limits)) {
8e771aed
MP
366 if (in_array(0, $limits)) {
367 $override->timelimit = 0;
368 } else {
369 $override->timelimit = max($limits);
370 }
990650f9
TH
371 }
372 if (is_null($override->attempts) && count($attempts)) {
8e771aed
MP
373 if (in_array(0, $attempts)) {
374 $override->attempts = 0;
375 } else {
376 $override->attempts = max($attempts);
377 }
990650f9
TH
378 }
379 if (is_null($override->password) && count($passwords)) {
25302dee 380 $override->password = array_shift($passwords);
990650f9 381 if (count($passwords)) {
25302dee 382 $override->extrapasswords = $passwords;
990650f9
TH
383 }
384 }
385
386 }
387
9e83f3d1 388 // Merge with quiz defaults.
25302dee 389 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
990650f9
TH
390 foreach ($keys as $key) {
391 if (isset($override->{$key})) {
392 $quiz->{$key} = $override->{$key};
393 }
394 }
395
396 return $quiz;
397}
398
53004e48 399/**
400 * Delete all the attempts belonging to a quiz.
8cc86111 401 *
8cc86111 402 * @param object $quiz The quiz object.
53004e48 403 */
404function quiz_delete_all_attempts($quiz) {
405 global $CFG, $DB;
6b5f24d3
TH
406 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
407 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
53004e48 408 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
409 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
730fd187 410}
411
4c729982
AN
412/**
413 * Delete all the attempts belonging to a user in a particular quiz.
414 *
415 * @param object $quiz The quiz object.
416 * @param object $user The user object.
417 */
418function quiz_delete_user_attempts($quiz, $user) {
419 global $CFG, $DB;
420 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
421 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz_user($quiz->get_quizid(), $user->id));
422 $params = [
423 'quiz' => $quiz->get_quizid(),
424 'userid' => $user->id,
425 ];
426 $DB->delete_records('quiz_attempts', $params);
427 $DB->delete_records('quiz_grades', $params);
428}
429
25302dee
TH
430/**
431 * Get the best current grade for a particular user in a quiz.
432 *
433 * @param object $quiz the quiz settings.
f7970e3c 434 * @param int $userid the id of the user.
25a03faa 435 * @return float the user's current grade for this quiz, or null if this user does
25302dee
TH
436 * not have a grade on this quiz.
437 */
438function quiz_get_best_grade($quiz, $userid) {
439 global $DB;
25a03faa
TH
440 $grade = $DB->get_field('quiz_grades', 'grade',
441 array('quiz' => $quiz->id, 'userid' => $userid));
25302dee 442
b2607ccc 443 // Need to detect errors/no result, without catching 0 grades.
25302dee
TH
444 if ($grade === false) {
445 return null;
446 }
447
448 return $grade + 0; // Convert to number.
449}
450
451/**
452 * Is this a graded quiz? If this method returns true, you can assume that
453 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
454 * divide by them).
455 *
456 * @param object $quiz a row from the quiz table.
f7970e3c 457 * @return bool whether this is a graded quiz.
25302dee
TH
458 */
459function quiz_has_grades($quiz) {
460 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
461}
462
99caa248
JP
463/**
464 * Does this quiz allow multiple tries?
465 *
466 * @return bool
467 */
468function quiz_allows_multiple_tries($quiz) {
469 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
470 return $bt->allows_multiple_submitted_responses();
471}
472
8cc86111 473/**
474 * Return a small object with summary information about what a
475 * user has done with a given particular instance of this module
476 * Used for user activity reports.
477 * $return->time = the time they did it
478 * $return->info = a short text description
479 *
8cc86111 480 * @param object $course
481 * @param object $user
482 * @param object $mod
483 * @param object $quiz
484 * @return object|null
485 */
730fd187 486function quiz_user_outline($course, $user, $mod, $quiz) {
1a96363a 487 global $DB, $CFG;
172238f4 488 require_once($CFG->libdir . '/gradelib.php');
1a96363a
NC
489 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
490
491 if (empty($grades->items[0]->grades)) {
492 return null;
493 } else {
494 $grade = reset($grades->items[0]->grades);
5ecfab51 495 }
496
0ff4bd08 497 $result = new stdClass();
930570b4
MC
498 // If the user can't see hidden grades, don't return that information.
499 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
500 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
501 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
502 } else {
503 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
504 }
4433f871 505
4bb39eab 506 $result->time = grade_get_date_for_user_grade($grade, $user);
4433f871 507
5ecfab51 508 return $result;
1a96363a 509}
730fd187 510
8cc86111 511/**
512 * Print a detailed representation of what a user has done with
513 * a given particular instance of this module, for user activity reports.
514 *
8cc86111 515 * @param object $course
516 * @param object $user
517 * @param object $mod
518 * @param object $quiz
519 * @return bool
520 */
730fd187 521function quiz_user_complete($course, $user, $mod, $quiz) {
1a14a14b 522 global $DB, $CFG, $OUTPUT;
be18f589 523 require_once($CFG->libdir . '/gradelib.php');
172238f4 524 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
25302dee 525
1a96363a
NC
526 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
527 if (!empty($grades->items[0]->grades)) {
528 $grade = reset($grades->items[0]->grades);
930570b4
MC
529 // If the user can't see hidden grades, don't return that information.
530 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
531 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
532 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
533 if ($grade->str_feedback) {
534 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
535 }
536 } else {
537 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
538 if ($grade->str_feedback) {
539 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
540 }
1a96363a
NC
541 }
542 }
730fd187 543
25a03faa
TH
544 if ($attempts = $DB->get_records('quiz_attempts',
545 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
ee1fb969 546 foreach ($attempts as $attempt) {
9378c99b 547 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
be18f589
TH
548 if ($attempt->state != quiz_attempt::FINISHED) {
549 echo quiz_attempt_state_name($attempt->state);
ee1fb969 550 } else {
930570b4
MC
551 if (!isset($gitem)) {
552 if (!empty($grades->items[0]->grades)) {
553 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
554 } else {
555 $gitem = new stdClass();
556 $gitem->hidden = true;
557 }
558 }
559 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
560 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
561 } else {
562 echo get_string('hidden', 'grades');
563 }
bceb4280 564 echo ' - '.userdate($attempt->timefinish).'<br />';
ee1fb969 565 }
ee1fb969 566 }
567 } else {
25a03faa 568 print_string('noattempts', 'quiz');
ee1fb969 569 }
570
730fd187 571 return true;
572}
573
730fd187 574
b5a16eb7 575/**
ac032e0e 576 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
f7970e3c 577 * @param int $userid the userid.
b5a16eb7 578 * @param string $status 'all', 'finished' or 'unfinished' to control
8cc86111 579 * @param bool $includepreviews
25a03faa
TH
580 * @return an array of all the user's attempts at this quiz. Returns an empty
581 * array if there are none.
b5a16eb7 582 */
ac032e0e 583function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
36e48cb8
TH
584 global $DB, $CFG;
585 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
586 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
587 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
588 // MDL-33048.
589 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
34b7d838
TH
590
591 $params = array();
592 switch ($status) {
593 case 'all':
594 $statuscondition = '';
595 break;
596
597 case 'finished':
598 $statuscondition = ' AND state IN (:state1, :state2)';
599 $params['state1'] = quiz_attempt::FINISHED;
600 $params['state2'] = quiz_attempt::ABANDONED;
601 break;
602
603 case 'unfinished':
604 $statuscondition = ' AND state IN (:state1, :state2)';
605 $params['state1'] = quiz_attempt::IN_PROGRESS;
606 $params['state2'] = quiz_attempt::OVERDUE;
607 break;
608 }
609
ac032e0e
FM
610 $quizids = (array) $quizids;
611 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
612 $params += $inparams;
613 $params['userid'] = $userid;
614
b5a16eb7 615 $previewclause = '';
616 if (!$includepreviews) {
617 $previewclause = ' AND preview = 0';
618 }
34b7d838 619
25302dee 620 return $DB->get_records_select('quiz_attempts',
ac032e0e 621 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
8675453e 622 $params, 'quiz, attempt ASC');
b5a16eb7 623}
858deff0 624
d6dd2108 625/**
626 * Return grade for given user or all users.
627 *
628 * @param int $quizid id of quiz
629 * @param int $userid optional user id, 0 means all users
f88fb62c 630 * @return array array of grades, false if none. These are raw grades. They should
631 * be processed with quiz_format_grade for display.
d6dd2108 632 */
25302dee 633function quiz_get_user_grades($quiz, $userid = 0) {
9cf4a18b 634 global $CFG, $DB;
d6dd2108 635
9cf4a18b 636 $params = array($quiz->id);
25302dee 637 $usertest = '';
9cf4a18b 638 if ($userid) {
639 $params[] = $userid;
25302dee
TH
640 $usertest = 'AND u.id = ?';
641 }
8f37f7fb 642 return $DB->get_records_sql("
25302dee
TH
643 SELECT
644 u.id,
645 u.id AS userid,
646 qg.grade AS rawgrade,
647 qg.timemodified AS dategraded,
648 MAX(qa.timefinish) AS datesubmitted
649
650 FROM {user} u
651 JOIN {quiz_grades} qg ON u.id = qg.userid
652 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
653
8f37f7fb
TH
654 WHERE qg.quiz = ?
655 $usertest
656 GROUP BY u.id, qg.grade, qg.timemodified", $params);
d6dd2108 657}
658
f88fb62c 659/**
660 * Round a grade to to the correct number of decimal places, and format it for display.
661 *
662 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
663 * @param float $grade The grade to round.
8cc86111 664 * @return float
f88fb62c 665 */
666function quiz_format_grade($quiz, $grade) {
25302dee
TH
667 if (is_null($grade)) {
668 return get_string('notyetgraded', 'quiz');
669 }
f88fb62c 670 return format_float($grade, $quiz->decimalpoints);
671}
672
84e628a0 673/**
e1a2d0d9 674 * Determine the correct number of decimal places required to format a grade.
84e628a0 675 *
676 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
e1a2d0d9 677 * @return integer
84e628a0 678 */
e1a2d0d9 679function quiz_get_grade_format($quiz) {
25302dee
TH
680 if (empty($quiz->questiondecimalpoints)) {
681 $quiz->questiondecimalpoints = -1;
682 }
e1a2d0d9 683
84e628a0 684 if ($quiz->questiondecimalpoints == -1) {
e1a2d0d9 685 return $quiz->decimalpoints;
84e628a0 686 }
e1a2d0d9
CC
687
688 return $quiz->questiondecimalpoints;
689}
690
691/**
692 * Round a grade to the correct number of decimal places, and format it for display.
693 *
694 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
695 * @param float $grade The grade to round.
696 * @return float
697 */
698function quiz_format_question_grade($quiz, $grade) {
699 return format_float($grade, quiz_get_grade_format($quiz));
84e628a0 700}
701
d6dd2108 702/**
703 * Update grades in central gradebook
704 *
a153c9f2 705 * @category grade
25302dee
TH
706 * @param object $quiz the quiz settings.
707 * @param int $userid specific user only, 0 means all users.
a153c9f2 708 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
d6dd2108 709 */
25302dee 710function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
9cf4a18b 711 global $CFG, $DB;
172238f4 712 require_once($CFG->libdir . '/gradelib.php');
ed1daaa9 713
775f811a 714 if ($quiz->grade == 0) {
715 quiz_grade_item_update($quiz);
d6dd2108 716
775f811a 717 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
718 quiz_grade_item_update($quiz, $grades);
eafb9d9e 719
25302dee 720 } else if ($userid && $nullifnone) {
39790bd8 721 $grade = new stdClass();
25302dee
TH
722 $grade->userid = $userid;
723 $grade->rawgrade = null;
775f811a 724 quiz_grade_item_update($quiz, $grade);
d6dd2108 725
726 } else {
775f811a 727 quiz_grade_item_update($quiz);
728 }
729}
3b1d5cc4 730
d6dd2108 731/**
a153c9f2 732 * Create or update the grade item for given quiz
d6dd2108 733 *
a153c9f2 734 * @category grade
d6dd2108 735 * @param object $quiz object with extra cmidnumber
8cc86111 736 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
d6dd2108 737 * @return int 0 if ok, error code otherwise
738 */
25a03faa 739function quiz_grade_item_update($quiz, $grades = null) {
3b1d5cc4 740 global $CFG, $OUTPUT;
609c0d6b 741 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
172238f4 742 require_once($CFG->libdir . '/gradelib.php');
d6dd2108 743
f4feabb8 744 if (property_exists($quiz, 'cmidnumber')) { // May not be always present.
25302dee 745 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
d6dd2108 746 } else {
25302dee 747 $params = array('itemname' => $quiz->name);
d6dd2108 748 }
749
750 if ($quiz->grade > 0) {
751 $params['gradetype'] = GRADE_TYPE_VALUE;
752 $params['grademax'] = $quiz->grade;
753 $params['grademin'] = 0;
754
755 } else {
756 $params['gradetype'] = GRADE_TYPE_NONE;
757 }
758
9e83f3d1 759 // What this is trying to do:
25a03faa
TH
760 // 1. If the quiz is set to not show grades while the quiz is still open,
761 // and is set to show grades after the quiz is closed, then create the
762 // grade_item with a show-after date that is the quiz close date.
763 // 2. If the quiz is set to not show grades at either of those times,
764 // create the grade_item as hidden.
765 // 3. If the quiz is set to show grades, create the grade_item visible.
25302dee
TH
766 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
767 mod_quiz_display_options::LATER_WHILE_OPEN);
768 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
769 mod_quiz_display_options::AFTER_CLOSE);
6d03fd98
TH
770 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
771 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
1223d24a 772 $params['hidden'] = 1;
773
6d03fd98
TH
774 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
775 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
1223d24a 776 if ($quiz->timeclose) {
777 $params['hidden'] = $quiz->timeclose;
778 } else {
779 $params['hidden'] = 1;
780 }
781
782 } else {
9e83f3d1 783 // Either
1223d24a 784 // a) both open and closed enabled
25a03faa 785 // b) open enabled, closed disabled - we can not "hide after",
9e83f3d1 786 // grades are kept visible even after closing.
1223d24a 787 $params['hidden'] = 0;
788 }
789
39873128
TH
790 if (!$params['hidden']) {
791 // If the grade item is not hidden by the quiz logic, then we need to
792 // hide it if the quiz is hidden from students.
1c73df9e
TH
793 if (property_exists($quiz, 'visible')) {
794 // Saving the quiz form, and cm not yet updated in the database.
795 $params['hidden'] = !$quiz->visible;
796 } else {
797 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
798 $params['hidden'] = !$cm->visible;
799 }
39873128
TH
800 }
801
0b5a80a1 802 if ($grades === 'reset') {
803 $params['reset'] = true;
25a03faa 804 $grades = null;
0b5a80a1 805 }
9cf4a18b 806
49460d84 807 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
d45459b7 808 if (!empty($gradebook_grades->items)) {
809 $grade_item = $gradebook_grades->items[0];
810 if ($grade_item->locked) {
9e83f3d1 811 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
d45459b7 812 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
813 if (!$confirm_regrade) {
f5f36584
MP
814 if (!AJAX_SCRIPT) {
815 $message = get_string('gradeitemislocked', 'grades');
816 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
817 '&amp;mode=overview';
818 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
819 echo $OUTPUT->box_start('generalbox', 'notice');
820 echo '<p>'. $message .'</p>';
821 echo $OUTPUT->container_start('buttons');
822 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
823 echo $OUTPUT->single_button($back_link, get_string('cancel'));
824 echo $OUTPUT->container_end();
825 echo $OUTPUT->box_end();
826 }
d45459b7 827 return GRADE_UPDATE_ITEM_LOCKED;
828 }
49460d84 829 }
830 }
0b5a80a1 831
ced5ee59 832 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
d6dd2108 833}
834
835/**
836 * Delete grade item for given quiz
837 *
a153c9f2 838 * @category grade
d6dd2108 839 * @param object $quiz object
840 * @return object quiz
841 */
842function quiz_grade_item_delete($quiz) {
843 global $CFG;
53004e48 844 require_once($CFG->libdir . '/gradelib.php');
d6dd2108 845
25a03faa
TH
846 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
847 null, array('deleted' => 1));
d6dd2108 848}
849
8cc86111 850/**
851 * This standard function will check all instances of this module
852 * and make sure there are up-to-date events created for each of them.
853 * If courseid = 0, then every quiz event in the site is checked, else
854 * only quiz events belonging to the course specified are checked.
855 * This function is used, in its new format, by restore_refresh_events()
856 *
8cc86111 857 * @param int $courseid
9ffbdafc
AG
858 * @param int|stdClass $instance Quiz module instance or ID.
859 * @param int|stdClass $cm Course module object or ID (not used in this module).
8cc86111 860 * @return bool
861 */
9ffbdafc 862function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
9cf4a18b 863 global $DB;
d2f308c0 864
9ffbdafc
AG
865 // If we have instance information then we can just update the one event instead of updating all events.
866 if (isset($instance)) {
867 if (!is_object($instance)) {
868 $instance = $DB->get_record('quiz', array('id' => $instance), '*', MUST_EXIST);
869 }
870 quiz_update_events($instance);
871 return true;
872 }
873
d2f308c0 874 if ($courseid == 0) {
25302dee 875 if (!$quizzes = $DB->get_records('quiz')) {
d2f308c0 876 return true;
877 }
878 } else {
25302dee 879 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
d2f308c0 880 return true;
881 }
882 }
f41e824f 883
d2f308c0 884 foreach ($quizzes as $quiz) {
990650f9 885 quiz_update_events($quiz);
d2f308c0 886 }
990650f9 887
d2f308c0 888 return true;
889}
890
dd97c328 891/**
892 * Returns all quiz graded users since a given time for specified quiz
893 */
8d297188
TH
894function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
895 $courseid, $cmid, $userid = 0, $groupid = 0) {
e19c086c 896 global $CFG, $USER, $DB;
172238f4 897 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
6710ec87 898
e19c086c 899 $course = get_course($courseid);
f20edd52 900 $modinfo = get_fast_modinfo($course);
6710ec87 901
dd97c328 902 $cm = $modinfo->cms[$cmid];
8d297188 903 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
9cf4a18b 904
dd97c328 905 if ($userid) {
8d297188
TH
906 $userselect = "AND u.id = :userid";
907 $params['userid'] = $userid;
dd97c328 908 } else {
8d297188 909 $userselect = '';
dd97c328 910 }
ac21ad39 911
dd97c328 912 if ($groupid) {
8d297188
TH
913 $groupselect = 'AND gm.groupid = :groupid';
914 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
915 $params['groupid'] = $groupid;
dd97c328 916 } else {
8d297188
TH
917 $groupselect = '';
918 $groupjoin = '';
919 }
920
122fc5d9
DM
921 $params['timestart'] = $timestart;
922 $params['quizid'] = $quiz->id;
923
21d22803 924 $ufields = user_picture::fields('u', null, 'useridagain');
8d297188
TH
925 if (!$attempts = $DB->get_records_sql("
926 SELECT qa.*,
3047f140 927 {$ufields}
8d297188
TH
928 FROM {quiz_attempts} qa
929 JOIN {user} u ON u.id = qa.userid
930 $groupjoin
931 WHERE qa.timefinish > :timestart
932 AND qa.quiz = :quizid
933 AND qa.preview = 0
934 $userselect
935 $groupselect
936 ORDER BY qa.timefinish ASC", $params)) {
937 return;
938 }
939
c492a78e 940 $context = context_module::instance($cm->id);
8d297188
TH
941 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
942 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
cb323d02 943 $grader = has_capability('mod/quiz:viewreports', $context);
dd97c328 944 $groupmode = groups_get_activity_groupmode($cm, $course);
6710ec87 945
8d297188 946 $usersgroups = null;
25a03faa 947 $aname = format_string($cm->name, true);
dd97c328 948 foreach ($attempts as $attempt) {
949 if ($attempt->userid != $USER->id) {
950 if (!$grader) {
9e83f3d1 951 // Grade permission required.
dd97c328 952 continue;
953 }
6710ec87 954
9cf4a18b 955 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
e19c086c
MG
956 $usersgroups = groups_get_all_groups($course->id,
957 $attempt->userid, $cm->groupingid);
958 $usersgroups = array_keys($usersgroups);
959 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
dd97c328 960 continue;
961 }
962 }
8d297188
TH
963 }
964
7ee80cab 965 $options = quiz_get_review_options($quiz, $attempt, $context);
dd97c328 966
0ff4bd08 967 $tmpactivity = new stdClass();
dd97c328 968
8d297188
TH
969 $tmpactivity->type = 'quiz';
970 $tmpactivity->cmid = $cm->id;
971 $tmpactivity->name = $aname;
972 $tmpactivity->sectionnum = $cm->sectionnum;
973 $tmpactivity->timestamp = $attempt->timefinish;
9cf4a18b 974
a957e97f 975 $tmpactivity->content = new stdClass();
dd97c328 976 $tmpactivity->content->attemptid = $attempt->id;
dd97c328 977 $tmpactivity->content->attempt = $attempt->attempt;
6d03fd98 978 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
8d297188
TH
979 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
980 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
981 } else {
982 $tmpactivity->content->sumgrades = null;
983 $tmpactivity->content->maxgrade = null;
984 }
9cf4a18b 985
21d22803 986 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
3047f140 987 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
9cf4a18b 988
dd97c328 989 $activities[$index++] = $tmpactivity;
6710ec87 990 }
6710ec87 991}
992
dd97c328 993function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
e63f88c9 994 global $CFG, $OUTPUT;
6710ec87 995
dd97c328 996 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
6710ec87 997
8d297188
TH
998 echo '<tr><td class="userpicture" valign="top">';
999 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
1000 echo '</td><td>';
6710ec87 1001
1002 if ($detail) {
dd97c328 1003 $modname = $modnames[$activity->type];
1004 echo '<div class="title">';
3e6adcd6 1005 echo $OUTPUT->image_icon('icon', $modname, $activity->type);
8d297188
TH
1006 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1007 $activity->cmid . '">' . $activity->name . '</a>';
dd97c328 1008 echo '</div>';
6710ec87 1009 }
1010
dd97c328 1011 echo '<div class="grade">';
8d297188
TH
1012 echo get_string('attempt', 'quiz', $activity->content->attempt);
1013 if (isset($activity->content->maxgrade)) {
1014 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1015 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1016 $activity->content->attemptid . '">' . $grades . '</a>)';
1017 }
dd97c328 1018 echo '</div>';
6710ec87 1019
dd97c328 1020 echo '<div class="user">';
8d297188
TH
1021 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1022 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
1023 '</a> - ' . userdate($activity->timestamp);
dd97c328 1024 echo '</div>';
6710ec87 1025
8d297188 1026 echo '</td></tr></table>';
6710ec87 1027
1028 return;
1029}
1030
ee1fb969 1031/**
920b93d1 1032 * Pre-process the quiz options form data, making any necessary adjustments.
ad4cd837 1033 * Called by add/update instance in this file.
b159da78 1034 *
920b93d1 1035 * @param object $quiz The variables set on the form.
1036 */
25302dee
TH
1037function quiz_process_options($quiz) {
1038 global $CFG;
1039 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1040 require_once($CFG->libdir . '/questionlib.php');
1041
920b93d1 1042 $quiz->timemodified = time();
ee1fb969 1043
dc5c6851 1044 // Quiz name.
1045 if (!empty($quiz->name)) {
1046 $quiz->name = trim($quiz->name);
1047 }
a23f0aaf 1048
ab0a8ff2 1049 // Password field - different in form to stop browsers that remember passwords
1050 // getting confused.
1051 $quiz->password = $quiz->quizpassword;
1052 unset($quiz->quizpassword);
1053
9e83f3d1 1054 // Quiz feedback.
a0807a00 1055 if (isset($quiz->feedbacktext)) {
1056 // Clean up the boundary text.
1057 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
fe6ce234
DC
1058 if (empty($quiz->feedbacktext[$i]['text'])) {
1059 $quiz->feedbacktext[$i]['text'] = '';
a0807a00 1060 } else {
fe6ce234 1061 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
a0807a00 1062 }
212b7b8c 1063 }
b159da78 1064
a0807a00 1065 // Check the boundary value is a number or a percentage, and in range.
1066 $i = 0;
1067 while (!empty($quiz->feedbackboundaries[$i])) {
1068 $boundary = trim($quiz->feedbackboundaries[$i]);
1069 if (!is_numeric($boundary)) {
1070 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1071 $boundary = trim(substr($boundary, 0, -1));
1072 if (is_numeric($boundary)) {
1073 $boundary = $boundary * $quiz->grade / 100.0;
1074 } else {
1075 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1076 }
212b7b8c 1077 }
1078 }
a0807a00 1079 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1080 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1081 }
1082 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1083 return get_string('feedbackerrororder', 'quiz', $i + 1);
1084 }
1085 $quiz->feedbackboundaries[$i] = $boundary;
1086 $i += 1;
212b7b8c 1087 }
a0807a00 1088 $numboundaries = $i;
b159da78 1089
a0807a00 1090 // Check there is nothing in the remaining unused fields.
e0b7cfcb 1091 if (!empty($quiz->feedbackboundaries)) {
1092 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
25a03faa
TH
1093 if (!empty($quiz->feedbackboundaries[$i]) &&
1094 trim($quiz->feedbackboundaries[$i]) != '') {
e0b7cfcb 1095 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1096 }
a0807a00 1097 }
212b7b8c 1098 }
a0807a00 1099 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
25a03faa
TH
1100 if (!empty($quiz->feedbacktext[$i]['text']) &&
1101 trim($quiz->feedbacktext[$i]['text']) != '') {
a0807a00 1102 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1103 }
212b7b8c 1104 }
25a03faa
TH
1105 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1106 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
a0807a00 1107 $quiz->feedbackboundaries[$numboundaries] = 0;
1108 $quiz->feedbackboundarycount = $numboundaries;
2cf5ab10
TH
1109 } else {
1110 $quiz->feedbackboundarycount = -1;
212b7b8c 1111 }
a23f0aaf 1112
25302dee
TH
1113 // Combing the individual settings into the review columns.
1114 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1115 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1116 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1117 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1118 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1119 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1120 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1121 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1122 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
91472736
AN
1123
1124 // Ensure that disabled checkboxes in completion settings are set to 0.
1125 if (empty($quiz->completionusegrade)) {
1126 $quiz->completionpass = 0;
1127 }
1128 if (empty($quiz->completionpass)) {
1129 $quiz->completionattemptsexhausted = 0;
1130 }
760ed019
FM
1131 if (empty($quiz->completionminattemptsenabled)) {
1132 $quiz->completionminattempts = 0;
1133 }
25302dee 1134}
ee1fb969 1135
25302dee
TH
1136/**
1137 * Helper function for {@link quiz_process_options()}.
1138 * @param object $fromform the sumbitted form date.
1139 * @param string $field one of the review option field names.
1140 */
1141function quiz_review_option_form_to_db($fromform, $field) {
1142 static $times = array(
1143 'during' => mod_quiz_display_options::DURING,
1144 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1145 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1146 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1147 );
00719c02 1148
25302dee
TH
1149 $review = 0;
1150 foreach ($times as $whenname => $when) {
1151 $fieldname = $field . $whenname;
1152 if (isset($fromform->$fieldname)) {
1153 $review |= $when;
1154 unset($fromform->$fieldname);
1155 }
1b8a7434 1156 }
1157
25302dee 1158 return $review;
920b93d1 1159}
1160
1161/**
1162 * This function is called at the end of quiz_add_instance
1163 * and quiz_update_instance, to do the common processing.
a23f0aaf 1164 *
920b93d1 1165 * @param object $quiz the quiz object.
1166 */
1167function quiz_after_add_or_update($quiz) {
c18269c7 1168 global $DB;
fe6ce234
DC
1169 $cmid = $quiz->coursemodule;
1170
9e83f3d1 1171 // We need to use context now, so we need to make sure all needed info is already in db.
fe6ce234 1172 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
c492a78e 1173 $context = context_module::instance($cmid);
920b93d1 1174
9e83f3d1 1175 // Save the feedback.
53004e48 1176 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
a23f0aaf 1177
fe6ce234 1178 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
0ff4bd08 1179 $feedback = new stdClass();
212b7b8c 1180 $feedback->quizid = $quiz->id;
fe6ce234
DC
1181 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1182 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
212b7b8c 1183 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1184 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
fe6ce234 1185 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
25a03faa
TH
1186 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1187 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1188 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1189 $quiz->feedbacktext[$i]['text']);
1190 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1191 array('id' => $feedback->id));
212b7b8c 1192 }
1193
b83c32d3
TH
1194 // Store any settings belonging to the access rules.
1195 quiz_access_manager::save_settings($quiz);
1196
920b93d1 1197 // Update the events relating to this quiz.
990650f9 1198 quiz_update_events($quiz);
9ffbdafc
AG
1199 $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null;
1200 \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected);
990650f9 1201
9e83f3d1 1202 // Update related grade item.
990650f9 1203 quiz_grade_item_update($quiz);
990650f9
TH
1204}
1205
1206/**
1207 * This function updates the events associated to the quiz.
1208 * If $override is non-zero, then it updates only the events
1209 * associated with the specified override.
1210 *
1211 * @uses QUIZ_MAX_EVENT_LENGTH
1212 * @param object $quiz the quiz object.
1213 * @param object optional $override limit to a specific override
1214 */
1215function quiz_update_events($quiz, $override = null) {
1216 global $DB;
1217
1218 // Load the old events relating to this quiz.
1219 $conds = array('modulename'=>'quiz',
1220 'instance'=>$quiz->id);
1221 if (!empty($override)) {
9e83f3d1 1222 // Only load events for this override.
cc4fba86
MN
1223 if (isset($override->userid)) {
1224 $conds['userid'] = $override->userid;
1225 } else {
1226 $conds['groupid'] = $override->groupid;
1227 }
990650f9 1228 }
4133df6f 1229 $oldevents = $DB->get_records('event', $conds, 'id ASC');
990650f9 1230
98239b2d 1231 // Now make a to-do list of all that needs to be updated.
990650f9 1232 if (empty($override)) {
4133df6f
CB
1233 // We are updating the primary settings for the quiz, so we need to add all the overrides.
1234 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id ASC');
1235 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1236 // list contains the original (non-override) event for the module. If this is not included
1237 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1238 // list against the $oldevents list.
1239 array_unshift($overrides, new stdClass());
25a03faa 1240 } else {
9e83f3d1 1241 // Just do the one override.
990650f9 1242 $overrides = array($override);
920b93d1 1243 }
1244
98239b2d
JP
1245 // Get group override priorities.
1246 $grouppriorities = quiz_get_group_override_priorities($quiz->id);
1247
990650f9
TH
1248 foreach ($overrides as $current) {
1249 $groupid = isset($current->groupid)? $current->groupid : 0;
1250 $userid = isset($current->userid)? $current->userid : 0;
1251 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1252 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1253
9e83f3d1 1254 // Only add open/close events for an override if they differ from the quiz default.
990650f9
TH
1255 $addopen = empty($current->id) || !empty($current->timeopen);
1256 $addclose = empty($current->id) || !empty($current->timeclose);
1257
2079c732
TH
1258 if (!empty($quiz->coursemodule)) {
1259 $cmid = $quiz->coursemodule;
1260 } else {
393cadf2 1261 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
2079c732
TH
1262 }
1263
0ff4bd08 1264 $event = new stdClass();
b3d7d175 1265 $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
005b00dd
DM
1266 $event->description = format_module_intro('quiz', $quiz, $cmid, false);
1267 $event->format = FORMAT_HTML;
9e83f3d1 1268 // Events module won't show user events when the courseid is nonzero.
25a03faa 1269 $event->courseid = ($userid) ? 0 : $quiz->course;
990650f9
TH
1270 $event->groupid = $groupid;
1271 $event->userid = $userid;
1272 $event->modulename = 'quiz';
1273 $event->instance = $quiz->id;
1274 $event->timestart = $timeopen;
1275 $event->timeduration = max($timeclose - $timeopen, 0);
b3d7d175 1276 $event->timesort = $timeopen;
990650f9 1277 $event->visible = instance_is_visible('quiz', $quiz);
b3d7d175 1278 $event->eventtype = QUIZ_EVENT_TYPE_OPEN;
4133df6f 1279 $event->priority = null;
990650f9 1280
98239b2d 1281 // Determine the event name and priority.
990650f9 1282 if ($groupid) {
98239b2d 1283 // Group override event.
0ff4bd08 1284 $params = new stdClass();
990650f9
TH
1285 $params->quiz = $quiz->name;
1286 $params->group = groups_get_group_name($groupid);
1287 if ($params->group === false) {
9e83f3d1 1288 // Group doesn't exist, just skip it.
990650f9
TH
1289 continue;
1290 }
1291 $eventname = get_string('overridegroupeventname', 'quiz', $params);
98239b2d
JP
1292 // Set group override priority.
1293 if ($grouppriorities !== null) {
1294 $openpriorities = $grouppriorities['open'];
1295 if (isset($openpriorities[$timeopen])) {
1296 $event->priority = $openpriorities[$timeopen];
1297 }
1298 }
25a03faa 1299 } else if ($userid) {
98239b2d 1300 // User override event.
0ff4bd08 1301 $params = new stdClass();
990650f9
TH
1302 $params->quiz = $quiz->name;
1303 $eventname = get_string('overrideusereventname', 'quiz', $params);
98239b2d
JP
1304 // Set user override priority.
1305 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
990650f9 1306 } else {
98239b2d 1307 // The parent event.
990650f9
TH
1308 $eventname = $quiz->name;
1309 }
98239b2d 1310
990650f9 1311 if ($addopen or $addclose) {
98239b2d
JP
1312 // Separate start and end events.
1313 $event->timeduration = 0;
1314 if ($timeopen && $addopen) {
990650f9
TH
1315 if ($oldevent = array_shift($oldevents)) {
1316 $event->id = $oldevent->id;
25a03faa 1317 } else {
990650f9
TH
1318 unset($event->id);
1319 }
f10721d6 1320 $event->name = get_string('quizeventopens', 'quiz', $eventname);
9e83f3d1 1321 // The method calendar_event::create will reuse a db record if the id field is set.
bbf1fde4 1322 calendar_event::create($event, false);
98239b2d
JP
1323 }
1324 if ($timeclose && $addclose) {
1325 if ($oldevent = array_shift($oldevents)) {
1326 $event->id = $oldevent->id;
1327 } else {
1328 unset($event->id);
990650f9 1329 }
b3d7d175 1330 $event->type = CALENDAR_EVENT_TYPE_ACTION;
f10721d6 1331 $event->name = get_string('quizeventcloses', 'quiz', $eventname);
98239b2d 1332 $event->timestart = $timeclose;
b3d7d175
MN
1333 $event->timesort = $timeclose;
1334 $event->eventtype = QUIZ_EVENT_TYPE_CLOSE;
98239b2d
JP
1335 if ($groupid && $grouppriorities !== null) {
1336 $closepriorities = $grouppriorities['close'];
1337 if (isset($closepriorities[$timeclose])) {
1338 $event->priority = $closepriorities[$timeclose];
990650f9 1339 }
990650f9 1340 }
bbf1fde4 1341 calendar_event::create($event, false);
990650f9 1342 }
920b93d1 1343 }
1344 }
d6dd2108 1345
9e83f3d1 1346 // Delete any leftover events.
990650f9
TH
1347 foreach ($oldevents as $badevent) {
1348 $badevent = calendar_event::load($badevent);
1349 $badevent->delete();
1350 }
ee1fb969 1351}
1352
efe24976
JP
1353/**
1354 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1355 *
1356 * @param int $quizid The quiz ID.
1357 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1358 */
1359function quiz_get_group_override_priorities($quizid) {
1360 global $DB;
1361
1362 // Fetch group overrides.
1363 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1364 $params = ['quiz' => $quizid];
1365 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1366 if (!$overrides) {
1367 return null;
1368 }
1369
1370 $grouptimeopen = [];
1371 $grouptimeclose = [];
1372 foreach ($overrides as $override) {
1373 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1374 $grouptimeopen[] = $override->timeopen;
1375 }
1376 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1377 $grouptimeclose[] = $override->timeclose;
1378 }
1379 }
1380
7eae70e1
CB
1381 // Sort open times in ascending manner. The earlier open time gets higher priority.
1382 sort($grouptimeopen);
efe24976
JP
1383 // Set priorities.
1384 $opengrouppriorities = [];
1385 $openpriority = 1;
1386 foreach ($grouptimeopen as $timeopen) {
1387 $opengrouppriorities[$timeopen] = $openpriority++;
1388 }
1389
7eae70e1
CB
1390 // Sort close times in descending manner. The later close time gets higher priority.
1391 rsort($grouptimeclose);
efe24976
JP
1392 // Set priorities.
1393 $closegrouppriorities = [];
1394 $closepriority = 1;
1395 foreach ($grouptimeclose as $timeclose) {
1396 $closegrouppriorities[$timeclose] = $closepriority++;
1397 }
1398
1399 return [
1400 'open' => $opengrouppriorities,
1401 'close' => $closegrouppriorities
1402 ];
1403}
1404
8cc86111 1405/**
b2b4ec30
RT
1406 * List the actions that correspond to a view of this module.
1407 * This is used by the participation report.
1408 *
1409 * Note: This is not used by new logging system. Event with
1410 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1411 * be considered as view action.
1412 *
8cc86111 1413 * @return array
1414 */
f3221af9 1415function quiz_get_view_actions() {
cf051cc4 1416 return array('view', 'view all', 'report', 'review');
f3221af9 1417}
ee1fb969 1418
8cc86111 1419/**
b2b4ec30
RT
1420 * List the actions that correspond to a post of this module.
1421 * This is used by the participation report.
1422 *
1423 * Note: This is not used by new logging system. Event with
1424 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1425 * will be considered as post action.
1426 *
8cc86111 1427 * @return array
1428 */
f3221af9 1429function quiz_get_post_actions() {
25a03faa
TH
1430 return array('attempt', 'close attempt', 'preview', 'editquestions',
1431 'delete attempt', 'manualgrade');
f3221af9 1432}
ee1fb969 1433
f67172b6 1434/**
25302dee 1435 * @param array $questionids of question ids.
f7970e3c 1436 * @return bool whether any of these questions are used by any instance of this module.
f67172b6 1437 */
25302dee 1438function quiz_questions_in_use($questionids) {
07f88584
TH
1439 global $DB, $CFG;
1440 require_once($CFG->libdir . '/questionlib.php');
25302dee 1441 list($test, $params) = $DB->get_in_or_equal($questionids);
ccba5b88 1442 return $DB->record_exists_select('quiz_slots',
dc4a3ea1 1443 'questionid ' . $test, $params) || question_engine::questions_in_use(
6b5f24d3 1444 $questionids, new qubaid_join('{quiz_attempts} quiza',
07f88584 1445 'quiza.uniqueid', 'quiza.preview = 0'));
f67172b6 1446}
1447
7a6f4066 1448/**
1449 * Implementation of the function for printing the form elements that control
1450 * whether the course reset functionality affects the quiz.
3b1d5cc4 1451 *
25302dee 1452 * @param $mform the course reset form that is being built.
0b5a80a1 1453 */
25302dee 1454function quiz_reset_course_form_definition($mform) {
c159da4c 1455 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
25a03faa
TH
1456 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1457 get_string('removeallquizattempts', 'quiz'));
113486d2
SB
1458 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1459 get_string('removealluseroverrides', 'quiz'));
1460 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1461 get_string('removeallgroupoverrides', 'quiz'));
0b5a80a1 1462}
1463
1464/**
1465 * Course reset form defaults.
25302dee 1466 * @return array the defaults.
0b5a80a1 1467 */
1468function quiz_reset_course_form_defaults($course) {
113486d2
SB
1469 return array('reset_quiz_attempts' => 1,
1470 'reset_quiz_group_overrides' => 1,
1471 'reset_quiz_user_overrides' => 1);
0b5a80a1 1472}
1473
1474/**
1475 * Removes all grades from gradebook
8cc86111 1476 *
0b5a80a1 1477 * @param int $courseid
1478 * @param string optional type
7a6f4066 1479 */
0b5a80a1 1480function quiz_reset_gradebook($courseid, $type='') {
9cf4a18b 1481 global $CFG, $DB;
0b5a80a1 1482
25302dee
TH
1483 $quizzes = $DB->get_records_sql("
1484 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1485 FROM {modules} m
1486 JOIN {course_modules} cm ON m.id = cm.module
1487 JOIN {quiz} q ON cm.instance = q.id
1488 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
0b5a80a1 1489
25302dee
TH
1490 foreach ($quizzes as $quiz) {
1491 quiz_grade_item_update($quiz, 'reset');
0b5a80a1 1492 }
7a6f4066 1493}
1494
1495/**
72d2982e 1496 * Actual implementation of the reset course functionality, delete all the
7a6f4066 1497 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1498 * set and true.
6ef56c99 1499 *
1500 * Also, move the quiz open and close dates, if the course start date is changing.
8cc86111 1501 *
8cc86111 1502 * @param object $data the data submitted from the reset course.
0b5a80a1 1503 * @return array status array
7a6f4066 1504 */
0b5a80a1 1505function quiz_reset_userdata($data) {
53004e48 1506 global $CFG, $DB;
172238f4 1507 require_once($CFG->libdir . '/questionlib.php');
be0ba083 1508
0b5a80a1 1509 $componentstr = get_string('modulenameplural', 'quiz');
1510 $status = array();
b159da78 1511
25a03faa 1512 // Delete attempts.
6ef56c99 1513 if (!empty($data->reset_quiz_attempts)) {
6b5f24d3
TH
1514 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1515 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1516 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1517 array('quizcourseid' => $data->courseid)));
25302dee
TH
1518
1519 $DB->delete_records_select('quiz_attempts',
1520 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1521 $status[] = array(
1522 'component' => $componentstr,
25a03faa 1523 'item' => get_string('attemptsdeleted', 'quiz'),
25302dee
TH
1524 'error' => false);
1525
9e83f3d1 1526 // Remove all grades from gradebook.
8dd9ccf4
TH
1527 $DB->delete_records_select('quiz_grades',
1528 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
0b5a80a1 1529 if (empty($data->reset_gradebook_grades)) {
1530 quiz_reset_gradebook($data->courseid);
7a6f4066 1531 }
25302dee
TH
1532 $status[] = array(
1533 'component' => $componentstr,
8dd9ccf4 1534 'item' => get_string('gradesdeleted', 'quiz'),
25302dee 1535 'error' => false);
7a6f4066 1536 }
6ef56c99 1537
113486d2
SB
1538 // Remove user overrides.
1539 if (!empty($data->reset_quiz_user_overrides)) {
1540 $DB->delete_records_select('quiz_overrides',
1541 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1542 $status[] = array(
1543 'component' => $componentstr,
1544 'item' => get_string('useroverridesdeleted', 'quiz'),
1545 'error' => false);
1546 }
1547 // Remove group overrides.
1548 if (!empty($data->reset_quiz_group_overrides)) {
1549 $DB->delete_records_select('quiz_overrides',
1550 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1551 $status[] = array(
1552 'component' => $componentstr,
1553 'item' => get_string('groupoverridesdeleted', 'quiz'),
1554 'error' => false);
1555 }
1556
9e83f3d1 1557 // Updating dates - shift may be negative too.
0b5a80a1 1558 if ($data->timeshift) {
2079c732
TH
1559 $DB->execute("UPDATE {quiz_overrides}
1560 SET timeopen = timeopen + ?
1561 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1562 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1563 $DB->execute("UPDATE {quiz_overrides}
1564 SET timeclose = timeclose + ?
1565 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1566 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1567
0d14fcbc
AA
1568 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1569 // See MDL-9367.
25a03faa
TH
1570 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1571 $data->timeshift, $data->courseid);
2079c732 1572
25302dee
TH
1573 $status[] = array(
1574 'component' => $componentstr,
1575 'item' => get_string('openclosedatesupdated', 'quiz'),
1576 'error' => false);
7a6f4066 1577 }
0b5a80a1 1578
1579 return $status;
7a6f4066 1580}
14e6dc79 1581
b5a16eb7 1582/**
a1bf1b04 1583 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
b5a16eb7 1584 */
a1bf1b04
SA
1585function quiz_print_overview() {
1586 throw new coding_exception('quiz_print_overview() can not be used any more and is obsolete.');
b5a16eb7 1587}
6c58e198 1588
1589/**
25302dee 1590 * Return a textual summary of the number of attempts that have been made at a particular quiz,
cd300cf3 1591 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
8cc86111 1592 *
6c58e198 1593 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
25a03faa
TH
1594 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1595 * $cm->groupingid fields are used at the moment.
1596 * @param bool $returnzero if false (default), when no attempts have been
1597 * made '' is returned instead of 'Attempts: 0'.
2a13e454 1598 * @param int $currentgroup if there is a concept of current group where this method is being called
1599 * (e.g. a report) pass it in here. Default 0 which means no current group.
1600 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1601 * "Attemtps 123 (45 from this group)".
6c58e198 1602 */
2a13e454 1603function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
a49cb927 1604 global $DB, $USER;
9cf4a18b 1605 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
6c58e198 1606 if ($numattempts || $returnzero) {
2a13e454 1607 if (groups_get_activity_groupmode($cm)) {
92701024 1608 $a = new stdClass();
2a13e454 1609 $a->total = $numattempts;
1610 if ($currentgroup) {
3f11d7f9 1611 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
9cf4a18b 1612 '{quiz_attempts} qa JOIN ' .
1613 '{groups_members} gm ON qa.userid = gm.userid ' .
25a03faa
TH
1614 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1615 array($quiz->id, $currentgroup));
2a13e454 1616 return get_string('attemptsnumthisgroup', 'quiz', $a);
9cf4a18b 1617 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1618 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
3f11d7f9 1619 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
9cf4a18b 1620 '{quiz_attempts} qa JOIN ' .
1621 '{groups_members} gm ON qa.userid = gm.userid ' .
1622 'WHERE quiz = ? AND preview = 0 AND ' .
1623 "groupid $usql", array_merge(array($quiz->id), $params));
2a13e454 1624 return get_string('attemptsnumyourgroups', 'quiz', $a);
1625 }
1626 }
6c58e198 1627 return get_string('attemptsnum', 'quiz', $numattempts);
1628 }
1629 return '';
1630}
f432bebf 1631
4e781c7b 1632/**
a49cb927
TH
1633 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1634 * to the quiz reports.
1635 *
1636 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
25a03faa
TH
1637 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1638 * $cm->groupingid fields are used at the moment.
a49cb927 1639 * @param object $context the quiz context.
25a03faa
TH
1640 * @param bool $returnzero if false (default), when no attempts have been made
1641 * '' is returned instead of 'Attempts: 0'.
a49cb927
TH
1642 * @param int $currentgroup if there is a concept of current group where this method is being called
1643 * (e.g. a report) pass it in here. Default 0 which means no current group.
1644 * @return string HTML fragment for the link.
1645 */
25a03faa
TH
1646function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1647 $currentgroup = 0) {
a49cb927
TH
1648 global $CFG;
1649 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1650 if (!$summary) {
1651 return '';
1652 }
1653
1654 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1655 $url = new moodle_url('/mod/quiz/report.php', array(
1656 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1657 return html_writer::link($url, $summary);
1658}
1659
1660/**
4e781c7b 1661 * @param string $feature FEATURE_xx constant for requested feature
1662 * @return bool True if quiz supports feature
1663 */
1664function quiz_supports($feature) {
1665 switch($feature) {
455dc0de
FM
1666 case FEATURE_GROUPS: return true;
1667 case FEATURE_GROUPINGS: return true;
455dc0de
FM
1668 case FEATURE_MOD_INTRO: return true;
1669 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
349c9303 1670 case FEATURE_COMPLETION_HAS_RULES: return true;
455dc0de 1671 case FEATURE_GRADE_HAS_GRADE: return true;
7e48778b 1672 case FEATURE_GRADE_OUTCOMES: return true;
455dc0de
FM
1673 case FEATURE_BACKUP_MOODLE2: return true;
1674 case FEATURE_SHOW_DESCRIPTION: return true;
1675 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
b07ef13b 1676 case FEATURE_USES_QUESTIONS: return true;
42f103be 1677
49f6e5f4 1678 default: return null;
4e781c7b 1679 }
1680}
1681
f432bebf 1682/**
cca6e300 1683 * @return array all other caps used in module
f432bebf 1684 */
1685function quiz_get_extra_capabilities() {
d774e817 1686 global $CFG;
172238f4 1687 require_once($CFG->libdir . '/questionlib.php');
939218c2 1688 return question_get_all_capabilities();
f432bebf 1689}
55f599f0 1690
55f599f0 1691/**
1692 * This function extends the settings navigation block for the site.
1693 *
1694 * It is safe to rely on PAGE here as we will only ever be within the module
1695 * context when this is called
1696 *
0b29477b
SH
1697 * @param settings_navigation $settings
1698 * @param navigation_node $quiznode
ebd9ae65 1699 * @return void
55f599f0 1700 */
0b29477b
SH
1701function quiz_extend_settings_navigation($settings, $quiznode) {
1702 global $PAGE, $CFG;
55f599f0 1703
9e83f3d1
TH
1704 // Require {@link questionlib.php}
1705 // Included here as we only ever want to include this file if we really need to.
56ed242b 1706 require_once($CFG->libdir . '/questionlib.php');
55f599f0 1707
bc502c16
TH
1708 // We want to add these new nodes after the Edit settings node, and before the
1709 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1710 $keys = $quiznode->get_children_key_list();
1b8655ab 1711 $beforekey = null;
bc502c16 1712 $i = array_search('modedit', $keys);
1b8655ab 1713 if ($i === false and array_key_exists(0, $keys)) {
bc502c16
TH
1714 $beforekey = $keys[0];
1715 } else if (array_key_exists($i + 1, $keys)) {
1716 $beforekey = $keys[$i + 1];
bc502c16
TH
1717 }
1718
56ed242b 1719 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
56ed242b 1720 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
bc502c16 1721 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
25a03faa 1722 new moodle_url($url, array('mode'=>'group')),
bc502c16
TH
1723 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1724 $quiznode->add_node($node, $beforekey);
1725
1726 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
25a03faa 1727 new moodle_url($url, array('mode'=>'user')),
bc502c16
TH
1728 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1729 $quiznode->add_node($node, $beforekey);
55f599f0 1730 }
56ed242b 1731
55f599f0 1732 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
bc502c16
TH
1733 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1734 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1735 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1736 new pix_icon('t/edit', ''));
1737 $quiznode->add_node($node, $beforekey);
55f599f0 1738 }
56ed242b
SH
1739
1740 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
25a03faa
TH
1741 $url = new moodle_url('/mod/quiz/startattempt.php',
1742 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
bc502c16
TH
1743 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1744 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
c3847443 1745 new pix_icon('i/preview', ''));
bc502c16 1746 $quiznode->add_node($node, $beforekey);
55f599f0 1747 }
56ed242b 1748
ebd9ae65
FM
1749 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1750 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1751 $reportlist = quiz_report_list($PAGE->cm->context);
1752
1753 $url = new moodle_url('/mod/quiz/report.php',
1754 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1755 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1756 navigation_node::TYPE_SETTING,
1757 null, null, new pix_icon('i/report', '')), $beforekey);
1758
1759 foreach ($reportlist as $report) {
1760 $url = new moodle_url('/mod/quiz/report.php',
1761 array('id' => $PAGE->cm->id, 'mode' => $report));
1762 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1763 navigation_node::TYPE_SETTING,
1764 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1765 }
1766 }
1767
2a8a78c3 1768 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
56ed242b 1769}
fe6ce234
DC
1770
1771/**
1772 * Serves the quiz files.
1773 *
d2b7803e
DC
1774 * @package mod_quiz
1775 * @category files
1776 * @param stdClass $course course object
1777 * @param stdClass $cm course module object
1778 * @param stdClass $context context object
1779 * @param string $filearea file area
1780 * @param array $args extra arguments
1781 * @param bool $forcedownload whether or not force download
261cbbac 1782 * @param array $options additional options affecting the file serving
fe6ce234
DC
1783 * @return bool false if file not found, does not return if found - justsend the file
1784 */
261cbbac 1785function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
fe6ce234
DC
1786 global $CFG, $DB;
1787
1788 if ($context->contextlevel != CONTEXT_MODULE) {
1789 return false;
1790 }
1791
1792 require_login($course, false, $cm);
1793
1794 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1795 return false;
1796 }
1797
9e83f3d1 1798 // The 'intro' area is served by pluginfile.php.
fe6ce234
DC
1799 $fileareas = array('feedback');
1800 if (!in_array($filearea, $fileareas)) {
1801 return false;
1802 }
1803
1804 $feedbackid = (int)array_shift($args);
1805 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1806 return false;
1807 }
1808
1809 $fs = get_file_storage();
1810 $relativepath = implode('/', $args);
1811 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1812 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1813 return false;
1814 }
261cbbac 1815 send_stored_file($file, 0, 0, true, $options);
fe6ce234
DC
1816}
1817
1818/**
1819 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1820 * a question in a question_attempt when that attempt is a quiz attempt.
1821 *
d2b7803e
DC
1822 * @package mod_quiz
1823 * @category files
1824 * @param stdClass $course course settings object
1825 * @param stdClass $context context object
fe6ce234
DC
1826 * @param string $component the name of the component we are serving files for.
1827 * @param string $filearea the name of the file area.
d2b7803e
DC
1828 * @param int $qubaid the attempt usage id.
1829 * @param int $slot the id of a question in this quiz attempt.
fe6ce234
DC
1830 * @param array $args the remaining bits of the file path.
1831 * @param bool $forcedownload whether the user must be forced to download the file.
261cbbac 1832 * @param array $options additional options affecting the file serving
fe6ce234
DC
1833 * @return bool false if file not found, does not return if found - justsend the file
1834 */
6b8b0b2e 1835function quiz_question_pluginfile($course, $context, $component,
261cbbac 1836 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
cef18275 1837 global $CFG;
fe6ce234
DC
1838 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1839
56e82d99 1840 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
cdbea7ee 1841 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
fe6ce234
DC
1842
1843 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1844 // In the middle of an attempt.
1845 if (!$attemptobj->is_preview_user()) {
1846 $attemptobj->require_capability('mod/quiz:attempt');
1847 }
1848 $isreviewing = false;
1849
1850 } else {
1851 // Reviewing an attempt.
1852 $attemptobj->check_review_capability();
1853 $isreviewing = true;
1854 }
1855
56e82d99 1856 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
fe6ce234
DC
1857 $component, $filearea, $args, $forcedownload)) {
1858 send_file_not_found();
1859 }
1860
1861 $fs = get_file_storage();
1862 $relativepath = implode('/', $args);
1863 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1864 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1865 send_file_not_found();
1866 }
1867
261cbbac 1868 send_stored_file($file, 0, 0, $forcedownload, $options);
fe6ce234 1869}
b1627a92
DC
1870
1871/**
1872 * Return a list of page types
1873 * @param string $pagetype current page type
1874 * @param stdClass $parentcontext Block's parent context
1875 * @param stdClass $currentcontext Current context of block
1876 */
b38e2e28 1877function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
346a32a7 1878 $module_pagetype = array(
f38965db
TH
1879 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1880 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1881 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1882 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1883 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1884 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1885 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1886 );
b1627a92
DC
1887 return $module_pagetype;
1888}
33c8d37b
CF
1889
1890/**
1891 * @return the options for quiz navigation.
1892 */
1893function quiz_get_navigation_options() {
1894 return array(
1895 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1896 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1897 );
1898}
349c9303 1899
760ed019
FM
1900/**
1901 * Internal function used in quiz_get_completion_state. Check passing grade (or no attempts left) requirement for completion.
1902 *
1903 * @param object $course
1904 * @param object $cm
1905 * @param int $userid
1906 * @param object $quiz
1907 * @return bool True if the passing grade (or no attempts left) requirement is disabled or met.
1908 * @throws coding_exception
1909 */
1910function quiz_completion_check_passing_grade_or_all_attempts($course, $cm, $userid, $quiz) {
1911 global $CFG;
1912
1913 if (!$quiz->completionpass) {
1914 return true;
1915 }
1916
1917 // Check for passing grade.
1918 require_once($CFG->libdir . '/gradelib.php');
1919 $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
1920 'itemmodule' => 'quiz', 'iteminstance' => $cm->instance, 'outcomeid' => null));
1921 if ($item) {
1922 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
1923 if (!empty($grades[$userid]) && $grades[$userid]->is_passed($item)) {
1924 return true;
1925 }
1926 }
1927
1928 // If a passing grade is required and exhausting all available attempts is not accepted for completion,
1929 // then this quiz is not complete.
1930 if (!$quiz->completionattemptsexhausted) {
1931 return false;
1932 }
1933
1934 // Check if all attempts are used up.
1935 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
1936 if (!$attempts) {
1937 return false;
1938 }
1939 $lastfinishedattempt = end($attempts);
1940 $context = context_module::instance($cm->id);
1941 $quizobj = quiz::create($quiz->id, $userid);
1942 $accessmanager = new quiz_access_manager($quizobj, time(),
1943 has_capability('mod/quiz:ignoretimelimits', $context, $userid, false));
1944
1945 return $accessmanager->is_finished(count($attempts), $lastfinishedattempt);
1946}
1947
1948/**
1949 * Internal function used in quiz_get_completion_state. Check minimum attempts requirement for completion.
1950 *
1951 * @param int $userid
1952 * @param object $quiz
1953 * @return bool True if minimum attempts requirement is disabled or met.
1954 * @throws coding_exception
1955 */
1956function quiz_completion_check_min_attempts($userid, $quiz) {
1957 global $DB;
1958
1959 if (empty($quiz->completionminattempts)) {
1960 return true;
1961 }
1962
1963 // Check if the user has done enough attempts.
1964 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
1965 return $quiz->completionminattempts <= count($attempts);
1966}
1967
349c9303
RM
1968/**
1969 * Obtains the automatic completion state for this quiz on any conditions
1970 * in quiz settings, such as if all attempts are used or a certain grade is achieved.
1971 *
1972 * @param object $course Course
1973 * @param object $cm Course-module
1974 * @param int $userid User ID
1975 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1976 * @return bool True if completed, false if not. (If no conditions, then return
1977 * value depends on comparison type)
1978 */
1979function quiz_get_completion_state($course, $cm, $userid, $type) {
1980 global $DB;
349c9303
RM
1981
1982 $quiz = $DB->get_record('quiz', array('id' => $cm->instance), '*', MUST_EXIST);
760ed019 1983 if (!$quiz->completionattemptsexhausted && !$quiz->completionpass && !$quiz->completionminattempts) {
349c9303
RM
1984 return $type;
1985 }
1986
760ed019
FM
1987 if (!quiz_completion_check_passing_grade_or_all_attempts($course, $cm, $userid, $quiz)) {
1988 return false;
349c9303
RM
1989 }
1990
760ed019
FM
1991 if (!quiz_completion_check_min_attempts($userid, $quiz)) {
1992 return false;
349c9303 1993 }
760ed019
FM
1994
1995 return true;
349c9303 1996}
02a73d76
JL
1997
1998/**
1999 * Check if the module has any update that affects the current user since a given time.
2000 *
2001 * @param cm_info $cm course module data
2002 * @param int $from the time to check updates from
2003 * @param array $filter if we need to check only specific updates
2004 * @return stdClass an object with the different type of areas indicating if they were updated or not
2005 * @since Moodle 3.2
2006 */
2007function quiz_check_updates_since(cm_info $cm, $from, $filter = array()) {
2008 global $DB, $USER, $CFG;
2009 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2010
2011 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2012
2013 // Check if questions were updated.
65b2669d 2014 $updates->questions = (object) array('updated' => false);
02a73d76
JL
2015 $quizobj = quiz::create($cm->instance, $USER->id);
2016 $quizobj->preload_questions();
2017 $quizobj->load_questions();
2018 $questionids = array_keys($quizobj->get_questions());
2019 if (!empty($questionids)) {
2020 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
2021 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
2022 $params['time1'] = $from;
2023 $params['time2'] = $from;
8abfb7b1 2024 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
65b2669d
JL
2025 if (!empty($questions)) {
2026 $updates->questions->updated = true;
2027 $updates->questions->itemids = array_keys($questions);
2028 }
02a73d76
JL
2029 }
2030
2031 // Check for new attempts or grades.
65b2669d
JL
2032 $updates->attempts = (object) array('updated' => false);
2033 $updates->grades = (object) array('updated' => false);
02a73d76
JL
2034 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
2035 $params = array($cm->instance, $USER->id, $from);
65b2669d
JL
2036
2037 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2038 if (!empty($attempts)) {
2039 $updates->attempts->updated = true;
2040 $updates->attempts->itemids = array_keys($attempts);
2041 }
2042 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2043 if (!empty($grades)) {
2044 $updates->grades->updated = true;
2045 $updates->grades->itemids = array_keys($grades);
2046 }
02a73d76 2047
0a348387
JL
2048 // Now, teachers should see other students updates.
2049 if (has_capability('mod/quiz:viewreports', $cm->context)) {
2050 $select = 'quiz = ? AND timemodified > ?';
2051 $params = array($cm->instance, $from);
2052
2053 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
2054 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
2055 if (empty($groupusers)) {
2056 return $updates;
2057 }
2058 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
2059 $select .= ' AND userid ' . $insql;
2060 $params = array_merge($params, $inparams);
2061 }
2062
2063 $updates->userattempts = (object) array('updated' => false);
2064 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2065 if (!empty($attempts)) {
2066 $updates->userattempts->updated = true;
2067 $updates->userattempts->itemids = array_keys($attempts);
2068 }
2069
2070 $updates->usergrades = (object) array('updated' => false);
2071 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2072 if (!empty($grades)) {
2073 $updates->usergrades->updated = true;
2074 $updates->usergrades->itemids = array_keys($grades);
2075 }
2076 }
02a73d76
JL
2077 return $updates;
2078}
2b931458
DW
2079
2080/**
2081 * Get icon mapping for font-awesome.
2082 */
2083function mod_quiz_get_fontawesome_icon_map() {
2084 return [
2085 'mod_quiz:navflagged' => 'fa-flag',
2086 ];
2087}
b3d7d175
MN
2088
2089/**
59391e80
MN
2090 * This function receives a calendar event and returns the action associated with it, or null if there is none.
2091 *
2092 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
2093 * is not displayed on the block.
b3d7d175 2094 *
e1cd93ce 2095 * @param calendar_event $event
b3d7d175 2096 * @param \core_calendar\action_factory $factory
3f4d7f80 2097 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
01f96180 2098 * @return \core_calendar\local\event\entities\action_interface|null
b3d7d175 2099 */
e1cd93ce 2100function mod_quiz_core_calendar_provide_event_action(calendar_event $event,
3f4d7f80
SR
2101 \core_calendar\action_factory $factory,
2102 int $userid = 0) {
b3d7d175
MN
2103 global $CFG, $USER;
2104
2105 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2106
3f4d7f80
SR
2107 if (empty($userid)) {
2108 $userid = $USER->id;
2109 }
2110
2111 $cm = get_fast_modinfo($event->courseid, $userid)->instances['quiz'][$event->instance];
2112 $quizobj = quiz::create($cm->instance, $userid);
b3d7d175
MN
2113 $quiz = $quizobj->get_quiz();
2114
2115 // Check they have capabilities allowing them to view the quiz.
3f4d7f80 2116 if (!has_any_capability(['mod/quiz:reviewmyattempts', 'mod/quiz:attempt'], $quizobj->get_context(), $userid)) {
b3d7d175
MN
2117 return null;
2118 }
2119
96e44466
JY
2120 $completion = new \completion_info($cm->get_course());
2121
2122 $completiondata = $completion->get_data($cm, false, $userid);
2123
2124 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
2125 return null;
2126 }
2127
3f4d7f80 2128 quiz_update_effective_access($quiz, $userid);
b3d7d175
MN
2129
2130 // Check if quiz is closed, if so don't display it.
2131 if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) {
2132 return null;
2133 }
2134
3f4d7f80 2135 if (!$quizobj->is_participant($userid)) {
286631e7
P
2136 // If the user is not a participant then they have
2137 // no action to take. This will filter out the events for teachers.
2138 return null;
2139 }
2140
3f4d7f80 2141 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $userid);
b3d7d175
MN
2142 if (!empty($attempts)) {
2143 // The student's last attempt is finished.
2144 return null;
2145 }
2146
2147 $name = get_string('attemptquiznow', 'quiz');
2148 $url = new \moodle_url('/mod/quiz/view.php', [
2149 'id' => $cm->id
2150 ]);
2151 $itemcount = 1;
2152 $actionable = true;
2153
2154 // Check if the quiz is not currently actionable.
2155 if (!empty($quiz->timeopen) && $quiz->timeopen > time()) {
2156 $actionable = false;
2157 }
2158
2159 return $factory->create_instance(
2160 $name,
2161 $url,
2162 $itemcount,
2163 $actionable
2164 );
de66ac3c 2165}
b54bcddd
JD
2166
2167/**
2168 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2169 * for the course (see resource).
2170 *
2171 * Given a course_module object, this function returns any "extra" information that may be needed
2172 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2173 *
2174 * @param stdClass $coursemodule The coursemodule object (record).
2175 * @return cached_cm_info An object on information that the courses
2176 * will know about (most noticeably, an icon).
2177 */
2178function quiz_get_coursemodule_info($coursemodule) {
2179 global $DB;
2180
2181 $dbparams = ['id' => $coursemodule->instance];
438c01d0 2182 $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionpass';
b54bcddd
JD
2183 if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2184 return false;
2185 }
2186
2187 $result = new cached_cm_info();
23e5104a 2188 $result->name = $quiz->name;
b54bcddd 2189
438c01d0
MG
2190 if ($coursemodule->showdescription) {
2191 // Convert intro to html. Do not filter cached version, filters run at display time.
2192 $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false);
2193 }
2194
b54bcddd
JD
2195 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2196 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
2197 $result->customdata['customcompletionrules']['completionattemptsexhausted'] = $quiz->completionattemptsexhausted;
2198 $result->customdata['customcompletionrules']['completionpass'] = $quiz->completionpass;
2199 }
2200
2201 return $result;
2202}
2203
2204/**
2205 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2206 *
7f53e8aa 2207 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
b54bcddd
JD
2208 * @return array $descriptions the array of descriptions for the custom rules.
2209 */
2210function mod_quiz_get_completion_active_rule_descriptions($cm) {
2211 // Values will be present in cm_info, and we assume these are up to date.
7f53e8aa 2212 if (empty($cm->customdata['customcompletionrules'])
b54bcddd
JD
2213 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
2214 return [];
2215 }
2216
2217 $descriptions = [];
2218 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
2219 switch ($key) {
2220 case 'completionattemptsexhausted':
bd5fdcfc
EL
2221 if (!empty($val)) {
2222 $descriptions[] = get_string('completionattemptsexhausteddesc', 'quiz');
b54bcddd 2223 }
b54bcddd
JD
2224 break;
2225 case 'completionpass':
bd5fdcfc
EL
2226 if (!empty($val)) {
2227 $descriptions[] = get_string('completionpassdesc', 'quiz', format_time($val));
b54bcddd 2228 }
b54bcddd
JD
2229 break;
2230 default:
2231 break;
2232 }
2233 }
2234 return $descriptions;
2235}
9aac9f70
RW
2236
2237/**
2238 * Returns the min and max values for the timestart property of a quiz
2239 * activity event.
2240 *
2241 * The min and max values will be the timeopen and timeclose properties
2242 * of the quiz, respectively, if they are set.
2243 *
2244 * If either value isn't set then null will be returned instead to
2245 * indicate that there is no cutoff for that value.
2246 *
6688ae2b
RW
2247 * If the vent has no valid timestart range then [false, false] will
2248 * be returned. This is the case for overriden events.
2249 *
9aac9f70
RW
2250 * A minimum and maximum cutoff return value will look like:
2251 * [
2252 * [1505704373, 'The date must be after this date'],
2253 * [1506741172, 'The date must be before this date']
2254 * ]
2255 *
478b1d19 2256 * @throws \moodle_exception
9aac9f70 2257 * @param \calendar_event $event The calendar event to get the time range for
478b1d19 2258 * @param stdClass $quiz The module instance to get the range from
9aac9f70
RW
2259 * @return array
2260 */
478b1d19 2261function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz) {
9aac9f70
RW
2262 global $CFG, $DB;
2263 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2264
6688ae2b 2265 // Overrides do not have a valid timestart range.
9aac9f70 2266 if (quiz_is_overriden_calendar_event($event)) {
6688ae2b 2267 return [false, false];
9aac9f70
RW
2268 }
2269
9aac9f70
RW
2270 $mindate = null;
2271 $maxdate = null;
2272
2273 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2274 if (!empty($quiz->timeclose)) {
2275 $maxdate = [
2276 $quiz->timeclose,
2277 get_string('openafterclose', 'quiz')
2278 ];
2279 }
2280 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2281 if (!empty($quiz->timeopen)) {
2282 $mindate = [
2283 $quiz->timeopen,
2284 get_string('closebeforeopen', 'quiz')
2285 ];
2286 }
2287 }
2288
2289 return [$mindate, $maxdate];
2290}
2291
9aac9f70
RW
2292/**
2293 * This function will update the quiz module according to the
2294 * event that has been modified.
2295 *
2296 * It will set the timeopen or timeclose value of the quiz instance
2297 * according to the type of event provided.
2298 *
2299 * @throws \moodle_exception
478b1d19
RW
2300 * @param \calendar_event $event A quiz activity calendar event
2301 * @param \stdClass $quiz A quiz activity instance
9aac9f70 2302 */
478b1d19 2303function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz) {
9aac9f70
RW
2304 global $CFG, $DB;
2305 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2306
478b1d19
RW
2307 if (!in_array($event->eventtype, [QUIZ_EVENT_TYPE_OPEN, QUIZ_EVENT_TYPE_CLOSE])) {
2308 // This isn't an event that we care about so we can ignore it.
9aac9f70
RW
2309 return;
2310 }
2311
2312 $courseid = $event->courseid;
2313 $modulename = $event->modulename;
2314 $instanceid = $event->instance;
2315 $modified = false;
2316 $closedatechanged = false;
2317
2318 // Something weird going on. The event is for a different module so
2319 // we should ignore it.
2320 if ($modulename != 'quiz') {
2321 return;
2322 }
2323
478b1d19
RW
2324 if ($quiz->id != $instanceid) {
2325 // The provided quiz instance doesn't match the event so
2326 // there is nothing to do here.
2327 return;
2328 }
2329
2330 // We don't update the activity if it's an override event that has
2331 // been modified.
2332 if (quiz_is_overriden_calendar_event($event)) {
2333 return;
2334 }
2335
9aac9f70
RW
2336 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2337 $context = context_module::instance($coursemodule->id);
2338
2339 // The user does not have the capability to modify this activity.
2340 if (!has_capability('moodle/course:manageactivities', $context)) {
2341 return;
2342 }
2343
2344 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2345 // If the event is for the quiz activity opening then we should
2346 // set the start time of the quiz activity to be the new start
2347 // time of the event.
9aac9f70
RW
2348 if ($quiz->timeopen != $event->timestart) {
2349 $quiz->timeopen = $event->timestart;
2350 $modified = true;
2351 }
2352 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2353 // If the event is for the quiz activity closing then we should
2354 // set the end time of the quiz activity to be the new start
2355 // time of the event.
9aac9f70
RW
2356 if ($quiz->timeclose != $event->timestart) {
2357 $quiz->timeclose = $event->timestart;
2358 $modified = true;
2359 $closedatechanged = true;
2360 }
2361 }
2362
2363 if ($modified) {
2364 $quiz->timemodified = time();
2365 $DB->update_record('quiz', $quiz);
2366
2367 if ($closedatechanged) {
2368 quiz_update_open_attempts(array('quizid' => $quiz->id));
2369 }
2370
2371 // Delete any previous preview attempts.
2372 quiz_delete_previews($quiz);
2373 quiz_update_events($quiz);
2374 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2375 $event->trigger();
2376 }
2377}
f33dc783
RW
2378
2379/**
f046b9a4 2380 * Generates the question bank in a fragment output. This allows
f33dc783
RW
2381 * the question bank to be displayed in a modal.
2382 *
2383 * The only expected argument provided in the $args array is
2384 * 'querystring'. The value should be the list of parameters
2385 * URL encoded and used to build the question bank page.
2386 *
2387 * The individual list of parameters expected can be found in
2388 * question_build_edit_resources.
2389 *
2390 * @param array $args The fragment arguments.
2391 * @return string The rendered mform fragment.
2392 */
2393function mod_quiz_output_fragment_quiz_question_bank($args) {
2394 global $CFG, $DB, $PAGE;
2395 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2396 require_once($CFG->dirroot . '/question/editlib.php');
2397
2398 $querystring = preg_replace('/^\?/', '', $args['querystring']);
2399 $params = [];
2400 parse_str($querystring, $params);
2401
2402 // Build the required resources. The $params are all cleaned as
2403 // part of this process.
2404 list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) =
2405 question_build_edit_resources('editq', '/mod/quiz/edit.php', $params);
2406
2407 // Get the course object and related bits.
2408 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
2409 require_capability('mod/quiz:manage', $contexts->lowest());
2410
2411 // Create quiz question bank view.
fc23bc85 2412 $questionbank = new mod_quiz\question\bank\custom_view($contexts, $thispageurl, $course, $cm, $quiz);
f33dc783
RW
2413 $questionbank->set_quiz_has_attempts(quiz_has_attempts($quiz->id));
2414
2415 // Output.
2416 $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2417 return $renderer->question_bank_contents($questionbank, $pagevars);
2418}
f046b9a4
RW
2419
2420/**
2421 * Generates the add random question in a fragment output. This allows the
2422 * form to be rendered in javascript, for example inside a modal.
2423 *
2424 * The required arguments as keys in the $args array are:
2425 * cat {string} The category and category context ids comma separated.
2426 * addonpage {int} The page id to add this question to.
2427 * returnurl {string} URL to return to after form submission.
2428 * cmid {int} The course module id the questions are being added to.
2429 *
2430 * @param array $args The fragment arguments.
2431 * @return string The rendered mform fragment.
2432 */
2433function mod_quiz_output_fragment_add_random_question_form($args) {
2434 global $CFG;
2435 require_once($CFG->dirroot . '/mod/quiz/addrandomform.php');
2436
2437 $contexts = new \question_edit_contexts($args['context']);
2438 $formoptions = [
2439 'contexts' => $contexts,
2440 'cat' => $args['cat']
2441 ];
2442 $formdata = [
2443 'category' => $args['cat'],
2444 'addonpage' => $args['addonpage'],
2445 'returnurl' => $args['returnurl'],
2446 'cmid' => $args['cmid']
2447 ];
2448
2449 $form = new quiz_add_random_form(
2450 new \moodle_url('/mod/quiz/addrandom.php'),
2451 $formoptions,
2452 'post',
2453 '',
2454 null,
2455 true,
2456 $formdata
2457 );
2458 $form->set_data($formdata);
2459
2460 return $form->render();
2461}