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