2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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}
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 use qbank_managecategories\helper
;
31 defined('MOODLE_INTERNAL') ||
die();
33 use mod_quiz\access_manager
;
34 use mod_quiz\grade_calculator
;
35 use mod_quiz\question\bank\custom_view
;
36 use mod_quiz\question\bank\qbank_helper
;
37 use mod_quiz\question\display_options
;
38 use mod_quiz\question\qubaids_for_quiz
;
39 use mod_quiz\question\qubaids_for_users_attempts
;
40 use core_question\statistics\questions\all_calculated_for_qubaid_condition
;
41 use mod_quiz\quiz_attempt
;
42 use mod_quiz\quiz_settings
;
44 require_once($CFG->dirroot
. '/calendar/lib.php');
45 require_once($CFG->dirroot
. '/question/editlib.php');
48 * Option controlling what options are offered on the quiz settings form.
50 define('QUIZ_MAX_ATTEMPT_OPTION', 10);
51 define('QUIZ_MAX_QPP_OPTION', 50);
52 define('QUIZ_MAX_DECIMAL_OPTION', 5);
53 define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
57 * Options determining how the grades from individual attempts are combined to give
58 * the overall grade for a user
60 define('QUIZ_GRADEHIGHEST', '1');
61 define('QUIZ_GRADEAVERAGE', '2');
62 define('QUIZ_ATTEMPTFIRST', '3');
63 define('QUIZ_ATTEMPTLAST', '4');
67 * @var int If start and end date for the quiz are more than this many seconds apart
68 * they will be represented by two separate events in the calendar
70 define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
73 * Options for navigation method within quizzes.
75 define('QUIZ_NAVMETHOD_FREE', 'free');
76 define('QUIZ_NAVMETHOD_SEQ', 'sequential');
82 define('QUIZ_EVENT_TYPE_OPEN', 'open');
83 define('QUIZ_EVENT_TYPE_CLOSE', 'close');
85 require_once(__DIR__
. '/deprecatedlib.php');
88 * Given an object containing all the necessary data,
89 * (defined by the form in mod_form.php) this function
90 * will create a new instance and return the id number
91 * of the new instance.
93 * @param stdClass $quiz the data that came from the form.
94 * @return mixed the id of the new instance on success,
95 * false or a string error message on failure.
97 function quiz_add_instance($quiz) {
99 $cmid = $quiz->coursemodule
;
101 // Process the options from the form.
102 $quiz->timecreated
= time();
103 $result = quiz_process_options($quiz);
104 if ($result && is_string($result)) {
108 // Try to store it in the database.
109 $quiz->id
= $DB->insert_record('quiz', $quiz);
111 // Create the first section for this quiz.
112 $DB->insert_record('quiz_sections', ['quizid' => $quiz->id
,
113 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0]);
115 // Do the processing required after an add or an update.
116 quiz_after_add_or_update($quiz);
122 * Given an object containing all the necessary data,
123 * (defined by the form in mod_form.php) this function
124 * will update an existing instance with new data.
126 * @param stdClass $quiz the data that came from the form.
127 * @param stdClass $mform no longer used.
128 * @return mixed true on success, false or a string error message on failure.
130 function quiz_update_instance($quiz, $mform) {
132 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
134 // Process the options from the form.
135 $result = quiz_process_options($quiz);
136 if ($result && is_string($result)) {
140 // Get the current value, so we can see what changed.
141 $oldquiz = $DB->get_record('quiz', ['id' => $quiz->instance
]);
143 // We need two values from the existing DB record that are not in the form,
144 // in some of the function calls below.
145 $quiz->sumgrades
= $oldquiz->sumgrades
;
146 $quiz->grade
= $oldquiz->grade
;
148 // Update the database.
149 $quiz->id
= $quiz->instance
;
150 $DB->update_record('quiz', $quiz);
152 // Do the processing required after an add or an update.
153 quiz_after_add_or_update($quiz);
155 if ($oldquiz->grademethod
!= $quiz->grademethod
) {
156 $gradecalculator = quiz_settings
::create($quiz->id
)->get_grade_calculator();
157 $gradecalculator->recompute_all_final_grades();
158 quiz_update_grades($quiz);
161 $quizdateschanged = $oldquiz->timelimit
!= $quiz->timelimit
162 ||
$oldquiz->timeclose
!= $quiz->timeclose
163 ||
$oldquiz->graceperiod
!= $quiz->graceperiod
;
164 if ($quizdateschanged) {
165 quiz_update_open_attempts(['quizid' => $quiz->id
]);
168 // Delete any previous preview attempts.
169 quiz_delete_previews($quiz);
171 // Repaginate, if asked to.
172 if (!empty($quiz->repaginatenow
) && !quiz_has_attempts($quiz->id
)) {
173 quiz_repaginate_questions($quiz->id
, $quiz->questionsperpage
);
180 * Given an ID of an instance of this module,
181 * this function will permanently delete the instance
182 * and any data that depends on it.
184 * @param int $id the id of the quiz to delete.
185 * @return bool success or failure.
187 function quiz_delete_instance($id) {
190 $quiz = $DB->get_record('quiz', ['id' => $id], '*', MUST_EXIST
);
192 quiz_delete_all_attempts($quiz);
193 quiz_delete_all_overrides($quiz);
194 quiz_delete_references($quiz->id
);
196 // We need to do the following deletes before we try and delete randoms, otherwise they would still be 'in use'.
197 $DB->delete_records('quiz_slots', ['quizid' => $quiz->id
]);
198 $DB->delete_records('quiz_sections', ['quizid' => $quiz->id
]);
200 $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id
]);
202 access_manager
::delete_settings($quiz);
204 $events = $DB->get_records('event', ['modulename' => 'quiz', 'instance' => $quiz->id
]);
205 foreach ($events as $event) {
206 $event = calendar_event
::load($event);
210 quiz_grade_item_delete($quiz);
211 // We must delete the module record after we delete the grade item.
212 $DB->delete_records('quiz', ['id' => $quiz->id
]);
218 * Deletes a quiz override from the database and clears any corresponding calendar events
220 * @param stdClass $quiz The quiz object.
221 * @param int $overrideid The id of the override being deleted
222 * @param bool $log Whether to trigger logs.
223 * @return bool true on success
225 function quiz_delete_override($quiz, $overrideid, $log = true) {
228 if (!isset($quiz->cmid
)) {
229 $cm = get_coursemodule_from_instance('quiz', $quiz->id
, $quiz->course
);
230 $quiz->cmid
= $cm->id
;
233 $override = $DB->get_record('quiz_overrides', ['id' => $overrideid], '*', MUST_EXIST
);
235 // Delete the events.
236 if (isset($override->groupid
)) {
237 // Create the search array for a group override.
238 $eventsearcharray = ['modulename' => 'quiz',
239 'instance' => $quiz->id
, 'groupid' => (int)$override->groupid
];
240 $cachekey = "{$quiz->id}_g_{$override->groupid}";
242 // Create the search array for a user override.
243 $eventsearcharray = ['modulename' => 'quiz',
244 'instance' => $quiz->id
, 'userid' => (int)$override->userid
];
245 $cachekey = "{$quiz->id}_u_{$override->userid}";
247 $events = $DB->get_records('event', $eventsearcharray);
248 foreach ($events as $event) {
249 $eventold = calendar_event
::load($event);
253 $DB->delete_records('quiz_overrides', ['id' => $overrideid]);
254 cache
::make('mod_quiz', 'overrides')->delete($cachekey);
257 // Set the common parameters for one of the events we will be triggering.
259 'objectid' => $override->id
,
260 'context' => context_module
::instance($quiz->cmid
),
262 'quizid' => $override->quiz
265 // Determine which override deleted event to fire.
266 if (!empty($override->userid
)) {
267 $params['relateduserid'] = $override->userid
;
268 $event = \mod_quiz\event\user_override_deleted
::create($params);
270 $params['other']['groupid'] = $override->groupid
;
271 $event = \mod_quiz\event\group_override_deleted
::create($params);
274 // Trigger the override deleted event.
275 $event->add_record_snapshot('quiz_overrides', $override);
283 * Deletes all quiz overrides from the database and clears any corresponding calendar events
285 * @param stdClass $quiz The quiz object.
286 * @param bool $log Whether to trigger logs.
288 function quiz_delete_all_overrides($quiz, $log = true) {
291 $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id
], 'id');
292 foreach ($overrides as $override) {
293 quiz_delete_override($quiz, $override->id
, $log);
298 * Updates a quiz object with override information for a user.
300 * Algorithm: For each quiz setting, if there is a matching user-specific override,
301 * then use that otherwise, if there are group-specific overrides, return the most
302 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
304 * Special case: if there is more than one password that applies to the user, then
305 * quiz->extrapasswords will contain an array of strings giving the remaining
308 * @param stdClass $quiz The quiz object.
309 * @param int $userid The userid.
310 * @return stdClass $quiz The updated quiz object.
312 function quiz_update_effective_access($quiz, $userid) {
315 // Check for user override.
316 $override = $DB->get_record('quiz_overrides', ['quiz' => $quiz->id
, 'userid' => $userid]);
319 $override = new stdClass();
320 $override->timeopen
= null;
321 $override->timeclose
= null;
322 $override->timelimit
= null;
323 $override->attempts
= null;
324 $override->password
= null;
327 // Check for group overrides.
328 $groupings = groups_get_user_groups($quiz->course
, $userid);
330 if (!empty($groupings[0])) {
331 // Select all overrides that apply to the User's groups.
332 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
333 $sql = "SELECT * FROM {quiz_overrides}
334 WHERE groupid $extra AND quiz = ?";
335 $params[] = $quiz->id
;
336 $records = $DB->get_records_sql($sql, $params);
338 // Combine the overrides.
345 foreach ($records as $gpoverride) {
346 if (isset($gpoverride->timeopen
)) {
347 $opens[] = $gpoverride->timeopen
;
349 if (isset($gpoverride->timeclose
)) {
350 $closes[] = $gpoverride->timeclose
;
352 if (isset($gpoverride->timelimit
)) {
353 $limits[] = $gpoverride->timelimit
;
355 if (isset($gpoverride->attempts
)) {
356 $attempts[] = $gpoverride->attempts
;
358 if (isset($gpoverride->password
)) {
359 $passwords[] = $gpoverride->password
;
362 // If there is a user override for a setting, ignore the group override.
363 if (is_null($override->timeopen
) && count($opens)) {
364 $override->timeopen
= min($opens);
366 if (is_null($override->timeclose
) && count($closes)) {
367 if (in_array(0, $closes)) {
368 $override->timeclose
= 0;
370 $override->timeclose
= max($closes);
373 if (is_null($override->timelimit
) && count($limits)) {
374 if (in_array(0, $limits)) {
375 $override->timelimit
= 0;
377 $override->timelimit
= max($limits);
380 if (is_null($override->attempts
) && count($attempts)) {
381 if (in_array(0, $attempts)) {
382 $override->attempts
= 0;
384 $override->attempts
= max($attempts);
387 if (is_null($override->password
) && count($passwords)) {
388 $override->password
= array_shift($passwords);
389 if (count($passwords)) {
390 $override->extrapasswords
= $passwords;
396 // Merge with quiz defaults.
397 $keys = ['timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords'];
398 foreach ($keys as $key) {
399 if (isset($override->{$key})) {
400 $quiz->{$key} = $override->{$key};
408 * Delete all the attempts belonging to a quiz.
410 * @param stdClass $quiz The quiz object.
412 function quiz_delete_all_attempts($quiz) {
414 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
415 question_engine
::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id
));
416 $DB->delete_records('quiz_attempts', ['quiz' => $quiz->id
]);
417 $DB->delete_records('quiz_grades', ['quiz' => $quiz->id
]);
421 * Delete all the attempts belonging to a user in a particular quiz.
423 * @param \mod_quiz\quiz_settings $quiz The quiz object.
424 * @param stdClass $user The user object.
426 function quiz_delete_user_attempts($quiz, $user) {
428 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
429 question_engine
::delete_questions_usage_by_activities(new qubaids_for_users_attempts(
430 $quiz->get_quizid(), $user->id
, 'all'));
432 'quiz' => $quiz->get_quizid(),
433 'userid' => $user->id
,
435 $DB->delete_records('quiz_attempts', $params);
436 $DB->delete_records('quiz_grades', $params);
440 * Get the best current grade for a particular user in a quiz.
442 * @param stdClass $quiz the quiz settings.
443 * @param int $userid the id of the user.
444 * @return float the user's current grade for this quiz, or null if this user does
445 * not have a grade on this quiz.
447 function quiz_get_best_grade($quiz, $userid) {
449 $grade = $DB->get_field('quiz_grades', 'grade',
450 ['quiz' => $quiz->id
, 'userid' => $userid]);
452 // Need to detect errors/no result, without catching 0 grades.
453 if ($grade === false) {
457 return $grade +
0; // Convert to number.
461 * Is this a graded quiz? If this method returns true, you can assume that
462 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
465 * @param stdClass $quiz a row from the quiz table.
466 * @return bool whether this is a graded quiz.
468 function quiz_has_grades($quiz) {
469 return $quiz->grade
>= grade_calculator
::ALMOST_ZERO
&& $quiz->sumgrades
>= grade_calculator
::ALMOST_ZERO
;
473 * Does this quiz allow multiple tries?
477 function quiz_allows_multiple_tries($quiz) {
478 $bt = question_engine
::get_behaviour_type($quiz->preferredbehaviour
);
479 return $bt->allows_multiple_submitted_responses();
483 * Return a small object with summary information about what a
484 * user has done with a given particular instance of this module
485 * Used for user activity reports.
486 * $return->time = the time they did it
487 * $return->info = a short text description
489 * @param stdClass $course
490 * @param stdClass $user
491 * @param stdClass $mod
492 * @param stdClass $quiz
493 * @return stdClass|null
495 function quiz_user_outline($course, $user, $mod, $quiz) {
497 require_once($CFG->libdir
. '/gradelib.php');
498 $grades = grade_get_grades($course->id
, 'mod', 'quiz', $quiz->id
, $user->id
);
500 if (empty($grades->items
[0]->grades
)) {
503 $grade = reset($grades->items
[0]->grades
);
506 $result = new stdClass();
507 // If the user can't see hidden grades, don't return that information.
508 $gitem = grade_item
::fetch(['id' => $grades->items
[0]->id
]);
509 if (!$gitem->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
510 $result->info
= get_string('gradenoun') . ': ' . $grade->str_long_grade
;
512 $result->info
= get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
515 $result->time
= grade_get_date_for_user_grade($grade, $user);
521 * Print a detailed representation of what a user has done with
522 * a given particular instance of this module, for user activity reports.
524 * @param stdClass $course
525 * @param stdClass $user
526 * @param stdClass $mod
527 * @param stdClass $quiz
530 function quiz_user_complete($course, $user, $mod, $quiz) {
531 global $DB, $CFG, $OUTPUT;
532 require_once($CFG->libdir
. '/gradelib.php');
533 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
535 $grades = grade_get_grades($course->id
, 'mod', 'quiz', $quiz->id
, $user->id
);
536 if (!empty($grades->items
[0]->grades
)) {
537 $grade = reset($grades->items
[0]->grades
);
538 // If the user can't see hidden grades, don't return that information.
539 $gitem = grade_item
::fetch(['id' => $grades->items
[0]->id
]);
540 if (!$gitem->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
541 echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade
);
542 if ($grade->str_feedback
) {
543 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
546 echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
547 if ($grade->str_feedback
) {
548 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
553 if ($attempts = $DB->get_records('quiz_attempts',
554 ['userid' => $user->id
, 'quiz' => $quiz->id
], 'attempt')) {
555 foreach ($attempts as $attempt) {
556 echo get_string('attempt', 'quiz', $attempt->attempt
) . ': ';
557 if ($attempt->state
!= quiz_attempt
::FINISHED
) {
558 echo quiz_attempt_state_name($attempt->state
);
560 if (!isset($gitem)) {
561 if (!empty($grades->items
[0]->grades
)) {
562 $gitem = grade_item
::fetch(['id' => $grades->items
[0]->id
]);
564 $gitem = new stdClass();
565 $gitem->hidden
= true;
568 if (!$gitem->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
569 echo quiz_format_grade($quiz, $attempt->sumgrades
) . '/' . quiz_format_grade($quiz, $quiz->sumgrades
);
571 echo get_string('hidden', 'grades');
573 echo ' - '.userdate($attempt->timefinish
).'<br />';
577 print_string('noattempts', 'quiz');
585 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
586 * @param int $userid the userid.
587 * @param string $status 'all', 'finished' or 'unfinished' to control
588 * @param bool $includepreviews
589 * @return array of all the user's attempts at this quiz. Returns an empty
590 * array if there are none.
592 function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
598 $statuscondition = '';
602 $statuscondition = ' AND state IN (:state1, :state2)';
603 $params['state1'] = quiz_attempt
::FINISHED
;
604 $params['state2'] = quiz_attempt
::ABANDONED
;
608 $statuscondition = ' AND state IN (:state1, :state2)';
609 $params['state1'] = quiz_attempt
::IN_PROGRESS
;
610 $params['state2'] = quiz_attempt
::OVERDUE
;
614 $quizids = (array) $quizids;
615 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED
);
616 $params +
= $inparams;
617 $params['userid'] = $userid;
620 if (!$includepreviews) {
621 $previewclause = ' AND preview = 0';
624 return $DB->get_records_select('quiz_attempts',
625 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
626 $params, 'quiz, attempt ASC');
630 * Return grade for given user or all users.
632 * @param int $quizid id of quiz
633 * @param int $userid optional user id, 0 means all users
634 * @return array array of grades, false if none. These are raw grades. They should
635 * be processed with quiz_format_grade for display.
637 function quiz_get_user_grades($quiz, $userid = 0) {
640 $params = [$quiz->id
];
644 $usertest = 'AND u.id = ?';
646 return $DB->get_records_sql("
650 qg.grade AS rawgrade,
651 qg.timemodified AS dategraded,
652 MAX(qa.timefinish) AS datesubmitted
655 JOIN {quiz_grades} qg ON u.id = qg.userid
656 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
660 GROUP BY u.id, qg.grade, qg.timemodified", $params);
664 * Round a grade to the correct number of decimal places, and format it for display.
666 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
667 * @param float|null $grade The grade to round and display (or null meaning no grade).
670 function quiz_format_grade($quiz, $grade) {
671 if (is_null($grade)) {
672 return get_string('notyetgraded', 'quiz');
674 return format_float($grade, $quiz->decimalpoints
);
678 * Determine the correct number of decimal places required to format a grade.
680 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints and
681 * ->questiondecimalpoints are used.
684 function quiz_get_grade_format($quiz) {
685 if (empty($quiz->questiondecimalpoints
)) {
686 $quiz->questiondecimalpoints
= -1;
689 if ($quiz->questiondecimalpoints
== -1) {
690 return $quiz->decimalpoints
;
693 return $quiz->questiondecimalpoints
;
697 * Round a grade to the correct number of decimal places, and format it for display.
699 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
700 * @param float $grade The grade to round.
703 function quiz_format_question_grade($quiz, $grade) {
704 return format_float($grade, quiz_get_grade_format($quiz));
708 * Update grades in central gradebook
711 * @param stdClass $quiz the quiz settings.
712 * @param int $userid specific user only, 0 means all users.
713 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
715 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
717 require_once($CFG->libdir
. '/gradelib.php');
719 if ($quiz->grade
== 0) {
720 quiz_grade_item_update($quiz);
722 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
723 quiz_grade_item_update($quiz, $grades);
725 } else if ($userid && $nullifnone) {
726 $grade = new stdClass();
727 $grade->userid
= $userid;
728 $grade->rawgrade
= null;
729 quiz_grade_item_update($quiz, $grade);
732 quiz_grade_item_update($quiz);
737 * Create or update the grade item for given quiz
740 * @param stdClass $quiz object with extra cmidnumber
741 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
742 * @return int 0 if ok, error code otherwise
744 function quiz_grade_item_update($quiz, $grades = null) {
745 global $CFG, $OUTPUT;
746 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
747 require_once($CFG->libdir
. '/gradelib.php');
749 if (property_exists($quiz, 'cmidnumber')) { // May not be always present.
750 $params = ['itemname' => $quiz->name
, 'idnumber' => $quiz->cmidnumber
];
752 $params = ['itemname' => $quiz->name
];
755 if ($quiz->grade
> 0) {
756 $params['gradetype'] = GRADE_TYPE_VALUE
;
757 $params['grademax'] = $quiz->grade
;
758 $params['grademin'] = 0;
761 $params['gradetype'] = GRADE_TYPE_NONE
;
764 // What this is trying to do:
765 // 1. If the quiz is set to not show grades while the quiz is still open,
766 // and is set to show grades after the quiz is closed, then create the
767 // grade_item with a show-after date that is the quiz close date.
768 // 2. If the quiz is set to not show grades at either of those times,
769 // create the grade_item as hidden.
770 // 3. If the quiz is set to show grades, create the grade_item visible.
771 $openreviewoptions = display_options
::make_from_quiz($quiz,
772 display_options
::LATER_WHILE_OPEN
);
773 $closedreviewoptions = display_options
::make_from_quiz($quiz,
774 display_options
::AFTER_CLOSE
);
775 if ($openreviewoptions->marks
< question_display_options
::MARK_AND_MAX
&&
776 $closedreviewoptions->marks
< question_display_options
::MARK_AND_MAX
) {
777 $params['hidden'] = 1;
779 } else if ($openreviewoptions->marks
< question_display_options
::MARK_AND_MAX
&&
780 $closedreviewoptions->marks
>= question_display_options
::MARK_AND_MAX
) {
781 if ($quiz->timeclose
) {
782 $params['hidden'] = $quiz->timeclose
;
784 $params['hidden'] = 1;
789 // a) both open and closed enabled
790 // b) open enabled, closed disabled - we can not "hide after",
791 // grades are kept visible even after closing.
792 $params['hidden'] = 0;
795 if (!$params['hidden']) {
796 // If the grade item is not hidden by the quiz logic, then we need to
797 // hide it if the quiz is hidden from students.
798 if (property_exists($quiz, 'visible')) {
799 // Saving the quiz form, and cm not yet updated in the database.
800 $params['hidden'] = !$quiz->visible
;
802 $cm = get_coursemodule_from_instance('quiz', $quiz->id
);
803 $params['hidden'] = !$cm->visible
;
807 if ($grades === 'reset') {
808 $params['reset'] = true;
812 $gradebook_grades = grade_get_grades($quiz->course
, 'mod', 'quiz', $quiz->id
);
813 if (!empty($gradebook_grades->items
)) {
814 $grade_item = $gradebook_grades->items
[0];
815 if ($grade_item->locked
) {
816 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
817 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT
);
818 if (!$confirm_regrade) {
820 $message = get_string('gradeitemislocked', 'grades');
821 $back_link = $CFG->wwwroot
. '/mod/quiz/report.php?q=' . $quiz->id
.
822 '&mode=overview';
823 $regrade_link = qualified_me() . '&confirm_regrade=1';
824 echo $OUTPUT->box_start('generalbox', 'notice');
825 echo '<p>'. $message .'</p>';
826 echo $OUTPUT->container_start('buttons');
827 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
828 echo $OUTPUT->single_button($back_link, get_string('cancel'));
829 echo $OUTPUT->container_end();
830 echo $OUTPUT->box_end();
832 return GRADE_UPDATE_ITEM_LOCKED
;
837 return grade_update('mod/quiz', $quiz->course
, 'mod', 'quiz', $quiz->id
, 0, $grades, $params);
841 * Delete grade item for given quiz
844 * @param stdClass $quiz object
847 function quiz_grade_item_delete($quiz) {
849 require_once($CFG->libdir
. '/gradelib.php');
851 return grade_update('mod/quiz', $quiz->course
, 'mod', 'quiz', $quiz->id
, 0,
852 null, ['deleted' => 1]);
856 * This standard function will check all instances of this module
857 * and make sure there are up-to-date events created for each of them.
858 * If courseid = 0, then every quiz event in the site is checked, else
859 * only quiz events belonging to the course specified are checked.
860 * This function is used, in its new format, by restore_refresh_events()
862 * @param int $courseid
863 * @param int|stdClass $instance Quiz module instance or ID.
864 * @param int|stdClass $cm Course module object or ID (not used in this module).
867 function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
870 // If we have instance information then we can just update the one event instead of updating all events.
871 if (isset($instance)) {
872 if (!is_object($instance)) {
873 $instance = $DB->get_record('quiz', ['id' => $instance], '*', MUST_EXIST
);
875 quiz_update_events($instance);
879 if ($courseid == 0) {
880 if (!$quizzes = $DB->get_records('quiz')) {
884 if (!$quizzes = $DB->get_records('quiz', ['course' => $courseid])) {
889 foreach ($quizzes as $quiz) {
890 quiz_update_events($quiz);
897 * Returns all quiz graded users since a given time for specified quiz
899 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
900 $courseid, $cmid, $userid = 0, $groupid = 0) {
901 global $CFG, $USER, $DB;
902 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
904 $course = get_course($courseid);
905 $modinfo = get_fast_modinfo($course);
907 $cm = $modinfo->cms
[$cmid];
908 $quiz = $DB->get_record('quiz', ['id' => $cm->instance
]);
911 $userselect = "AND u.id = :userid";
912 $params['userid'] = $userid;
918 $groupselect = 'AND gm.groupid = :groupid';
919 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
920 $params['groupid'] = $groupid;
926 $params['timestart'] = $timestart;
927 $params['quizid'] = $quiz->id
;
929 $userfieldsapi = \core_user\fields
::for_userpic();
930 $ufields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects
;
931 if (!$attempts = $DB->get_records_sql("
934 FROM {quiz_attempts} qa
935 JOIN {user} u ON u.id = qa.userid
937 WHERE qa.timefinish > :timestart
938 AND qa.quiz = :quizid
942 ORDER BY qa.timefinish ASC", $params)) {
946 $context = context_module
::instance($cm->id
);
947 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
948 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
949 $grader = has_capability('mod/quiz:viewreports', $context);
950 $groupmode = groups_get_activity_groupmode($cm, $course);
953 $aname = format_string($cm->name
, true);
954 foreach ($attempts as $attempt) {
955 if ($attempt->userid
!= $USER->id
) {
957 // Grade permission required.
961 if ($groupmode == SEPARATEGROUPS
and !$accessallgroups) {
962 $usersgroups = groups_get_all_groups($course->id
,
963 $attempt->userid
, $cm->groupingid
);
964 $usersgroups = array_keys($usersgroups);
965 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid
))) {
971 $options = quiz_get_review_options($quiz, $attempt, $context);
973 $tmpactivity = new stdClass();
975 $tmpactivity->type
= 'quiz';
976 $tmpactivity->cmid
= $cm->id
;
977 $tmpactivity->name
= $aname;
978 $tmpactivity->sectionnum
= $cm->sectionnum
;
979 $tmpactivity->timestamp
= $attempt->timefinish
;
981 $tmpactivity->content
= new stdClass();
982 $tmpactivity->content
->attemptid
= $attempt->id
;
983 $tmpactivity->content
->attempt
= $attempt->attempt
;
984 if (quiz_has_grades($quiz) && $options->marks
>= question_display_options
::MARK_AND_MAX
) {
985 $tmpactivity->content
->sumgrades
= quiz_format_grade($quiz, $attempt->sumgrades
);
986 $tmpactivity->content
->maxgrade
= quiz_format_grade($quiz, $quiz->sumgrades
);
988 $tmpactivity->content
->sumgrades
= null;
989 $tmpactivity->content
->maxgrade
= null;
992 $tmpactivity->user
= user_picture
::unalias($attempt, null, 'useridagain');
993 $tmpactivity->user
->fullname
= fullname($tmpactivity->user
, $viewfullnames);
995 $activities[$index++
] = $tmpactivity;
999 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
1000 global $CFG, $OUTPUT;
1002 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
1004 echo '<tr><td class="userpicture" valign="top">';
1005 echo $OUTPUT->user_picture($activity->user
, ['courseid' => $courseid]);
1009 $modname = $modnames[$activity->type
];
1010 echo '<div class="title">';
1011 echo $OUTPUT->image_icon('monologo', $modname, $activity->type
);
1012 echo '<a href="' . $CFG->wwwroot
. '/mod/quiz/view.php?id=' .
1013 $activity->cmid
. '">' . $activity->name
. '</a>';
1017 echo '<div class="grade">';
1018 echo get_string('attempt', 'quiz', $activity->content
->attempt
);
1019 if (isset($activity->content
->maxgrade
)) {
1020 $grades = $activity->content
->sumgrades
. ' / ' . $activity->content
->maxgrade
;
1021 echo ': (<a href="' . $CFG->wwwroot
. '/mod/quiz/review.php?attempt=' .
1022 $activity->content
->attemptid
. '">' . $grades . '</a>)';
1026 echo '<div class="user">';
1027 echo '<a href="' . $CFG->wwwroot
. '/user/view.php?id=' . $activity->user
->id
.
1028 '&course=' . $courseid . '">' . $activity->user
->fullname
.
1029 '</a> - ' . userdate($activity->timestamp
);
1032 echo '</td></tr></table>';
1038 * Pre-process the quiz options form data, making any necessary adjustments.
1039 * Called by add/update instance in this file.
1041 * @param stdClass $quiz The variables set on the form.
1043 function quiz_process_options($quiz) {
1045 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
1046 require_once($CFG->libdir
. '/questionlib.php');
1048 $quiz->timemodified
= time();
1051 if (!empty($quiz->name
)) {
1052 $quiz->name
= trim($quiz->name
);
1055 // Password field - different in form to stop browsers that remember passwords
1056 // getting confused.
1057 $quiz->password
= $quiz->quizpassword
;
1058 unset($quiz->quizpassword
);
1061 if (isset($quiz->feedbacktext
)) {
1062 // Clean up the boundary text.
1063 for ($i = 0; $i < count($quiz->feedbacktext
); $i +
= 1) {
1064 if (empty($quiz->feedbacktext
[$i]['text'])) {
1065 $quiz->feedbacktext
[$i]['text'] = '';
1067 $quiz->feedbacktext
[$i]['text'] = trim($quiz->feedbacktext
[$i]['text']);
1071 // Check the boundary value is a number or a percentage, and in range.
1073 while (!empty($quiz->feedbackboundaries
[$i])) {
1074 $boundary = trim($quiz->feedbackboundaries
[$i]);
1075 if (!is_numeric($boundary)) {
1076 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1077 $boundary = trim(substr($boundary, 0, -1));
1078 if (is_numeric($boundary)) {
1079 $boundary = $boundary * $quiz->grade
/ 100.0;
1081 return get_string('feedbackerrorboundaryformat', 'quiz', $i +
1);
1085 if ($boundary <= 0 ||
$boundary >= $quiz->grade
) {
1086 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i +
1);
1088 if ($i > 0 && $boundary >= $quiz->feedbackboundaries
[$i - 1]) {
1089 return get_string('feedbackerrororder', 'quiz', $i +
1);
1091 $quiz->feedbackboundaries
[$i] = $boundary;
1094 $numboundaries = $i;
1096 // Check there is nothing in the remaining unused fields.
1097 if (!empty($quiz->feedbackboundaries
)) {
1098 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries
); $i +
= 1) {
1099 if (!empty($quiz->feedbackboundaries
[$i]) &&
1100 trim($quiz->feedbackboundaries
[$i]) != '') {
1101 return get_string('feedbackerrorjunkinboundary', 'quiz', $i +
1);
1105 for ($i = $numboundaries +
1; $i < count($quiz->feedbacktext
); $i +
= 1) {
1106 if (!empty($quiz->feedbacktext
[$i]['text']) &&
1107 trim($quiz->feedbacktext
[$i]['text']) != '') {
1108 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i +
1);
1111 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1112 $quiz->feedbackboundaries
[-1] = $quiz->grade +
1;
1113 $quiz->feedbackboundaries
[$numboundaries] = 0;
1114 $quiz->feedbackboundarycount
= $numboundaries;
1116 $quiz->feedbackboundarycount
= -1;
1119 // Combing the individual settings into the review columns.
1120 $quiz->reviewattempt
= quiz_review_option_form_to_db($quiz, 'attempt');
1121 $quiz->reviewcorrectness
= quiz_review_option_form_to_db($quiz, 'correctness');
1122 $quiz->reviewmaxmarks
= quiz_review_option_form_to_db($quiz, 'maxmarks');
1123 $quiz->reviewmarks
= quiz_review_option_form_to_db($quiz, 'marks');
1124 $quiz->reviewspecificfeedback
= quiz_review_option_form_to_db($quiz, 'specificfeedback');
1125 $quiz->reviewgeneralfeedback
= quiz_review_option_form_to_db($quiz, 'generalfeedback');
1126 $quiz->reviewrightanswer
= quiz_review_option_form_to_db($quiz, 'rightanswer');
1127 $quiz->reviewoverallfeedback
= quiz_review_option_form_to_db($quiz, 'overallfeedback');
1128 $quiz->reviewattempt |
= display_options
::DURING
;
1129 $quiz->reviewoverallfeedback
&= ~display_options
::DURING
;
1131 // Ensure that disabled checkboxes in completion settings are set to 0.
1132 // But only if the completion settinsg are unlocked.
1133 if (!empty($quiz->completionunlocked
)) {
1134 if (empty($quiz->completionusegrade
)) {
1135 $quiz->completionpassgrade
= 0;
1137 if (empty($quiz->completionpassgrade
)) {
1138 $quiz->completionattemptsexhausted
= 0;
1140 if (empty($quiz->completionminattemptsenabled
)) {
1141 $quiz->completionminattempts
= 0;
1147 * Helper function for {@link quiz_process_options()}.
1148 * @param stdClass $fromform the sumbitted form date.
1149 * @param string $field one of the review option field names.
1151 function quiz_review_option_form_to_db($fromform, $field) {
1153 'during' => display_options
::DURING
,
1154 'immediately' => display_options
::IMMEDIATELY_AFTER
,
1155 'open' => display_options
::LATER_WHILE_OPEN
,
1156 'closed' => display_options
::AFTER_CLOSE
,
1160 foreach ($times as $whenname => $when) {
1161 $fieldname = $field . $whenname;
1162 if (!empty($fromform->$fieldname)) {
1164 unset($fromform->$fieldname);
1172 * In place editable callback for slot displaynumber.
1174 * @param string $itemtype slotdisplarnumber
1175 * @param int $itemid the id of the slot in the quiz_slots table
1176 * @param string $newvalue the new value for displaynumber field for a given slot in the quiz_slots table
1177 * @return \core\output\inplace_editable|void
1179 function mod_quiz_inplace_editable(string $itemtype, int $itemid, string $newvalue): \core\output\inplace_editable
{
1182 if ($itemtype === 'slotdisplaynumber') {
1183 // Work out which quiz and slot this is.
1184 $slot = $DB->get_record('quiz_slots', ['id' => $itemid], '*', MUST_EXIST
);
1185 $quizobj = quiz_settings
::create($slot->quizid
);
1187 // Validate the context, and check the required capability.
1188 $context = $quizobj->get_context();
1189 \core_external\external_api
::validate_context($context);
1190 require_capability('mod/quiz:manage', $context);
1192 // Update the value - truncating the size of the DB column.
1193 $structure = $quizobj->get_structure();
1194 $structure->update_slot_display_number($itemid, core_text
::substr($newvalue, 0, 16));
1196 // Prepare the element for the output.
1197 return $structure->make_slot_display_number_in_place_editable($itemid, $context);
1202 * This function is called at the end of quiz_add_instance
1203 * and quiz_update_instance, to do the common processing.
1205 * @param stdClass $quiz the quiz object.
1207 function quiz_after_add_or_update($quiz) {
1209 $cmid = $quiz->coursemodule
;
1211 // We need to use context now, so we need to make sure all needed info is already in db.
1212 $DB->set_field('course_modules', 'instance', $quiz->id
, ['id' => $cmid]);
1213 $context = context_module
::instance($cmid);
1215 // Save the feedback.
1216 $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id
]);
1218 for ($i = 0; $i <= $quiz->feedbackboundarycount
; $i++
) {
1219 $feedback = new stdClass();
1220 $feedback->quizid
= $quiz->id
;
1221 $feedback->feedbacktext
= $quiz->feedbacktext
[$i]['text'];
1222 $feedback->feedbacktextformat
= $quiz->feedbacktext
[$i]['format'];
1223 $feedback->mingrade
= $quiz->feedbackboundaries
[$i];
1224 $feedback->maxgrade
= $quiz->feedbackboundaries
[$i - 1];
1225 $feedback->id
= $DB->insert_record('quiz_feedback', $feedback);
1226 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext
[$i]['itemid'],
1227 $context->id
, 'mod_quiz', 'feedback', $feedback->id
,
1228 ['subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0],
1229 $quiz->feedbacktext
[$i]['text']);
1230 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1231 ['id' => $feedback->id
]);
1234 // Store any settings belonging to the access rules.
1235 access_manager
::save_settings($quiz);
1237 // Update the events relating to this quiz.
1238 quiz_update_events($quiz);
1239 $completionexpected = (!empty($quiz->completionexpected
)) ?
$quiz->completionexpected
: null;
1240 \core_completion\api
::update_completion_date_event($quiz->coursemodule
, 'quiz', $quiz->id
, $completionexpected);
1242 // Update related grade item.
1243 quiz_grade_item_update($quiz);
1247 * This function updates the events associated to the quiz.
1248 * If $override is non-zero, then it updates only the events
1249 * associated with the specified override.
1251 * @param stdClass $quiz the quiz object.
1252 * @param stdClass|null $override limit to a specific override
1254 function quiz_update_events($quiz, $override = null) {
1257 // Load the old events relating to this quiz.
1258 $conds = ['modulename' => 'quiz',
1259 'instance' => $quiz->id
];
1260 if (!empty($override)) {
1261 // Only load events for this override.
1262 if (isset($override->userid
)) {
1263 $conds['userid'] = $override->userid
;
1265 $conds['groupid'] = $override->groupid
;
1268 $oldevents = $DB->get_records('event', $conds, 'id ASC');
1270 // Now make a to-do list of all that needs to be updated.
1271 if (empty($override)) {
1272 // We are updating the primary settings for the quiz, so we need to add all the overrides.
1273 $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id
], 'id ASC');
1274 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1275 // list contains the original (non-override) event for the module. If this is not included
1276 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1277 // list against the $oldevents list.
1278 array_unshift($overrides, new stdClass());
1280 // Just do the one override.
1281 $overrides = [$override];
1284 // Get group override priorities.
1285 $grouppriorities = quiz_get_group_override_priorities($quiz->id
);
1287 foreach ($overrides as $current) {
1288 $groupid = isset($current->groupid
)?
$current->groupid
: 0;
1289 $userid = isset($current->userid
)?
$current->userid
: 0;
1290 $timeopen = isset($current->timeopen
)?
$current->timeopen
: $quiz->timeopen
;
1291 $timeclose = isset($current->timeclose
)?
$current->timeclose
: $quiz->timeclose
;
1293 // Only add open/close events for an override if they differ from the quiz default.
1294 $addopen = empty($current->id
) ||
!empty($current->timeopen
);
1295 $addclose = empty($current->id
) ||
!empty($current->timeclose
);
1297 if (!empty($quiz->coursemodule
)) {
1298 $cmid = $quiz->coursemodule
;
1300 $cmid = get_coursemodule_from_instance('quiz', $quiz->id
, $quiz->course
)->id
;
1303 $event = new stdClass();
1304 $event->type
= !$timeclose ? CALENDAR_EVENT_TYPE_ACTION
: CALENDAR_EVENT_TYPE_STANDARD
;
1305 $event->description
= format_module_intro('quiz', $quiz, $cmid, false);
1306 $event->format
= FORMAT_HTML
;
1307 // Events module won't show user events when the courseid is nonzero.
1308 $event->courseid
= ($userid) ?
0 : $quiz->course
;
1309 $event->groupid
= $groupid;
1310 $event->userid
= $userid;
1311 $event->modulename
= 'quiz';
1312 $event->instance
= $quiz->id
;
1313 $event->timestart
= $timeopen;
1314 $event->timeduration
= max($timeclose - $timeopen, 0);
1315 $event->timesort
= $timeopen;
1316 $event->visible
= instance_is_visible('quiz', $quiz);
1317 $event->eventtype
= QUIZ_EVENT_TYPE_OPEN
;
1318 $event->priority
= null;
1320 // Determine the event name and priority.
1322 // Group override event.
1323 $params = new stdClass();
1324 $params->quiz
= $quiz->name
;
1325 $params->group
= groups_get_group_name($groupid);
1326 if ($params->group
=== false) {
1327 // Group doesn't exist, just skip it.
1330 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1331 // Set group override priority.
1332 if ($grouppriorities !== null) {
1333 $openpriorities = $grouppriorities['open'];
1334 if (isset($openpriorities[$timeopen])) {
1335 $event->priority
= $openpriorities[$timeopen];
1338 } else if ($userid) {
1339 // User override event.
1340 $params = new stdClass();
1341 $params->quiz
= $quiz->name
;
1342 $eventname = get_string('overrideusereventname', 'quiz', $params);
1343 // Set user override priority.
1344 $event->priority
= CALENDAR_EVENT_USER_OVERRIDE_PRIORITY
;
1346 // The parent event.
1347 $eventname = $quiz->name
;
1350 if ($addopen or $addclose) {
1351 // Separate start and end events.
1352 $event->timeduration
= 0;
1353 if ($timeopen && $addopen) {
1354 if ($oldevent = array_shift($oldevents)) {
1355 $event->id
= $oldevent->id
;
1359 $event->name
= get_string('quizeventopens', 'quiz', $eventname);
1360 // The method calendar_event::create will reuse a db record if the id field is set.
1361 calendar_event
::create($event, false);
1363 if ($timeclose && $addclose) {
1364 if ($oldevent = array_shift($oldevents)) {
1365 $event->id
= $oldevent->id
;
1369 $event->type
= CALENDAR_EVENT_TYPE_ACTION
;
1370 $event->name
= get_string('quizeventcloses', 'quiz', $eventname);
1371 $event->timestart
= $timeclose;
1372 $event->timesort
= $timeclose;
1373 $event->eventtype
= QUIZ_EVENT_TYPE_CLOSE
;
1374 if ($groupid && $grouppriorities !== null) {
1375 $closepriorities = $grouppriorities['close'];
1376 if (isset($closepriorities[$timeclose])) {
1377 $event->priority
= $closepriorities[$timeclose];
1380 calendar_event
::create($event, false);
1385 // Delete any leftover events.
1386 foreach ($oldevents as $badevent) {
1387 $badevent = calendar_event
::load($badevent);
1388 $badevent->delete();
1393 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1395 * @param int $quizid The quiz ID.
1396 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1398 function quiz_get_group_override_priorities($quizid) {
1401 // Fetch group overrides.
1402 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1403 $params = ['quiz' => $quizid];
1404 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1409 $grouptimeopen = [];
1410 $grouptimeclose = [];
1411 foreach ($overrides as $override) {
1412 if ($override->timeopen
!== null && !in_array($override->timeopen
, $grouptimeopen)) {
1413 $grouptimeopen[] = $override->timeopen
;
1415 if ($override->timeclose
!== null && !in_array($override->timeclose
, $grouptimeclose)) {
1416 $grouptimeclose[] = $override->timeclose
;
1420 // Sort open times in ascending manner. The earlier open time gets higher priority.
1421 sort($grouptimeopen);
1423 $opengrouppriorities = [];
1425 foreach ($grouptimeopen as $timeopen) {
1426 $opengrouppriorities[$timeopen] = $openpriority++
;
1429 // Sort close times in descending manner. The later close time gets higher priority.
1430 rsort($grouptimeclose);
1432 $closegrouppriorities = [];
1434 foreach ($grouptimeclose as $timeclose) {
1435 $closegrouppriorities[$timeclose] = $closepriority++
;
1439 'open' => $opengrouppriorities,
1440 'close' => $closegrouppriorities
1445 * List the actions that correspond to a view of this module.
1446 * This is used by the participation report.
1448 * Note: This is not used by new logging system. Event with
1449 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1450 * be considered as view action.
1454 function quiz_get_view_actions() {
1455 return ['view', 'view all', 'report', 'review'];
1459 * List the actions that correspond to a post of this module.
1460 * This is used by the participation report.
1462 * Note: This is not used by new logging system. Event with
1463 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1464 * will be considered as post action.
1468 function quiz_get_post_actions() {
1469 return ['attempt', 'close attempt', 'preview', 'editquestions',
1470 'delete attempt', 'manualgrade'];
1474 * Standard callback used by questions_in_use.
1476 * @param array $questionids of question ids.
1477 * @return bool whether any of these questions are used by any instance of this module.
1479 function quiz_questions_in_use($questionids) {
1480 return question_engine
::questions_in_use($questionids,
1481 new qubaid_join('{quiz_attempts} quiza', 'quiza.uniqueid',
1482 'quiza.preview = 0'));
1486 * Implementation of the function for printing the form elements that control
1487 * whether the course reset functionality affects the quiz.
1489 * @param MoodleQuickForm $mform the course reset form that is being built.
1491 function quiz_reset_course_form_definition($mform) {
1492 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1493 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1494 get_string('removeallquizattempts', 'quiz'));
1495 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1496 get_string('removealluseroverrides', 'quiz'));
1497 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1498 get_string('removeallgroupoverrides', 'quiz'));
1502 * Course reset form defaults.
1503 * @return array the defaults.
1505 function quiz_reset_course_form_defaults($course) {
1506 return ['reset_quiz_attempts' => 1,
1507 'reset_quiz_group_overrides' => 1,
1508 'reset_quiz_user_overrides' => 1];
1512 * Removes all grades from gradebook
1514 * @param int $courseid
1515 * @param string optional type
1517 function quiz_reset_gradebook($courseid, $type='') {
1520 $quizzes = $DB->get_records_sql("
1521 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1523 JOIN {course_modules} cm ON m.id = cm.module
1524 JOIN {quiz} q ON cm.instance = q.id
1525 WHERE m.name = 'quiz' AND cm.course = ?", [$courseid]);
1527 foreach ($quizzes as $quiz) {
1528 quiz_grade_item_update($quiz, 'reset');
1533 * Actual implementation of the reset course functionality, delete all the
1534 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1537 * Also, move the quiz open and close dates, if the course start date is changing.
1539 * @param stdClass $data the data submitted from the reset course.
1540 * @return array status array
1542 function quiz_reset_userdata($data) {
1544 require_once($CFG->libdir
. '/questionlib.php');
1546 $componentstr = get_string('modulenameplural', 'quiz');
1550 if (!empty($data->reset_quiz_attempts
)) {
1551 question_engine
::delete_questions_usage_by_activities(new qubaid_join(
1552 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1553 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1554 ['quizcourseid' => $data->courseid
]));
1556 $DB->delete_records_select('quiz_attempts',
1557 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid
]);
1559 'component' => $componentstr,
1560 'item' => get_string('attemptsdeleted', 'quiz'),
1563 // Remove all grades from gradebook.
1564 $DB->delete_records_select('quiz_grades',
1565 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid
]);
1566 if (empty($data->reset_gradebook_grades
)) {
1567 quiz_reset_gradebook($data->courseid
);
1570 'component' => $componentstr,
1571 'item' => get_string('gradesdeleted', 'quiz'),
1575 $purgeoverrides = false;
1577 // Remove user overrides.
1578 if (!empty($data->reset_quiz_user_overrides
)) {
1579 $DB->delete_records_select('quiz_overrides',
1580 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid
]);
1582 'component' => $componentstr,
1583 'item' => get_string('useroverridesdeleted', 'quiz'),
1585 $purgeoverrides = true;
1587 // Remove group overrides.
1588 if (!empty($data->reset_quiz_group_overrides
)) {
1589 $DB->delete_records_select('quiz_overrides',
1590 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid
]);
1592 'component' => $componentstr,
1593 'item' => get_string('groupoverridesdeleted', 'quiz'),
1595 $purgeoverrides = true;
1598 // Updating dates - shift may be negative too.
1599 if ($data->timeshift
) {
1600 $DB->execute("UPDATE {quiz_overrides}
1601 SET timeopen = timeopen + ?
1602 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1603 AND timeopen <> 0", [$data->timeshift
, $data->courseid
]);
1604 $DB->execute("UPDATE {quiz_overrides}
1605 SET timeclose = timeclose + ?
1606 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1607 AND timeclose <> 0", [$data->timeshift
, $data->courseid
]);
1609 $purgeoverrides = true;
1611 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1613 shift_course_mod_dates('quiz', ['timeopen', 'timeclose'],
1614 $data->timeshift
, $data->courseid
);
1617 'component' => $componentstr,
1618 'item' => get_string('openclosedatesupdated', 'quiz'),
1622 if ($purgeoverrides) {
1623 cache
::make('mod_quiz', 'overrides')->purge();
1630 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1631 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1633 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1634 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1635 * $cm->groupingid fields are used at the moment.
1636 * @param bool $returnzero if false (default), when no attempts have been
1637 * made '' is returned instead of 'Attempts: 0'.
1638 * @param int $currentgroup if there is a concept of current group where this method is being called
1639 * (e.g. a report) pass it in here. Default 0 which means no current group.
1640 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1641 * "Attemtps 123 (45 from this group)".
1643 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1645 $numattempts = $DB->count_records('quiz_attempts', ['quiz' => $quiz->id
, 'preview' => 0]);
1646 if ($numattempts ||
$returnzero) {
1647 if (groups_get_activity_groupmode($cm)) {
1648 $a = new stdClass();
1649 $a->total
= $numattempts;
1650 if ($currentgroup) {
1651 $a->group
= $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1652 '{quiz_attempts} qa JOIN ' .
1653 '{groups_members} gm ON qa.userid = gm.userid ' .
1654 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1655 [$quiz->id
, $currentgroup]);
1656 return get_string('attemptsnumthisgroup', 'quiz', $a);
1657 } else if ($groups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
)) {
1658 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1659 $a->group
= $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1660 '{quiz_attempts} qa JOIN ' .
1661 '{groups_members} gm ON qa.userid = gm.userid ' .
1662 'WHERE quiz = ? AND preview = 0 AND ' .
1663 "groupid $usql", array_merge([$quiz->id
], $params));
1664 return get_string('attemptsnumyourgroups', 'quiz', $a);
1667 return get_string('attemptsnum', 'quiz', $numattempts);
1673 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1674 * to the quiz reports.
1676 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1677 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1678 * $cm->groupingid fields are used at the moment.
1679 * @param stdClass $context the quiz context.
1680 * @param bool $returnzero if false (default), when no attempts have been made
1681 * '' is returned instead of 'Attempts: 0'.
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 HTML fragment for the link.
1686 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1687 $currentgroup = 0) {
1690 return $PAGE->get_renderer('mod_quiz')->quiz_attempt_summary_link_to_reports(
1691 $quiz, $cm, $context, $returnzero, $currentgroup);
1695 * @param string $feature FEATURE_xx constant for requested feature
1696 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1698 function quiz_supports($feature) {
1700 case FEATURE_GROUPS
: return true;
1701 case FEATURE_GROUPINGS
: return true;
1702 case FEATURE_MOD_INTRO
: return true;
1703 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
1704 case FEATURE_COMPLETION_HAS_RULES
: return true;
1705 case FEATURE_GRADE_HAS_GRADE
: return true;
1706 case FEATURE_GRADE_OUTCOMES
: return true;
1707 case FEATURE_BACKUP_MOODLE2
: return true;
1708 case FEATURE_SHOW_DESCRIPTION
: return true;
1709 case FEATURE_CONTROLS_GRADE_VISIBILITY
: return true;
1710 case FEATURE_USES_QUESTIONS
: return true;
1711 case FEATURE_PLAGIARISM
: return true;
1712 case FEATURE_MOD_PURPOSE
: return MOD_PURPOSE_ASSESSMENT
;
1714 default: return null;
1719 * @return array all other caps used in module
1721 function quiz_get_extra_capabilities() {
1723 require_once($CFG->libdir
. '/questionlib.php');
1724 return question_get_all_capabilities();
1728 * This function extends the settings navigation block for the site.
1730 * It is safe to rely on PAGE here as we will only ever be within the module
1731 * context when this is called
1733 * @param settings_navigation $settings
1734 * @param navigation_node $quiznode
1737 function quiz_extend_settings_navigation(settings_navigation
$settings, navigation_node
$quiznode) {
1740 // Require {@link questionlib.php}
1741 // Included here as we only ever want to include this file if we really need to.
1742 require_once($CFG->libdir
. '/questionlib.php');
1744 // We want to add these new nodes after the Edit settings node, and before the
1745 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1746 $keys = $quiznode->get_children_key_list();
1748 $i = array_search('modedit', $keys);
1749 if ($i === false and array_key_exists(0, $keys)) {
1750 $beforekey = $keys[0];
1751 } else if (array_key_exists($i +
1, $keys)) {
1752 $beforekey = $keys[$i +
1];
1755 if (has_any_capability(['mod/quiz:manageoverrides', 'mod/quiz:viewoverrides'], $settings->get_page()->cm
->context
)) {
1756 $url = new moodle_url('/mod/quiz/overrides.php', ['cmid' => $settings->get_page()->cm
->id
, 'mode' => 'user']);
1757 $node = navigation_node
::create(get_string('overrides', 'quiz'),
1758 $url, navigation_node
::TYPE_SETTING
, null, 'mod_quiz_useroverrides');
1759 $settingsoverride = $quiznode->add_node($node, $beforekey);
1762 if (has_capability('mod/quiz:manage', $settings->get_page()->cm
->context
)) {
1763 $node = navigation_node
::create(get_string('questions', 'quiz'),
1764 new moodle_url('/mod/quiz/edit.php', ['cmid' => $settings->get_page()->cm
->id
]),
1765 navigation_node
::TYPE_SETTING
, null, 'mod_quiz_edit', new pix_icon('t/edit', ''));
1766 $quiznode->add_node($node, $beforekey);
1769 if (has_capability('mod/quiz:preview', $settings->get_page()->cm
->context
)) {
1770 $url = new moodle_url('/mod/quiz/startattempt.php',
1771 ['cmid' => $settings->get_page()->cm
->id
, 'sesskey' => sesskey()]);
1772 $node = navigation_node
::create(get_string('preview', 'quiz'), $url,
1773 navigation_node
::TYPE_SETTING
, null, 'mod_quiz_preview',
1774 new pix_icon('i/preview', ''));
1775 $previewnode = $quiznode->add_node($node, $beforekey);
1776 $previewnode->set_show_in_secondary_navigation(false);
1779 question_extend_settings_navigation($quiznode, $settings->get_page()->cm
->context
)->trim_if_empty();
1781 if (has_any_capability(['mod/quiz:viewreports', 'mod/quiz:grade'], $settings->get_page()->cm
->context
)) {
1782 require_once($CFG->dirroot
. '/mod/quiz/report/reportlib.php');
1783 $reportlist = quiz_report_list($settings->get_page()->cm
->context
);
1785 $url = new moodle_url('/mod/quiz/report.php',
1786 ['id' => $settings->get_page()->cm
->id
, 'mode' => reset($reportlist)]);
1787 $reportnode = $quiznode->add_node(navigation_node
::create(get_string('results', 'quiz'), $url,
1788 navigation_node
::TYPE_SETTING
,
1789 null, 'quiz_report', new pix_icon('i/report', '')));
1791 foreach ($reportlist as $report) {
1792 $url = new moodle_url('/mod/quiz/report.php', ['id' => $settings->get_page()->cm
->id
, 'mode' => $report]);
1793 $reportnode->add_node(navigation_node
::create(get_string($report, 'quiz_'.$report), $url,
1794 navigation_node
::TYPE_SETTING
,
1795 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1801 * Serves the quiz files.
1805 * @param stdClass $course course object
1806 * @param stdClass $cm course module object
1807 * @param stdClass $context context object
1808 * @param string $filearea file area
1809 * @param array $args extra arguments
1810 * @param bool $forcedownload whether or not force download
1811 * @param array $options additional options affecting the file serving
1812 * @return bool false if file not found, does not return if found - justsend the file
1814 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options= []) {
1817 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1821 require_login($course, false, $cm);
1823 if (!$quiz = $DB->get_record('quiz', ['id' => $cm->instance
])) {
1827 // The 'intro' area is served by pluginfile.php.
1828 $fileareas = ['feedback'];
1829 if (!in_array($filearea, $fileareas)) {
1833 $feedbackid = (int)array_shift($args);
1834 if (!$feedback = $DB->get_record('quiz_feedback', ['id' => $feedbackid])) {
1838 $fs = get_file_storage();
1839 $relativepath = implode('/', $args);
1840 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1841 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1844 send_stored_file($file, 0, 0, true, $options);
1848 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1849 * a question in a question_attempt when that attempt is a quiz attempt.
1853 * @param stdClass $course course settings object
1854 * @param stdClass $context context object
1855 * @param string $component the name of the component we are serving files for.
1856 * @param string $filearea the name of the file area.
1857 * @param int $qubaid the attempt usage id.
1858 * @param int $slot the id of a question in this quiz attempt.
1859 * @param array $args the remaining bits of the file path.
1860 * @param bool $forcedownload whether the user must be forced to download the file.
1861 * @param array $options additional options affecting the file serving
1862 * @return bool false if file not found, does not return if found - justsend the file
1864 function quiz_question_pluginfile($course, $context, $component,
1865 $filearea, $qubaid, $slot, $args, $forcedownload, array $options= []) {
1867 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
1869 $attemptobj = quiz_attempt
::create_from_usage_id($qubaid);
1870 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1872 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1873 // In the middle of an attempt.
1874 if (!$attemptobj->is_preview_user()) {
1875 $attemptobj->require_capability('mod/quiz:attempt');
1877 $isreviewing = false;
1880 // Reviewing an attempt.
1881 $attemptobj->check_review_capability();
1882 $isreviewing = true;
1885 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id
,
1886 $component, $filearea, $args, $forcedownload)) {
1887 send_file_not_found();
1890 $fs = get_file_storage();
1891 $relativepath = implode('/', $args);
1892 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1893 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1894 send_file_not_found();
1897 send_stored_file($file, 0, 0, $forcedownload, $options);
1901 * Return a list of page types
1902 * @param string $pagetype current page type
1903 * @param stdClass $parentcontext Block's parent context
1904 * @param stdClass $currentcontext Current context of block
1906 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1908 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1909 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1910 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1911 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1912 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1913 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1914 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1916 return $modulepagetype;
1920 * @return the options for quiz navigation.
1922 function quiz_get_navigation_options() {
1924 QUIZ_NAVMETHOD_FREE
=> get_string('navmethod_free', 'quiz'),
1925 QUIZ_NAVMETHOD_SEQ
=> get_string('navmethod_seq', 'quiz')
1930 * Check if the module has any update that affects the current user since a given time.
1932 * @param cm_info $cm course module data
1933 * @param int $from the time to check updates from
1934 * @param array $filter if we need to check only specific updates
1935 * @return stdClass an object with the different type of areas indicating if they were updated or not
1938 function quiz_check_updates_since(cm_info
$cm, $from, $filter = []) {
1939 global $DB, $USER, $CFG;
1940 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
1942 $updates = course_check_module_updates_since($cm, $from, [], $filter);
1944 // Check if questions were updated.
1945 $updates->questions
= (object) ['updated' => false];
1946 $quizobj = quiz_settings
::create($cm->instance
, $USER->id
);
1947 $quizobj->preload_questions();
1948 $questionids = array_keys($quizobj->get_questions(null, false));
1949 if (!empty($questionids)) {
1950 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED
);
1951 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
1952 $params['time1'] = $from;
1953 $params['time2'] = $from;
1954 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
1955 if (!empty($questions)) {
1956 $updates->questions
->updated
= true;
1957 $updates->questions
->itemids
= array_keys($questions);
1961 // Check for new attempts or grades.
1962 $updates->attempts
= (object) ['updated' => false];
1963 $updates->grades
= (object) ['updated' => false];
1964 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
1965 $params = [$cm->instance
, $USER->id
, $from];
1967 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1968 if (!empty($attempts)) {
1969 $updates->attempts
->updated
= true;
1970 $updates->attempts
->itemids
= array_keys($attempts);
1972 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
1973 if (!empty($grades)) {
1974 $updates->grades
->updated
= true;
1975 $updates->grades
->itemids
= array_keys($grades);
1978 // Now, teachers should see other students updates.
1979 if (has_capability('mod/quiz:viewreports', $cm->context
)) {
1980 $select = 'quiz = ? AND timemodified > ?';
1981 $params = [$cm->instance
, $from];
1983 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS
) {
1984 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1985 if (empty($groupusers)) {
1988 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1989 $select .= ' AND userid ' . $insql;
1990 $params = array_merge($params, $inparams);
1993 $updates->userattempts
= (object) ['updated' => false];
1994 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1995 if (!empty($attempts)) {
1996 $updates->userattempts
->updated
= true;
1997 $updates->userattempts
->itemids
= array_keys($attempts);
2000 $updates->usergrades
= (object) ['updated' => false];
2001 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2002 if (!empty($grades)) {
2003 $updates->usergrades
->updated
= true;
2004 $updates->usergrades
->itemids
= array_keys($grades);
2011 * Get icon mapping for font-awesome.
2013 function mod_quiz_get_fontawesome_icon_map() {
2015 'mod_quiz:navflagged' => 'fa-flag',
2020 * This function receives a calendar event and returns the action associated with it, or null if there is none.
2022 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
2023 * is not displayed on the block.
2025 * @param calendar_event $event
2026 * @param \core_calendar\action_factory $factory
2027 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
2028 * @return \core_calendar\local\event\entities\action_interface|null
2030 function mod_quiz_core_calendar_provide_event_action(calendar_event
$event,
2031 \core_calendar\action_factory
$factory,
2035 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
2037 if (empty($userid)) {
2038 $userid = $USER->id
;
2041 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['quiz'][$event->instance
];
2042 $quizobj = quiz_settings
::create($cm->instance
, $userid);
2043 $quiz = $quizobj->get_quiz();
2045 // Check they have capabilities allowing them to view the quiz.
2046 if (!has_any_capability(['mod/quiz:reviewmyattempts', 'mod/quiz:attempt'], $quizobj->get_context(), $userid)) {
2050 $completion = new \
completion_info($cm->get_course());
2052 $completiondata = $completion->get_data($cm, false, $userid);
2054 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
2058 quiz_update_effective_access($quiz, $userid);
2060 // Check if quiz is closed, if so don't display it.
2061 if (!empty($quiz->timeclose
) && $quiz->timeclose
<= time()) {
2065 if (!$quizobj->is_participant($userid)) {
2066 // If the user is not a participant then they have
2067 // no action to take. This will filter out the events for teachers.
2071 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $userid);
2072 if (!empty($attempts)) {
2073 // The student's last attempt is finished.
2077 $name = get_string('attemptquiznow', 'quiz');
2078 $url = new \
moodle_url('/mod/quiz/view.php', [
2084 // Check if the quiz is not currently actionable.
2085 if (!empty($quiz->timeopen
) && $quiz->timeopen
> time()) {
2086 $actionable = false;
2089 return $factory->create_instance(
2098 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2099 * for the course (see resource).
2101 * Given a course_module object, this function returns any "extra" information that may be needed
2102 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2104 * @param stdClass $coursemodule The coursemodule object (record).
2105 * @return cached_cm_info|false An object on information that the courses
2106 * will know about (most noticeably, an icon).
2108 function quiz_get_coursemodule_info($coursemodule) {
2111 $dbparams = ['id' => $coursemodule->instance
];
2112 $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionminattempts,
2113 timeopen, timeclose';
2114 if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2118 $result = new cached_cm_info();
2119 $result->name
= $quiz->name
;
2121 if ($coursemodule->showdescription
) {
2122 // Convert intro to html. Do not filter cached version, filters run at display time.
2123 $result->content
= format_module_intro('quiz', $quiz, $coursemodule->id
, false);
2126 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2127 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
2128 if ($quiz->completionattemptsexhausted
) {
2129 $result->customdata
['customcompletionrules']['completionpassorattemptsexhausted'] = [
2130 'completionpassgrade' => $coursemodule->completionpassgrade
,
2131 'completionattemptsexhausted' => $quiz->completionattemptsexhausted
,
2134 $result->customdata
['customcompletionrules']['completionpassorattemptsexhausted'] = [];
2137 $result->customdata
['customcompletionrules']['completionminattempts'] = $quiz->completionminattempts
;
2140 // Populate some other values that can be used in calendar or on dashboard.
2141 if ($quiz->timeopen
) {
2142 $result->customdata
['timeopen'] = $quiz->timeopen
;
2144 if ($quiz->timeclose
) {
2145 $result->customdata
['timeclose'] = $quiz->timeclose
;
2152 * Sets dynamic information about a course module
2154 * This function is called from cm_info when displaying the module
2156 * @param cm_info $cm
2158 function mod_quiz_cm_info_dynamic(cm_info
$cm) {
2161 $cache = cache
::make('mod_quiz', 'overrides');
2162 $override = $cache->get("{$cm->instance}_u_{$USER->id}");
2165 $override = (object) [
2167 'timeclose' => null,
2171 // No need to look for group overrides if there are user overrides for both timeopen and timeclose.
2172 if (is_null($override->timeopen
) ||
is_null($override->timeclose
)) {
2175 $groupings = groups_get_user_groups($cm->course
, $USER->id
);
2176 foreach ($groupings[0] as $groupid) {
2177 $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}");
2178 if (isset($groupoverride->timeopen
)) {
2179 $opens[] = $groupoverride->timeopen
;
2181 if (isset($groupoverride->timeclose
)) {
2182 $closes[] = $groupoverride->timeclose
;
2185 // If there is a user override for a setting, ignore the group override.
2186 if (is_null($override->timeopen
) && count($opens)) {
2187 $override->timeopen
= min($opens);
2189 if (is_null($override->timeclose
) && count($closes)) {
2190 if (in_array(0, $closes)) {
2191 $override->timeclose
= 0;
2193 $override->timeclose
= max($closes);
2198 // Populate some other values that can be used in calendar or on dashboard.
2199 if (!is_null($override->timeopen
)) {
2200 $cm->override_customdata('timeopen', $override->timeopen
);
2202 if (!is_null($override->timeclose
)) {
2203 $cm->override_customdata('timeclose', $override->timeclose
);
2208 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2210 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
2211 * @return array $descriptions the array of descriptions for the custom rules.
2213 function mod_quiz_get_completion_active_rule_descriptions($cm) {
2214 // Values will be present in cm_info, and we assume these are up to date.
2215 if (empty($cm->customdata
['customcompletionrules'])
2216 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
2221 $rules = $cm->customdata
['customcompletionrules'];
2223 if (!empty($rules['completionpassorattemptsexhausted'])) {
2224 if (!empty($rules['completionpassorattemptsexhausted']['completionattemptsexhausted'])) {
2225 $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2229 if (!empty($rules['completionattemptsexhausted'])) {
2230 $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2234 if (!empty($rules['completionminattempts'])) {
2235 $descriptions[] = get_string('completionminattemptsdesc', 'quiz', $rules['completionminattempts']);
2238 return $descriptions;
2242 * Returns the min and max values for the timestart property of a quiz
2245 * The min and max values will be the timeopen and timeclose properties
2246 * of the quiz, respectively, if they are set.
2248 * If either value isn't set then null will be returned instead to
2249 * indicate that there is no cutoff for that value.
2251 * If the vent has no valid timestart range then [false, false] will
2252 * be returned. This is the case for overriden events.
2254 * A minimum and maximum cutoff return value will look like:
2256 * [1505704373, 'The date must be after this date'],
2257 * [1506741172, 'The date must be before this date']
2260 * @throws \moodle_exception
2261 * @param \calendar_event $event The calendar event to get the time range for
2262 * @param stdClass $quiz The module instance to get the range from
2265 function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, \stdClass
$quiz) {
2267 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
2269 // Overrides do not have a valid timestart range.
2270 if (quiz_is_overriden_calendar_event($event)) {
2271 return [false, false];
2277 if ($event->eventtype
== QUIZ_EVENT_TYPE_OPEN
) {
2278 if (!empty($quiz->timeclose
)) {
2281 get_string('openafterclose', 'quiz')
2284 } else if ($event->eventtype
== QUIZ_EVENT_TYPE_CLOSE
) {
2285 if (!empty($quiz->timeopen
)) {
2288 get_string('closebeforeopen', 'quiz')
2293 return [$mindate, $maxdate];
2297 * This function will update the quiz module according to the
2298 * event that has been modified.
2300 * It will set the timeopen or timeclose value of the quiz instance
2301 * according to the type of event provided.
2303 * @throws \moodle_exception
2304 * @param \calendar_event $event A quiz activity calendar event
2305 * @param \stdClass $quiz A quiz activity instance
2307 function mod_quiz_core_calendar_event_timestart_updated(\calendar_event
$event, \stdClass
$quiz) {
2309 require_once($CFG->dirroot
. '/mod/quiz/locallib.php');
2311 if (!in_array($event->eventtype
, [QUIZ_EVENT_TYPE_OPEN
, QUIZ_EVENT_TYPE_CLOSE
])) {
2312 // This isn't an event that we care about so we can ignore it.
2316 $courseid = $event->courseid
;
2317 $modulename = $event->modulename
;
2318 $instanceid = $event->instance
;
2320 $closedatechanged = false;
2322 // Something weird going on. The event is for a different module so
2323 // we should ignore it.
2324 if ($modulename != 'quiz') {
2328 if ($quiz->id
!= $instanceid) {
2329 // The provided quiz instance doesn't match the event so
2330 // there is nothing to do here.
2334 // We don't update the activity if it's an override event that has
2336 if (quiz_is_overriden_calendar_event($event)) {
2340 $coursemodule = get_fast_modinfo($courseid)->instances
[$modulename][$instanceid];
2341 $context = context_module
::instance($coursemodule->id
);
2343 // The user does not have the capability to modify this activity.
2344 if (!has_capability('moodle/course:manageactivities', $context)) {
2348 if ($event->eventtype
== QUIZ_EVENT_TYPE_OPEN
) {
2349 // If the event is for the quiz activity opening then we should
2350 // set the start time of the quiz activity to be the new start
2351 // time of the event.
2352 if ($quiz->timeopen
!= $event->timestart
) {
2353 $quiz->timeopen
= $event->timestart
;
2356 } else if ($event->eventtype
== QUIZ_EVENT_TYPE_CLOSE
) {
2357 // If the event is for the quiz activity closing then we should
2358 // set the end time of the quiz activity to be the new start
2359 // time of the event.
2360 if ($quiz->timeclose
!= $event->timestart
) {
2361 $quiz->timeclose
= $event->timestart
;
2363 $closedatechanged = true;
2368 $quiz->timemodified
= time();
2369 $DB->update_record('quiz', $quiz);
2371 if ($closedatechanged) {
2372 quiz_update_open_attempts(['quizid' => $quiz->id
]);
2375 // Delete any previous preview attempts.
2376 quiz_delete_previews($quiz);
2377 quiz_update_events($quiz);
2378 $event = \core\event\course_module_updated
::create_from_cm($coursemodule, $context);
2384 * Generates the question bank in a fragment output. This allows
2385 * the question bank to be displayed in a modal.
2387 * The only expected argument provided in the $args array is
2388 * 'querystring'. The value should be the list of parameters
2389 * URL encoded and used to build the question bank page.
2391 * The individual list of parameters expected can be found in
2392 * question_build_edit_resources.
2394 * @param array $args The fragment arguments.
2395 * @return string The rendered mform fragment.
2397 function mod_quiz_output_fragment_quiz_question_bank($args): string {
2403 $querystring = parse_url($args['querystring'], PHP_URL_QUERY
);
2404 parse_str($querystring, $params);
2406 $viewclass = \mod_quiz\question\bank\custom_view
::class;
2407 $extraparams['view'] = $viewclass;
2409 // Build required parameters.
2410 [$contexts, $thispageurl, $cm, $pagevars, $extraparams] =
2411 build_required_parameters_for_custom_view($params, $extraparams);
2413 $course = get_course($cm->course
);
2414 require_capability('mod/quiz:manage', $contexts->lowest());
2417 $questionbank = new $viewclass($contexts, $thispageurl, $course, $cm, $pagevars, $extraparams);
2420 $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2421 return $renderer->question_bank_contents($questionbank, $pagevars);
2425 * Generates the add random question in a fragment output. This allows the
2426 * form to be rendered in javascript, for example inside a modal.
2428 * The required arguments as keys in the $args array are:
2429 * cat {string} The category and category context ids comma separated.
2430 * addonpage {int} The page id to add this question to.
2431 * returnurl {string} URL to return to after form submission.
2432 * cmid {int} The course module id the questions are being added to.
2434 * @param array $args The fragment arguments.
2435 * @return string The rendered mform fragment.
2437 function mod_quiz_output_fragment_add_random_question_form($args) {
2438 global $PAGE, $OUTPUT;
2442 // Build required parameters.
2443 [$contexts, $thispageurl, $cm, $pagevars, $extraparams] =
2444 build_required_parameters_for_custom_view($args, $extraparams);
2446 // Additional param to differentiate with other question bank view.
2447 $extraparams['view'] = mod_quiz\question\bank\random_question_view
::class;
2449 $course = get_course($cm->course
);
2450 require_capability('mod/quiz:manage', $contexts->lowest());
2453 $questionbank = new mod_quiz\question\bank\random_question_view
($contexts, $thispageurl, $course, $cm, $pagevars, $extraparams);
2455 $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2456 $questionbankoutput = $renderer->question_bank_contents($questionbank, $pagevars);
2459 for ($i = 1; $i <= min(100, $maxrand); $i++
) {
2460 $randomcount[] = ['value' => $i, 'name' => $i];
2463 // Parent category select.
2464 $usablecontexts = $contexts->having_cap('moodle/question:useall');
2465 $categoriesarray = helper
::question_category_options($usablecontexts);
2467 foreach ($categoriesarray as $group => $opts) {
2468 // Options for each category group.
2470 foreach ($opts as $context => $name) {
2471 $categories[] = ['value' => $context, 'name' => $name];
2473 $catoptions[] = ['label' => $group, 'options' => $categories];
2478 'questionbank' => $questionbankoutput,
2479 'randomoptions' => $randomcount,
2480 'questioncategoryoptions' => $catoptions,
2483 $result = $OUTPUT->render_from_template('mod_quiz/add_random_question_form', $data);
2489 * Callback to fetch the activity event type lang string.
2491 * @param string $eventtype The event type.
2492 * @return lang_string The event type lang string.
2494 function mod_quiz_core_calendar_get_event_action_string(string $eventtype): string {
2495 $modulename = get_string('modulename', 'quiz');
2497 switch ($eventtype) {
2498 case QUIZ_EVENT_TYPE_OPEN
:
2499 $identifier = 'quizeventopens';
2501 case QUIZ_EVENT_TYPE_CLOSE
:
2502 $identifier = 'quizeventcloses';
2505 return get_string('requiresaction', 'calendar', $modulename);
2508 return get_string($identifier, 'quiz', $modulename);
2512 * Delete question reference data.
2514 * @param int $quizid The id of quiz.
2516 function quiz_delete_references($quizid): void
{
2518 $slots = $DB->get_records('quiz_slots', ['quizid' => $quizid]);
2519 foreach ($slots as $slot) {
2521 'itemid' => $slot->id
,
2522 'component' => 'mod_quiz',
2523 'questionarea' => 'slot'
2525 // Delete any set references.
2526 $DB->delete_records('question_set_references', $params);
2527 // Delete any references.
2528 $DB->delete_records('question_references', $params);
2533 * Question data fragment to get the question html via ajax call.
2535 * @param array $args
2538 function mod_quiz_output_fragment_question_data(array $args): string {
2539 // Return if there is no args.
2544 // Retrieve params from query string.
2545 [$params, $extraparams] = \core_question\local\bank\filter_condition_manager
::extract_parameters_from_fragment_args($args);
2547 // Build required parameters.
2548 $cmid = clean_param($args['cmid'], PARAM_INT
);
2549 $thispageurl = new \
moodle_url('/mod/quiz/edit.php', ['cmid' => $cmid]);
2550 $thiscontext = \context_module
::instance($cmid);
2551 $contexts = new \core_question\local\bank\
question_edit_contexts($thiscontext);
2552 $defaultcategory = question_make_default_categories($contexts->all());
2553 $params['cat'] = implode(',', [$defaultcategory->id
, $defaultcategory->contextid
]);
2555 $course = get_course($params['courseid']);
2556 [, $cm] = get_module_from_cmid($cmid);
2557 $params['tabname'] = 'questions';
2559 // Custom question bank View.
2560 $viewclass = clean_param($args['view'], PARAM_NOTAGS
);
2561 $questionbank = new $viewclass($contexts, $thispageurl, $course, $cm, $params, $extraparams);
2564 $questionbank->add_standard_search_conditions();
2566 $questionbank->display_question_list();
2567 return ob_get_clean();
2571 * Build required parameters for question bank custom view
2573 * @param array $params the page parameters
2574 * @param array $extraparams additional parameters
2577 function build_required_parameters_for_custom_view(array $params, array $extraparams): array {
2578 // Retrieve questions per page.
2579 $viewclass = $extraparams['view'] ??
null;
2580 $defaultpagesize = $viewclass ?
$viewclass::DEFAULT_PAGE_SIZE
: DEFAULT_QUESTIONS_PER_PAGE
;
2581 // Build the required params.
2582 [$thispageurl, $contexts, $cmid, $cm, , $pagevars] = question_build_edit_resources(
2584 '/mod/quiz/edit.php',
2585 array_merge($params, $extraparams),
2588 // Add cmid so we can retrieve later in extra params.
2589 $extraparams['cmid'] = $cmid;
2591 return [$contexts, $thispageurl, $cm, $pagevars, $extraparams];
2595 * Implement the calculate_question_stats callback.
2597 * This enables quiz statistics to be shown in statistics columns in the database.
2599 * @param context $context return the statistics related to this context (which will be a quiz context).
2600 * @return all_calculated_for_qubaid_condition|null The statistics for this quiz, if available, else null.
2602 function mod_quiz_calculate_question_stats(context
$context): ?all_calculated_for_qubaid_condition
{
2604 require_once($CFG->dirroot
. '/mod/quiz/report/statistics/report.php');
2605 $cm = get_coursemodule_from_id('quiz', $context->instanceid
);
2606 $report = new quiz_statistics_report();
2607 return $report->calculate_questions_stats_for_question_bank($cm->instance
, false, false);
2611 * Return a list of all the user preferences used by mod_quiz.
2613 * @uses core_user::is_current_user
2617 function mod_quiz_user_preferences(): array {
2619 $preferences['quiz_timerhidden'] = [
2620 'type' => PARAM_INT
,
2621 'null' => NULL_NOT_ALLOWED
,
2623 'permissioncallback' => [core_user
::class, 'is_current_user'],
2625 return $preferences;