MDL-49813 quiz: add sections in the right place after page changes
[moodle.git] / mod / quiz / lib.php
blobcd021e3f95c194185faf7cdb3dd2cdc98ef44383
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 * 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) {
78 global $DB;
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)) {
85 return $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);
98 return $quiz->id;
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) {
110 global $CFG, $DB;
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)) {
116 return $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);
154 return true;
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) {
166 global $DB;
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.
174 $sql = "SELECT q.id
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);
195 $event->delete();
198 quiz_grade_item_delete($quiz);
199 $DB->delete_records('quiz', array('id' => $quiz->id));
201 return true;
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) {
212 global $DB;
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);
227 $eventold->delete();
230 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
232 // Set the common parameters for one of the events we will be triggering.
233 $params = array(
234 'objectid' => $override->id,
235 'context' => context_module::instance($quiz->cmid),
236 'other' => array(
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);
244 } else {
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);
251 $event->trigger();
253 return true;
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) {
262 global $DB;
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
279 * passwords.
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) {
286 global $DB;
288 // Check for user override.
289 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
291 if (!$override) {
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.
312 $opens = array();
313 $closes = array();
314 $limits = array();
315 $attempts = array();
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;
342 } else {
343 $override->timeclose = max($closes);
346 if (is_null($override->timelimit) && count($limits)) {
347 if (in_array(0, $limits)) {
348 $override->timelimit = 0;
349 } else {
350 $override->timelimit = max($limits);
353 if (is_null($override->attempts) && count($attempts)) {
354 if (in_array(0, $attempts)) {
355 $override->attempts = 0;
356 } else {
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};
377 return $quiz;
381 * Delete all the attempts belonging to a quiz.
383 * @param object $quiz The quiz object.
385 function quiz_delete_all_attempts($quiz) {
386 global $CFG, $DB;
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) {
402 global $DB;
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) {
408 return null;
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
417 * divide by them).
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?
429 * @return bool
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
445 * @param object $mod
446 * @param object $quiz
447 * @return object|null
449 function quiz_user_outline($course, $user, $mod, $quiz) {
450 global $DB, $CFG;
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)) {
455 return null;
456 } else {
457 $grade = reset($grades->items[0]->grades);
460 $result = new stdClass();
461 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
463 // Datesubmitted == time created. dategraded == time modified or time overridden
464 // if grade was last modified by the user themselves use date graded. Otherwise use
465 // date submitted.
466 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
467 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
468 $result->time = $grade->dategraded;
469 } else {
470 $result->time = $grade->datesubmitted;
473 return $result;
477 * Print a detailed representation of what a user has done with
478 * a given particular instance of this module, for user activity reports.
480 * @param object $course
481 * @param object $user
482 * @param object $mod
483 * @param object $quiz
484 * @return bool
486 function quiz_user_complete($course, $user, $mod, $quiz) {
487 global $DB, $CFG, $OUTPUT;
488 require_once($CFG->libdir . '/gradelib.php');
489 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
491 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
492 if (!empty($grades->items[0]->grades)) {
493 $grade = reset($grades->items[0]->grades);
494 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
495 if ($grade->str_feedback) {
496 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
500 if ($attempts = $DB->get_records('quiz_attempts',
501 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
502 foreach ($attempts as $attempt) {
503 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
504 if ($attempt->state != quiz_attempt::FINISHED) {
505 echo quiz_attempt_state_name($attempt->state);
506 } else {
507 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
508 quiz_format_grade($quiz, $quiz->sumgrades);
510 echo ' - '.userdate($attempt->timemodified).'<br />';
512 } else {
513 print_string('noattempts', 'quiz');
516 return true;
520 * Quiz periodic clean-up tasks.
522 function quiz_cron() {
523 global $CFG;
525 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
526 mtrace('');
528 $timenow = time();
529 $overduehander = new mod_quiz_overdue_attempt_updater();
531 $processto = $timenow - get_config('quiz', 'graceperiodmin');
533 mtrace(' Looking for quiz overdue quiz attempts...');
535 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
537 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
539 // Run cron for our sub-plugin types.
540 cron_execute_plugin_type('quiz', 'quiz reports');
541 cron_execute_plugin_type('quizaccess', 'quiz access rules');
543 return true;
547 * @param int $quizid the quiz id.
548 * @param int $userid the userid.
549 * @param string $status 'all', 'finished' or 'unfinished' to control
550 * @param bool $includepreviews
551 * @return an array of all the user's attempts at this quiz. Returns an empty
552 * array if there are none.
554 function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
555 global $DB, $CFG;
556 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
557 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
558 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
559 // MDL-33048.
560 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
562 $params = array();
563 switch ($status) {
564 case 'all':
565 $statuscondition = '';
566 break;
568 case 'finished':
569 $statuscondition = ' AND state IN (:state1, :state2)';
570 $params['state1'] = quiz_attempt::FINISHED;
571 $params['state2'] = quiz_attempt::ABANDONED;
572 break;
574 case 'unfinished':
575 $statuscondition = ' AND state IN (:state1, :state2)';
576 $params['state1'] = quiz_attempt::IN_PROGRESS;
577 $params['state2'] = quiz_attempt::OVERDUE;
578 break;
581 $previewclause = '';
582 if (!$includepreviews) {
583 $previewclause = ' AND preview = 0';
586 $params['quizid'] = $quizid;
587 $params['userid'] = $userid;
588 return $DB->get_records_select('quiz_attempts',
589 'quiz = :quizid AND userid = :userid' . $previewclause . $statuscondition,
590 $params, 'attempt ASC');
594 * Return grade for given user or all users.
596 * @param int $quizid id of quiz
597 * @param int $userid optional user id, 0 means all users
598 * @return array array of grades, false if none. These are raw grades. They should
599 * be processed with quiz_format_grade for display.
601 function quiz_get_user_grades($quiz, $userid = 0) {
602 global $CFG, $DB;
604 $params = array($quiz->id);
605 $usertest = '';
606 if ($userid) {
607 $params[] = $userid;
608 $usertest = 'AND u.id = ?';
610 return $DB->get_records_sql("
611 SELECT
612 u.id,
613 u.id AS userid,
614 qg.grade AS rawgrade,
615 qg.timemodified AS dategraded,
616 MAX(qa.timefinish) AS datesubmitted
618 FROM {user} u
619 JOIN {quiz_grades} qg ON u.id = qg.userid
620 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
622 WHERE qg.quiz = ?
623 $usertest
624 GROUP BY u.id, qg.grade, qg.timemodified", $params);
628 * Round a grade to to the correct number of decimal places, and format it for display.
630 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
631 * @param float $grade The grade to round.
632 * @return float
634 function quiz_format_grade($quiz, $grade) {
635 if (is_null($grade)) {
636 return get_string('notyetgraded', 'quiz');
638 return format_float($grade, $quiz->decimalpoints);
642 * Determine the correct number of decimal places required to format a grade.
644 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
645 * @return integer
647 function quiz_get_grade_format($quiz) {
648 if (empty($quiz->questiondecimalpoints)) {
649 $quiz->questiondecimalpoints = -1;
652 if ($quiz->questiondecimalpoints == -1) {
653 return $quiz->decimalpoints;
656 return $quiz->questiondecimalpoints;
660 * Round a grade to the correct number of decimal places, and format it for display.
662 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
663 * @param float $grade The grade to round.
664 * @return float
666 function quiz_format_question_grade($quiz, $grade) {
667 return format_float($grade, quiz_get_grade_format($quiz));
671 * Update grades in central gradebook
673 * @category grade
674 * @param object $quiz the quiz settings.
675 * @param int $userid specific user only, 0 means all users.
676 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
678 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
679 global $CFG, $DB;
680 require_once($CFG->libdir . '/gradelib.php');
682 if ($quiz->grade == 0) {
683 quiz_grade_item_update($quiz);
685 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
686 quiz_grade_item_update($quiz, $grades);
688 } else if ($userid && $nullifnone) {
689 $grade = new stdClass();
690 $grade->userid = $userid;
691 $grade->rawgrade = null;
692 quiz_grade_item_update($quiz, $grade);
694 } else {
695 quiz_grade_item_update($quiz);
700 * Create or update the grade item for given quiz
702 * @category grade
703 * @param object $quiz object with extra cmidnumber
704 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
705 * @return int 0 if ok, error code otherwise
707 function quiz_grade_item_update($quiz, $grades = null) {
708 global $CFG, $OUTPUT;
709 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
710 require_once($CFG->libdir . '/gradelib.php');
712 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
713 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
714 } else {
715 $params = array('itemname' => $quiz->name);
718 if ($quiz->grade > 0) {
719 $params['gradetype'] = GRADE_TYPE_VALUE;
720 $params['grademax'] = $quiz->grade;
721 $params['grademin'] = 0;
723 } else {
724 $params['gradetype'] = GRADE_TYPE_NONE;
727 // What this is trying to do:
728 // 1. If the quiz is set to not show grades while the quiz is still open,
729 // and is set to show grades after the quiz is closed, then create the
730 // grade_item with a show-after date that is the quiz close date.
731 // 2. If the quiz is set to not show grades at either of those times,
732 // create the grade_item as hidden.
733 // 3. If the quiz is set to show grades, create the grade_item visible.
734 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
735 mod_quiz_display_options::LATER_WHILE_OPEN);
736 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
737 mod_quiz_display_options::AFTER_CLOSE);
738 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
739 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
740 $params['hidden'] = 1;
742 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
743 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
744 if ($quiz->timeclose) {
745 $params['hidden'] = $quiz->timeclose;
746 } else {
747 $params['hidden'] = 1;
750 } else {
751 // Either
752 // a) both open and closed enabled
753 // b) open enabled, closed disabled - we can not "hide after",
754 // grades are kept visible even after closing.
755 $params['hidden'] = 0;
758 if (!$params['hidden']) {
759 // If the grade item is not hidden by the quiz logic, then we need to
760 // hide it if the quiz is hidden from students.
761 if (property_exists($quiz, 'visible')) {
762 // Saving the quiz form, and cm not yet updated in the database.
763 $params['hidden'] = !$quiz->visible;
764 } else {
765 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
766 $params['hidden'] = !$cm->visible;
770 if ($grades === 'reset') {
771 $params['reset'] = true;
772 $grades = null;
775 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
776 if (!empty($gradebook_grades->items)) {
777 $grade_item = $gradebook_grades->items[0];
778 if ($grade_item->locked) {
779 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
780 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
781 if (!$confirm_regrade) {
782 if (!AJAX_SCRIPT) {
783 $message = get_string('gradeitemislocked', 'grades');
784 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
785 '&amp;mode=overview';
786 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
787 echo $OUTPUT->box_start('generalbox', 'notice');
788 echo '<p>'. $message .'</p>';
789 echo $OUTPUT->container_start('buttons');
790 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
791 echo $OUTPUT->single_button($back_link, get_string('cancel'));
792 echo $OUTPUT->container_end();
793 echo $OUTPUT->box_end();
795 return GRADE_UPDATE_ITEM_LOCKED;
800 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
804 * Delete grade item for given quiz
806 * @category grade
807 * @param object $quiz object
808 * @return object quiz
810 function quiz_grade_item_delete($quiz) {
811 global $CFG;
812 require_once($CFG->libdir . '/gradelib.php');
814 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
815 null, array('deleted' => 1));
819 * This standard function will check all instances of this module
820 * and make sure there are up-to-date events created for each of them.
821 * If courseid = 0, then every quiz event in the site is checked, else
822 * only quiz events belonging to the course specified are checked.
823 * This function is used, in its new format, by restore_refresh_events()
825 * @param int $courseid
826 * @return bool
828 function quiz_refresh_events($courseid = 0) {
829 global $DB;
831 if ($courseid == 0) {
832 if (!$quizzes = $DB->get_records('quiz')) {
833 return true;
835 } else {
836 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
837 return true;
841 foreach ($quizzes as $quiz) {
842 quiz_update_events($quiz);
845 return true;
849 * Returns all quiz graded users since a given time for specified quiz
851 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
852 $courseid, $cmid, $userid = 0, $groupid = 0) {
853 global $CFG, $USER, $DB;
854 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
856 $course = get_course($courseid);
857 $modinfo = get_fast_modinfo($course);
859 $cm = $modinfo->cms[$cmid];
860 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
862 if ($userid) {
863 $userselect = "AND u.id = :userid";
864 $params['userid'] = $userid;
865 } else {
866 $userselect = '';
869 if ($groupid) {
870 $groupselect = 'AND gm.groupid = :groupid';
871 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
872 $params['groupid'] = $groupid;
873 } else {
874 $groupselect = '';
875 $groupjoin = '';
878 $params['timestart'] = $timestart;
879 $params['quizid'] = $quiz->id;
881 $ufields = user_picture::fields('u', null, 'useridagain');
882 if (!$attempts = $DB->get_records_sql("
883 SELECT qa.*,
884 {$ufields}
885 FROM {quiz_attempts} qa
886 JOIN {user} u ON u.id = qa.userid
887 $groupjoin
888 WHERE qa.timefinish > :timestart
889 AND qa.quiz = :quizid
890 AND qa.preview = 0
891 $userselect
892 $groupselect
893 ORDER BY qa.timefinish ASC", $params)) {
894 return;
897 $context = context_module::instance($cm->id);
898 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
899 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
900 $grader = has_capability('mod/quiz:viewreports', $context);
901 $groupmode = groups_get_activity_groupmode($cm, $course);
903 $usersgroups = null;
904 $aname = format_string($cm->name, true);
905 foreach ($attempts as $attempt) {
906 if ($attempt->userid != $USER->id) {
907 if (!$grader) {
908 // Grade permission required.
909 continue;
912 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
913 $usersgroups = groups_get_all_groups($course->id,
914 $attempt->userid, $cm->groupingid);
915 $usersgroups = array_keys($usersgroups);
916 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
917 continue;
922 $options = quiz_get_review_options($quiz, $attempt, $context);
924 $tmpactivity = new stdClass();
926 $tmpactivity->type = 'quiz';
927 $tmpactivity->cmid = $cm->id;
928 $tmpactivity->name = $aname;
929 $tmpactivity->sectionnum = $cm->sectionnum;
930 $tmpactivity->timestamp = $attempt->timefinish;
932 $tmpactivity->content = new stdClass();
933 $tmpactivity->content->attemptid = $attempt->id;
934 $tmpactivity->content->attempt = $attempt->attempt;
935 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
936 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
937 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
938 } else {
939 $tmpactivity->content->sumgrades = null;
940 $tmpactivity->content->maxgrade = null;
943 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
944 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
946 $activities[$index++] = $tmpactivity;
950 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
951 global $CFG, $OUTPUT;
953 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
955 echo '<tr><td class="userpicture" valign="top">';
956 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
957 echo '</td><td>';
959 if ($detail) {
960 $modname = $modnames[$activity->type];
961 echo '<div class="title">';
962 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
963 'class="icon" alt="' . $modname . '" />';
964 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
965 $activity->cmid . '">' . $activity->name . '</a>';
966 echo '</div>';
969 echo '<div class="grade">';
970 echo get_string('attempt', 'quiz', $activity->content->attempt);
971 if (isset($activity->content->maxgrade)) {
972 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
973 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
974 $activity->content->attemptid . '">' . $grades . '</a>)';
976 echo '</div>';
978 echo '<div class="user">';
979 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
980 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
981 '</a> - ' . userdate($activity->timestamp);
982 echo '</div>';
984 echo '</td></tr></table>';
986 return;
990 * Pre-process the quiz options form data, making any necessary adjustments.
991 * Called by add/update instance in this file.
993 * @param object $quiz The variables set on the form.
995 function quiz_process_options($quiz) {
996 global $CFG;
997 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
998 require_once($CFG->libdir . '/questionlib.php');
1000 $quiz->timemodified = time();
1002 // Quiz name.
1003 if (!empty($quiz->name)) {
1004 $quiz->name = trim($quiz->name);
1007 // Password field - different in form to stop browsers that remember passwords
1008 // getting confused.
1009 $quiz->password = $quiz->quizpassword;
1010 unset($quiz->quizpassword);
1012 // Quiz feedback.
1013 if (isset($quiz->feedbacktext)) {
1014 // Clean up the boundary text.
1015 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1016 if (empty($quiz->feedbacktext[$i]['text'])) {
1017 $quiz->feedbacktext[$i]['text'] = '';
1018 } else {
1019 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1023 // Check the boundary value is a number or a percentage, and in range.
1024 $i = 0;
1025 while (!empty($quiz->feedbackboundaries[$i])) {
1026 $boundary = trim($quiz->feedbackboundaries[$i]);
1027 if (!is_numeric($boundary)) {
1028 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1029 $boundary = trim(substr($boundary, 0, -1));
1030 if (is_numeric($boundary)) {
1031 $boundary = $boundary * $quiz->grade / 100.0;
1032 } else {
1033 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1037 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1038 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1040 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1041 return get_string('feedbackerrororder', 'quiz', $i + 1);
1043 $quiz->feedbackboundaries[$i] = $boundary;
1044 $i += 1;
1046 $numboundaries = $i;
1048 // Check there is nothing in the remaining unused fields.
1049 if (!empty($quiz->feedbackboundaries)) {
1050 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1051 if (!empty($quiz->feedbackboundaries[$i]) &&
1052 trim($quiz->feedbackboundaries[$i]) != '') {
1053 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1057 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1058 if (!empty($quiz->feedbacktext[$i]['text']) &&
1059 trim($quiz->feedbacktext[$i]['text']) != '') {
1060 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1063 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1064 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1065 $quiz->feedbackboundaries[$numboundaries] = 0;
1066 $quiz->feedbackboundarycount = $numboundaries;
1067 } else {
1068 $quiz->feedbackboundarycount = -1;
1071 // Combing the individual settings into the review columns.
1072 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1073 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1074 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1075 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1076 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1077 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1078 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1079 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1080 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1084 * Helper function for {@link quiz_process_options()}.
1085 * @param object $fromform the sumbitted form date.
1086 * @param string $field one of the review option field names.
1088 function quiz_review_option_form_to_db($fromform, $field) {
1089 static $times = array(
1090 'during' => mod_quiz_display_options::DURING,
1091 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1092 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1093 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1096 $review = 0;
1097 foreach ($times as $whenname => $when) {
1098 $fieldname = $field . $whenname;
1099 if (isset($fromform->$fieldname)) {
1100 $review |= $when;
1101 unset($fromform->$fieldname);
1105 return $review;
1109 * This function is called at the end of quiz_add_instance
1110 * and quiz_update_instance, to do the common processing.
1112 * @param object $quiz the quiz object.
1114 function quiz_after_add_or_update($quiz) {
1115 global $DB;
1116 $cmid = $quiz->coursemodule;
1118 // We need to use context now, so we need to make sure all needed info is already in db.
1119 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1120 $context = context_module::instance($cmid);
1122 // Save the feedback.
1123 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1125 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1126 $feedback = new stdClass();
1127 $feedback->quizid = $quiz->id;
1128 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1129 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1130 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1131 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1132 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1133 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1134 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1135 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1136 $quiz->feedbacktext[$i]['text']);
1137 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1138 array('id' => $feedback->id));
1141 // Store any settings belonging to the access rules.
1142 quiz_access_manager::save_settings($quiz);
1144 // Update the events relating to this quiz.
1145 quiz_update_events($quiz);
1147 // Update related grade item.
1148 quiz_grade_item_update($quiz);
1152 * This function updates the events associated to the quiz.
1153 * If $override is non-zero, then it updates only the events
1154 * associated with the specified override.
1156 * @uses QUIZ_MAX_EVENT_LENGTH
1157 * @param object $quiz the quiz object.
1158 * @param object optional $override limit to a specific override
1160 function quiz_update_events($quiz, $override = null) {
1161 global $DB;
1163 // Load the old events relating to this quiz.
1164 $conds = array('modulename'=>'quiz',
1165 'instance'=>$quiz->id);
1166 if (!empty($override)) {
1167 // Only load events for this override.
1168 $conds['groupid'] = isset($override->groupid)? $override->groupid : 0;
1169 $conds['userid'] = isset($override->userid)? $override->userid : 0;
1171 $oldevents = $DB->get_records('event', $conds);
1173 // Now make a todo list of all that needs to be updated.
1174 if (empty($override)) {
1175 // We are updating the primary settings for the quiz, so we
1176 // need to add all the overrides.
1177 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
1178 // As well as the original quiz (empty override).
1179 $overrides[] = new stdClass();
1180 } else {
1181 // Just do the one override.
1182 $overrides = array($override);
1185 foreach ($overrides as $current) {
1186 $groupid = isset($current->groupid)? $current->groupid : 0;
1187 $userid = isset($current->userid)? $current->userid : 0;
1188 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1189 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1191 // Only add open/close events for an override if they differ from the quiz default.
1192 $addopen = empty($current->id) || !empty($current->timeopen);
1193 $addclose = empty($current->id) || !empty($current->timeclose);
1195 if (!empty($quiz->coursemodule)) {
1196 $cmid = $quiz->coursemodule;
1197 } else {
1198 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1201 $event = new stdClass();
1202 $event->description = format_module_intro('quiz', $quiz, $cmid);
1203 // Events module won't show user events when the courseid is nonzero.
1204 $event->courseid = ($userid) ? 0 : $quiz->course;
1205 $event->groupid = $groupid;
1206 $event->userid = $userid;
1207 $event->modulename = 'quiz';
1208 $event->instance = $quiz->id;
1209 $event->timestart = $timeopen;
1210 $event->timeduration = max($timeclose - $timeopen, 0);
1211 $event->visible = instance_is_visible('quiz', $quiz);
1212 $event->eventtype = 'open';
1214 // Determine the event name.
1215 if ($groupid) {
1216 $params = new stdClass();
1217 $params->quiz = $quiz->name;
1218 $params->group = groups_get_group_name($groupid);
1219 if ($params->group === false) {
1220 // Group doesn't exist, just skip it.
1221 continue;
1223 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1224 } else if ($userid) {
1225 $params = new stdClass();
1226 $params->quiz = $quiz->name;
1227 $eventname = get_string('overrideusereventname', 'quiz', $params);
1228 } else {
1229 $eventname = $quiz->name;
1231 if ($addopen or $addclose) {
1232 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1233 // Single event for the whole quiz.
1234 if ($oldevent = array_shift($oldevents)) {
1235 $event->id = $oldevent->id;
1236 } else {
1237 unset($event->id);
1239 $event->name = $eventname;
1240 // The method calendar_event::create will reuse a db record if the id field is set.
1241 calendar_event::create($event);
1242 } else {
1243 // Separate start and end events.
1244 $event->timeduration = 0;
1245 if ($timeopen && $addopen) {
1246 if ($oldevent = array_shift($oldevents)) {
1247 $event->id = $oldevent->id;
1248 } else {
1249 unset($event->id);
1251 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
1252 // The method calendar_event::create will reuse a db record if the id field is set.
1253 calendar_event::create($event);
1255 if ($timeclose && $addclose) {
1256 if ($oldevent = array_shift($oldevents)) {
1257 $event->id = $oldevent->id;
1258 } else {
1259 unset($event->id);
1261 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1262 $event->timestart = $timeclose;
1263 $event->eventtype = 'close';
1264 calendar_event::create($event);
1270 // Delete any leftover events.
1271 foreach ($oldevents as $badevent) {
1272 $badevent = calendar_event::load($badevent);
1273 $badevent->delete();
1278 * List the actions that correspond to a view of this module.
1279 * This is used by the participation report.
1281 * Note: This is not used by new logging system. Event with
1282 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1283 * be considered as view action.
1285 * @return array
1287 function quiz_get_view_actions() {
1288 return array('view', 'view all', 'report', 'review');
1292 * List the actions that correspond to a post of this module.
1293 * This is used by the participation report.
1295 * Note: This is not used by new logging system. Event with
1296 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1297 * will be considered as post action.
1299 * @return array
1301 function quiz_get_post_actions() {
1302 return array('attempt', 'close attempt', 'preview', 'editquestions',
1303 'delete attempt', 'manualgrade');
1307 * @param array $questionids of question ids.
1308 * @return bool whether any of these questions are used by any instance of this module.
1310 function quiz_questions_in_use($questionids) {
1311 global $DB, $CFG;
1312 require_once($CFG->libdir . '/questionlib.php');
1313 list($test, $params) = $DB->get_in_or_equal($questionids);
1314 return $DB->record_exists_select('quiz_slots',
1315 'questionid ' . $test, $params) || question_engine::questions_in_use(
1316 $questionids, new qubaid_join('{quiz_attempts} quiza',
1317 'quiza.uniqueid', 'quiza.preview = 0'));
1321 * Implementation of the function for printing the form elements that control
1322 * whether the course reset functionality affects the quiz.
1324 * @param $mform the course reset form that is being built.
1326 function quiz_reset_course_form_definition($mform) {
1327 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1328 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1329 get_string('removeallquizattempts', 'quiz'));
1330 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1331 get_string('removealluseroverrides', 'quiz'));
1332 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1333 get_string('removeallgroupoverrides', 'quiz'));
1337 * Course reset form defaults.
1338 * @return array the defaults.
1340 function quiz_reset_course_form_defaults($course) {
1341 return array('reset_quiz_attempts' => 1,
1342 'reset_quiz_group_overrides' => 1,
1343 'reset_quiz_user_overrides' => 1);
1347 * Removes all grades from gradebook
1349 * @param int $courseid
1350 * @param string optional type
1352 function quiz_reset_gradebook($courseid, $type='') {
1353 global $CFG, $DB;
1355 $quizzes = $DB->get_records_sql("
1356 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1357 FROM {modules} m
1358 JOIN {course_modules} cm ON m.id = cm.module
1359 JOIN {quiz} q ON cm.instance = q.id
1360 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1362 foreach ($quizzes as $quiz) {
1363 quiz_grade_item_update($quiz, 'reset');
1368 * Actual implementation of the reset course functionality, delete all the
1369 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1370 * set and true.
1372 * Also, move the quiz open and close dates, if the course start date is changing.
1374 * @param object $data the data submitted from the reset course.
1375 * @return array status array
1377 function quiz_reset_userdata($data) {
1378 global $CFG, $DB;
1379 require_once($CFG->libdir . '/questionlib.php');
1381 $componentstr = get_string('modulenameplural', 'quiz');
1382 $status = array();
1384 // Delete attempts.
1385 if (!empty($data->reset_quiz_attempts)) {
1386 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1387 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1388 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1389 array('quizcourseid' => $data->courseid)));
1391 $DB->delete_records_select('quiz_attempts',
1392 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1393 $status[] = array(
1394 'component' => $componentstr,
1395 'item' => get_string('attemptsdeleted', 'quiz'),
1396 'error' => false);
1398 // Remove all grades from gradebook.
1399 $DB->delete_records_select('quiz_grades',
1400 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1401 if (empty($data->reset_gradebook_grades)) {
1402 quiz_reset_gradebook($data->courseid);
1404 $status[] = array(
1405 'component' => $componentstr,
1406 'item' => get_string('gradesdeleted', 'quiz'),
1407 'error' => false);
1410 // Remove user overrides.
1411 if (!empty($data->reset_quiz_user_overrides)) {
1412 $DB->delete_records_select('quiz_overrides',
1413 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1414 $status[] = array(
1415 'component' => $componentstr,
1416 'item' => get_string('useroverridesdeleted', 'quiz'),
1417 'error' => false);
1419 // Remove group overrides.
1420 if (!empty($data->reset_quiz_group_overrides)) {
1421 $DB->delete_records_select('quiz_overrides',
1422 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1423 $status[] = array(
1424 'component' => $componentstr,
1425 'item' => get_string('groupoverridesdeleted', 'quiz'),
1426 'error' => false);
1429 // Updating dates - shift may be negative too.
1430 if ($data->timeshift) {
1431 $DB->execute("UPDATE {quiz_overrides}
1432 SET timeopen = timeopen + ?
1433 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1434 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1435 $DB->execute("UPDATE {quiz_overrides}
1436 SET timeclose = timeclose + ?
1437 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1438 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1440 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1441 $data->timeshift, $data->courseid);
1443 $status[] = array(
1444 'component' => $componentstr,
1445 'item' => get_string('openclosedatesupdated', 'quiz'),
1446 'error' => false);
1449 return $status;
1453 * Prints quiz summaries on MyMoodle Page
1454 * @param arry $courses
1455 * @param array $htmlarray
1457 function quiz_print_overview($courses, &$htmlarray) {
1458 global $USER, $CFG;
1459 // These next 6 Lines are constant in all modules (just change module name).
1460 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1461 return array();
1464 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1465 return;
1468 // Fetch some language strings outside the main loop.
1469 $strquiz = get_string('modulename', 'quiz');
1470 $strnoattempts = get_string('noattempts', 'quiz');
1472 // We want to list quizzes that are currently available, and which have a close date.
1473 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1474 $now = time();
1475 foreach ($quizzes as $quiz) {
1476 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1477 // Give a link to the quiz, and the deadline.
1478 $str = '<div class="quiz overview">' .
1479 '<div class="name">' . $strquiz . ': <a ' .
1480 ($quiz->visible ? '' : ' class="dimmed"') .
1481 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1482 $quiz->coursemodule . '">' .
1483 $quiz->name . '</a></div>';
1484 $str .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1485 userdate($quiz->timeclose)) . '</div>';
1487 // Now provide more information depending on the uers's role.
1488 $context = context_module::instance($quiz->coursemodule);
1489 if (has_capability('mod/quiz:viewreports', $context)) {
1490 // For teacher-like people, show a summary of the number of student attempts.
1491 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1492 // fields set to make the following call work.
1493 $str .= '<div class="info">' .
1494 quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1495 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'),
1496 $context)) { // Student
1497 // For student-like people, tell them how many attempts they have made.
1498 if (isset($USER->id) &&
1499 ($attempts = quiz_get_user_attempts($quiz->id, $USER->id))) {
1500 $numattempts = count($attempts);
1501 $str .= '<div class="info">' .
1502 get_string('numattemptsmade', 'quiz', $numattempts) . '</div>';
1503 } else {
1504 $str .= '<div class="info">' . $strnoattempts . '</div>';
1506 } else {
1507 // For ayone else, there is no point listing this quiz, so stop processing.
1508 continue;
1511 // Add the output for this quiz to the rest.
1512 $str .= '</div>';
1513 if (empty($htmlarray[$quiz->course]['quiz'])) {
1514 $htmlarray[$quiz->course]['quiz'] = $str;
1515 } else {
1516 $htmlarray[$quiz->course]['quiz'] .= $str;
1523 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1524 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1526 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1527 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1528 * $cm->groupingid fields are used at the moment.
1529 * @param bool $returnzero if false (default), when no attempts have been
1530 * made '' is returned instead of 'Attempts: 0'.
1531 * @param int $currentgroup if there is a concept of current group where this method is being called
1532 * (e.g. a report) pass it in here. Default 0 which means no current group.
1533 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1534 * "Attemtps 123 (45 from this group)".
1536 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1537 global $DB, $USER;
1538 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1539 if ($numattempts || $returnzero) {
1540 if (groups_get_activity_groupmode($cm)) {
1541 $a = new stdClass();
1542 $a->total = $numattempts;
1543 if ($currentgroup) {
1544 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1545 '{quiz_attempts} qa JOIN ' .
1546 '{groups_members} gm ON qa.userid = gm.userid ' .
1547 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1548 array($quiz->id, $currentgroup));
1549 return get_string('attemptsnumthisgroup', 'quiz', $a);
1550 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1551 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1552 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1553 '{quiz_attempts} qa JOIN ' .
1554 '{groups_members} gm ON qa.userid = gm.userid ' .
1555 'WHERE quiz = ? AND preview = 0 AND ' .
1556 "groupid $usql", array_merge(array($quiz->id), $params));
1557 return get_string('attemptsnumyourgroups', 'quiz', $a);
1560 return get_string('attemptsnum', 'quiz', $numattempts);
1562 return '';
1566 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1567 * to the quiz reports.
1569 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1570 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1571 * $cm->groupingid fields are used at the moment.
1572 * @param object $context the quiz context.
1573 * @param bool $returnzero if false (default), when no attempts have been made
1574 * '' is returned instead of 'Attempts: 0'.
1575 * @param int $currentgroup if there is a concept of current group where this method is being called
1576 * (e.g. a report) pass it in here. Default 0 which means no current group.
1577 * @return string HTML fragment for the link.
1579 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1580 $currentgroup = 0) {
1581 global $CFG;
1582 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1583 if (!$summary) {
1584 return '';
1587 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1588 $url = new moodle_url('/mod/quiz/report.php', array(
1589 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1590 return html_writer::link($url, $summary);
1594 * @param string $feature FEATURE_xx constant for requested feature
1595 * @return bool True if quiz supports feature
1597 function quiz_supports($feature) {
1598 switch($feature) {
1599 case FEATURE_GROUPS: return true;
1600 case FEATURE_GROUPINGS: return true;
1601 case FEATURE_MOD_INTRO: return true;
1602 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1603 case FEATURE_COMPLETION_HAS_RULES: return true;
1604 case FEATURE_GRADE_HAS_GRADE: return true;
1605 case FEATURE_GRADE_OUTCOMES: return true;
1606 case FEATURE_BACKUP_MOODLE2: return true;
1607 case FEATURE_SHOW_DESCRIPTION: return true;
1608 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1609 case FEATURE_USES_QUESTIONS: return true;
1611 default: return null;
1616 * @return array all other caps used in module
1618 function quiz_get_extra_capabilities() {
1619 global $CFG;
1620 require_once($CFG->libdir . '/questionlib.php');
1621 $caps = question_get_all_capabilities();
1622 $caps[] = 'moodle/site:accessallgroups';
1623 return $caps;
1627 * This function extends the settings navigation block for the site.
1629 * It is safe to rely on PAGE here as we will only ever be within the module
1630 * context when this is called
1632 * @param settings_navigation $settings
1633 * @param navigation_node $quiznode
1634 * @return void
1636 function quiz_extend_settings_navigation($settings, $quiznode) {
1637 global $PAGE, $CFG;
1639 // Require {@link questionlib.php}
1640 // Included here as we only ever want to include this file if we really need to.
1641 require_once($CFG->libdir . '/questionlib.php');
1643 // We want to add these new nodes after the Edit settings node, and before the
1644 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1645 $keys = $quiznode->get_children_key_list();
1646 $beforekey = null;
1647 $i = array_search('modedit', $keys);
1648 if ($i === false and array_key_exists(0, $keys)) {
1649 $beforekey = $keys[0];
1650 } else if (array_key_exists($i + 1, $keys)) {
1651 $beforekey = $keys[$i + 1];
1654 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1655 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1656 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1657 new moodle_url($url, array('mode'=>'group')),
1658 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1659 $quiznode->add_node($node, $beforekey);
1661 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1662 new moodle_url($url, array('mode'=>'user')),
1663 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1664 $quiznode->add_node($node, $beforekey);
1667 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1668 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1669 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1670 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1671 new pix_icon('t/edit', ''));
1672 $quiznode->add_node($node, $beforekey);
1675 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1676 $url = new moodle_url('/mod/quiz/startattempt.php',
1677 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1678 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1679 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1680 new pix_icon('i/preview', ''));
1681 $quiznode->add_node($node, $beforekey);
1684 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1685 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1686 $reportlist = quiz_report_list($PAGE->cm->context);
1688 $url = new moodle_url('/mod/quiz/report.php',
1689 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1690 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1691 navigation_node::TYPE_SETTING,
1692 null, null, new pix_icon('i/report', '')), $beforekey);
1694 foreach ($reportlist as $report) {
1695 $url = new moodle_url('/mod/quiz/report.php',
1696 array('id' => $PAGE->cm->id, 'mode' => $report));
1697 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1698 navigation_node::TYPE_SETTING,
1699 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1703 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1707 * Serves the quiz files.
1709 * @package mod_quiz
1710 * @category files
1711 * @param stdClass $course course object
1712 * @param stdClass $cm course module object
1713 * @param stdClass $context context object
1714 * @param string $filearea file area
1715 * @param array $args extra arguments
1716 * @param bool $forcedownload whether or not force download
1717 * @param array $options additional options affecting the file serving
1718 * @return bool false if file not found, does not return if found - justsend the file
1720 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1721 global $CFG, $DB;
1723 if ($context->contextlevel != CONTEXT_MODULE) {
1724 return false;
1727 require_login($course, false, $cm);
1729 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1730 return false;
1733 // The 'intro' area is served by pluginfile.php.
1734 $fileareas = array('feedback');
1735 if (!in_array($filearea, $fileareas)) {
1736 return false;
1739 $feedbackid = (int)array_shift($args);
1740 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1741 return false;
1744 $fs = get_file_storage();
1745 $relativepath = implode('/', $args);
1746 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1747 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1748 return false;
1750 send_stored_file($file, 0, 0, true, $options);
1754 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1755 * a question in a question_attempt when that attempt is a quiz attempt.
1757 * @package mod_quiz
1758 * @category files
1759 * @param stdClass $course course settings object
1760 * @param stdClass $context context object
1761 * @param string $component the name of the component we are serving files for.
1762 * @param string $filearea the name of the file area.
1763 * @param int $qubaid the attempt usage id.
1764 * @param int $slot the id of a question in this quiz attempt.
1765 * @param array $args the remaining bits of the file path.
1766 * @param bool $forcedownload whether the user must be forced to download the file.
1767 * @param array $options additional options affecting the file serving
1768 * @return bool false if file not found, does not return if found - justsend the file
1770 function quiz_question_pluginfile($course, $context, $component,
1771 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
1772 global $CFG;
1773 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1775 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1776 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1778 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1779 // In the middle of an attempt.
1780 if (!$attemptobj->is_preview_user()) {
1781 $attemptobj->require_capability('mod/quiz:attempt');
1783 $isreviewing = false;
1785 } else {
1786 // Reviewing an attempt.
1787 $attemptobj->check_review_capability();
1788 $isreviewing = true;
1791 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1792 $component, $filearea, $args, $forcedownload)) {
1793 send_file_not_found();
1796 $fs = get_file_storage();
1797 $relativepath = implode('/', $args);
1798 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1799 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1800 send_file_not_found();
1803 send_stored_file($file, 0, 0, $forcedownload, $options);
1807 * Return a list of page types
1808 * @param string $pagetype current page type
1809 * @param stdClass $parentcontext Block's parent context
1810 * @param stdClass $currentcontext Current context of block
1812 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1813 $module_pagetype = array(
1814 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1815 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1816 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1817 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1818 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1819 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1820 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1822 return $module_pagetype;
1826 * @return the options for quiz navigation.
1828 function quiz_get_navigation_options() {
1829 return array(
1830 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1831 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1836 * Obtains the automatic completion state for this quiz on any conditions
1837 * in quiz settings, such as if all attempts are used or a certain grade is achieved.
1839 * @param object $course Course
1840 * @param object $cm Course-module
1841 * @param int $userid User ID
1842 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1843 * @return bool True if completed, false if not. (If no conditions, then return
1844 * value depends on comparison type)
1846 function quiz_get_completion_state($course, $cm, $userid, $type) {
1847 global $DB;
1848 global $CFG;
1850 $quiz = $DB->get_record('quiz', array('id' => $cm->instance), '*', MUST_EXIST);
1851 if (!$quiz->completionattemptsexhausted && !$quiz->completionpass) {
1852 return $type;
1855 // Check if the user has used up all attempts.
1856 if ($quiz->completionattemptsexhausted) {
1857 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
1858 if ($attempts) {
1859 $lastfinishedattempt = end($attempts);
1860 $context = context_module::instance($cm->id);
1861 $quizobj = quiz::create($quiz->id, $userid);
1862 $accessmanager = new quiz_access_manager($quizobj, time(),
1863 has_capability('mod/quiz:ignoretimelimits', $context, $userid, false));
1864 if ($accessmanager->is_finished(count($attempts), $lastfinishedattempt)) {
1865 return true;
1870 // Check for passing grade.
1871 if ($quiz->completionpass) {
1872 require_once($CFG->libdir . '/gradelib.php');
1873 $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
1874 'itemmodule' => 'quiz', 'iteminstance' => $cm->instance, 'outcomeid' => null));
1875 if ($item) {
1876 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
1877 if (!empty($grades[$userid])) {
1878 return $grades[$userid]->is_passed($item);
1882 return false;