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 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir . '/eventslib.php');
32 require_once($CFG->dirroot . '/calendar/lib.php');
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);
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');
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.
61 * Options for navigation method within quizzes.
63 define('QUIZ_NAVMETHOD_FREE', 'free');
64 define('QUIZ_NAVMETHOD_SEQ', 'sequential');
68 * Given an object containing all the necessary data,
69 * (defined by the form in mod_form.php) this function
70 * will create a new instance and return the id number
71 * of the new instance.
73 * @param object $quiz the data that came from the form.
74 * @return mixed the id of the new instance on success,
75 * false or a string error message on failure.
77 function quiz_add_instance($quiz) {
79 $cmid = $quiz->coursemodule;
81 // Process the options from the form.
82 $quiz->created = time();
83 $result = quiz_process_options($quiz);
84 if ($result && is_string($result)) {
88 // Try to store it in the database.
89 $quiz->id = $DB->insert_record('quiz', $quiz);
91 // Create the first section for this quiz.
92 $DB->insert_record('quiz_sections', array('quizid' => $quiz->id,
93 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0));
95 // Do the processing required after an add or an update.
96 quiz_after_add_or_update($quiz);
102 * Given an object containing all the necessary data,
103 * (defined by the form in mod_form.php) this function
104 * will update an existing instance with new data.
106 * @param object $quiz the data that came from the form.
107 * @return mixed true on success, false or a string error message on failure.
109 function quiz_update_instance($quiz, $mform) {
111 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
113 // Process the options from the form.
114 $result = quiz_process_options($quiz);
115 if ($result && is_string($result)) {
119 // Get the current value, so we can see what changed.
120 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
122 // We need two values from the existing DB record that are not in the form,
123 // in some of the function calls below.
124 $quiz->sumgrades = $oldquiz->sumgrades;
125 $quiz->grade = $oldquiz->grade;
127 // Update the database.
128 $quiz->id = $quiz->instance;
129 $DB->update_record('quiz', $quiz);
131 // Do the processing required after an add or an update.
132 quiz_after_add_or_update($quiz);
134 if ($oldquiz->grademethod != $quiz->grademethod) {
135 quiz_update_all_final_grades($quiz);
136 quiz_update_grades($quiz);
139 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
140 || $oldquiz->timeclose != $quiz->timeclose
141 || $oldquiz->graceperiod != $quiz->graceperiod;
142 if ($quizdateschanged) {
143 quiz_update_open_attempts(array('quizid' => $quiz->id));
146 // Delete any previous preview attempts.
147 quiz_delete_previews($quiz);
149 // Repaginate, if asked to.
150 if (!empty($quiz->repaginatenow)) {
151 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
158 * Given an ID of an instance of this module,
159 * this function will permanently delete the instance
160 * and any data that depends on it.
162 * @param int $id the id of the quiz to delete.
163 * @return bool success or failure.
165 function quiz_delete_instance($id) {
168 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
170 quiz_delete_all_attempts($quiz);
171 quiz_delete_all_overrides($quiz);
173 // Look for random questions that may no longer be used when this quiz is gone.
175 FROM {quiz_slots} slot
176 JOIN {question} q ON q.id = slot.questionid
177 WHERE slot.quizid = ? AND q.qtype = ?";
178 $questionids = $DB->get_fieldset_sql($sql, array($quiz->id, 'random'));
180 // We need to do this before we try and delete randoms, otherwise they would still be 'in use'.
181 $DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
182 $DB->delete_records('quiz_sections', array('quizid' => $quiz->id));
184 foreach ($questionids as $questionid) {
185 question_delete_question($questionid);
188 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
190 quiz_access_manager::delete_settings($quiz);
192 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
193 foreach ($events as $event) {
194 $event = calendar_event::load($event);
198 quiz_grade_item_delete($quiz);
199 $DB->delete_records('quiz', array('id' => $quiz->id));
205 * Deletes a quiz override from the database and clears any corresponding calendar events
207 * @param object $quiz The quiz object.
208 * @param int $overrideid The id of the override being deleted
209 * @return bool true on success
211 function quiz_delete_override($quiz, $overrideid) {
214 if (!isset($quiz->cmid)) {
215 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
216 $quiz->cmid = $cm->id;
219 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
221 // Delete the events.
222 $events = $DB->get_records('event', array('modulename' => 'quiz',
223 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
224 'userid' => (int)$override->userid));
225 foreach ($events as $event) {
226 $eventold = calendar_event::load($event);
230 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
232 // Set the common parameters for one of the events we will be triggering.
234 'objectid' => $override->id,
235 'context' => context_module::instance($quiz->cmid),
237 'quizid' => $override->quiz
240 // Determine which override deleted event to fire.
241 if (!empty($override->userid)) {
242 $params['relateduserid'] = $override->userid;
243 $event = \mod_quiz\event\user_override_deleted::create($params);
245 $params['other']['groupid'] = $override->groupid;
246 $event = \mod_quiz\event\group_override_deleted::create($params);
249 // Trigger the override deleted event.
250 $event->add_record_snapshot('quiz_overrides', $override);
257 * Deletes all quiz overrides from the database and clears any corresponding calendar events
259 * @param object $quiz The quiz object.
261 function quiz_delete_all_overrides($quiz) {
264 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
265 foreach ($overrides as $override) {
266 quiz_delete_override($quiz, $override->id);
271 * Updates a quiz object with override information for a user.
273 * Algorithm: For each quiz setting, if there is a matching user-specific override,
274 * then use that otherwise, if there are group-specific overrides, return the most
275 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
277 * Special case: if there is more than one password that applies to the user, then
278 * quiz->extrapasswords will contain an array of strings giving the remaining
281 * @param object $quiz The quiz object.
282 * @param int $userid The userid.
283 * @return object $quiz The updated quiz object.
285 function quiz_update_effective_access($quiz, $userid) {
288 // Check for user override.
289 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
292 $override = new stdClass();
293 $override->timeopen = null;
294 $override->timeclose = null;
295 $override->timelimit = null;
296 $override->attempts = null;
297 $override->password = null;
300 // Check for group overrides.
301 $groupings = groups_get_user_groups($quiz->course, $userid);
303 if (!empty($groupings[0])) {
304 // Select all overrides that apply to the User's groups.
305 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
306 $sql = "SELECT * FROM {quiz_overrides}
307 WHERE groupid $extra AND quiz = ?";
308 $params[] = $quiz->id;
309 $records = $DB->get_records_sql($sql, $params);
311 // Combine the overrides.
316 $passwords = array();
318 foreach ($records as $gpoverride) {
319 if (isset($gpoverride->timeopen)) {
320 $opens[] = $gpoverride->timeopen;
322 if (isset($gpoverride->timeclose)) {
323 $closes[] = $gpoverride->timeclose;
325 if (isset($gpoverride->timelimit)) {
326 $limits[] = $gpoverride->timelimit;
328 if (isset($gpoverride->attempts)) {
329 $attempts[] = $gpoverride->attempts;
331 if (isset($gpoverride->password)) {
332 $passwords[] = $gpoverride->password;
335 // If there is a user override for a setting, ignore the group override.
336 if (is_null($override->timeopen) && count($opens)) {
337 $override->timeopen = min($opens);
339 if (is_null($override->timeclose) && count($closes)) {
340 if (in_array(0, $closes)) {
341 $override->timeclose = 0;
343 $override->timeclose = max($closes);
346 if (is_null($override->timelimit) && count($limits)) {
347 if (in_array(0, $limits)) {
348 $override->timelimit = 0;
350 $override->timelimit = max($limits);
353 if (is_null($override->attempts) && count($attempts)) {
354 if (in_array(0, $attempts)) {
355 $override->attempts = 0;
357 $override->attempts = max($attempts);
360 if (is_null($override->password) && count($passwords)) {
361 $override->password = array_shift($passwords);
362 if (count($passwords)) {
363 $override->extrapasswords = $passwords;
369 // Merge with quiz defaults.
370 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
371 foreach ($keys as $key) {
372 if (isset($override->{$key})) {
373 $quiz->{$key} = $override->{$key};
381 * Delete all the attempts belonging to a quiz.
383 * @param object $quiz The quiz object.
385 function quiz_delete_all_attempts($quiz) {
387 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
388 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
389 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
390 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
394 * Get the best current grade for a particular user in a quiz.
396 * @param object $quiz the quiz settings.
397 * @param int $userid the id of the user.
398 * @return float the user's current grade for this quiz, or null if this user does
399 * not have a grade on this quiz.
401 function quiz_get_best_grade($quiz, $userid) {
403 $grade = $DB->get_field('quiz_grades', 'grade',
404 array('quiz' => $quiz->id, 'userid' => $userid));
406 // Need to detect errors/no result, without catching 0 grades.
407 if ($grade === false) {
411 return $grade + 0; // Convert to number.
415 * Is this a graded quiz? If this method returns true, you can assume that
416 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
419 * @param object $quiz a row from the quiz table.
420 * @return bool whether this is a graded quiz.
422 function quiz_has_grades($quiz) {
423 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
427 * Does this quiz allow multiple tries?
431 function quiz_allows_multiple_tries($quiz) {
432 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
433 return $bt->allows_multiple_submitted_responses();
437 * Return a small object with summary information about what a
438 * user has done with a given particular instance of this module
439 * Used for user activity reports.
440 * $return->time = the time they did it
441 * $return->info = a short text description
443 * @param object $course
444 * @param object $user
446 * @param object $quiz
447 * @return object|null
449 function quiz_user_outline($course, $user, $mod, $quiz) {
451 require_once($CFG->libdir . '/gradelib.php');
452 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
454 if (empty($grades->items[0]->grades)) {
457 $grade = reset($grades->items[0]->grades);
460 $result = new stdClass();
461 // If the user can't see hidden grades, don't return that information.
462 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
463 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
464 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
466 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
469 // Datesubmitted == time created. dategraded == time modified or time overridden
470 // if grade was last modified by the user themselves use date graded. Otherwise use
472 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
473 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
474 $result->time = $grade->dategraded;
476 $result->time = $grade->datesubmitted;
483 * Print a detailed representation of what a user has done with
484 * a given particular instance of this module, for user activity reports.
486 * @param object $course
487 * @param object $user
489 * @param object $quiz
492 function quiz_user_complete($course, $user, $mod, $quiz) {
493 global $DB, $CFG, $OUTPUT;
494 require_once($CFG->libdir . '/gradelib.php');
495 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
497 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
498 if (!empty($grades->items[0]->grades)) {
499 $grade = reset($grades->items[0]->grades);
500 // If the user can't see hidden grades, don't return that information.
501 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
502 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
503 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
504 if ($grade->str_feedback) {
505 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
508 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
509 if ($grade->str_feedback) {
510 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
515 if ($attempts = $DB->get_records('quiz_attempts',
516 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
517 foreach ($attempts as $attempt) {
518 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
519 if ($attempt->state != quiz_attempt::FINISHED) {
520 echo quiz_attempt_state_name($attempt->state);
522 if (!isset($gitem)) {
523 if (!empty($grades->items[0]->grades)) {
524 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
526 $gitem = new stdClass();
527 $gitem->hidden = true;
530 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
531 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
533 echo get_string('hidden', 'grades');
536 echo ' - '.userdate($attempt->timemodified).'<br />';
539 print_string('noattempts', 'quiz');
546 * Quiz periodic clean-up tasks.
548 function quiz_cron() {
551 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
555 $overduehander = new mod_quiz_overdue_attempt_updater();
557 $processto = $timenow - get_config('quiz', 'graceperiodmin');
559 mtrace(' Looking for quiz overdue quiz attempts...');
561 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
563 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
565 // Run cron for our sub-plugin types.
566 cron_execute_plugin_type('quiz', 'quiz reports');
567 cron_execute_plugin_type('quizaccess', 'quiz access rules');
573 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
574 * @param int $userid the userid.
575 * @param string $status 'all', 'finished' or 'unfinished' to control
576 * @param bool $includepreviews
577 * @return an array of all the user's attempts at this quiz. Returns an empty
578 * array if there are none.
580 function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
582 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
583 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
584 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
586 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
591 $statuscondition = '';
595 $statuscondition = ' AND state IN (:state1, :state2)';
596 $params['state1'] = quiz_attempt::FINISHED;
597 $params['state2'] = quiz_attempt::ABANDONED;
601 $statuscondition = ' AND state IN (:state1, :state2)';
602 $params['state1'] = quiz_attempt::IN_PROGRESS;
603 $params['state2'] = quiz_attempt::OVERDUE;
607 $quizids = (array) $quizids;
608 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
609 $params += $inparams;
610 $params['userid'] = $userid;
613 if (!$includepreviews) {
614 $previewclause = ' AND preview = 0';
617 return $DB->get_records_select('quiz_attempts',
618 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
619 $params, 'quiz, attempt ASC');
623 * Return grade for given user or all users.
625 * @param int $quizid id of quiz
626 * @param int $userid optional user id, 0 means all users
627 * @return array array of grades, false if none. These are raw grades. They should
628 * be processed with quiz_format_grade for display.
630 function quiz_get_user_grades($quiz, $userid = 0) {
633 $params = array($quiz->id);
637 $usertest = 'AND u.id = ?';
639 return $DB->get_records_sql("
643 qg.grade AS rawgrade,
644 qg.timemodified AS dategraded,
645 MAX(qa.timefinish) AS datesubmitted
648 JOIN {quiz_grades} qg ON u.id = qg.userid
649 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
653 GROUP BY u.id, qg.grade, qg.timemodified", $params);
657 * Round a grade to to the correct number of decimal places, and format it for display.
659 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
660 * @param float $grade The grade to round.
663 function quiz_format_grade($quiz, $grade) {
664 if (is_null($grade)) {
665 return get_string('notyetgraded', 'quiz');
667 return format_float($grade, $quiz->decimalpoints);
671 * Determine the correct number of decimal places required to format a grade.
673 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
676 function quiz_get_grade_format($quiz) {
677 if (empty($quiz->questiondecimalpoints)) {
678 $quiz->questiondecimalpoints = -1;
681 if ($quiz->questiondecimalpoints == -1) {
682 return $quiz->decimalpoints;
685 return $quiz->questiondecimalpoints;
689 * Round a grade to the correct number of decimal places, and format it for display.
691 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
692 * @param float $grade The grade to round.
695 function quiz_format_question_grade($quiz, $grade) {
696 return format_float($grade, quiz_get_grade_format($quiz));
700 * Update grades in central gradebook
703 * @param object $quiz the quiz settings.
704 * @param int $userid specific user only, 0 means all users.
705 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
707 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
709 require_once($CFG->libdir . '/gradelib.php');
711 if ($quiz->grade == 0) {
712 quiz_grade_item_update($quiz);
714 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
715 quiz_grade_item_update($quiz, $grades);
717 } else if ($userid && $nullifnone) {
718 $grade = new stdClass();
719 $grade->userid = $userid;
720 $grade->rawgrade = null;
721 quiz_grade_item_update($quiz, $grade);
724 quiz_grade_item_update($quiz);
729 * Create or update the grade item for given quiz
732 * @param object $quiz object with extra cmidnumber
733 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
734 * @return int 0 if ok, error code otherwise
736 function quiz_grade_item_update($quiz, $grades = null) {
737 global $CFG, $OUTPUT;
738 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
739 require_once($CFG->libdir . '/gradelib.php');
741 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
742 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
744 $params = array('itemname' => $quiz->name);
747 if ($quiz->grade > 0) {
748 $params['gradetype'] = GRADE_TYPE_VALUE;
749 $params['grademax'] = $quiz->grade;
750 $params['grademin'] = 0;
753 $params['gradetype'] = GRADE_TYPE_NONE;
756 // What this is trying to do:
757 // 1. If the quiz is set to not show grades while the quiz is still open,
758 // and is set to show grades after the quiz is closed, then create the
759 // grade_item with a show-after date that is the quiz close date.
760 // 2. If the quiz is set to not show grades at either of those times,
761 // create the grade_item as hidden.
762 // 3. If the quiz is set to show grades, create the grade_item visible.
763 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
764 mod_quiz_display_options::LATER_WHILE_OPEN);
765 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
766 mod_quiz_display_options::AFTER_CLOSE);
767 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
768 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
769 $params['hidden'] = 1;
771 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
772 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
773 if ($quiz->timeclose) {
774 $params['hidden'] = $quiz->timeclose;
776 $params['hidden'] = 1;
781 // a) both open and closed enabled
782 // b) open enabled, closed disabled - we can not "hide after",
783 // grades are kept visible even after closing.
784 $params['hidden'] = 0;
787 if (!$params['hidden']) {
788 // If the grade item is not hidden by the quiz logic, then we need to
789 // hide it if the quiz is hidden from students.
790 if (property_exists($quiz, 'visible')) {
791 // Saving the quiz form, and cm not yet updated in the database.
792 $params['hidden'] = !$quiz->visible;
794 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
795 $params['hidden'] = !$cm->visible;
799 if ($grades === 'reset') {
800 $params['reset'] = true;
804 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
805 if (!empty($gradebook_grades->items)) {
806 $grade_item = $gradebook_grades->items[0];
807 if ($grade_item->locked) {
808 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
809 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
810 if (!$confirm_regrade) {
812 $message = get_string('gradeitemislocked', 'grades');
813 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
814 '&mode=overview';
815 $regrade_link = qualified_me() . '&confirm_regrade=1';
816 echo $OUTPUT->box_start('generalbox', 'notice');
817 echo '<p>'. $message .'</p>';
818 echo $OUTPUT->container_start('buttons');
819 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
820 echo $OUTPUT->single_button($back_link, get_string('cancel'));
821 echo $OUTPUT->container_end();
822 echo $OUTPUT->box_end();
824 return GRADE_UPDATE_ITEM_LOCKED;
829 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
833 * Delete grade item for given quiz
836 * @param object $quiz object
837 * @return object quiz
839 function quiz_grade_item_delete($quiz) {
841 require_once($CFG->libdir . '/gradelib.php');
843 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
844 null, array('deleted' => 1));
848 * This standard function will check all instances of this module
849 * and make sure there are up-to-date events created for each of them.
850 * If courseid = 0, then every quiz event in the site is checked, else
851 * only quiz events belonging to the course specified are checked.
852 * This function is used, in its new format, by restore_refresh_events()
854 * @param int $courseid
857 function quiz_refresh_events($courseid = 0) {
860 if ($courseid == 0) {
861 if (!$quizzes = $DB->get_records('quiz')) {
865 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
870 foreach ($quizzes as $quiz) {
871 quiz_update_events($quiz);
878 * Returns all quiz graded users since a given time for specified quiz
880 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
881 $courseid, $cmid, $userid = 0, $groupid = 0) {
882 global $CFG, $USER, $DB;
883 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
885 $course = get_course($courseid);
886 $modinfo = get_fast_modinfo($course);
888 $cm = $modinfo->cms[$cmid];
889 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
892 $userselect = "AND u.id = :userid";
893 $params['userid'] = $userid;
899 $groupselect = 'AND gm.groupid = :groupid';
900 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
901 $params['groupid'] = $groupid;
907 $params['timestart'] = $timestart;
908 $params['quizid'] = $quiz->id;
910 $ufields = user_picture::fields('u', null, 'useridagain');
911 if (!$attempts = $DB->get_records_sql("
914 FROM {quiz_attempts} qa
915 JOIN {user} u ON u.id = qa.userid
917 WHERE qa.timefinish > :timestart
918 AND qa.quiz = :quizid
922 ORDER BY qa.timefinish ASC", $params)) {
926 $context = context_module::instance($cm->id);
927 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
928 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
929 $grader = has_capability('mod/quiz:viewreports', $context);
930 $groupmode = groups_get_activity_groupmode($cm, $course);
933 $aname = format_string($cm->name, true);
934 foreach ($attempts as $attempt) {
935 if ($attempt->userid != $USER->id) {
937 // Grade permission required.
941 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
942 $usersgroups = groups_get_all_groups($course->id,
943 $attempt->userid, $cm->groupingid);
944 $usersgroups = array_keys($usersgroups);
945 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
951 $options = quiz_get_review_options($quiz, $attempt, $context);
953 $tmpactivity = new stdClass();
955 $tmpactivity->type = 'quiz';
956 $tmpactivity->cmid = $cm->id;
957 $tmpactivity->name = $aname;
958 $tmpactivity->sectionnum = $cm->sectionnum;
959 $tmpactivity->timestamp = $attempt->timefinish;
961 $tmpactivity->content = new stdClass();
962 $tmpactivity->content->attemptid = $attempt->id;
963 $tmpactivity->content->attempt = $attempt->attempt;
964 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
965 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
966 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
968 $tmpactivity->content->sumgrades = null;
969 $tmpactivity->content->maxgrade = null;
972 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
973 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
975 $activities[$index++] = $tmpactivity;
979 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
980 global $CFG, $OUTPUT;
982 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
984 echo '<tr><td class="userpicture" valign="top">';
985 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
989 $modname = $modnames[$activity->type];
990 echo '<div class="title">';
991 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
992 'class="icon" alt="' . $modname . '" />';
993 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
994 $activity->cmid . '">' . $activity->name . '</a>';
998 echo '<div class="grade">';
999 echo get_string('attempt', 'quiz', $activity->content->attempt);
1000 if (isset($activity->content->maxgrade)) {
1001 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1002 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1003 $activity->content->attemptid . '">' . $grades . '</a>)';
1007 echo '<div class="user">';
1008 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1009 '&course=' . $courseid . '">' . $activity->user->fullname .
1010 '</a> - ' . userdate($activity->timestamp);
1013 echo '</td></tr></table>';
1019 * Pre-process the quiz options form data, making any necessary adjustments.
1020 * Called by add/update instance in this file.
1022 * @param object $quiz The variables set on the form.
1024 function quiz_process_options($quiz) {
1026 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1027 require_once($CFG->libdir . '/questionlib.php');
1029 $quiz->timemodified = time();
1032 if (!empty($quiz->name)) {
1033 $quiz->name = trim($quiz->name);
1036 // Password field - different in form to stop browsers that remember passwords
1037 // getting confused.
1038 $quiz->password = $quiz->quizpassword;
1039 unset($quiz->quizpassword);
1042 if (isset($quiz->feedbacktext)) {
1043 // Clean up the boundary text.
1044 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1045 if (empty($quiz->feedbacktext[$i]['text'])) {
1046 $quiz->feedbacktext[$i]['text'] = '';
1048 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1052 // Check the boundary value is a number or a percentage, and in range.
1054 while (!empty($quiz->feedbackboundaries[$i])) {
1055 $boundary = trim($quiz->feedbackboundaries[$i]);
1056 if (!is_numeric($boundary)) {
1057 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1058 $boundary = trim(substr($boundary, 0, -1));
1059 if (is_numeric($boundary)) {
1060 $boundary = $boundary * $quiz->grade / 100.0;
1062 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1066 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1067 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1069 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1070 return get_string('feedbackerrororder', 'quiz', $i + 1);
1072 $quiz->feedbackboundaries[$i] = $boundary;
1075 $numboundaries = $i;
1077 // Check there is nothing in the remaining unused fields.
1078 if (!empty($quiz->feedbackboundaries)) {
1079 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1080 if (!empty($quiz->feedbackboundaries[$i]) &&
1081 trim($quiz->feedbackboundaries[$i]) != '') {
1082 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1086 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1087 if (!empty($quiz->feedbacktext[$i]['text']) &&
1088 trim($quiz->feedbacktext[$i]['text']) != '') {
1089 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1092 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1093 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1094 $quiz->feedbackboundaries[$numboundaries] = 0;
1095 $quiz->feedbackboundarycount = $numboundaries;
1097 $quiz->feedbackboundarycount = -1;
1100 // Combing the individual settings into the review columns.
1101 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1102 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1103 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1104 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1105 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1106 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1107 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1108 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1109 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1113 * Helper function for {@link quiz_process_options()}.
1114 * @param object $fromform the sumbitted form date.
1115 * @param string $field one of the review option field names.
1117 function quiz_review_option_form_to_db($fromform, $field) {
1118 static $times = array(
1119 'during' => mod_quiz_display_options::DURING,
1120 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1121 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1122 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1126 foreach ($times as $whenname => $when) {
1127 $fieldname = $field . $whenname;
1128 if (isset($fromform->$fieldname)) {
1130 unset($fromform->$fieldname);
1138 * This function is called at the end of quiz_add_instance
1139 * and quiz_update_instance, to do the common processing.
1141 * @param object $quiz the quiz object.
1143 function quiz_after_add_or_update($quiz) {
1145 $cmid = $quiz->coursemodule;
1147 // We need to use context now, so we need to make sure all needed info is already in db.
1148 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1149 $context = context_module::instance($cmid);
1151 // Save the feedback.
1152 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1154 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1155 $feedback = new stdClass();
1156 $feedback->quizid = $quiz->id;
1157 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1158 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1159 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1160 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1161 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1162 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1163 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1164 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1165 $quiz->feedbacktext[$i]['text']);
1166 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1167 array('id' => $feedback->id));
1170 // Store any settings belonging to the access rules.
1171 quiz_access_manager::save_settings($quiz);
1173 // Update the events relating to this quiz.
1174 quiz_update_events($quiz);
1176 // Update related grade item.
1177 quiz_grade_item_update($quiz);
1181 * This function updates the events associated to the quiz.
1182 * If $override is non-zero, then it updates only the events
1183 * associated with the specified override.
1185 * @uses QUIZ_MAX_EVENT_LENGTH
1186 * @param object $quiz the quiz object.
1187 * @param object optional $override limit to a specific override
1189 function quiz_update_events($quiz, $override = null) {
1192 // Load the old events relating to this quiz.
1193 $conds = array('modulename'=>'quiz',
1194 'instance'=>$quiz->id);
1195 if (!empty($override)) {
1196 // Only load events for this override.
1197 if (isset($override->userid)) {
1198 $conds['userid'] = $override->userid;
1200 $conds['groupid'] = $override->groupid;
1203 $oldevents = $DB->get_records('event', $conds);
1205 // Now make a todo list of all that needs to be updated.
1206 if (empty($override)) {
1207 // We are updating the primary settings for the quiz, so we
1208 // need to add all the overrides.
1209 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
1210 // As well as the original quiz (empty override).
1211 $overrides[] = new stdClass();
1213 // Just do the one override.
1214 $overrides = array($override);
1217 foreach ($overrides as $current) {
1218 $groupid = isset($current->groupid)? $current->groupid : 0;
1219 $userid = isset($current->userid)? $current->userid : 0;
1220 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1221 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1223 // Only add open/close events for an override if they differ from the quiz default.
1224 $addopen = empty($current->id) || !empty($current->timeopen);
1225 $addclose = empty($current->id) || !empty($current->timeclose);
1227 if (!empty($quiz->coursemodule)) {
1228 $cmid = $quiz->coursemodule;
1230 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1233 $event = new stdClass();
1234 $event->description = format_module_intro('quiz', $quiz, $cmid);
1235 // Events module won't show user events when the courseid is nonzero.
1236 $event->courseid = ($userid) ? 0 : $quiz->course;
1237 $event->groupid = $groupid;
1238 $event->userid = $userid;
1239 $event->modulename = 'quiz';
1240 $event->instance = $quiz->id;
1241 $event->timestart = $timeopen;
1242 $event->timeduration = max($timeclose - $timeopen, 0);
1243 $event->visible = instance_is_visible('quiz', $quiz);
1244 $event->eventtype = 'open';
1246 // Determine the event name.
1248 $params = new stdClass();
1249 $params->quiz = $quiz->name;
1250 $params->group = groups_get_group_name($groupid);
1251 if ($params->group === false) {
1252 // Group doesn't exist, just skip it.
1255 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1256 } else if ($userid) {
1257 $params = new stdClass();
1258 $params->quiz = $quiz->name;
1259 $eventname = get_string('overrideusereventname', 'quiz', $params);
1261 $eventname = $quiz->name;
1263 if ($addopen or $addclose) {
1264 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1265 // Single event for the whole quiz.
1266 if ($oldevent = array_shift($oldevents)) {
1267 $event->id = $oldevent->id;
1271 $event->name = $eventname;
1272 // The method calendar_event::create will reuse a db record if the id field is set.
1273 calendar_event::create($event);
1275 // Separate start and end events.
1276 $event->timeduration = 0;
1277 if ($timeopen && $addopen) {
1278 if ($oldevent = array_shift($oldevents)) {
1279 $event->id = $oldevent->id;
1283 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
1284 // The method calendar_event::create will reuse a db record if the id field is set.
1285 calendar_event::create($event);
1287 if ($timeclose && $addclose) {
1288 if ($oldevent = array_shift($oldevents)) {
1289 $event->id = $oldevent->id;
1293 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1294 $event->timestart = $timeclose;
1295 $event->eventtype = 'close';
1296 calendar_event::create($event);
1302 // Delete any leftover events.
1303 foreach ($oldevents as $badevent) {
1304 $badevent = calendar_event::load($badevent);
1305 $badevent->delete();
1310 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1312 * @param int $quizid The quiz ID.
1313 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1315 function quiz_get_group_override_priorities($quizid) {
1318 // Fetch group overrides.
1319 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1320 $params = ['quiz' => $quizid];
1321 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1326 $grouptimeopen = [];
1327 $grouptimeclose = [];
1328 foreach ($overrides as $override) {
1329 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1330 $grouptimeopen[] = $override->timeopen;
1332 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1333 $grouptimeclose[] = $override->timeclose;
1337 // Sort open times in descending manner. The earlier open time gets higher priority.
1338 rsort($grouptimeopen);
1340 $opengrouppriorities = [];
1342 foreach ($grouptimeopen as $timeopen) {
1343 $opengrouppriorities[$timeopen] = $openpriority++;
1346 // Sort close times in ascending manner. The later close time gets higher priority.
1347 sort($grouptimeclose);
1349 $closegrouppriorities = [];
1351 foreach ($grouptimeclose as $timeclose) {
1352 $closegrouppriorities[$timeclose] = $closepriority++;
1356 'open' => $opengrouppriorities,
1357 'close' => $closegrouppriorities
1362 * List the actions that correspond to a view of this module.
1363 * This is used by the participation report.
1365 * Note: This is not used by new logging system. Event with
1366 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1367 * be considered as view action.
1371 function quiz_get_view_actions() {
1372 return array('view', 'view all', 'report', 'review');
1376 * List the actions that correspond to a post of this module.
1377 * This is used by the participation report.
1379 * Note: This is not used by new logging system. Event with
1380 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1381 * will be considered as post action.
1385 function quiz_get_post_actions() {
1386 return array('attempt', 'close attempt', 'preview', 'editquestions',
1387 'delete attempt', 'manualgrade');
1391 * @param array $questionids of question ids.
1392 * @return bool whether any of these questions are used by any instance of this module.
1394 function quiz_questions_in_use($questionids) {
1396 require_once($CFG->libdir . '/questionlib.php');
1397 list($test, $params) = $DB->get_in_or_equal($questionids);
1398 return $DB->record_exists_select('quiz_slots',
1399 'questionid ' . $test, $params) || question_engine::questions_in_use(
1400 $questionids, new qubaid_join('{quiz_attempts} quiza',
1401 'quiza.uniqueid', 'quiza.preview = 0'));
1405 * Implementation of the function for printing the form elements that control
1406 * whether the course reset functionality affects the quiz.
1408 * @param $mform the course reset form that is being built.
1410 function quiz_reset_course_form_definition($mform) {
1411 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1412 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1413 get_string('removeallquizattempts', 'quiz'));
1414 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1415 get_string('removealluseroverrides', 'quiz'));
1416 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1417 get_string('removeallgroupoverrides', 'quiz'));
1421 * Course reset form defaults.
1422 * @return array the defaults.
1424 function quiz_reset_course_form_defaults($course) {
1425 return array('reset_quiz_attempts' => 1,
1426 'reset_quiz_group_overrides' => 1,
1427 'reset_quiz_user_overrides' => 1);
1431 * Removes all grades from gradebook
1433 * @param int $courseid
1434 * @param string optional type
1436 function quiz_reset_gradebook($courseid, $type='') {
1439 $quizzes = $DB->get_records_sql("
1440 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1442 JOIN {course_modules} cm ON m.id = cm.module
1443 JOIN {quiz} q ON cm.instance = q.id
1444 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1446 foreach ($quizzes as $quiz) {
1447 quiz_grade_item_update($quiz, 'reset');
1452 * Actual implementation of the reset course functionality, delete all the
1453 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1456 * Also, move the quiz open and close dates, if the course start date is changing.
1458 * @param object $data the data submitted from the reset course.
1459 * @return array status array
1461 function quiz_reset_userdata($data) {
1463 require_once($CFG->libdir . '/questionlib.php');
1465 $componentstr = get_string('modulenameplural', 'quiz');
1469 if (!empty($data->reset_quiz_attempts)) {
1470 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1471 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1472 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1473 array('quizcourseid' => $data->courseid)));
1475 $DB->delete_records_select('quiz_attempts',
1476 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1478 'component' => $componentstr,
1479 'item' => get_string('attemptsdeleted', 'quiz'),
1482 // Remove all grades from gradebook.
1483 $DB->delete_records_select('quiz_grades',
1484 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1485 if (empty($data->reset_gradebook_grades)) {
1486 quiz_reset_gradebook($data->courseid);
1489 'component' => $componentstr,
1490 'item' => get_string('gradesdeleted', 'quiz'),
1494 // Remove user overrides.
1495 if (!empty($data->reset_quiz_user_overrides)) {
1496 $DB->delete_records_select('quiz_overrides',
1497 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1499 'component' => $componentstr,
1500 'item' => get_string('useroverridesdeleted', 'quiz'),
1503 // Remove group overrides.
1504 if (!empty($data->reset_quiz_group_overrides)) {
1505 $DB->delete_records_select('quiz_overrides',
1506 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1508 'component' => $componentstr,
1509 'item' => get_string('groupoverridesdeleted', 'quiz'),
1513 // Updating dates - shift may be negative too.
1514 if ($data->timeshift) {
1515 $DB->execute("UPDATE {quiz_overrides}
1516 SET timeopen = timeopen + ?
1517 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1518 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1519 $DB->execute("UPDATE {quiz_overrides}
1520 SET timeclose = timeclose + ?
1521 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1522 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1524 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1525 $data->timeshift, $data->courseid);
1528 'component' => $componentstr,
1529 'item' => get_string('openclosedatesupdated', 'quiz'),
1537 * Prints quiz summaries on MyMoodle Page
1538 * @param arry $courses
1539 * @param array $htmlarray
1541 function quiz_print_overview($courses, &$htmlarray) {
1543 // These next 6 Lines are constant in all modules (just change module name).
1544 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1548 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1552 // Get the quizzes attempts.
1555 foreach ($quizzes as $quiz) {
1556 $quizids[] = $quiz->id;
1557 $attemptsinfo[$quiz->id] = ['count' => 0, 'hasfinished' => false];
1559 $attempts = quiz_get_user_attempts($quizids, $USER->id);
1560 foreach ($attempts as $attempt) {
1561 $attemptsinfo[$attempt->quiz]['count']++;
1562 $attemptsinfo[$attempt->quiz]['hasfinished'] = true;
1566 // Fetch some language strings outside the main loop.
1567 $strquiz = get_string('modulename', 'quiz');
1568 $strnoattempts = get_string('noattempts', 'quiz');
1570 // We want to list quizzes that are currently available, and which have a close date.
1571 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1573 foreach ($quizzes as $quiz) {
1574 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1577 // Now provide more information depending on the uers's role.
1578 $context = context_module::instance($quiz->coursemodule);
1579 if (has_capability('mod/quiz:viewreports', $context)) {
1580 // For teacher-like people, show a summary of the number of student attempts.
1581 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1582 // fields set to make the following call work.
1583 $str .= '<div class="info">' . quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1585 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $context)) { // Student
1586 // For student-like people, tell them how many attempts they have made.
1588 if (isset($USER->id)) {
1589 if ($attemptsinfo[$quiz->id]['hasfinished']) {
1590 // The student's last attempt is finished.
1594 if ($attemptsinfo[$quiz->id]['count'] > 0) {
1595 $str .= '<div class="info">' .
1596 get_string('numattemptsmade', 'quiz', $attemptsinfo[$quiz->id]['count']) . '</div>';
1598 $str .= '<div class="info">' . $strnoattempts . '</div>';
1602 $str .= '<div class="info">' . $strnoattempts . '</div>';
1606 // For ayone else, there is no point listing this quiz, so stop processing.
1610 // Give a link to the quiz, and the deadline.
1611 $html = '<div class="quiz overview">' .
1612 '<div class="name">' . $strquiz . ': <a ' .
1613 ($quiz->visible ? '' : ' class="dimmed"') .
1614 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1615 $quiz->coursemodule . '">' .
1616 $quiz->name . '</a></div>';
1617 $html .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1618 userdate($quiz->timeclose)) . '</div>';
1621 if (empty($htmlarray[$quiz->course]['quiz'])) {
1622 $htmlarray[$quiz->course]['quiz'] = $html;
1624 $htmlarray[$quiz->course]['quiz'] .= $html;
1631 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1632 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1634 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1635 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1636 * $cm->groupingid fields are used at the moment.
1637 * @param bool $returnzero if false (default), when no attempts have been
1638 * made '' is returned instead of 'Attempts: 0'.
1639 * @param int $currentgroup if there is a concept of current group where this method is being called
1640 * (e.g. a report) pass it in here. Default 0 which means no current group.
1641 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1642 * "Attemtps 123 (45 from this group)".
1644 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1646 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1647 if ($numattempts || $returnzero) {
1648 if (groups_get_activity_groupmode($cm)) {
1649 $a = new stdClass();
1650 $a->total = $numattempts;
1651 if ($currentgroup) {
1652 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1653 '{quiz_attempts} qa JOIN ' .
1654 '{groups_members} gm ON qa.userid = gm.userid ' .
1655 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1656 array($quiz->id, $currentgroup));
1657 return get_string('attemptsnumthisgroup', 'quiz', $a);
1658 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1659 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1660 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1661 '{quiz_attempts} qa JOIN ' .
1662 '{groups_members} gm ON qa.userid = gm.userid ' .
1663 'WHERE quiz = ? AND preview = 0 AND ' .
1664 "groupid $usql", array_merge(array($quiz->id), $params));
1665 return get_string('attemptsnumyourgroups', 'quiz', $a);
1668 return get_string('attemptsnum', 'quiz', $numattempts);
1674 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1675 * to the quiz reports.
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 object $context the quiz context.
1681 * @param bool $returnzero if false (default), when no attempts have been made
1682 * '' is returned instead of 'Attempts: 0'.
1683 * @param int $currentgroup if there is a concept of current group where this method is being called
1684 * (e.g. a report) pass it in here. Default 0 which means no current group.
1685 * @return string HTML fragment for the link.
1687 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1688 $currentgroup = 0) {
1690 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1695 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1696 $url = new moodle_url('/mod/quiz/report.php', array(
1697 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1698 return html_writer::link($url, $summary);
1702 * @param string $feature FEATURE_xx constant for requested feature
1703 * @return bool True if quiz supports feature
1705 function quiz_supports($feature) {
1707 case FEATURE_GROUPS: return true;
1708 case FEATURE_GROUPINGS: return true;
1709 case FEATURE_MOD_INTRO: return true;
1710 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1711 case FEATURE_COMPLETION_HAS_RULES: return true;
1712 case FEATURE_GRADE_HAS_GRADE: return true;
1713 case FEATURE_GRADE_OUTCOMES: return true;
1714 case FEATURE_BACKUP_MOODLE2: return true;
1715 case FEATURE_SHOW_DESCRIPTION: return true;
1716 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1717 case FEATURE_USES_QUESTIONS: return true;
1719 default: return null;
1724 * @return array all other caps used in module
1726 function quiz_get_extra_capabilities() {
1728 require_once($CFG->libdir . '/questionlib.php');
1729 $caps = question_get_all_capabilities();
1730 $caps[] = 'moodle/site:accessallgroups';
1735 * This function extends the settings navigation block for the site.
1737 * It is safe to rely on PAGE here as we will only ever be within the module
1738 * context when this is called
1740 * @param settings_navigation $settings
1741 * @param navigation_node $quiznode
1744 function quiz_extend_settings_navigation($settings, $quiznode) {
1747 // Require {@link questionlib.php}
1748 // Included here as we only ever want to include this file if we really need to.
1749 require_once($CFG->libdir . '/questionlib.php');
1751 // We want to add these new nodes after the Edit settings node, and before the
1752 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1753 $keys = $quiznode->get_children_key_list();
1755 $i = array_search('modedit', $keys);
1756 if ($i === false and array_key_exists(0, $keys)) {
1757 $beforekey = $keys[0];
1758 } else if (array_key_exists($i + 1, $keys)) {
1759 $beforekey = $keys[$i + 1];
1762 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1763 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1764 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1765 new moodle_url($url, array('mode'=>'group')),
1766 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1767 $quiznode->add_node($node, $beforekey);
1769 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1770 new moodle_url($url, array('mode'=>'user')),
1771 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1772 $quiznode->add_node($node, $beforekey);
1775 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1776 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1777 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1778 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1779 new pix_icon('t/edit', ''));
1780 $quiznode->add_node($node, $beforekey);
1783 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1784 $url = new moodle_url('/mod/quiz/startattempt.php',
1785 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1786 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1787 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1788 new pix_icon('i/preview', ''));
1789 $quiznode->add_node($node, $beforekey);
1792 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1793 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1794 $reportlist = quiz_report_list($PAGE->cm->context);
1796 $url = new moodle_url('/mod/quiz/report.php',
1797 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1798 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1799 navigation_node::TYPE_SETTING,
1800 null, null, new pix_icon('i/report', '')), $beforekey);
1802 foreach ($reportlist as $report) {
1803 $url = new moodle_url('/mod/quiz/report.php',
1804 array('id' => $PAGE->cm->id, 'mode' => $report));
1805 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1806 navigation_node::TYPE_SETTING,
1807 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1811 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1815 * Serves the quiz files.
1819 * @param stdClass $course course object
1820 * @param stdClass $cm course module object
1821 * @param stdClass $context context object
1822 * @param string $filearea file area
1823 * @param array $args extra arguments
1824 * @param bool $forcedownload whether or not force download
1825 * @param array $options additional options affecting the file serving
1826 * @return bool false if file not found, does not return if found - justsend the file
1828 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1831 if ($context->contextlevel != CONTEXT_MODULE) {
1835 require_login($course, false, $cm);
1837 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1841 // The 'intro' area is served by pluginfile.php.
1842 $fileareas = array('feedback');
1843 if (!in_array($filearea, $fileareas)) {
1847 $feedbackid = (int)array_shift($args);
1848 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1852 $fs = get_file_storage();
1853 $relativepath = implode('/', $args);
1854 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1855 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1858 send_stored_file($file, 0, 0, true, $options);
1862 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1863 * a question in a question_attempt when that attempt is a quiz attempt.
1867 * @param stdClass $course course settings object
1868 * @param stdClass $context context object
1869 * @param string $component the name of the component we are serving files for.
1870 * @param string $filearea the name of the file area.
1871 * @param int $qubaid the attempt usage id.
1872 * @param int $slot the id of a question in this quiz attempt.
1873 * @param array $args the remaining bits of the file path.
1874 * @param bool $forcedownload whether the user must be forced to download the file.
1875 * @param array $options additional options affecting the file serving
1876 * @return bool false if file not found, does not return if found - justsend the file
1878 function quiz_question_pluginfile($course, $context, $component,
1879 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
1881 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1883 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1884 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1886 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1887 // In the middle of an attempt.
1888 if (!$attemptobj->is_preview_user()) {
1889 $attemptobj->require_capability('mod/quiz:attempt');
1891 $isreviewing = false;
1894 // Reviewing an attempt.
1895 $attemptobj->check_review_capability();
1896 $isreviewing = true;
1899 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1900 $component, $filearea, $args, $forcedownload)) {
1901 send_file_not_found();
1904 $fs = get_file_storage();
1905 $relativepath = implode('/', $args);
1906 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1907 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1908 send_file_not_found();
1911 send_stored_file($file, 0, 0, $forcedownload, $options);
1915 * Return a list of page types
1916 * @param string $pagetype current page type
1917 * @param stdClass $parentcontext Block's parent context
1918 * @param stdClass $currentcontext Current context of block
1920 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1921 $module_pagetype = array(
1922 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1923 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1924 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1925 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1926 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1927 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1928 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1930 return $module_pagetype;
1934 * @return the options for quiz navigation.
1936 function quiz_get_navigation_options() {
1938 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1939 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1944 * Obtains the automatic completion state for this quiz on any conditions
1945 * in quiz settings, such as if all attempts are used or a certain grade is achieved.
1947 * @param object $course Course
1948 * @param object $cm Course-module
1949 * @param int $userid User ID
1950 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1951 * @return bool True if completed, false if not. (If no conditions, then return
1952 * value depends on comparison type)
1954 function quiz_get_completion_state($course, $cm, $userid, $type) {
1958 $quiz = $DB->get_record('quiz', array('id' => $cm->instance), '*', MUST_EXIST);
1959 if (!$quiz->completionattemptsexhausted && !$quiz->completionpass) {
1963 // Check if the user has used up all attempts.
1964 if ($quiz->completionattemptsexhausted) {
1965 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
1967 $lastfinishedattempt = end($attempts);
1968 $context = context_module::instance($cm->id);
1969 $quizobj = quiz::create($quiz->id, $userid);
1970 $accessmanager = new quiz_access_manager($quizobj, time(),
1971 has_capability('mod/quiz:ignoretimelimits', $context, $userid, false));
1972 if ($accessmanager->is_finished(count($attempts), $lastfinishedattempt)) {
1978 // Check for passing grade.
1979 if ($quiz->completionpass) {
1980 require_once($CFG->libdir . '/gradelib.php');
1981 $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
1982 'itemmodule' => 'quiz', 'iteminstance' => $cm->instance, 'outcomeid' => null));
1984 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
1985 if (!empty($grades[$userid])) {
1986 return $grades[$userid]->is_passed($item);
1994 * Check if the module has any update that affects the current user since a given time.
1996 * @param cm_info $cm course module data
1997 * @param int $from the time to check updates from
1998 * @param array $filter if we need to check only specific updates
1999 * @return stdClass an object with the different type of areas indicating if they were updated or not
2002 function quiz_check_updates_since(cm_info $cm, $from, $filter = array()) {
2003 global $DB, $USER, $CFG;
2004 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2006 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2008 // Check if questions were updated.
2009 $updates->questions = (object) array('updated' => false);
2010 $quizobj = quiz::create($cm->instance, $USER->id);
2011 $quizobj->preload_questions();
2012 $quizobj->load_questions();
2013 $questionids = array_keys($quizobj->get_questions());
2014 if (!empty($questionids)) {
2015 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
2016 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
2017 $params['time1'] = $from;
2018 $params['time2'] = $from;
2019 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
2020 if (!empty($questions)) {
2021 $updates->questions->updated = true;
2022 $updates->questions->itemids = array_keys($questions);
2026 // Check for new attempts or grades.
2027 $updates->attempts = (object) array('updated' => false);
2028 $updates->grades = (object) array('updated' => false);
2029 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
2030 $params = array($cm->instance, $USER->id, $from);
2032 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2033 if (!empty($attempts)) {
2034 $updates->attempts->updated = true;
2035 $updates->attempts->itemids = array_keys($attempts);
2037 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2038 if (!empty($grades)) {
2039 $updates->grades->updated = true;
2040 $updates->grades->itemids = array_keys($grades);