MDL-61135 mod_quiz: add question bank fragment
[moodle.git] / mod / quiz / lib.php
blob6bab4c4ab4ed317524e2cecf9aad5dbc6c2f3195
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for the quiz module.
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}
23 * @package mod_quiz
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir . '/eventslib.php');
32 require_once($CFG->dirroot . '/calendar/lib.php');
35 /**#@+
36 * Option controlling what options are offered on the quiz settings form.
38 define('QUIZ_MAX_ATTEMPT_OPTION', 10);
39 define('QUIZ_MAX_QPP_OPTION', 50);
40 define('QUIZ_MAX_DECIMAL_OPTION', 5);
41 define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
42 /**#@-*/
44 /**#@+
45 * Options determining how the grades from individual attempts are combined to give
46 * the overall grade for a user
48 define('QUIZ_GRADEHIGHEST', '1');
49 define('QUIZ_GRADEAVERAGE', '2');
50 define('QUIZ_ATTEMPTFIRST', '3');
51 define('QUIZ_ATTEMPTLAST', '4');
52 /**#@-*/
54 /**
55 * @var int If start and end date for the quiz are more than this many seconds apart
56 * they will be represented by two separate events in the calendar
58 define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
60 /**#@+
61 * Options for navigation method within quizzes.
63 define('QUIZ_NAVMETHOD_FREE', 'free');
64 define('QUIZ_NAVMETHOD_SEQ', 'sequential');
65 /**#@-*/
67 /**
68 * Event types.
70 define('QUIZ_EVENT_TYPE_OPEN', 'open');
71 define('QUIZ_EVENT_TYPE_CLOSE', 'close');
73 /**
74 * Given an object containing all the necessary data,
75 * (defined by the form in mod_form.php) this function
76 * will create a new instance and return the id number
77 * of the new instance.
79 * @param object $quiz the data that came from the form.
80 * @return mixed the id of the new instance on success,
81 * false or a string error message on failure.
83 function quiz_add_instance($quiz) {
84 global $DB;
85 $cmid = $quiz->coursemodule;
87 // Process the options from the form.
88 $quiz->created = time();
89 $result = quiz_process_options($quiz);
90 if ($result && is_string($result)) {
91 return $result;
94 // Try to store it in the database.
95 $quiz->id = $DB->insert_record('quiz', $quiz);
97 // Create the first section for this quiz.
98 $DB->insert_record('quiz_sections', array('quizid' => $quiz->id,
99 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0));
101 // Do the processing required after an add or an update.
102 quiz_after_add_or_update($quiz);
104 return $quiz->id;
108 * Given an object containing all the necessary data,
109 * (defined by the form in mod_form.php) this function
110 * will update an existing instance with new data.
112 * @param object $quiz the data that came from the form.
113 * @return mixed true on success, false or a string error message on failure.
115 function quiz_update_instance($quiz, $mform) {
116 global $CFG, $DB;
117 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
119 // Process the options from the form.
120 $result = quiz_process_options($quiz);
121 if ($result && is_string($result)) {
122 return $result;
125 // Get the current value, so we can see what changed.
126 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
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;
133 // Update the database.
134 $quiz->id = $quiz->instance;
135 $DB->update_record('quiz', $quiz);
137 // Do the processing required after an add or an update.
138 quiz_after_add_or_update($quiz);
140 if ($oldquiz->grademethod != $quiz->grademethod) {
141 quiz_update_all_final_grades($quiz);
142 quiz_update_grades($quiz);
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));
152 // Delete any previous preview attempts.
153 quiz_delete_previews($quiz);
155 // Repaginate, if asked to.
156 if (!empty($quiz->repaginatenow)) {
157 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
160 return true;
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.
168 * @param int $id the id of the quiz to delete.
169 * @return bool success or failure.
171 function quiz_delete_instance($id) {
172 global $DB;
174 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
176 quiz_delete_all_attempts($quiz);
177 quiz_delete_all_overrides($quiz);
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'));
186 // We need to do this before we try and delete randoms, otherwise they would still be 'in use'.
187 $DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
188 $DB->delete_records('quiz_sections', array('quizid' => $quiz->id));
190 foreach ($questionids as $questionid) {
191 question_delete_question($questionid);
194 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
196 quiz_access_manager::delete_settings($quiz);
198 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
199 foreach ($events as $event) {
200 $event = calendar_event::load($event);
201 $event->delete();
204 quiz_grade_item_delete($quiz);
205 $DB->delete_records('quiz', array('id' => $quiz->id));
207 return true;
211 * Deletes a quiz override from the database and clears any corresponding calendar events
213 * @param object $quiz The quiz object.
214 * @param int $overrideid The id of the override being deleted
215 * @return bool true on success
217 function quiz_delete_override($quiz, $overrideid) {
218 global $DB;
220 if (!isset($quiz->cmid)) {
221 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
222 $quiz->cmid = $cm->id;
225 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
227 // Delete the events.
228 if (isset($override->groupid)) {
229 // Create the search array for a group override.
230 $eventsearcharray = array('modulename' => 'quiz',
231 'instance' => $quiz->id, 'groupid' => (int)$override->groupid);
232 } else {
233 // Create the search array for a user override.
234 $eventsearcharray = array('modulename' => 'quiz',
235 'instance' => $quiz->id, 'userid' => (int)$override->userid);
237 $events = $DB->get_records('event', $eventsearcharray);
238 foreach ($events as $event) {
239 $eventold = calendar_event::load($event);
240 $eventold->delete();
243 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
245 // Set the common parameters for one of the events we will be triggering.
246 $params = array(
247 'objectid' => $override->id,
248 'context' => context_module::instance($quiz->cmid),
249 'other' => array(
250 'quizid' => $override->quiz
253 // Determine which override deleted event to fire.
254 if (!empty($override->userid)) {
255 $params['relateduserid'] = $override->userid;
256 $event = \mod_quiz\event\user_override_deleted::create($params);
257 } else {
258 $params['other']['groupid'] = $override->groupid;
259 $event = \mod_quiz\event\group_override_deleted::create($params);
262 // Trigger the override deleted event.
263 $event->add_record_snapshot('quiz_overrides', $override);
264 $event->trigger();
266 return true;
270 * Deletes all quiz overrides from the database and clears any corresponding calendar events
272 * @param object $quiz The quiz object.
274 function quiz_delete_all_overrides($quiz) {
275 global $DB;
277 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
278 foreach ($overrides as $override) {
279 quiz_delete_override($quiz, $override->id);
284 * Updates a quiz object with override information for a user.
286 * Algorithm: For each quiz setting, if there is a matching user-specific override,
287 * then use that otherwise, if there are group-specific overrides, return the most
288 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
290 * Special case: if there is more than one password that applies to the user, then
291 * quiz->extrapasswords will contain an array of strings giving the remaining
292 * passwords.
294 * @param object $quiz The quiz object.
295 * @param int $userid The userid.
296 * @return object $quiz The updated quiz object.
298 function quiz_update_effective_access($quiz, $userid) {
299 global $DB;
301 // Check for user override.
302 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
304 if (!$override) {
305 $override = new stdClass();
306 $override->timeopen = null;
307 $override->timeclose = null;
308 $override->timelimit = null;
309 $override->attempts = null;
310 $override->password = null;
313 // Check for group overrides.
314 $groupings = groups_get_user_groups($quiz->course, $userid);
316 if (!empty($groupings[0])) {
317 // Select all overrides that apply to the User's groups.
318 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
319 $sql = "SELECT * FROM {quiz_overrides}
320 WHERE groupid $extra AND quiz = ?";
321 $params[] = $quiz->id;
322 $records = $DB->get_records_sql($sql, $params);
324 // Combine the overrides.
325 $opens = array();
326 $closes = array();
327 $limits = array();
328 $attempts = array();
329 $passwords = array();
331 foreach ($records as $gpoverride) {
332 if (isset($gpoverride->timeopen)) {
333 $opens[] = $gpoverride->timeopen;
335 if (isset($gpoverride->timeclose)) {
336 $closes[] = $gpoverride->timeclose;
338 if (isset($gpoverride->timelimit)) {
339 $limits[] = $gpoverride->timelimit;
341 if (isset($gpoverride->attempts)) {
342 $attempts[] = $gpoverride->attempts;
344 if (isset($gpoverride->password)) {
345 $passwords[] = $gpoverride->password;
348 // If there is a user override for a setting, ignore the group override.
349 if (is_null($override->timeopen) && count($opens)) {
350 $override->timeopen = min($opens);
352 if (is_null($override->timeclose) && count($closes)) {
353 if (in_array(0, $closes)) {
354 $override->timeclose = 0;
355 } else {
356 $override->timeclose = max($closes);
359 if (is_null($override->timelimit) && count($limits)) {
360 if (in_array(0, $limits)) {
361 $override->timelimit = 0;
362 } else {
363 $override->timelimit = max($limits);
366 if (is_null($override->attempts) && count($attempts)) {
367 if (in_array(0, $attempts)) {
368 $override->attempts = 0;
369 } else {
370 $override->attempts = max($attempts);
373 if (is_null($override->password) && count($passwords)) {
374 $override->password = array_shift($passwords);
375 if (count($passwords)) {
376 $override->extrapasswords = $passwords;
382 // Merge with quiz defaults.
383 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
384 foreach ($keys as $key) {
385 if (isset($override->{$key})) {
386 $quiz->{$key} = $override->{$key};
390 return $quiz;
394 * Delete all the attempts belonging to a quiz.
396 * @param object $quiz The quiz object.
398 function quiz_delete_all_attempts($quiz) {
399 global $CFG, $DB;
400 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
401 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
402 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
403 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
407 * Get the best current grade for a particular user in a quiz.
409 * @param object $quiz the quiz settings.
410 * @param int $userid the id of the user.
411 * @return float the user's current grade for this quiz, or null if this user does
412 * not have a grade on this quiz.
414 function quiz_get_best_grade($quiz, $userid) {
415 global $DB;
416 $grade = $DB->get_field('quiz_grades', 'grade',
417 array('quiz' => $quiz->id, 'userid' => $userid));
419 // Need to detect errors/no result, without catching 0 grades.
420 if ($grade === false) {
421 return null;
424 return $grade + 0; // Convert to number.
428 * Is this a graded quiz? If this method returns true, you can assume that
429 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
430 * divide by them).
432 * @param object $quiz a row from the quiz table.
433 * @return bool whether this is a graded quiz.
435 function quiz_has_grades($quiz) {
436 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
440 * Does this quiz allow multiple tries?
442 * @return bool
444 function quiz_allows_multiple_tries($quiz) {
445 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
446 return $bt->allows_multiple_submitted_responses();
450 * Return a small object with summary information about what a
451 * user has done with a given particular instance of this module
452 * Used for user activity reports.
453 * $return->time = the time they did it
454 * $return->info = a short text description
456 * @param object $course
457 * @param object $user
458 * @param object $mod
459 * @param object $quiz
460 * @return object|null
462 function quiz_user_outline($course, $user, $mod, $quiz) {
463 global $DB, $CFG;
464 require_once($CFG->libdir . '/gradelib.php');
465 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
467 if (empty($grades->items[0]->grades)) {
468 return null;
469 } else {
470 $grade = reset($grades->items[0]->grades);
473 $result = new stdClass();
474 // If the user can't see hidden grades, don't return that information.
475 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
476 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
477 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
478 } else {
479 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
482 // Datesubmitted == time created. dategraded == time modified or time overridden
483 // if grade was last modified by the user themselves use date graded. Otherwise use
484 // date submitted.
485 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
486 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
487 $result->time = $grade->dategraded;
488 } else {
489 $result->time = $grade->datesubmitted;
492 return $result;
496 * Print a detailed representation of what a user has done with
497 * a given particular instance of this module, for user activity reports.
499 * @param object $course
500 * @param object $user
501 * @param object $mod
502 * @param object $quiz
503 * @return bool
505 function quiz_user_complete($course, $user, $mod, $quiz) {
506 global $DB, $CFG, $OUTPUT;
507 require_once($CFG->libdir . '/gradelib.php');
508 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
510 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
511 if (!empty($grades->items[0]->grades)) {
512 $grade = reset($grades->items[0]->grades);
513 // If the user can't see hidden grades, don't return that information.
514 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
515 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
516 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
517 if ($grade->str_feedback) {
518 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
520 } else {
521 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
522 if ($grade->str_feedback) {
523 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
528 if ($attempts = $DB->get_records('quiz_attempts',
529 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
530 foreach ($attempts as $attempt) {
531 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
532 if ($attempt->state != quiz_attempt::FINISHED) {
533 echo quiz_attempt_state_name($attempt->state);
534 } else {
535 if (!isset($gitem)) {
536 if (!empty($grades->items[0]->grades)) {
537 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
538 } else {
539 $gitem = new stdClass();
540 $gitem->hidden = true;
543 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
544 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
545 } else {
546 echo get_string('hidden', 'grades');
549 echo ' - '.userdate($attempt->timemodified).'<br />';
551 } else {
552 print_string('noattempts', 'quiz');
555 return true;
559 * Quiz periodic clean-up tasks.
561 function quiz_cron() {
562 global $CFG;
564 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
565 mtrace('');
567 $timenow = time();
568 $overduehander = new mod_quiz_overdue_attempt_updater();
570 $processto = $timenow - get_config('quiz', 'graceperiodmin');
572 mtrace(' Looking for quiz overdue quiz attempts...');
574 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
576 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
578 // Run cron for our sub-plugin types.
579 cron_execute_plugin_type('quiz', 'quiz reports');
580 cron_execute_plugin_type('quizaccess', 'quiz access rules');
582 return true;
586 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
587 * @param int $userid the userid.
588 * @param string $status 'all', 'finished' or 'unfinished' to control
589 * @param bool $includepreviews
590 * @return an array of all the user's attempts at this quiz. Returns an empty
591 * array if there are none.
593 function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
594 global $DB, $CFG;
595 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
596 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
597 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
598 // MDL-33048.
599 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
601 $params = array();
602 switch ($status) {
603 case 'all':
604 $statuscondition = '';
605 break;
607 case 'finished':
608 $statuscondition = ' AND state IN (:state1, :state2)';
609 $params['state1'] = quiz_attempt::FINISHED;
610 $params['state2'] = quiz_attempt::ABANDONED;
611 break;
613 case 'unfinished':
614 $statuscondition = ' AND state IN (:state1, :state2)';
615 $params['state1'] = quiz_attempt::IN_PROGRESS;
616 $params['state2'] = quiz_attempt::OVERDUE;
617 break;
620 $quizids = (array) $quizids;
621 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
622 $params += $inparams;
623 $params['userid'] = $userid;
625 $previewclause = '';
626 if (!$includepreviews) {
627 $previewclause = ' AND preview = 0';
630 return $DB->get_records_select('quiz_attempts',
631 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
632 $params, 'quiz, attempt ASC');
636 * Return grade for given user or all users.
638 * @param int $quizid id of quiz
639 * @param int $userid optional user id, 0 means all users
640 * @return array array of grades, false if none. These are raw grades. They should
641 * be processed with quiz_format_grade for display.
643 function quiz_get_user_grades($quiz, $userid = 0) {
644 global $CFG, $DB;
646 $params = array($quiz->id);
647 $usertest = '';
648 if ($userid) {
649 $params[] = $userid;
650 $usertest = 'AND u.id = ?';
652 return $DB->get_records_sql("
653 SELECT
654 u.id,
655 u.id AS userid,
656 qg.grade AS rawgrade,
657 qg.timemodified AS dategraded,
658 MAX(qa.timefinish) AS datesubmitted
660 FROM {user} u
661 JOIN {quiz_grades} qg ON u.id = qg.userid
662 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
664 WHERE qg.quiz = ?
665 $usertest
666 GROUP BY u.id, qg.grade, qg.timemodified", $params);
670 * Round a grade to to the correct number of decimal places, and format it for display.
672 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
673 * @param float $grade The grade to round.
674 * @return float
676 function quiz_format_grade($quiz, $grade) {
677 if (is_null($grade)) {
678 return get_string('notyetgraded', 'quiz');
680 return format_float($grade, $quiz->decimalpoints);
684 * Determine the correct number of decimal places required to format a grade.
686 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
687 * @return integer
689 function quiz_get_grade_format($quiz) {
690 if (empty($quiz->questiondecimalpoints)) {
691 $quiz->questiondecimalpoints = -1;
694 if ($quiz->questiondecimalpoints == -1) {
695 return $quiz->decimalpoints;
698 return $quiz->questiondecimalpoints;
702 * Round a grade to the correct number of decimal places, and format it for display.
704 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
705 * @param float $grade The grade to round.
706 * @return float
708 function quiz_format_question_grade($quiz, $grade) {
709 return format_float($grade, quiz_get_grade_format($quiz));
713 * Update grades in central gradebook
715 * @category grade
716 * @param object $quiz the quiz settings.
717 * @param int $userid specific user only, 0 means all users.
718 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
720 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
721 global $CFG, $DB;
722 require_once($CFG->libdir . '/gradelib.php');
724 if ($quiz->grade == 0) {
725 quiz_grade_item_update($quiz);
727 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
728 quiz_grade_item_update($quiz, $grades);
730 } else if ($userid && $nullifnone) {
731 $grade = new stdClass();
732 $grade->userid = $userid;
733 $grade->rawgrade = null;
734 quiz_grade_item_update($quiz, $grade);
736 } else {
737 quiz_grade_item_update($quiz);
742 * Create or update the grade item for given quiz
744 * @category grade
745 * @param object $quiz object with extra cmidnumber
746 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
747 * @return int 0 if ok, error code otherwise
749 function quiz_grade_item_update($quiz, $grades = null) {
750 global $CFG, $OUTPUT;
751 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
752 require_once($CFG->libdir . '/gradelib.php');
754 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
755 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
756 } else {
757 $params = array('itemname' => $quiz->name);
760 if ($quiz->grade > 0) {
761 $params['gradetype'] = GRADE_TYPE_VALUE;
762 $params['grademax'] = $quiz->grade;
763 $params['grademin'] = 0;
765 } else {
766 $params['gradetype'] = GRADE_TYPE_NONE;
769 // What this is trying to do:
770 // 1. If the quiz is set to not show grades while the quiz is still open,
771 // and is set to show grades after the quiz is closed, then create the
772 // grade_item with a show-after date that is the quiz close date.
773 // 2. If the quiz is set to not show grades at either of those times,
774 // create the grade_item as hidden.
775 // 3. If the quiz is set to show grades, create the grade_item visible.
776 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
777 mod_quiz_display_options::LATER_WHILE_OPEN);
778 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
779 mod_quiz_display_options::AFTER_CLOSE);
780 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
781 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
782 $params['hidden'] = 1;
784 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
785 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
786 if ($quiz->timeclose) {
787 $params['hidden'] = $quiz->timeclose;
788 } else {
789 $params['hidden'] = 1;
792 } else {
793 // Either
794 // a) both open and closed enabled
795 // b) open enabled, closed disabled - we can not "hide after",
796 // grades are kept visible even after closing.
797 $params['hidden'] = 0;
800 if (!$params['hidden']) {
801 // If the grade item is not hidden by the quiz logic, then we need to
802 // hide it if the quiz is hidden from students.
803 if (property_exists($quiz, 'visible')) {
804 // Saving the quiz form, and cm not yet updated in the database.
805 $params['hidden'] = !$quiz->visible;
806 } else {
807 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
808 $params['hidden'] = !$cm->visible;
812 if ($grades === 'reset') {
813 $params['reset'] = true;
814 $grades = null;
817 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
818 if (!empty($gradebook_grades->items)) {
819 $grade_item = $gradebook_grades->items[0];
820 if ($grade_item->locked) {
821 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
822 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
823 if (!$confirm_regrade) {
824 if (!AJAX_SCRIPT) {
825 $message = get_string('gradeitemislocked', 'grades');
826 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
827 '&amp;mode=overview';
828 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
829 echo $OUTPUT->box_start('generalbox', 'notice');
830 echo '<p>'. $message .'</p>';
831 echo $OUTPUT->container_start('buttons');
832 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
833 echo $OUTPUT->single_button($back_link, get_string('cancel'));
834 echo $OUTPUT->container_end();
835 echo $OUTPUT->box_end();
837 return GRADE_UPDATE_ITEM_LOCKED;
842 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
846 * Delete grade item for given quiz
848 * @category grade
849 * @param object $quiz object
850 * @return object quiz
852 function quiz_grade_item_delete($quiz) {
853 global $CFG;
854 require_once($CFG->libdir . '/gradelib.php');
856 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
857 null, array('deleted' => 1));
861 * This standard function will check all instances of this module
862 * and make sure there are up-to-date events created for each of them.
863 * If courseid = 0, then every quiz event in the site is checked, else
864 * only quiz events belonging to the course specified are checked.
865 * This function is used, in its new format, by restore_refresh_events()
867 * @param int $courseid
868 * @param int|stdClass $instance Quiz module instance or ID.
869 * @param int|stdClass $cm Course module object or ID (not used in this module).
870 * @return bool
872 function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
873 global $DB;
875 // If we have instance information then we can just update the one event instead of updating all events.
876 if (isset($instance)) {
877 if (!is_object($instance)) {
878 $instance = $DB->get_record('quiz', array('id' => $instance), '*', MUST_EXIST);
880 quiz_update_events($instance);
881 return true;
884 if ($courseid == 0) {
885 if (!$quizzes = $DB->get_records('quiz')) {
886 return true;
888 } else {
889 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
890 return true;
894 foreach ($quizzes as $quiz) {
895 quiz_update_events($quiz);
898 return true;
902 * Returns all quiz graded users since a given time for specified quiz
904 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
905 $courseid, $cmid, $userid = 0, $groupid = 0) {
906 global $CFG, $USER, $DB;
907 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
909 $course = get_course($courseid);
910 $modinfo = get_fast_modinfo($course);
912 $cm = $modinfo->cms[$cmid];
913 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
915 if ($userid) {
916 $userselect = "AND u.id = :userid";
917 $params['userid'] = $userid;
918 } else {
919 $userselect = '';
922 if ($groupid) {
923 $groupselect = 'AND gm.groupid = :groupid';
924 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
925 $params['groupid'] = $groupid;
926 } else {
927 $groupselect = '';
928 $groupjoin = '';
931 $params['timestart'] = $timestart;
932 $params['quizid'] = $quiz->id;
934 $ufields = user_picture::fields('u', null, 'useridagain');
935 if (!$attempts = $DB->get_records_sql("
936 SELECT qa.*,
937 {$ufields}
938 FROM {quiz_attempts} qa
939 JOIN {user} u ON u.id = qa.userid
940 $groupjoin
941 WHERE qa.timefinish > :timestart
942 AND qa.quiz = :quizid
943 AND qa.preview = 0
944 $userselect
945 $groupselect
946 ORDER BY qa.timefinish ASC", $params)) {
947 return;
950 $context = context_module::instance($cm->id);
951 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
952 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
953 $grader = has_capability('mod/quiz:viewreports', $context);
954 $groupmode = groups_get_activity_groupmode($cm, $course);
956 $usersgroups = null;
957 $aname = format_string($cm->name, true);
958 foreach ($attempts as $attempt) {
959 if ($attempt->userid != $USER->id) {
960 if (!$grader) {
961 // Grade permission required.
962 continue;
965 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
966 $usersgroups = groups_get_all_groups($course->id,
967 $attempt->userid, $cm->groupingid);
968 $usersgroups = array_keys($usersgroups);
969 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
970 continue;
975 $options = quiz_get_review_options($quiz, $attempt, $context);
977 $tmpactivity = new stdClass();
979 $tmpactivity->type = 'quiz';
980 $tmpactivity->cmid = $cm->id;
981 $tmpactivity->name = $aname;
982 $tmpactivity->sectionnum = $cm->sectionnum;
983 $tmpactivity->timestamp = $attempt->timefinish;
985 $tmpactivity->content = new stdClass();
986 $tmpactivity->content->attemptid = $attempt->id;
987 $tmpactivity->content->attempt = $attempt->attempt;
988 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
989 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
990 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
991 } else {
992 $tmpactivity->content->sumgrades = null;
993 $tmpactivity->content->maxgrade = null;
996 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
997 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
999 $activities[$index++] = $tmpactivity;
1003 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
1004 global $CFG, $OUTPUT;
1006 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
1008 echo '<tr><td class="userpicture" valign="top">';
1009 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
1010 echo '</td><td>';
1012 if ($detail) {
1013 $modname = $modnames[$activity->type];
1014 echo '<div class="title">';
1015 echo $OUTPUT->image_icon('icon', $modname, $activity->type);
1016 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1017 $activity->cmid . '">' . $activity->name . '</a>';
1018 echo '</div>';
1021 echo '<div class="grade">';
1022 echo get_string('attempt', 'quiz', $activity->content->attempt);
1023 if (isset($activity->content->maxgrade)) {
1024 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1025 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1026 $activity->content->attemptid . '">' . $grades . '</a>)';
1028 echo '</div>';
1030 echo '<div class="user">';
1031 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1032 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
1033 '</a> - ' . userdate($activity->timestamp);
1034 echo '</div>';
1036 echo '</td></tr></table>';
1038 return;
1042 * Pre-process the quiz options form data, making any necessary adjustments.
1043 * Called by add/update instance in this file.
1045 * @param object $quiz The variables set on the form.
1047 function quiz_process_options($quiz) {
1048 global $CFG;
1049 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1050 require_once($CFG->libdir . '/questionlib.php');
1052 $quiz->timemodified = time();
1054 // Quiz name.
1055 if (!empty($quiz->name)) {
1056 $quiz->name = trim($quiz->name);
1059 // Password field - different in form to stop browsers that remember passwords
1060 // getting confused.
1061 $quiz->password = $quiz->quizpassword;
1062 unset($quiz->quizpassword);
1064 // Quiz feedback.
1065 if (isset($quiz->feedbacktext)) {
1066 // Clean up the boundary text.
1067 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1068 if (empty($quiz->feedbacktext[$i]['text'])) {
1069 $quiz->feedbacktext[$i]['text'] = '';
1070 } else {
1071 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1075 // Check the boundary value is a number or a percentage, and in range.
1076 $i = 0;
1077 while (!empty($quiz->feedbackboundaries[$i])) {
1078 $boundary = trim($quiz->feedbackboundaries[$i]);
1079 if (!is_numeric($boundary)) {
1080 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1081 $boundary = trim(substr($boundary, 0, -1));
1082 if (is_numeric($boundary)) {
1083 $boundary = $boundary * $quiz->grade / 100.0;
1084 } else {
1085 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1089 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1090 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1092 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1093 return get_string('feedbackerrororder', 'quiz', $i + 1);
1095 $quiz->feedbackboundaries[$i] = $boundary;
1096 $i += 1;
1098 $numboundaries = $i;
1100 // Check there is nothing in the remaining unused fields.
1101 if (!empty($quiz->feedbackboundaries)) {
1102 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1103 if (!empty($quiz->feedbackboundaries[$i]) &&
1104 trim($quiz->feedbackboundaries[$i]) != '') {
1105 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1109 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1110 if (!empty($quiz->feedbacktext[$i]['text']) &&
1111 trim($quiz->feedbacktext[$i]['text']) != '') {
1112 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1115 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1116 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1117 $quiz->feedbackboundaries[$numboundaries] = 0;
1118 $quiz->feedbackboundarycount = $numboundaries;
1119 } else {
1120 $quiz->feedbackboundarycount = -1;
1123 // Combing the individual settings into the review columns.
1124 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1125 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1126 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1127 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1128 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1129 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1130 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1131 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1132 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1136 * Helper function for {@link quiz_process_options()}.
1137 * @param object $fromform the sumbitted form date.
1138 * @param string $field one of the review option field names.
1140 function quiz_review_option_form_to_db($fromform, $field) {
1141 static $times = array(
1142 'during' => mod_quiz_display_options::DURING,
1143 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1144 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1145 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1148 $review = 0;
1149 foreach ($times as $whenname => $when) {
1150 $fieldname = $field . $whenname;
1151 if (isset($fromform->$fieldname)) {
1152 $review |= $when;
1153 unset($fromform->$fieldname);
1157 return $review;
1161 * This function is called at the end of quiz_add_instance
1162 * and quiz_update_instance, to do the common processing.
1164 * @param object $quiz the quiz object.
1166 function quiz_after_add_or_update($quiz) {
1167 global $DB;
1168 $cmid = $quiz->coursemodule;
1170 // We need to use context now, so we need to make sure all needed info is already in db.
1171 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1172 $context = context_module::instance($cmid);
1174 // Save the feedback.
1175 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1177 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1178 $feedback = new stdClass();
1179 $feedback->quizid = $quiz->id;
1180 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1181 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1182 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1183 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1184 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1185 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1186 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1187 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1188 $quiz->feedbacktext[$i]['text']);
1189 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1190 array('id' => $feedback->id));
1193 // Store any settings belonging to the access rules.
1194 quiz_access_manager::save_settings($quiz);
1196 // Update the events relating to this quiz.
1197 quiz_update_events($quiz);
1198 $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null;
1199 \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected);
1201 // Update related grade item.
1202 quiz_grade_item_update($quiz);
1206 * This function updates the events associated to the quiz.
1207 * If $override is non-zero, then it updates only the events
1208 * associated with the specified override.
1210 * @uses QUIZ_MAX_EVENT_LENGTH
1211 * @param object $quiz the quiz object.
1212 * @param object optional $override limit to a specific override
1214 function quiz_update_events($quiz, $override = null) {
1215 global $DB;
1217 // Load the old events relating to this quiz.
1218 $conds = array('modulename'=>'quiz',
1219 'instance'=>$quiz->id);
1220 if (!empty($override)) {
1221 // Only load events for this override.
1222 if (isset($override->userid)) {
1223 $conds['userid'] = $override->userid;
1224 } else {
1225 $conds['groupid'] = $override->groupid;
1228 $oldevents = $DB->get_records('event', $conds, 'id ASC');
1230 // Now make a to-do list of all that needs to be updated.
1231 if (empty($override)) {
1232 // We are updating the primary settings for the quiz, so we need to add all the overrides.
1233 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id ASC');
1234 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1235 // list contains the original (non-override) event for the module. If this is not included
1236 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1237 // list against the $oldevents list.
1238 array_unshift($overrides, new stdClass());
1239 } else {
1240 // Just do the one override.
1241 $overrides = array($override);
1244 // Get group override priorities.
1245 $grouppriorities = quiz_get_group_override_priorities($quiz->id);
1247 foreach ($overrides as $current) {
1248 $groupid = isset($current->groupid)? $current->groupid : 0;
1249 $userid = isset($current->userid)? $current->userid : 0;
1250 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1251 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1253 // Only add open/close events for an override if they differ from the quiz default.
1254 $addopen = empty($current->id) || !empty($current->timeopen);
1255 $addclose = empty($current->id) || !empty($current->timeclose);
1257 if (!empty($quiz->coursemodule)) {
1258 $cmid = $quiz->coursemodule;
1259 } else {
1260 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1263 $event = new stdClass();
1264 $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
1265 $event->description = format_module_intro('quiz', $quiz, $cmid);
1266 // Events module won't show user events when the courseid is nonzero.
1267 $event->courseid = ($userid) ? 0 : $quiz->course;
1268 $event->groupid = $groupid;
1269 $event->userid = $userid;
1270 $event->modulename = 'quiz';
1271 $event->instance = $quiz->id;
1272 $event->timestart = $timeopen;
1273 $event->timeduration = max($timeclose - $timeopen, 0);
1274 $event->timesort = $timeopen;
1275 $event->visible = instance_is_visible('quiz', $quiz);
1276 $event->eventtype = QUIZ_EVENT_TYPE_OPEN;
1277 $event->priority = null;
1279 // Determine the event name and priority.
1280 if ($groupid) {
1281 // Group override event.
1282 $params = new stdClass();
1283 $params->quiz = $quiz->name;
1284 $params->group = groups_get_group_name($groupid);
1285 if ($params->group === false) {
1286 // Group doesn't exist, just skip it.
1287 continue;
1289 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1290 // Set group override priority.
1291 if ($grouppriorities !== null) {
1292 $openpriorities = $grouppriorities['open'];
1293 if (isset($openpriorities[$timeopen])) {
1294 $event->priority = $openpriorities[$timeopen];
1297 } else if ($userid) {
1298 // User override event.
1299 $params = new stdClass();
1300 $params->quiz = $quiz->name;
1301 $eventname = get_string('overrideusereventname', 'quiz', $params);
1302 // Set user override priority.
1303 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
1304 } else {
1305 // The parent event.
1306 $eventname = $quiz->name;
1309 if ($addopen or $addclose) {
1310 // Separate start and end events.
1311 $event->timeduration = 0;
1312 if ($timeopen && $addopen) {
1313 if ($oldevent = array_shift($oldevents)) {
1314 $event->id = $oldevent->id;
1315 } else {
1316 unset($event->id);
1318 $event->name = get_string('quizeventopens', 'quiz', $eventname);
1319 // The method calendar_event::create will reuse a db record if the id field is set.
1320 calendar_event::create($event);
1322 if ($timeclose && $addclose) {
1323 if ($oldevent = array_shift($oldevents)) {
1324 $event->id = $oldevent->id;
1325 } else {
1326 unset($event->id);
1328 $event->type = CALENDAR_EVENT_TYPE_ACTION;
1329 $event->name = get_string('quizeventcloses', 'quiz', $eventname);
1330 $event->timestart = $timeclose;
1331 $event->timesort = $timeclose;
1332 $event->eventtype = QUIZ_EVENT_TYPE_CLOSE;
1333 if ($groupid && $grouppriorities !== null) {
1334 $closepriorities = $grouppriorities['close'];
1335 if (isset($closepriorities[$timeclose])) {
1336 $event->priority = $closepriorities[$timeclose];
1339 calendar_event::create($event);
1344 // Delete any leftover events.
1345 foreach ($oldevents as $badevent) {
1346 $badevent = calendar_event::load($badevent);
1347 $badevent->delete();
1352 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1354 * @param int $quizid The quiz ID.
1355 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1357 function quiz_get_group_override_priorities($quizid) {
1358 global $DB;
1360 // Fetch group overrides.
1361 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1362 $params = ['quiz' => $quizid];
1363 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1364 if (!$overrides) {
1365 return null;
1368 $grouptimeopen = [];
1369 $grouptimeclose = [];
1370 foreach ($overrides as $override) {
1371 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1372 $grouptimeopen[] = $override->timeopen;
1374 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1375 $grouptimeclose[] = $override->timeclose;
1379 // Sort open times in ascending manner. The earlier open time gets higher priority.
1380 sort($grouptimeopen);
1381 // Set priorities.
1382 $opengrouppriorities = [];
1383 $openpriority = 1;
1384 foreach ($grouptimeopen as $timeopen) {
1385 $opengrouppriorities[$timeopen] = $openpriority++;
1388 // Sort close times in descending manner. The later close time gets higher priority.
1389 rsort($grouptimeclose);
1390 // Set priorities.
1391 $closegrouppriorities = [];
1392 $closepriority = 1;
1393 foreach ($grouptimeclose as $timeclose) {
1394 $closegrouppriorities[$timeclose] = $closepriority++;
1397 return [
1398 'open' => $opengrouppriorities,
1399 'close' => $closegrouppriorities
1404 * List the actions that correspond to a view of this module.
1405 * This is used by the participation report.
1407 * Note: This is not used by new logging system. Event with
1408 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1409 * be considered as view action.
1411 * @return array
1413 function quiz_get_view_actions() {
1414 return array('view', 'view all', 'report', 'review');
1418 * List the actions that correspond to a post of this module.
1419 * This is used by the participation report.
1421 * Note: This is not used by new logging system. Event with
1422 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1423 * will be considered as post action.
1425 * @return array
1427 function quiz_get_post_actions() {
1428 return array('attempt', 'close attempt', 'preview', 'editquestions',
1429 'delete attempt', 'manualgrade');
1433 * @param array $questionids of question ids.
1434 * @return bool whether any of these questions are used by any instance of this module.
1436 function quiz_questions_in_use($questionids) {
1437 global $DB, $CFG;
1438 require_once($CFG->libdir . '/questionlib.php');
1439 list($test, $params) = $DB->get_in_or_equal($questionids);
1440 return $DB->record_exists_select('quiz_slots',
1441 'questionid ' . $test, $params) || question_engine::questions_in_use(
1442 $questionids, new qubaid_join('{quiz_attempts} quiza',
1443 'quiza.uniqueid', 'quiza.preview = 0'));
1447 * Implementation of the function for printing the form elements that control
1448 * whether the course reset functionality affects the quiz.
1450 * @param $mform the course reset form that is being built.
1452 function quiz_reset_course_form_definition($mform) {
1453 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1454 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1455 get_string('removeallquizattempts', 'quiz'));
1456 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1457 get_string('removealluseroverrides', 'quiz'));
1458 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1459 get_string('removeallgroupoverrides', 'quiz'));
1463 * Course reset form defaults.
1464 * @return array the defaults.
1466 function quiz_reset_course_form_defaults($course) {
1467 return array('reset_quiz_attempts' => 1,
1468 'reset_quiz_group_overrides' => 1,
1469 'reset_quiz_user_overrides' => 1);
1473 * Removes all grades from gradebook
1475 * @param int $courseid
1476 * @param string optional type
1478 function quiz_reset_gradebook($courseid, $type='') {
1479 global $CFG, $DB;
1481 $quizzes = $DB->get_records_sql("
1482 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1483 FROM {modules} m
1484 JOIN {course_modules} cm ON m.id = cm.module
1485 JOIN {quiz} q ON cm.instance = q.id
1486 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1488 foreach ($quizzes as $quiz) {
1489 quiz_grade_item_update($quiz, 'reset');
1494 * Actual implementation of the reset course functionality, delete all the
1495 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1496 * set and true.
1498 * Also, move the quiz open and close dates, if the course start date is changing.
1500 * @param object $data the data submitted from the reset course.
1501 * @return array status array
1503 function quiz_reset_userdata($data) {
1504 global $CFG, $DB;
1505 require_once($CFG->libdir . '/questionlib.php');
1507 $componentstr = get_string('modulenameplural', 'quiz');
1508 $status = array();
1510 // Delete attempts.
1511 if (!empty($data->reset_quiz_attempts)) {
1512 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1513 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1514 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1515 array('quizcourseid' => $data->courseid)));
1517 $DB->delete_records_select('quiz_attempts',
1518 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1519 $status[] = array(
1520 'component' => $componentstr,
1521 'item' => get_string('attemptsdeleted', 'quiz'),
1522 'error' => false);
1524 // Remove all grades from gradebook.
1525 $DB->delete_records_select('quiz_grades',
1526 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1527 if (empty($data->reset_gradebook_grades)) {
1528 quiz_reset_gradebook($data->courseid);
1530 $status[] = array(
1531 'component' => $componentstr,
1532 'item' => get_string('gradesdeleted', 'quiz'),
1533 'error' => false);
1536 // Remove user overrides.
1537 if (!empty($data->reset_quiz_user_overrides)) {
1538 $DB->delete_records_select('quiz_overrides',
1539 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1540 $status[] = array(
1541 'component' => $componentstr,
1542 'item' => get_string('useroverridesdeleted', 'quiz'),
1543 'error' => false);
1545 // Remove group overrides.
1546 if (!empty($data->reset_quiz_group_overrides)) {
1547 $DB->delete_records_select('quiz_overrides',
1548 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1549 $status[] = array(
1550 'component' => $componentstr,
1551 'item' => get_string('groupoverridesdeleted', 'quiz'),
1552 'error' => false);
1555 // Updating dates - shift may be negative too.
1556 if ($data->timeshift) {
1557 $DB->execute("UPDATE {quiz_overrides}
1558 SET timeopen = timeopen + ?
1559 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1560 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1561 $DB->execute("UPDATE {quiz_overrides}
1562 SET timeclose = timeclose + ?
1563 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1564 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1566 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1567 // See MDL-9367.
1568 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1569 $data->timeshift, $data->courseid);
1571 $status[] = array(
1572 'component' => $componentstr,
1573 'item' => get_string('openclosedatesupdated', 'quiz'),
1574 'error' => false);
1577 return $status;
1581 * Prints quiz summaries on MyMoodle Page
1583 * @deprecated since 3.3
1584 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1585 * @param array $courses
1586 * @param array $htmlarray
1588 function quiz_print_overview($courses, &$htmlarray) {
1589 global $USER, $CFG;
1591 debugging('The function quiz_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1593 // These next 6 Lines are constant in all modules (just change module name).
1594 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1595 return array();
1598 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1599 return;
1602 // Get the quizzes attempts.
1603 $attemptsinfo = [];
1604 $quizids = [];
1605 foreach ($quizzes as $quiz) {
1606 $quizids[] = $quiz->id;
1607 $attemptsinfo[$quiz->id] = ['count' => 0, 'hasfinished' => false];
1609 $attempts = quiz_get_user_attempts($quizids, $USER->id);
1610 foreach ($attempts as $attempt) {
1611 $attemptsinfo[$attempt->quiz]['count']++;
1612 $attemptsinfo[$attempt->quiz]['hasfinished'] = true;
1614 unset($attempts);
1616 // Fetch some language strings outside the main loop.
1617 $strquiz = get_string('modulename', 'quiz');
1618 $strnoattempts = get_string('noattempts', 'quiz');
1620 // We want to list quizzes that are currently available, and which have a close date.
1621 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1622 $now = time();
1623 foreach ($quizzes as $quiz) {
1624 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1625 $str = '';
1627 // Now provide more information depending on the uers's role.
1628 $context = context_module::instance($quiz->coursemodule);
1629 if (has_capability('mod/quiz:viewreports', $context)) {
1630 // For teacher-like people, show a summary of the number of student attempts.
1631 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1632 // fields set to make the following call work.
1633 $str .= '<div class="info">' . quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1635 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $context)) { // Student
1636 // For student-like people, tell them how many attempts they have made.
1638 if (isset($USER->id)) {
1639 if ($attemptsinfo[$quiz->id]['hasfinished']) {
1640 // The student's last attempt is finished.
1641 continue;
1644 if ($attemptsinfo[$quiz->id]['count'] > 0) {
1645 $str .= '<div class="info">' .
1646 get_string('numattemptsmade', 'quiz', $attemptsinfo[$quiz->id]['count']) . '</div>';
1647 } else {
1648 $str .= '<div class="info">' . $strnoattempts . '</div>';
1651 } else {
1652 $str .= '<div class="info">' . $strnoattempts . '</div>';
1655 } else {
1656 // For ayone else, there is no point listing this quiz, so stop processing.
1657 continue;
1660 // Give a link to the quiz, and the deadline.
1661 $html = '<div class="quiz overview">' .
1662 '<div class="name">' . $strquiz . ': <a ' .
1663 ($quiz->visible ? '' : ' class="dimmed"') .
1664 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1665 $quiz->coursemodule . '">' .
1666 $quiz->name . '</a></div>';
1667 $html .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1668 userdate($quiz->timeclose)) . '</div>';
1669 $html .= $str;
1670 $html .= '</div>';
1671 if (empty($htmlarray[$quiz->course]['quiz'])) {
1672 $htmlarray[$quiz->course]['quiz'] = $html;
1673 } else {
1674 $htmlarray[$quiz->course]['quiz'] .= $html;
1681 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1682 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1684 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1685 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1686 * $cm->groupingid fields are used at the moment.
1687 * @param bool $returnzero if false (default), when no attempts have been
1688 * made '' is returned instead of 'Attempts: 0'.
1689 * @param int $currentgroup if there is a concept of current group where this method is being called
1690 * (e.g. a report) pass it in here. Default 0 which means no current group.
1691 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1692 * "Attemtps 123 (45 from this group)".
1694 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1695 global $DB, $USER;
1696 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1697 if ($numattempts || $returnzero) {
1698 if (groups_get_activity_groupmode($cm)) {
1699 $a = new stdClass();
1700 $a->total = $numattempts;
1701 if ($currentgroup) {
1702 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1703 '{quiz_attempts} qa JOIN ' .
1704 '{groups_members} gm ON qa.userid = gm.userid ' .
1705 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1706 array($quiz->id, $currentgroup));
1707 return get_string('attemptsnumthisgroup', 'quiz', $a);
1708 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1709 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1710 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1711 '{quiz_attempts} qa JOIN ' .
1712 '{groups_members} gm ON qa.userid = gm.userid ' .
1713 'WHERE quiz = ? AND preview = 0 AND ' .
1714 "groupid $usql", array_merge(array($quiz->id), $params));
1715 return get_string('attemptsnumyourgroups', 'quiz', $a);
1718 return get_string('attemptsnum', 'quiz', $numattempts);
1720 return '';
1724 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1725 * to the quiz reports.
1727 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1728 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1729 * $cm->groupingid fields are used at the moment.
1730 * @param object $context the quiz context.
1731 * @param bool $returnzero if false (default), when no attempts have been made
1732 * '' is returned instead of 'Attempts: 0'.
1733 * @param int $currentgroup if there is a concept of current group where this method is being called
1734 * (e.g. a report) pass it in here. Default 0 which means no current group.
1735 * @return string HTML fragment for the link.
1737 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1738 $currentgroup = 0) {
1739 global $CFG;
1740 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1741 if (!$summary) {
1742 return '';
1745 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1746 $url = new moodle_url('/mod/quiz/report.php', array(
1747 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1748 return html_writer::link($url, $summary);
1752 * @param string $feature FEATURE_xx constant for requested feature
1753 * @return bool True if quiz supports feature
1755 function quiz_supports($feature) {
1756 switch($feature) {
1757 case FEATURE_GROUPS: return true;
1758 case FEATURE_GROUPINGS: return true;
1759 case FEATURE_MOD_INTRO: return true;
1760 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1761 case FEATURE_COMPLETION_HAS_RULES: return true;
1762 case FEATURE_GRADE_HAS_GRADE: return true;
1763 case FEATURE_GRADE_OUTCOMES: return true;
1764 case FEATURE_BACKUP_MOODLE2: return true;
1765 case FEATURE_SHOW_DESCRIPTION: return true;
1766 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1767 case FEATURE_USES_QUESTIONS: return true;
1769 default: return null;
1774 * @return array all other caps used in module
1776 function quiz_get_extra_capabilities() {
1777 global $CFG;
1778 require_once($CFG->libdir . '/questionlib.php');
1779 $caps = question_get_all_capabilities();
1780 $caps[] = 'moodle/site:accessallgroups';
1781 return $caps;
1785 * This function extends the settings navigation block for the site.
1787 * It is safe to rely on PAGE here as we will only ever be within the module
1788 * context when this is called
1790 * @param settings_navigation $settings
1791 * @param navigation_node $quiznode
1792 * @return void
1794 function quiz_extend_settings_navigation($settings, $quiznode) {
1795 global $PAGE, $CFG;
1797 // Require {@link questionlib.php}
1798 // Included here as we only ever want to include this file if we really need to.
1799 require_once($CFG->libdir . '/questionlib.php');
1801 // We want to add these new nodes after the Edit settings node, and before the
1802 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1803 $keys = $quiznode->get_children_key_list();
1804 $beforekey = null;
1805 $i = array_search('modedit', $keys);
1806 if ($i === false and array_key_exists(0, $keys)) {
1807 $beforekey = $keys[0];
1808 } else if (array_key_exists($i + 1, $keys)) {
1809 $beforekey = $keys[$i + 1];
1812 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1813 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1814 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1815 new moodle_url($url, array('mode'=>'group')),
1816 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1817 $quiznode->add_node($node, $beforekey);
1819 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1820 new moodle_url($url, array('mode'=>'user')),
1821 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1822 $quiznode->add_node($node, $beforekey);
1825 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1826 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1827 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1828 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1829 new pix_icon('t/edit', ''));
1830 $quiznode->add_node($node, $beforekey);
1833 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1834 $url = new moodle_url('/mod/quiz/startattempt.php',
1835 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1836 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1837 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1838 new pix_icon('i/preview', ''));
1839 $quiznode->add_node($node, $beforekey);
1842 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1843 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1844 $reportlist = quiz_report_list($PAGE->cm->context);
1846 $url = new moodle_url('/mod/quiz/report.php',
1847 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1848 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1849 navigation_node::TYPE_SETTING,
1850 null, null, new pix_icon('i/report', '')), $beforekey);
1852 foreach ($reportlist as $report) {
1853 $url = new moodle_url('/mod/quiz/report.php',
1854 array('id' => $PAGE->cm->id, 'mode' => $report));
1855 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1856 navigation_node::TYPE_SETTING,
1857 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1861 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1865 * Serves the quiz files.
1867 * @package mod_quiz
1868 * @category files
1869 * @param stdClass $course course object
1870 * @param stdClass $cm course module object
1871 * @param stdClass $context context object
1872 * @param string $filearea file area
1873 * @param array $args extra arguments
1874 * @param bool $forcedownload whether or not force download
1875 * @param array $options additional options affecting the file serving
1876 * @return bool false if file not found, does not return if found - justsend the file
1878 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1879 global $CFG, $DB;
1881 if ($context->contextlevel != CONTEXT_MODULE) {
1882 return false;
1885 require_login($course, false, $cm);
1887 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1888 return false;
1891 // The 'intro' area is served by pluginfile.php.
1892 $fileareas = array('feedback');
1893 if (!in_array($filearea, $fileareas)) {
1894 return false;
1897 $feedbackid = (int)array_shift($args);
1898 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1899 return false;
1902 $fs = get_file_storage();
1903 $relativepath = implode('/', $args);
1904 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1905 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1906 return false;
1908 send_stored_file($file, 0, 0, true, $options);
1912 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1913 * a question in a question_attempt when that attempt is a quiz attempt.
1915 * @package mod_quiz
1916 * @category files
1917 * @param stdClass $course course settings object
1918 * @param stdClass $context context object
1919 * @param string $component the name of the component we are serving files for.
1920 * @param string $filearea the name of the file area.
1921 * @param int $qubaid the attempt usage id.
1922 * @param int $slot the id of a question in this quiz attempt.
1923 * @param array $args the remaining bits of the file path.
1924 * @param bool $forcedownload whether the user must be forced to download the file.
1925 * @param array $options additional options affecting the file serving
1926 * @return bool false if file not found, does not return if found - justsend the file
1928 function quiz_question_pluginfile($course, $context, $component,
1929 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
1930 global $CFG;
1931 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1933 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1934 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1936 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1937 // In the middle of an attempt.
1938 if (!$attemptobj->is_preview_user()) {
1939 $attemptobj->require_capability('mod/quiz:attempt');
1941 $isreviewing = false;
1943 } else {
1944 // Reviewing an attempt.
1945 $attemptobj->check_review_capability();
1946 $isreviewing = true;
1949 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1950 $component, $filearea, $args, $forcedownload)) {
1951 send_file_not_found();
1954 $fs = get_file_storage();
1955 $relativepath = implode('/', $args);
1956 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1957 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1958 send_file_not_found();
1961 send_stored_file($file, 0, 0, $forcedownload, $options);
1965 * Return a list of page types
1966 * @param string $pagetype current page type
1967 * @param stdClass $parentcontext Block's parent context
1968 * @param stdClass $currentcontext Current context of block
1970 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1971 $module_pagetype = array(
1972 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1973 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1974 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1975 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1976 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1977 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1978 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1980 return $module_pagetype;
1984 * @return the options for quiz navigation.
1986 function quiz_get_navigation_options() {
1987 return array(
1988 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1989 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1994 * Obtains the automatic completion state for this quiz on any conditions
1995 * in quiz settings, such as if all attempts are used or a certain grade is achieved.
1997 * @param object $course Course
1998 * @param object $cm Course-module
1999 * @param int $userid User ID
2000 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2001 * @return bool True if completed, false if not. (If no conditions, then return
2002 * value depends on comparison type)
2004 function quiz_get_completion_state($course, $cm, $userid, $type) {
2005 global $DB;
2006 global $CFG;
2008 $quiz = $DB->get_record('quiz', array('id' => $cm->instance), '*', MUST_EXIST);
2009 if (!$quiz->completionattemptsexhausted && !$quiz->completionpass) {
2010 return $type;
2013 // Check if the user has used up all attempts.
2014 if ($quiz->completionattemptsexhausted) {
2015 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
2016 if ($attempts) {
2017 $lastfinishedattempt = end($attempts);
2018 $context = context_module::instance($cm->id);
2019 $quizobj = quiz::create($quiz->id, $userid);
2020 $accessmanager = new quiz_access_manager($quizobj, time(),
2021 has_capability('mod/quiz:ignoretimelimits', $context, $userid, false));
2022 if ($accessmanager->is_finished(count($attempts), $lastfinishedattempt)) {
2023 return true;
2028 // Check for passing grade.
2029 if ($quiz->completionpass) {
2030 require_once($CFG->libdir . '/gradelib.php');
2031 $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
2032 'itemmodule' => 'quiz', 'iteminstance' => $cm->instance, 'outcomeid' => null));
2033 if ($item) {
2034 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
2035 if (!empty($grades[$userid])) {
2036 return $grades[$userid]->is_passed($item);
2040 return false;
2044 * Check if the module has any update that affects the current user since a given time.
2046 * @param cm_info $cm course module data
2047 * @param int $from the time to check updates from
2048 * @param array $filter if we need to check only specific updates
2049 * @return stdClass an object with the different type of areas indicating if they were updated or not
2050 * @since Moodle 3.2
2052 function quiz_check_updates_since(cm_info $cm, $from, $filter = array()) {
2053 global $DB, $USER, $CFG;
2054 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2056 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2058 // Check if questions were updated.
2059 $updates->questions = (object) array('updated' => false);
2060 $quizobj = quiz::create($cm->instance, $USER->id);
2061 $quizobj->preload_questions();
2062 $quizobj->load_questions();
2063 $questionids = array_keys($quizobj->get_questions());
2064 if (!empty($questionids)) {
2065 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
2066 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
2067 $params['time1'] = $from;
2068 $params['time2'] = $from;
2069 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
2070 if (!empty($questions)) {
2071 $updates->questions->updated = true;
2072 $updates->questions->itemids = array_keys($questions);
2076 // Check for new attempts or grades.
2077 $updates->attempts = (object) array('updated' => false);
2078 $updates->grades = (object) array('updated' => false);
2079 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
2080 $params = array($cm->instance, $USER->id, $from);
2082 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2083 if (!empty($attempts)) {
2084 $updates->attempts->updated = true;
2085 $updates->attempts->itemids = array_keys($attempts);
2087 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2088 if (!empty($grades)) {
2089 $updates->grades->updated = true;
2090 $updates->grades->itemids = array_keys($grades);
2093 // Now, teachers should see other students updates.
2094 if (has_capability('mod/quiz:viewreports', $cm->context)) {
2095 $select = 'quiz = ? AND timemodified > ?';
2096 $params = array($cm->instance, $from);
2098 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
2099 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
2100 if (empty($groupusers)) {
2101 return $updates;
2103 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
2104 $select .= ' AND userid ' . $insql;
2105 $params = array_merge($params, $inparams);
2108 $updates->userattempts = (object) array('updated' => false);
2109 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2110 if (!empty($attempts)) {
2111 $updates->userattempts->updated = true;
2112 $updates->userattempts->itemids = array_keys($attempts);
2115 $updates->usergrades = (object) array('updated' => false);
2116 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2117 if (!empty($grades)) {
2118 $updates->usergrades->updated = true;
2119 $updates->usergrades->itemids = array_keys($grades);
2122 return $updates;
2126 * Get icon mapping for font-awesome.
2128 function mod_quiz_get_fontawesome_icon_map() {
2129 return [
2130 'mod_quiz:navflagged' => 'fa-flag',
2135 * This function receives a calendar event and returns the action associated with it, or null if there is none.
2137 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
2138 * is not displayed on the block.
2140 * @param calendar_event $event
2141 * @param \core_calendar\action_factory $factory
2142 * @return \core_calendar\local\event\entities\action_interface|null
2144 function mod_quiz_core_calendar_provide_event_action(calendar_event $event,
2145 \core_calendar\action_factory $factory) {
2146 global $CFG, $USER;
2148 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2150 $cm = get_fast_modinfo($event->courseid)->instances['quiz'][$event->instance];
2151 $quizobj = quiz::create($cm->instance, $USER->id);
2152 $quiz = $quizobj->get_quiz();
2154 // Check they have capabilities allowing them to view the quiz.
2155 if (!has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $quizobj->get_context())) {
2156 return null;
2159 quiz_update_effective_access($quiz, $USER->id);
2161 // Check if quiz is closed, if so don't display it.
2162 if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) {
2163 return null;
2166 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id);
2167 if (!empty($attempts)) {
2168 // The student's last attempt is finished.
2169 return null;
2172 $name = get_string('attemptquiznow', 'quiz');
2173 $url = new \moodle_url('/mod/quiz/view.php', [
2174 'id' => $cm->id
2176 $itemcount = 1;
2177 $actionable = true;
2179 // Check if the quiz is not currently actionable.
2180 if (!empty($quiz->timeopen) && $quiz->timeopen > time()) {
2181 $actionable = false;
2184 return $factory->create_instance(
2185 $name,
2186 $url,
2187 $itemcount,
2188 $actionable
2193 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2194 * for the course (see resource).
2196 * Given a course_module object, this function returns any "extra" information that may be needed
2197 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2199 * @param stdClass $coursemodule The coursemodule object (record).
2200 * @return cached_cm_info An object on information that the courses
2201 * will know about (most noticeably, an icon).
2203 function quiz_get_coursemodule_info($coursemodule) {
2204 global $DB;
2206 $dbparams = ['id' => $coursemodule->instance];
2207 $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionpass';
2208 if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2209 return false;
2212 $result = new cached_cm_info();
2213 $result->name = $quiz->name;
2215 if ($coursemodule->showdescription) {
2216 // Convert intro to html. Do not filter cached version, filters run at display time.
2217 $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false);
2220 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2221 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
2222 $result->customdata['customcompletionrules']['completionattemptsexhausted'] = $quiz->completionattemptsexhausted;
2223 $result->customdata['customcompletionrules']['completionpass'] = $quiz->completionpass;
2226 return $result;
2230 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2232 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
2233 * @return array $descriptions the array of descriptions for the custom rules.
2235 function mod_quiz_get_completion_active_rule_descriptions($cm) {
2236 // Values will be present in cm_info, and we assume these are up to date.
2237 if (empty($cm->customdata['customcompletionrules'])
2238 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
2239 return [];
2242 $descriptions = [];
2243 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
2244 switch ($key) {
2245 case 'completionattemptsexhausted':
2246 if (empty($val)) {
2247 continue;
2249 $descriptions[] = get_string('completionattemptsexhausteddesc', 'quiz');
2250 break;
2251 case 'completionpass':
2252 if (empty($val)) {
2253 continue;
2255 $descriptions[] = get_string('completionpassdesc', 'quiz', format_time($val));
2256 break;
2257 default:
2258 break;
2261 return $descriptions;
2265 * Returns the min and max values for the timestart property of a quiz
2266 * activity event.
2268 * The min and max values will be the timeopen and timeclose properties
2269 * of the quiz, respectively, if they are set.
2271 * If either value isn't set then null will be returned instead to
2272 * indicate that there is no cutoff for that value.
2274 * If the vent has no valid timestart range then [false, false] will
2275 * be returned. This is the case for overriden events.
2277 * A minimum and maximum cutoff return value will look like:
2279 * [1505704373, 'The date must be after this date'],
2280 * [1506741172, 'The date must be before this date']
2283 * @throws \moodle_exception
2284 * @param \calendar_event $event The calendar event to get the time range for
2285 * @param stdClass $quiz The module instance to get the range from
2286 * @return array
2288 function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz) {
2289 global $CFG, $DB;
2290 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2292 // Overrides do not have a valid timestart range.
2293 if (quiz_is_overriden_calendar_event($event)) {
2294 return [false, false];
2297 $mindate = null;
2298 $maxdate = null;
2300 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2301 if (!empty($quiz->timeclose)) {
2302 $maxdate = [
2303 $quiz->timeclose,
2304 get_string('openafterclose', 'quiz')
2307 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2308 if (!empty($quiz->timeopen)) {
2309 $mindate = [
2310 $quiz->timeopen,
2311 get_string('closebeforeopen', 'quiz')
2316 return [$mindate, $maxdate];
2320 * This function will update the quiz module according to the
2321 * event that has been modified.
2323 * It will set the timeopen or timeclose value of the quiz instance
2324 * according to the type of event provided.
2326 * @throws \moodle_exception
2327 * @param \calendar_event $event A quiz activity calendar event
2328 * @param \stdClass $quiz A quiz activity instance
2330 function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz) {
2331 global $CFG, $DB;
2332 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2334 if (!in_array($event->eventtype, [QUIZ_EVENT_TYPE_OPEN, QUIZ_EVENT_TYPE_CLOSE])) {
2335 // This isn't an event that we care about so we can ignore it.
2336 return;
2339 $courseid = $event->courseid;
2340 $modulename = $event->modulename;
2341 $instanceid = $event->instance;
2342 $modified = false;
2343 $closedatechanged = false;
2345 // Something weird going on. The event is for a different module so
2346 // we should ignore it.
2347 if ($modulename != 'quiz') {
2348 return;
2351 if ($quiz->id != $instanceid) {
2352 // The provided quiz instance doesn't match the event so
2353 // there is nothing to do here.
2354 return;
2357 // We don't update the activity if it's an override event that has
2358 // been modified.
2359 if (quiz_is_overriden_calendar_event($event)) {
2360 return;
2363 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2364 $context = context_module::instance($coursemodule->id);
2366 // The user does not have the capability to modify this activity.
2367 if (!has_capability('moodle/course:manageactivities', $context)) {
2368 return;
2371 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2372 // If the event is for the quiz activity opening then we should
2373 // set the start time of the quiz activity to be the new start
2374 // time of the event.
2375 if ($quiz->timeopen != $event->timestart) {
2376 $quiz->timeopen = $event->timestart;
2377 $modified = true;
2379 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2380 // If the event is for the quiz activity closing then we should
2381 // set the end time of the quiz activity to be the new start
2382 // time of the event.
2383 if ($quiz->timeclose != $event->timestart) {
2384 $quiz->timeclose = $event->timestart;
2385 $modified = true;
2386 $closedatechanged = true;
2390 if ($modified) {
2391 $quiz->timemodified = time();
2392 $DB->update_record('quiz', $quiz);
2394 if ($closedatechanged) {
2395 quiz_update_open_attempts(array('quizid' => $quiz->id));
2398 // Delete any previous preview attempts.
2399 quiz_delete_previews($quiz);
2400 quiz_update_events($quiz);
2401 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2402 $event->trigger();
2407 * Generates the question bank in a fargment output. This allows
2408 * the question bank to be displayed in a modal.
2410 * The only expected argument provided in the $args array is
2411 * 'querystring'. The value should be the list of parameters
2412 * URL encoded and used to build the question bank page.
2414 * The individual list of parameters expected can be found in
2415 * question_build_edit_resources.
2417 * @param array $args The fragment arguments.
2418 * @return string The rendered mform fragment.
2420 function mod_quiz_output_fragment_quiz_question_bank($args) {
2421 global $CFG, $DB, $PAGE;
2422 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2423 require_once($CFG->dirroot . '/question/editlib.php');
2425 $querystring = preg_replace('/^\?/', '', $args['querystring']);
2426 $params = [];
2427 parse_str($querystring, $params);
2429 // Build the required resources. The $params are all cleaned as
2430 // part of this process.
2431 list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) =
2432 question_build_edit_resources('editq', '/mod/quiz/edit.php', $params);
2434 // Get the course object and related bits.
2435 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
2436 require_capability('mod/quiz:manage', $contexts->lowest());
2438 // Create quiz question bank view.
2439 $questionbank = new mod_quiz\question\bank\fragment_view($contexts, $thispageurl, $course, $cm, $quiz);
2440 $questionbank->set_quiz_has_attempts(quiz_has_attempts($quiz->id));
2442 // Output.
2443 $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2444 return $renderer->question_bank_contents($questionbank, $pagevars);