MDL-60062 quiz: add support for drag drop of calendar events
[moodle.git] / mod / quiz / lib.php
blob4ee34de8e63e633ef7793ec0f8f08fe0920170d4
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 $events = $DB->get_records('event', array('modulename' => 'quiz',
229 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
230 'userid' => (int)$override->userid));
231 foreach ($events as $event) {
232 $eventold = calendar_event::load($event);
233 $eventold->delete();
236 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
238 // Set the common parameters for one of the events we will be triggering.
239 $params = array(
240 'objectid' => $override->id,
241 'context' => context_module::instance($quiz->cmid),
242 'other' => array(
243 'quizid' => $override->quiz
246 // Determine which override deleted event to fire.
247 if (!empty($override->userid)) {
248 $params['relateduserid'] = $override->userid;
249 $event = \mod_quiz\event\user_override_deleted::create($params);
250 } else {
251 $params['other']['groupid'] = $override->groupid;
252 $event = \mod_quiz\event\group_override_deleted::create($params);
255 // Trigger the override deleted event.
256 $event->add_record_snapshot('quiz_overrides', $override);
257 $event->trigger();
259 return true;
263 * Deletes all quiz overrides from the database and clears any corresponding calendar events
265 * @param object $quiz The quiz object.
267 function quiz_delete_all_overrides($quiz) {
268 global $DB;
270 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
271 foreach ($overrides as $override) {
272 quiz_delete_override($quiz, $override->id);
277 * Updates a quiz object with override information for a user.
279 * Algorithm: For each quiz setting, if there is a matching user-specific override,
280 * then use that otherwise, if there are group-specific overrides, return the most
281 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
283 * Special case: if there is more than one password that applies to the user, then
284 * quiz->extrapasswords will contain an array of strings giving the remaining
285 * passwords.
287 * @param object $quiz The quiz object.
288 * @param int $userid The userid.
289 * @return object $quiz The updated quiz object.
291 function quiz_update_effective_access($quiz, $userid) {
292 global $DB;
294 // Check for user override.
295 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
297 if (!$override) {
298 $override = new stdClass();
299 $override->timeopen = null;
300 $override->timeclose = null;
301 $override->timelimit = null;
302 $override->attempts = null;
303 $override->password = null;
306 // Check for group overrides.
307 $groupings = groups_get_user_groups($quiz->course, $userid);
309 if (!empty($groupings[0])) {
310 // Select all overrides that apply to the User's groups.
311 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
312 $sql = "SELECT * FROM {quiz_overrides}
313 WHERE groupid $extra AND quiz = ?";
314 $params[] = $quiz->id;
315 $records = $DB->get_records_sql($sql, $params);
317 // Combine the overrides.
318 $opens = array();
319 $closes = array();
320 $limits = array();
321 $attempts = array();
322 $passwords = array();
324 foreach ($records as $gpoverride) {
325 if (isset($gpoverride->timeopen)) {
326 $opens[] = $gpoverride->timeopen;
328 if (isset($gpoverride->timeclose)) {
329 $closes[] = $gpoverride->timeclose;
331 if (isset($gpoverride->timelimit)) {
332 $limits[] = $gpoverride->timelimit;
334 if (isset($gpoverride->attempts)) {
335 $attempts[] = $gpoverride->attempts;
337 if (isset($gpoverride->password)) {
338 $passwords[] = $gpoverride->password;
341 // If there is a user override for a setting, ignore the group override.
342 if (is_null($override->timeopen) && count($opens)) {
343 $override->timeopen = min($opens);
345 if (is_null($override->timeclose) && count($closes)) {
346 if (in_array(0, $closes)) {
347 $override->timeclose = 0;
348 } else {
349 $override->timeclose = max($closes);
352 if (is_null($override->timelimit) && count($limits)) {
353 if (in_array(0, $limits)) {
354 $override->timelimit = 0;
355 } else {
356 $override->timelimit = max($limits);
359 if (is_null($override->attempts) && count($attempts)) {
360 if (in_array(0, $attempts)) {
361 $override->attempts = 0;
362 } else {
363 $override->attempts = max($attempts);
366 if (is_null($override->password) && count($passwords)) {
367 $override->password = array_shift($passwords);
368 if (count($passwords)) {
369 $override->extrapasswords = $passwords;
375 // Merge with quiz defaults.
376 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
377 foreach ($keys as $key) {
378 if (isset($override->{$key})) {
379 $quiz->{$key} = $override->{$key};
383 return $quiz;
387 * Delete all the attempts belonging to a quiz.
389 * @param object $quiz The quiz object.
391 function quiz_delete_all_attempts($quiz) {
392 global $CFG, $DB;
393 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
394 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
395 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
396 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
400 * Get the best current grade for a particular user in a quiz.
402 * @param object $quiz the quiz settings.
403 * @param int $userid the id of the user.
404 * @return float the user's current grade for this quiz, or null if this user does
405 * not have a grade on this quiz.
407 function quiz_get_best_grade($quiz, $userid) {
408 global $DB;
409 $grade = $DB->get_field('quiz_grades', 'grade',
410 array('quiz' => $quiz->id, 'userid' => $userid));
412 // Need to detect errors/no result, without catching 0 grades.
413 if ($grade === false) {
414 return null;
417 return $grade + 0; // Convert to number.
421 * Is this a graded quiz? If this method returns true, you can assume that
422 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
423 * divide by them).
425 * @param object $quiz a row from the quiz table.
426 * @return bool whether this is a graded quiz.
428 function quiz_has_grades($quiz) {
429 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
433 * Does this quiz allow multiple tries?
435 * @return bool
437 function quiz_allows_multiple_tries($quiz) {
438 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
439 return $bt->allows_multiple_submitted_responses();
443 * Return a small object with summary information about what a
444 * user has done with a given particular instance of this module
445 * Used for user activity reports.
446 * $return->time = the time they did it
447 * $return->info = a short text description
449 * @param object $course
450 * @param object $user
451 * @param object $mod
452 * @param object $quiz
453 * @return object|null
455 function quiz_user_outline($course, $user, $mod, $quiz) {
456 global $DB, $CFG;
457 require_once($CFG->libdir . '/gradelib.php');
458 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
460 if (empty($grades->items[0]->grades)) {
461 return null;
462 } else {
463 $grade = reset($grades->items[0]->grades);
466 $result = new stdClass();
467 // If the user can't see hidden grades, don't return that information.
468 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
469 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
470 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
471 } else {
472 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
475 // Datesubmitted == time created. dategraded == time modified or time overridden
476 // if grade was last modified by the user themselves use date graded. Otherwise use
477 // date submitted.
478 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
479 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
480 $result->time = $grade->dategraded;
481 } else {
482 $result->time = $grade->datesubmitted;
485 return $result;
489 * Print a detailed representation of what a user has done with
490 * a given particular instance of this module, for user activity reports.
492 * @param object $course
493 * @param object $user
494 * @param object $mod
495 * @param object $quiz
496 * @return bool
498 function quiz_user_complete($course, $user, $mod, $quiz) {
499 global $DB, $CFG, $OUTPUT;
500 require_once($CFG->libdir . '/gradelib.php');
501 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
503 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
504 if (!empty($grades->items[0]->grades)) {
505 $grade = reset($grades->items[0]->grades);
506 // If the user can't see hidden grades, don't return that information.
507 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
508 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
509 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
510 if ($grade->str_feedback) {
511 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
513 } else {
514 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
515 if ($grade->str_feedback) {
516 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
521 if ($attempts = $DB->get_records('quiz_attempts',
522 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
523 foreach ($attempts as $attempt) {
524 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
525 if ($attempt->state != quiz_attempt::FINISHED) {
526 echo quiz_attempt_state_name($attempt->state);
527 } else {
528 if (!isset($gitem)) {
529 if (!empty($grades->items[0]->grades)) {
530 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
531 } else {
532 $gitem = new stdClass();
533 $gitem->hidden = true;
536 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
537 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
538 } else {
539 echo get_string('hidden', 'grades');
542 echo ' - '.userdate($attempt->timemodified).'<br />';
544 } else {
545 print_string('noattempts', 'quiz');
548 return true;
552 * Quiz periodic clean-up tasks.
554 function quiz_cron() {
555 global $CFG;
557 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
558 mtrace('');
560 $timenow = time();
561 $overduehander = new mod_quiz_overdue_attempt_updater();
563 $processto = $timenow - get_config('quiz', 'graceperiodmin');
565 mtrace(' Looking for quiz overdue quiz attempts...');
567 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
569 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
571 // Run cron for our sub-plugin types.
572 cron_execute_plugin_type('quiz', 'quiz reports');
573 cron_execute_plugin_type('quizaccess', 'quiz access rules');
575 return true;
579 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
580 * @param int $userid the userid.
581 * @param string $status 'all', 'finished' or 'unfinished' to control
582 * @param bool $includepreviews
583 * @return an array of all the user's attempts at this quiz. Returns an empty
584 * array if there are none.
586 function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
587 global $DB, $CFG;
588 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
589 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
590 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
591 // MDL-33048.
592 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
594 $params = array();
595 switch ($status) {
596 case 'all':
597 $statuscondition = '';
598 break;
600 case 'finished':
601 $statuscondition = ' AND state IN (:state1, :state2)';
602 $params['state1'] = quiz_attempt::FINISHED;
603 $params['state2'] = quiz_attempt::ABANDONED;
604 break;
606 case 'unfinished':
607 $statuscondition = ' AND state IN (:state1, :state2)';
608 $params['state1'] = quiz_attempt::IN_PROGRESS;
609 $params['state2'] = quiz_attempt::OVERDUE;
610 break;
613 $quizids = (array) $quizids;
614 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
615 $params += $inparams;
616 $params['userid'] = $userid;
618 $previewclause = '';
619 if (!$includepreviews) {
620 $previewclause = ' AND preview = 0';
623 return $DB->get_records_select('quiz_attempts',
624 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
625 $params, 'quiz, attempt ASC');
629 * Return grade for given user or all users.
631 * @param int $quizid id of quiz
632 * @param int $userid optional user id, 0 means all users
633 * @return array array of grades, false if none. These are raw grades. They should
634 * be processed with quiz_format_grade for display.
636 function quiz_get_user_grades($quiz, $userid = 0) {
637 global $CFG, $DB;
639 $params = array($quiz->id);
640 $usertest = '';
641 if ($userid) {
642 $params[] = $userid;
643 $usertest = 'AND u.id = ?';
645 return $DB->get_records_sql("
646 SELECT
647 u.id,
648 u.id AS userid,
649 qg.grade AS rawgrade,
650 qg.timemodified AS dategraded,
651 MAX(qa.timefinish) AS datesubmitted
653 FROM {user} u
654 JOIN {quiz_grades} qg ON u.id = qg.userid
655 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
657 WHERE qg.quiz = ?
658 $usertest
659 GROUP BY u.id, qg.grade, qg.timemodified", $params);
663 * Round a grade to to the correct number of decimal places, and format it for display.
665 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
666 * @param float $grade The grade to round.
667 * @return float
669 function quiz_format_grade($quiz, $grade) {
670 if (is_null($grade)) {
671 return get_string('notyetgraded', 'quiz');
673 return format_float($grade, $quiz->decimalpoints);
677 * Determine the correct number of decimal places required to format a grade.
679 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
680 * @return integer
682 function quiz_get_grade_format($quiz) {
683 if (empty($quiz->questiondecimalpoints)) {
684 $quiz->questiondecimalpoints = -1;
687 if ($quiz->questiondecimalpoints == -1) {
688 return $quiz->decimalpoints;
691 return $quiz->questiondecimalpoints;
695 * Round a grade to the correct number of decimal places, and format it for display.
697 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
698 * @param float $grade The grade to round.
699 * @return float
701 function quiz_format_question_grade($quiz, $grade) {
702 return format_float($grade, quiz_get_grade_format($quiz));
706 * Update grades in central gradebook
708 * @category grade
709 * @param object $quiz the quiz settings.
710 * @param int $userid specific user only, 0 means all users.
711 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
713 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
714 global $CFG, $DB;
715 require_once($CFG->libdir . '/gradelib.php');
717 if ($quiz->grade == 0) {
718 quiz_grade_item_update($quiz);
720 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
721 quiz_grade_item_update($quiz, $grades);
723 } else if ($userid && $nullifnone) {
724 $grade = new stdClass();
725 $grade->userid = $userid;
726 $grade->rawgrade = null;
727 quiz_grade_item_update($quiz, $grade);
729 } else {
730 quiz_grade_item_update($quiz);
735 * Create or update the grade item for given quiz
737 * @category grade
738 * @param object $quiz object with extra cmidnumber
739 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
740 * @return int 0 if ok, error code otherwise
742 function quiz_grade_item_update($quiz, $grades = null) {
743 global $CFG, $OUTPUT;
744 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
745 require_once($CFG->libdir . '/gradelib.php');
747 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
748 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
749 } else {
750 $params = array('itemname' => $quiz->name);
753 if ($quiz->grade > 0) {
754 $params['gradetype'] = GRADE_TYPE_VALUE;
755 $params['grademax'] = $quiz->grade;
756 $params['grademin'] = 0;
758 } else {
759 $params['gradetype'] = GRADE_TYPE_NONE;
762 // What this is trying to do:
763 // 1. If the quiz is set to not show grades while the quiz is still open,
764 // and is set to show grades after the quiz is closed, then create the
765 // grade_item with a show-after date that is the quiz close date.
766 // 2. If the quiz is set to not show grades at either of those times,
767 // create the grade_item as hidden.
768 // 3. If the quiz is set to show grades, create the grade_item visible.
769 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
770 mod_quiz_display_options::LATER_WHILE_OPEN);
771 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
772 mod_quiz_display_options::AFTER_CLOSE);
773 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
774 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
775 $params['hidden'] = 1;
777 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
778 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
779 if ($quiz->timeclose) {
780 $params['hidden'] = $quiz->timeclose;
781 } else {
782 $params['hidden'] = 1;
785 } else {
786 // Either
787 // a) both open and closed enabled
788 // b) open enabled, closed disabled - we can not "hide after",
789 // grades are kept visible even after closing.
790 $params['hidden'] = 0;
793 if (!$params['hidden']) {
794 // If the grade item is not hidden by the quiz logic, then we need to
795 // hide it if the quiz is hidden from students.
796 if (property_exists($quiz, 'visible')) {
797 // Saving the quiz form, and cm not yet updated in the database.
798 $params['hidden'] = !$quiz->visible;
799 } else {
800 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
801 $params['hidden'] = !$cm->visible;
805 if ($grades === 'reset') {
806 $params['reset'] = true;
807 $grades = null;
810 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
811 if (!empty($gradebook_grades->items)) {
812 $grade_item = $gradebook_grades->items[0];
813 if ($grade_item->locked) {
814 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
815 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
816 if (!$confirm_regrade) {
817 if (!AJAX_SCRIPT) {
818 $message = get_string('gradeitemislocked', 'grades');
819 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
820 '&amp;mode=overview';
821 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
822 echo $OUTPUT->box_start('generalbox', 'notice');
823 echo '<p>'. $message .'</p>';
824 echo $OUTPUT->container_start('buttons');
825 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
826 echo $OUTPUT->single_button($back_link, get_string('cancel'));
827 echo $OUTPUT->container_end();
828 echo $OUTPUT->box_end();
830 return GRADE_UPDATE_ITEM_LOCKED;
835 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
839 * Delete grade item for given quiz
841 * @category grade
842 * @param object $quiz object
843 * @return object quiz
845 function quiz_grade_item_delete($quiz) {
846 global $CFG;
847 require_once($CFG->libdir . '/gradelib.php');
849 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
850 null, array('deleted' => 1));
854 * This standard function will check all instances of this module
855 * and make sure there are up-to-date events created for each of them.
856 * If courseid = 0, then every quiz event in the site is checked, else
857 * only quiz events belonging to the course specified are checked.
858 * This function is used, in its new format, by restore_refresh_events()
860 * @param int $courseid
861 * @param int|stdClass $instance Quiz module instance or ID.
862 * @param int|stdClass $cm Course module object or ID (not used in this module).
863 * @return bool
865 function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
866 global $DB;
868 // If we have instance information then we can just update the one event instead of updating all events.
869 if (isset($instance)) {
870 if (!is_object($instance)) {
871 $instance = $DB->get_record('quiz', array('id' => $instance), '*', MUST_EXIST);
873 quiz_update_events($instance);
874 return true;
877 if ($courseid == 0) {
878 if (!$quizzes = $DB->get_records('quiz')) {
879 return true;
881 } else {
882 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
883 return true;
887 foreach ($quizzes as $quiz) {
888 quiz_update_events($quiz);
891 return true;
895 * Returns all quiz graded users since a given time for specified quiz
897 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
898 $courseid, $cmid, $userid = 0, $groupid = 0) {
899 global $CFG, $USER, $DB;
900 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
902 $course = get_course($courseid);
903 $modinfo = get_fast_modinfo($course);
905 $cm = $modinfo->cms[$cmid];
906 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
908 if ($userid) {
909 $userselect = "AND u.id = :userid";
910 $params['userid'] = $userid;
911 } else {
912 $userselect = '';
915 if ($groupid) {
916 $groupselect = 'AND gm.groupid = :groupid';
917 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
918 $params['groupid'] = $groupid;
919 } else {
920 $groupselect = '';
921 $groupjoin = '';
924 $params['timestart'] = $timestart;
925 $params['quizid'] = $quiz->id;
927 $ufields = user_picture::fields('u', null, 'useridagain');
928 if (!$attempts = $DB->get_records_sql("
929 SELECT qa.*,
930 {$ufields}
931 FROM {quiz_attempts} qa
932 JOIN {user} u ON u.id = qa.userid
933 $groupjoin
934 WHERE qa.timefinish > :timestart
935 AND qa.quiz = :quizid
936 AND qa.preview = 0
937 $userselect
938 $groupselect
939 ORDER BY qa.timefinish ASC", $params)) {
940 return;
943 $context = context_module::instance($cm->id);
944 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
945 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
946 $grader = has_capability('mod/quiz:viewreports', $context);
947 $groupmode = groups_get_activity_groupmode($cm, $course);
949 $usersgroups = null;
950 $aname = format_string($cm->name, true);
951 foreach ($attempts as $attempt) {
952 if ($attempt->userid != $USER->id) {
953 if (!$grader) {
954 // Grade permission required.
955 continue;
958 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
959 $usersgroups = groups_get_all_groups($course->id,
960 $attempt->userid, $cm->groupingid);
961 $usersgroups = array_keys($usersgroups);
962 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
963 continue;
968 $options = quiz_get_review_options($quiz, $attempt, $context);
970 $tmpactivity = new stdClass();
972 $tmpactivity->type = 'quiz';
973 $tmpactivity->cmid = $cm->id;
974 $tmpactivity->name = $aname;
975 $tmpactivity->sectionnum = $cm->sectionnum;
976 $tmpactivity->timestamp = $attempt->timefinish;
978 $tmpactivity->content = new stdClass();
979 $tmpactivity->content->attemptid = $attempt->id;
980 $tmpactivity->content->attempt = $attempt->attempt;
981 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
982 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
983 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
984 } else {
985 $tmpactivity->content->sumgrades = null;
986 $tmpactivity->content->maxgrade = null;
989 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
990 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
992 $activities[$index++] = $tmpactivity;
996 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
997 global $CFG, $OUTPUT;
999 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
1001 echo '<tr><td class="userpicture" valign="top">';
1002 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
1003 echo '</td><td>';
1005 if ($detail) {
1006 $modname = $modnames[$activity->type];
1007 echo '<div class="title">';
1008 echo $OUTPUT->image_icon('icon', $modname, $activity->type);
1009 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1010 $activity->cmid . '">' . $activity->name . '</a>';
1011 echo '</div>';
1014 echo '<div class="grade">';
1015 echo get_string('attempt', 'quiz', $activity->content->attempt);
1016 if (isset($activity->content->maxgrade)) {
1017 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1018 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1019 $activity->content->attemptid . '">' . $grades . '</a>)';
1021 echo '</div>';
1023 echo '<div class="user">';
1024 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1025 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
1026 '</a> - ' . userdate($activity->timestamp);
1027 echo '</div>';
1029 echo '</td></tr></table>';
1031 return;
1035 * Pre-process the quiz options form data, making any necessary adjustments.
1036 * Called by add/update instance in this file.
1038 * @param object $quiz The variables set on the form.
1040 function quiz_process_options($quiz) {
1041 global $CFG;
1042 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1043 require_once($CFG->libdir . '/questionlib.php');
1045 $quiz->timemodified = time();
1047 // Quiz name.
1048 if (!empty($quiz->name)) {
1049 $quiz->name = trim($quiz->name);
1052 // Password field - different in form to stop browsers that remember passwords
1053 // getting confused.
1054 $quiz->password = $quiz->quizpassword;
1055 unset($quiz->quizpassword);
1057 // Quiz feedback.
1058 if (isset($quiz->feedbacktext)) {
1059 // Clean up the boundary text.
1060 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1061 if (empty($quiz->feedbacktext[$i]['text'])) {
1062 $quiz->feedbacktext[$i]['text'] = '';
1063 } else {
1064 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1068 // Check the boundary value is a number or a percentage, and in range.
1069 $i = 0;
1070 while (!empty($quiz->feedbackboundaries[$i])) {
1071 $boundary = trim($quiz->feedbackboundaries[$i]);
1072 if (!is_numeric($boundary)) {
1073 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1074 $boundary = trim(substr($boundary, 0, -1));
1075 if (is_numeric($boundary)) {
1076 $boundary = $boundary * $quiz->grade / 100.0;
1077 } else {
1078 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1082 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1083 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1085 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1086 return get_string('feedbackerrororder', 'quiz', $i + 1);
1088 $quiz->feedbackboundaries[$i] = $boundary;
1089 $i += 1;
1091 $numboundaries = $i;
1093 // Check there is nothing in the remaining unused fields.
1094 if (!empty($quiz->feedbackboundaries)) {
1095 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1096 if (!empty($quiz->feedbackboundaries[$i]) &&
1097 trim($quiz->feedbackboundaries[$i]) != '') {
1098 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1102 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1103 if (!empty($quiz->feedbacktext[$i]['text']) &&
1104 trim($quiz->feedbacktext[$i]['text']) != '') {
1105 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1108 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1109 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1110 $quiz->feedbackboundaries[$numboundaries] = 0;
1111 $quiz->feedbackboundarycount = $numboundaries;
1112 } else {
1113 $quiz->feedbackboundarycount = -1;
1116 // Combing the individual settings into the review columns.
1117 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1118 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1119 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1120 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1121 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1122 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1123 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1124 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1125 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1129 * Helper function for {@link quiz_process_options()}.
1130 * @param object $fromform the sumbitted form date.
1131 * @param string $field one of the review option field names.
1133 function quiz_review_option_form_to_db($fromform, $field) {
1134 static $times = array(
1135 'during' => mod_quiz_display_options::DURING,
1136 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1137 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1138 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1141 $review = 0;
1142 foreach ($times as $whenname => $when) {
1143 $fieldname = $field . $whenname;
1144 if (isset($fromform->$fieldname)) {
1145 $review |= $when;
1146 unset($fromform->$fieldname);
1150 return $review;
1154 * This function is called at the end of quiz_add_instance
1155 * and quiz_update_instance, to do the common processing.
1157 * @param object $quiz the quiz object.
1159 function quiz_after_add_or_update($quiz) {
1160 global $DB;
1161 $cmid = $quiz->coursemodule;
1163 // We need to use context now, so we need to make sure all needed info is already in db.
1164 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1165 $context = context_module::instance($cmid);
1167 // Save the feedback.
1168 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1170 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1171 $feedback = new stdClass();
1172 $feedback->quizid = $quiz->id;
1173 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1174 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1175 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1176 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1177 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1178 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1179 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1180 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1181 $quiz->feedbacktext[$i]['text']);
1182 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1183 array('id' => $feedback->id));
1186 // Store any settings belonging to the access rules.
1187 quiz_access_manager::save_settings($quiz);
1189 // Update the events relating to this quiz.
1190 quiz_update_events($quiz);
1191 $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null;
1192 \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected);
1194 // Update related grade item.
1195 quiz_grade_item_update($quiz);
1199 * This function updates the events associated to the quiz.
1200 * If $override is non-zero, then it updates only the events
1201 * associated with the specified override.
1203 * @uses QUIZ_MAX_EVENT_LENGTH
1204 * @param object $quiz the quiz object.
1205 * @param object optional $override limit to a specific override
1207 function quiz_update_events($quiz, $override = null) {
1208 global $DB;
1210 // Load the old events relating to this quiz.
1211 $conds = array('modulename'=>'quiz',
1212 'instance'=>$quiz->id);
1213 if (!empty($override)) {
1214 // Only load events for this override.
1215 if (isset($override->userid)) {
1216 $conds['userid'] = $override->userid;
1217 } else {
1218 $conds['groupid'] = $override->groupid;
1221 $oldevents = $DB->get_records('event', $conds, 'id ASC');
1223 // Now make a to-do list of all that needs to be updated.
1224 if (empty($override)) {
1225 // We are updating the primary settings for the quiz, so we need to add all the overrides.
1226 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id ASC');
1227 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1228 // list contains the original (non-override) event for the module. If this is not included
1229 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1230 // list against the $oldevents list.
1231 array_unshift($overrides, new stdClass());
1232 } else {
1233 // Just do the one override.
1234 $overrides = array($override);
1237 // Get group override priorities.
1238 $grouppriorities = quiz_get_group_override_priorities($quiz->id);
1240 foreach ($overrides as $current) {
1241 $groupid = isset($current->groupid)? $current->groupid : 0;
1242 $userid = isset($current->userid)? $current->userid : 0;
1243 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1244 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1246 // Only add open/close events for an override if they differ from the quiz default.
1247 $addopen = empty($current->id) || !empty($current->timeopen);
1248 $addclose = empty($current->id) || !empty($current->timeclose);
1250 if (!empty($quiz->coursemodule)) {
1251 $cmid = $quiz->coursemodule;
1252 } else {
1253 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1256 $event = new stdClass();
1257 $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
1258 $event->description = format_module_intro('quiz', $quiz, $cmid);
1259 // Events module won't show user events when the courseid is nonzero.
1260 $event->courseid = ($userid) ? 0 : $quiz->course;
1261 $event->groupid = $groupid;
1262 $event->userid = $userid;
1263 $event->modulename = 'quiz';
1264 $event->instance = $quiz->id;
1265 $event->timestart = $timeopen;
1266 $event->timeduration = max($timeclose - $timeopen, 0);
1267 $event->timesort = $timeopen;
1268 $event->visible = instance_is_visible('quiz', $quiz);
1269 $event->eventtype = QUIZ_EVENT_TYPE_OPEN;
1270 $event->priority = null;
1272 // Determine the event name and priority.
1273 if ($groupid) {
1274 // Group override event.
1275 $params = new stdClass();
1276 $params->quiz = $quiz->name;
1277 $params->group = groups_get_group_name($groupid);
1278 if ($params->group === false) {
1279 // Group doesn't exist, just skip it.
1280 continue;
1282 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1283 // Set group override priority.
1284 if ($grouppriorities !== null) {
1285 $openpriorities = $grouppriorities['open'];
1286 if (isset($openpriorities[$timeopen])) {
1287 $event->priority = $openpriorities[$timeopen];
1290 } else if ($userid) {
1291 // User override event.
1292 $params = new stdClass();
1293 $params->quiz = $quiz->name;
1294 $eventname = get_string('overrideusereventname', 'quiz', $params);
1295 // Set user override priority.
1296 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
1297 } else {
1298 // The parent event.
1299 $eventname = $quiz->name;
1302 if ($addopen or $addclose) {
1303 // Separate start and end events.
1304 $event->timeduration = 0;
1305 if ($timeopen && $addopen) {
1306 if ($oldevent = array_shift($oldevents)) {
1307 $event->id = $oldevent->id;
1308 } else {
1309 unset($event->id);
1311 $event->name = get_string('quizeventopens', 'quiz', $eventname);
1312 // The method calendar_event::create will reuse a db record if the id field is set.
1313 calendar_event::create($event);
1315 if ($timeclose && $addclose) {
1316 if ($oldevent = array_shift($oldevents)) {
1317 $event->id = $oldevent->id;
1318 } else {
1319 unset($event->id);
1321 $event->type = CALENDAR_EVENT_TYPE_ACTION;
1322 $event->name = get_string('quizeventcloses', 'quiz', $eventname);
1323 $event->timestart = $timeclose;
1324 $event->timesort = $timeclose;
1325 $event->eventtype = QUIZ_EVENT_TYPE_CLOSE;
1326 if ($groupid && $grouppriorities !== null) {
1327 $closepriorities = $grouppriorities['close'];
1328 if (isset($closepriorities[$timeclose])) {
1329 $event->priority = $closepriorities[$timeclose];
1332 calendar_event::create($event);
1337 // Delete any leftover events.
1338 foreach ($oldevents as $badevent) {
1339 $badevent = calendar_event::load($badevent);
1340 $badevent->delete();
1345 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1347 * @param int $quizid The quiz ID.
1348 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1350 function quiz_get_group_override_priorities($quizid) {
1351 global $DB;
1353 // Fetch group overrides.
1354 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1355 $params = ['quiz' => $quizid];
1356 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1357 if (!$overrides) {
1358 return null;
1361 $grouptimeopen = [];
1362 $grouptimeclose = [];
1363 foreach ($overrides as $override) {
1364 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1365 $grouptimeopen[] = $override->timeopen;
1367 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1368 $grouptimeclose[] = $override->timeclose;
1372 // Sort open times in ascending manner. The earlier open time gets higher priority.
1373 sort($grouptimeopen);
1374 // Set priorities.
1375 $opengrouppriorities = [];
1376 $openpriority = 1;
1377 foreach ($grouptimeopen as $timeopen) {
1378 $opengrouppriorities[$timeopen] = $openpriority++;
1381 // Sort close times in descending manner. The later close time gets higher priority.
1382 rsort($grouptimeclose);
1383 // Set priorities.
1384 $closegrouppriorities = [];
1385 $closepriority = 1;
1386 foreach ($grouptimeclose as $timeclose) {
1387 $closegrouppriorities[$timeclose] = $closepriority++;
1390 return [
1391 'open' => $opengrouppriorities,
1392 'close' => $closegrouppriorities
1397 * List the actions that correspond to a view of this module.
1398 * This is used by the participation report.
1400 * Note: This is not used by new logging system. Event with
1401 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1402 * be considered as view action.
1404 * @return array
1406 function quiz_get_view_actions() {
1407 return array('view', 'view all', 'report', 'review');
1411 * List the actions that correspond to a post of this module.
1412 * This is used by the participation report.
1414 * Note: This is not used by new logging system. Event with
1415 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1416 * will be considered as post action.
1418 * @return array
1420 function quiz_get_post_actions() {
1421 return array('attempt', 'close attempt', 'preview', 'editquestions',
1422 'delete attempt', 'manualgrade');
1426 * @param array $questionids of question ids.
1427 * @return bool whether any of these questions are used by any instance of this module.
1429 function quiz_questions_in_use($questionids) {
1430 global $DB, $CFG;
1431 require_once($CFG->libdir . '/questionlib.php');
1432 list($test, $params) = $DB->get_in_or_equal($questionids);
1433 return $DB->record_exists_select('quiz_slots',
1434 'questionid ' . $test, $params) || question_engine::questions_in_use(
1435 $questionids, new qubaid_join('{quiz_attempts} quiza',
1436 'quiza.uniqueid', 'quiza.preview = 0'));
1440 * Implementation of the function for printing the form elements that control
1441 * whether the course reset functionality affects the quiz.
1443 * @param $mform the course reset form that is being built.
1445 function quiz_reset_course_form_definition($mform) {
1446 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1447 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1448 get_string('removeallquizattempts', 'quiz'));
1449 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1450 get_string('removealluseroverrides', 'quiz'));
1451 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1452 get_string('removeallgroupoverrides', 'quiz'));
1456 * Course reset form defaults.
1457 * @return array the defaults.
1459 function quiz_reset_course_form_defaults($course) {
1460 return array('reset_quiz_attempts' => 1,
1461 'reset_quiz_group_overrides' => 1,
1462 'reset_quiz_user_overrides' => 1);
1466 * Removes all grades from gradebook
1468 * @param int $courseid
1469 * @param string optional type
1471 function quiz_reset_gradebook($courseid, $type='') {
1472 global $CFG, $DB;
1474 $quizzes = $DB->get_records_sql("
1475 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1476 FROM {modules} m
1477 JOIN {course_modules} cm ON m.id = cm.module
1478 JOIN {quiz} q ON cm.instance = q.id
1479 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1481 foreach ($quizzes as $quiz) {
1482 quiz_grade_item_update($quiz, 'reset');
1487 * Actual implementation of the reset course functionality, delete all the
1488 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1489 * set and true.
1491 * Also, move the quiz open and close dates, if the course start date is changing.
1493 * @param object $data the data submitted from the reset course.
1494 * @return array status array
1496 function quiz_reset_userdata($data) {
1497 global $CFG, $DB;
1498 require_once($CFG->libdir . '/questionlib.php');
1500 $componentstr = get_string('modulenameplural', 'quiz');
1501 $status = array();
1503 // Delete attempts.
1504 if (!empty($data->reset_quiz_attempts)) {
1505 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1506 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1507 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1508 array('quizcourseid' => $data->courseid)));
1510 $DB->delete_records_select('quiz_attempts',
1511 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1512 $status[] = array(
1513 'component' => $componentstr,
1514 'item' => get_string('attemptsdeleted', 'quiz'),
1515 'error' => false);
1517 // Remove all grades from gradebook.
1518 $DB->delete_records_select('quiz_grades',
1519 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1520 if (empty($data->reset_gradebook_grades)) {
1521 quiz_reset_gradebook($data->courseid);
1523 $status[] = array(
1524 'component' => $componentstr,
1525 'item' => get_string('gradesdeleted', 'quiz'),
1526 'error' => false);
1529 // Remove user overrides.
1530 if (!empty($data->reset_quiz_user_overrides)) {
1531 $DB->delete_records_select('quiz_overrides',
1532 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1533 $status[] = array(
1534 'component' => $componentstr,
1535 'item' => get_string('useroverridesdeleted', 'quiz'),
1536 'error' => false);
1538 // Remove group overrides.
1539 if (!empty($data->reset_quiz_group_overrides)) {
1540 $DB->delete_records_select('quiz_overrides',
1541 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1542 $status[] = array(
1543 'component' => $componentstr,
1544 'item' => get_string('groupoverridesdeleted', 'quiz'),
1545 'error' => false);
1548 // Updating dates - shift may be negative too.
1549 if ($data->timeshift) {
1550 $DB->execute("UPDATE {quiz_overrides}
1551 SET timeopen = timeopen + ?
1552 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1553 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1554 $DB->execute("UPDATE {quiz_overrides}
1555 SET timeclose = timeclose + ?
1556 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1557 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1559 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1560 // See MDL-9367.
1561 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1562 $data->timeshift, $data->courseid);
1564 $status[] = array(
1565 'component' => $componentstr,
1566 'item' => get_string('openclosedatesupdated', 'quiz'),
1567 'error' => false);
1570 return $status;
1574 * Prints quiz summaries on MyMoodle Page
1576 * @deprecated since 3.3
1577 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1578 * @param array $courses
1579 * @param array $htmlarray
1581 function quiz_print_overview($courses, &$htmlarray) {
1582 global $USER, $CFG;
1584 debugging('The function quiz_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1586 // These next 6 Lines are constant in all modules (just change module name).
1587 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1588 return array();
1591 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1592 return;
1595 // Get the quizzes attempts.
1596 $attemptsinfo = [];
1597 $quizids = [];
1598 foreach ($quizzes as $quiz) {
1599 $quizids[] = $quiz->id;
1600 $attemptsinfo[$quiz->id] = ['count' => 0, 'hasfinished' => false];
1602 $attempts = quiz_get_user_attempts($quizids, $USER->id);
1603 foreach ($attempts as $attempt) {
1604 $attemptsinfo[$attempt->quiz]['count']++;
1605 $attemptsinfo[$attempt->quiz]['hasfinished'] = true;
1607 unset($attempts);
1609 // Fetch some language strings outside the main loop.
1610 $strquiz = get_string('modulename', 'quiz');
1611 $strnoattempts = get_string('noattempts', 'quiz');
1613 // We want to list quizzes that are currently available, and which have a close date.
1614 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1615 $now = time();
1616 foreach ($quizzes as $quiz) {
1617 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1618 $str = '';
1620 // Now provide more information depending on the uers's role.
1621 $context = context_module::instance($quiz->coursemodule);
1622 if (has_capability('mod/quiz:viewreports', $context)) {
1623 // For teacher-like people, show a summary of the number of student attempts.
1624 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1625 // fields set to make the following call work.
1626 $str .= '<div class="info">' . quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1628 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $context)) { // Student
1629 // For student-like people, tell them how many attempts they have made.
1631 if (isset($USER->id)) {
1632 if ($attemptsinfo[$quiz->id]['hasfinished']) {
1633 // The student's last attempt is finished.
1634 continue;
1637 if ($attemptsinfo[$quiz->id]['count'] > 0) {
1638 $str .= '<div class="info">' .
1639 get_string('numattemptsmade', 'quiz', $attemptsinfo[$quiz->id]['count']) . '</div>';
1640 } else {
1641 $str .= '<div class="info">' . $strnoattempts . '</div>';
1644 } else {
1645 $str .= '<div class="info">' . $strnoattempts . '</div>';
1648 } else {
1649 // For ayone else, there is no point listing this quiz, so stop processing.
1650 continue;
1653 // Give a link to the quiz, and the deadline.
1654 $html = '<div class="quiz overview">' .
1655 '<div class="name">' . $strquiz . ': <a ' .
1656 ($quiz->visible ? '' : ' class="dimmed"') .
1657 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1658 $quiz->coursemodule . '">' .
1659 $quiz->name . '</a></div>';
1660 $html .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1661 userdate($quiz->timeclose)) . '</div>';
1662 $html .= $str;
1663 $html .= '</div>';
1664 if (empty($htmlarray[$quiz->course]['quiz'])) {
1665 $htmlarray[$quiz->course]['quiz'] = $html;
1666 } else {
1667 $htmlarray[$quiz->course]['quiz'] .= $html;
1674 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1675 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1677 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1678 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1679 * $cm->groupingid fields are used at the moment.
1680 * @param bool $returnzero if false (default), when no attempts have been
1681 * made '' is returned instead of 'Attempts: 0'.
1682 * @param int $currentgroup if there is a concept of current group where this method is being called
1683 * (e.g. a report) pass it in here. Default 0 which means no current group.
1684 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1685 * "Attemtps 123 (45 from this group)".
1687 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1688 global $DB, $USER;
1689 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1690 if ($numattempts || $returnzero) {
1691 if (groups_get_activity_groupmode($cm)) {
1692 $a = new stdClass();
1693 $a->total = $numattempts;
1694 if ($currentgroup) {
1695 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1696 '{quiz_attempts} qa JOIN ' .
1697 '{groups_members} gm ON qa.userid = gm.userid ' .
1698 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1699 array($quiz->id, $currentgroup));
1700 return get_string('attemptsnumthisgroup', 'quiz', $a);
1701 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1702 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1703 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1704 '{quiz_attempts} qa JOIN ' .
1705 '{groups_members} gm ON qa.userid = gm.userid ' .
1706 'WHERE quiz = ? AND preview = 0 AND ' .
1707 "groupid $usql", array_merge(array($quiz->id), $params));
1708 return get_string('attemptsnumyourgroups', 'quiz', $a);
1711 return get_string('attemptsnum', 'quiz', $numattempts);
1713 return '';
1717 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1718 * to the quiz reports.
1720 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1721 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1722 * $cm->groupingid fields are used at the moment.
1723 * @param object $context the quiz context.
1724 * @param bool $returnzero if false (default), when no attempts have been made
1725 * '' is returned instead of 'Attempts: 0'.
1726 * @param int $currentgroup if there is a concept of current group where this method is being called
1727 * (e.g. a report) pass it in here. Default 0 which means no current group.
1728 * @return string HTML fragment for the link.
1730 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1731 $currentgroup = 0) {
1732 global $CFG;
1733 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1734 if (!$summary) {
1735 return '';
1738 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1739 $url = new moodle_url('/mod/quiz/report.php', array(
1740 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1741 return html_writer::link($url, $summary);
1745 * @param string $feature FEATURE_xx constant for requested feature
1746 * @return bool True if quiz supports feature
1748 function quiz_supports($feature) {
1749 switch($feature) {
1750 case FEATURE_GROUPS: return true;
1751 case FEATURE_GROUPINGS: return true;
1752 case FEATURE_MOD_INTRO: return true;
1753 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1754 case FEATURE_COMPLETION_HAS_RULES: return true;
1755 case FEATURE_GRADE_HAS_GRADE: return true;
1756 case FEATURE_GRADE_OUTCOMES: return true;
1757 case FEATURE_BACKUP_MOODLE2: return true;
1758 case FEATURE_SHOW_DESCRIPTION: return true;
1759 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1760 case FEATURE_USES_QUESTIONS: return true;
1762 default: return null;
1767 * @return array all other caps used in module
1769 function quiz_get_extra_capabilities() {
1770 global $CFG;
1771 require_once($CFG->libdir . '/questionlib.php');
1772 $caps = question_get_all_capabilities();
1773 $caps[] = 'moodle/site:accessallgroups';
1774 return $caps;
1778 * This function extends the settings navigation block for the site.
1780 * It is safe to rely on PAGE here as we will only ever be within the module
1781 * context when this is called
1783 * @param settings_navigation $settings
1784 * @param navigation_node $quiznode
1785 * @return void
1787 function quiz_extend_settings_navigation($settings, $quiznode) {
1788 global $PAGE, $CFG;
1790 // Require {@link questionlib.php}
1791 // Included here as we only ever want to include this file if we really need to.
1792 require_once($CFG->libdir . '/questionlib.php');
1794 // We want to add these new nodes after the Edit settings node, and before the
1795 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1796 $keys = $quiznode->get_children_key_list();
1797 $beforekey = null;
1798 $i = array_search('modedit', $keys);
1799 if ($i === false and array_key_exists(0, $keys)) {
1800 $beforekey = $keys[0];
1801 } else if (array_key_exists($i + 1, $keys)) {
1802 $beforekey = $keys[$i + 1];
1805 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1806 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1807 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1808 new moodle_url($url, array('mode'=>'group')),
1809 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1810 $quiznode->add_node($node, $beforekey);
1812 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1813 new moodle_url($url, array('mode'=>'user')),
1814 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1815 $quiznode->add_node($node, $beforekey);
1818 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1819 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1820 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1821 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1822 new pix_icon('t/edit', ''));
1823 $quiznode->add_node($node, $beforekey);
1826 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1827 $url = new moodle_url('/mod/quiz/startattempt.php',
1828 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1829 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1830 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1831 new pix_icon('i/preview', ''));
1832 $quiznode->add_node($node, $beforekey);
1835 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1836 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1837 $reportlist = quiz_report_list($PAGE->cm->context);
1839 $url = new moodle_url('/mod/quiz/report.php',
1840 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1841 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1842 navigation_node::TYPE_SETTING,
1843 null, null, new pix_icon('i/report', '')), $beforekey);
1845 foreach ($reportlist as $report) {
1846 $url = new moodle_url('/mod/quiz/report.php',
1847 array('id' => $PAGE->cm->id, 'mode' => $report));
1848 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1849 navigation_node::TYPE_SETTING,
1850 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1854 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1858 * Serves the quiz files.
1860 * @package mod_quiz
1861 * @category files
1862 * @param stdClass $course course object
1863 * @param stdClass $cm course module object
1864 * @param stdClass $context context object
1865 * @param string $filearea file area
1866 * @param array $args extra arguments
1867 * @param bool $forcedownload whether or not force download
1868 * @param array $options additional options affecting the file serving
1869 * @return bool false if file not found, does not return if found - justsend the file
1871 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1872 global $CFG, $DB;
1874 if ($context->contextlevel != CONTEXT_MODULE) {
1875 return false;
1878 require_login($course, false, $cm);
1880 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1881 return false;
1884 // The 'intro' area is served by pluginfile.php.
1885 $fileareas = array('feedback');
1886 if (!in_array($filearea, $fileareas)) {
1887 return false;
1890 $feedbackid = (int)array_shift($args);
1891 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1892 return false;
1895 $fs = get_file_storage();
1896 $relativepath = implode('/', $args);
1897 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1898 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1899 return false;
1901 send_stored_file($file, 0, 0, true, $options);
1905 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1906 * a question in a question_attempt when that attempt is a quiz attempt.
1908 * @package mod_quiz
1909 * @category files
1910 * @param stdClass $course course settings object
1911 * @param stdClass $context context object
1912 * @param string $component the name of the component we are serving files for.
1913 * @param string $filearea the name of the file area.
1914 * @param int $qubaid the attempt usage id.
1915 * @param int $slot the id of a question in this quiz attempt.
1916 * @param array $args the remaining bits of the file path.
1917 * @param bool $forcedownload whether the user must be forced to download the file.
1918 * @param array $options additional options affecting the file serving
1919 * @return bool false if file not found, does not return if found - justsend the file
1921 function quiz_question_pluginfile($course, $context, $component,
1922 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
1923 global $CFG;
1924 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1926 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1927 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1929 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1930 // In the middle of an attempt.
1931 if (!$attemptobj->is_preview_user()) {
1932 $attemptobj->require_capability('mod/quiz:attempt');
1934 $isreviewing = false;
1936 } else {
1937 // Reviewing an attempt.
1938 $attemptobj->check_review_capability();
1939 $isreviewing = true;
1942 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1943 $component, $filearea, $args, $forcedownload)) {
1944 send_file_not_found();
1947 $fs = get_file_storage();
1948 $relativepath = implode('/', $args);
1949 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1950 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1951 send_file_not_found();
1954 send_stored_file($file, 0, 0, $forcedownload, $options);
1958 * Return a list of page types
1959 * @param string $pagetype current page type
1960 * @param stdClass $parentcontext Block's parent context
1961 * @param stdClass $currentcontext Current context of block
1963 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1964 $module_pagetype = array(
1965 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1966 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1967 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1968 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1969 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1970 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1971 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1973 return $module_pagetype;
1977 * @return the options for quiz navigation.
1979 function quiz_get_navigation_options() {
1980 return array(
1981 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1982 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1987 * Obtains the automatic completion state for this quiz on any conditions
1988 * in quiz settings, such as if all attempts are used or a certain grade is achieved.
1990 * @param object $course Course
1991 * @param object $cm Course-module
1992 * @param int $userid User ID
1993 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1994 * @return bool True if completed, false if not. (If no conditions, then return
1995 * value depends on comparison type)
1997 function quiz_get_completion_state($course, $cm, $userid, $type) {
1998 global $DB;
1999 global $CFG;
2001 $quiz = $DB->get_record('quiz', array('id' => $cm->instance), '*', MUST_EXIST);
2002 if (!$quiz->completionattemptsexhausted && !$quiz->completionpass) {
2003 return $type;
2006 // Check if the user has used up all attempts.
2007 if ($quiz->completionattemptsexhausted) {
2008 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
2009 if ($attempts) {
2010 $lastfinishedattempt = end($attempts);
2011 $context = context_module::instance($cm->id);
2012 $quizobj = quiz::create($quiz->id, $userid);
2013 $accessmanager = new quiz_access_manager($quizobj, time(),
2014 has_capability('mod/quiz:ignoretimelimits', $context, $userid, false));
2015 if ($accessmanager->is_finished(count($attempts), $lastfinishedattempt)) {
2016 return true;
2021 // Check for passing grade.
2022 if ($quiz->completionpass) {
2023 require_once($CFG->libdir . '/gradelib.php');
2024 $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
2025 'itemmodule' => 'quiz', 'iteminstance' => $cm->instance, 'outcomeid' => null));
2026 if ($item) {
2027 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
2028 if (!empty($grades[$userid])) {
2029 return $grades[$userid]->is_passed($item);
2033 return false;
2037 * Check if the module has any update that affects the current user since a given time.
2039 * @param cm_info $cm course module data
2040 * @param int $from the time to check updates from
2041 * @param array $filter if we need to check only specific updates
2042 * @return stdClass an object with the different type of areas indicating if they were updated or not
2043 * @since Moodle 3.2
2045 function quiz_check_updates_since(cm_info $cm, $from, $filter = array()) {
2046 global $DB, $USER, $CFG;
2047 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2049 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2051 // Check if questions were updated.
2052 $updates->questions = (object) array('updated' => false);
2053 $quizobj = quiz::create($cm->instance, $USER->id);
2054 $quizobj->preload_questions();
2055 $quizobj->load_questions();
2056 $questionids = array_keys($quizobj->get_questions());
2057 if (!empty($questionids)) {
2058 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
2059 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
2060 $params['time1'] = $from;
2061 $params['time2'] = $from;
2062 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
2063 if (!empty($questions)) {
2064 $updates->questions->updated = true;
2065 $updates->questions->itemids = array_keys($questions);
2069 // Check for new attempts or grades.
2070 $updates->attempts = (object) array('updated' => false);
2071 $updates->grades = (object) array('updated' => false);
2072 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
2073 $params = array($cm->instance, $USER->id, $from);
2075 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2076 if (!empty($attempts)) {
2077 $updates->attempts->updated = true;
2078 $updates->attempts->itemids = array_keys($attempts);
2080 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2081 if (!empty($grades)) {
2082 $updates->grades->updated = true;
2083 $updates->grades->itemids = array_keys($grades);
2086 // Now, teachers should see other students updates.
2087 if (has_capability('mod/quiz:viewreports', $cm->context)) {
2088 $select = 'quiz = ? AND timemodified > ?';
2089 $params = array($cm->instance, $from);
2091 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
2092 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
2093 if (empty($groupusers)) {
2094 return $updates;
2096 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
2097 $select .= ' AND userid ' . $insql;
2098 $params = array_merge($params, $inparams);
2101 $updates->userattempts = (object) array('updated' => false);
2102 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2103 if (!empty($attempts)) {
2104 $updates->userattempts->updated = true;
2105 $updates->userattempts->itemids = array_keys($attempts);
2108 $updates->usergrades = (object) array('updated' => false);
2109 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2110 if (!empty($grades)) {
2111 $updates->usergrades->updated = true;
2112 $updates->usergrades->itemids = array_keys($grades);
2115 return $updates;
2119 * Get icon mapping for font-awesome.
2121 function mod_quiz_get_fontawesome_icon_map() {
2122 return [
2123 'mod_quiz:navflagged' => 'fa-flag',
2128 * This function receives a calendar event and returns the action associated with it, or null if there is none.
2130 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
2131 * is not displayed on the block.
2133 * @param calendar_event $event
2134 * @param \core_calendar\action_factory $factory
2135 * @return \core_calendar\local\event\entities\action_interface|null
2137 function mod_quiz_core_calendar_provide_event_action(calendar_event $event,
2138 \core_calendar\action_factory $factory) {
2139 global $CFG, $USER;
2141 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2143 $cm = get_fast_modinfo($event->courseid)->instances['quiz'][$event->instance];
2144 $quizobj = quiz::create($cm->instance, $USER->id);
2145 $quiz = $quizobj->get_quiz();
2147 // Check they have capabilities allowing them to view the quiz.
2148 if (!has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $quizobj->get_context())) {
2149 return null;
2152 quiz_update_effective_access($quiz, $USER->id);
2154 // Check if quiz is closed, if so don't display it.
2155 if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) {
2156 return null;
2159 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id);
2160 if (!empty($attempts)) {
2161 // The student's last attempt is finished.
2162 return null;
2165 $name = get_string('attemptquiznow', 'quiz');
2166 $url = new \moodle_url('/mod/quiz/view.php', [
2167 'id' => $cm->id
2169 $itemcount = 1;
2170 $actionable = true;
2172 // Check if the quiz is not currently actionable.
2173 if (!empty($quiz->timeopen) && $quiz->timeopen > time()) {
2174 $actionable = false;
2177 return $factory->create_instance(
2178 $name,
2179 $url,
2180 $itemcount,
2181 $actionable
2186 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2187 * for the course (see resource).
2189 * Given a course_module object, this function returns any "extra" information that may be needed
2190 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2192 * @param stdClass $coursemodule The coursemodule object (record).
2193 * @return cached_cm_info An object on information that the courses
2194 * will know about (most noticeably, an icon).
2196 function quiz_get_coursemodule_info($coursemodule) {
2197 global $DB;
2199 $dbparams = ['id' => $coursemodule->instance];
2200 $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionpass';
2201 if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2202 return false;
2205 $result = new cached_cm_info();
2206 $result->name = $quiz->name;
2208 if ($coursemodule->showdescription) {
2209 // Convert intro to html. Do not filter cached version, filters run at display time.
2210 $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false);
2213 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2214 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
2215 $result->customdata['customcompletionrules']['completionattemptsexhausted'] = $quiz->completionattemptsexhausted;
2216 $result->customdata['customcompletionrules']['completionpass'] = $quiz->completionpass;
2219 return $result;
2223 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2225 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
2226 * @return array $descriptions the array of descriptions for the custom rules.
2228 function mod_quiz_get_completion_active_rule_descriptions($cm) {
2229 // Values will be present in cm_info, and we assume these are up to date.
2230 if (empty($cm->customdata['customcompletionrules'])
2231 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
2232 return [];
2235 $descriptions = [];
2236 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
2237 switch ($key) {
2238 case 'completionattemptsexhausted':
2239 if (empty($val)) {
2240 continue;
2242 $descriptions[] = get_string('completionattemptsexhausteddesc', 'quiz');
2243 break;
2244 case 'completionpass':
2245 if (empty($val)) {
2246 continue;
2248 $descriptions[] = get_string('completionpassdesc', 'quiz', format_time($val));
2249 break;
2250 default:
2251 break;
2254 return $descriptions;
2258 * Returns the min and max values for the timestart property of a quiz
2259 * activity event.
2261 * The min and max values will be the timeopen and timeclose properties
2262 * of the quiz, respectively, if they are set.
2264 * If either value isn't set then null will be returned instead to
2265 * indicate that there is no cutoff for that value.
2267 * A minimum and maximum cutoff return value will look like:
2269 * [1505704373, 'The date must be after this date'],
2270 * [1506741172, 'The date must be before this date']
2273 * @param \calendar_event $event The calendar event to get the time range for
2274 * @param stdClass|null $quiz The module instance to get the range from
2275 * @return array
2277 function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz = null) {
2278 global $CFG, $DB;
2279 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2281 // No restrictions on override events.
2282 if (quiz_is_overriden_calendar_event($event)) {
2283 return [null, null];
2286 if (!$quiz) {
2287 $quiz = $DB->get_record('quiz', ['id' => $event->instance]);
2290 $mindate = null;
2291 $maxdate = null;
2293 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2294 if (!empty($quiz->timeclose)) {
2295 $maxdate = [
2296 $quiz->timeclose,
2297 get_string('openafterclose', 'quiz')
2300 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2301 if (!empty($quiz->timeopen)) {
2302 $mindate = [
2303 $quiz->timeopen,
2304 get_string('closebeforeopen', 'quiz')
2309 return [$mindate, $maxdate];
2313 * This function will check that the given event is valid for it's
2314 * corresponding quiz module.
2316 * An exception is thrown if the event fails validation.
2318 * @throws \moodle_exception
2319 * @param \calendar_event $event
2320 * @return bool
2322 function mod_quiz_core_calendar_validate_event_timestart(\calendar_event $event) {
2323 global $DB;
2325 if (!isset($event->instance)) {
2326 return;
2329 // Something weird going on. The event is for a different module so
2330 // we should ignore it.
2331 if ($event->modulename != 'quiz') {
2332 return;
2335 // We need to read from the DB directly because course module may
2336 // currently be getting created so it won't be in mod info yet.
2337 $quiz = $DB->get_record('quiz', ['id' => $event->instance], '*', MUST_EXIST);
2338 $timestart = $event->timestart;
2339 list($min, $max) = mod_quiz_core_calendar_get_valid_event_timestart_range($event, $quiz);
2341 if ($min && $timestart < $min[0]) {
2342 throw new \moodle_exception($min[1]);
2345 if ($max && $timestart > $max[0]) {
2346 throw new \moodle_exception($max[1]);
2351 * This function will update the quiz module according to the
2352 * event that has been modified.
2354 * It will set the timeopen or timeclose value of the quiz instance
2355 * according to the type of event provided.
2357 * @throws \moodle_exception
2358 * @param \calendar_event $event
2360 function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event) {
2361 global $CFG, $DB;
2362 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2364 // We don't update the activity if it's an override event that has
2365 // been modified.
2366 if (quiz_is_overriden_calendar_event($event)) {
2367 return;
2370 $courseid = $event->courseid;
2371 $modulename = $event->modulename;
2372 $instanceid = $event->instance;
2373 $modified = false;
2374 $closedatechanged = false;
2376 // Something weird going on. The event is for a different module so
2377 // we should ignore it.
2378 if ($modulename != 'quiz') {
2379 return;
2382 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2383 $context = context_module::instance($coursemodule->id);
2385 // The user does not have the capability to modify this activity.
2386 if (!has_capability('moodle/course:manageactivities', $context)) {
2387 return;
2390 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2391 // If the event is for the quiz activity opening then we should
2392 // set the start time of the quiz activity to be the new start
2393 // time of the event.
2394 $quiz = $DB->get_record('quiz', ['id' => $instanceid], '*', MUST_EXIST);
2396 if ($quiz->timeopen != $event->timestart) {
2397 $quiz->timeopen = $event->timestart;
2398 $modified = true;
2400 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2401 // If the event is for the quiz activity closing then we should
2402 // set the end time of the quiz activity to be the new start
2403 // time of the event.
2404 $quiz = $DB->get_record('quiz', ['id' => $instanceid], '*', MUST_EXIST);
2406 if ($quiz->timeclose != $event->timestart) {
2407 $quiz->timeclose = $event->timestart;
2408 $modified = true;
2409 $closedatechanged = true;
2413 if ($modified) {
2414 $quiz->timemodified = time();
2415 $DB->update_record('quiz', $quiz);
2417 if ($closedatechanged) {
2418 quiz_update_open_attempts(array('quizid' => $quiz->id));
2421 // Delete any previous preview attempts.
2422 quiz_delete_previews($quiz);
2423 quiz_update_events($quiz);
2424 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2425 $event->trigger();