Merge branch 'wip-mdl-45719-m27' of https://github.com/deraadt/moodle into MOODLE_27_...
[moodle.git] / mod / quiz / lib.php
blobcb3e0eb5c30533f1b874755d00371c56758517d8
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 // Do the processing required after an add or an update.
92 quiz_after_add_or_update($quiz);
94 return $quiz->id;
97 /**
98 * Given an object containing all the necessary data,
99 * (defined by the form in mod_form.php) this function
100 * will update an existing instance with new data.
102 * @param object $quiz the data that came from the form.
103 * @return mixed true on success, false or a string error message on failure.
105 function quiz_update_instance($quiz, $mform) {
106 global $CFG, $DB;
107 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
109 // Process the options from the form.
110 $result = quiz_process_options($quiz);
111 if ($result && is_string($result)) {
112 return $result;
115 // Get the current value, so we can see what changed.
116 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
118 // We need two values from the existing DB record that are not in the form,
119 // in some of the function calls below.
120 $quiz->sumgrades = $oldquiz->sumgrades;
121 $quiz->grade = $oldquiz->grade;
123 // Update the database.
124 $quiz->id = $quiz->instance;
125 $DB->update_record('quiz', $quiz);
127 // Do the processing required after an add or an update.
128 quiz_after_add_or_update($quiz);
130 if ($oldquiz->grademethod != $quiz->grademethod) {
131 quiz_update_all_final_grades($quiz);
132 quiz_update_grades($quiz);
135 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
136 || $oldquiz->timeclose != $quiz->timeclose
137 || $oldquiz->graceperiod != $quiz->graceperiod;
138 if ($quizdateschanged) {
139 quiz_update_open_attempts(array('quizid' => $quiz->id));
142 // Delete any previous preview attempts.
143 quiz_delete_previews($quiz);
145 // Repaginate, if asked to.
146 if (!$quiz->shufflequestions && !empty($quiz->repaginatenow)) {
147 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
150 return true;
154 * Given an ID of an instance of this module,
155 * this function will permanently delete the instance
156 * and any data that depends on it.
158 * @param int $id the id of the quiz to delete.
159 * @return bool success or failure.
161 function quiz_delete_instance($id) {
162 global $DB;
164 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
166 quiz_delete_all_attempts($quiz);
167 quiz_delete_all_overrides($quiz);
169 // Look for random questions that may no longer be used when this quiz is gone.
170 $sql = "SELECT q.id
171 FROM {quiz_slots} slot
172 JOIN {question} q ON q.id = slot.questionid
173 WHERE slot.quizid = ? AND q.qtype = ?";
174 $questionids = $DB->get_fieldset_sql($sql, array($quiz->id, 'random'));
176 // We need to do this before we try and delete randoms, otherwise they would still be 'in use'.
177 $DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
179 foreach ($questionids as $questionid) {
180 question_delete_question($questionid);
183 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
185 quiz_access_manager::delete_settings($quiz);
187 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
188 foreach ($events as $event) {
189 $event = calendar_event::load($event);
190 $event->delete();
193 quiz_grade_item_delete($quiz);
194 $DB->delete_records('quiz', array('id' => $quiz->id));
196 return true;
200 * Deletes a quiz override from the database and clears any corresponding calendar events
202 * @param object $quiz The quiz object.
203 * @param int $overrideid The id of the override being deleted
204 * @return bool true on success
206 function quiz_delete_override($quiz, $overrideid) {
207 global $DB;
209 if (!isset($quiz->cmid)) {
210 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
211 $quiz->cmid = $cm->id;
214 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
216 // Delete the events.
217 $events = $DB->get_records('event', array('modulename' => 'quiz',
218 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
219 'userid' => (int)$override->userid));
220 foreach ($events as $event) {
221 $eventold = calendar_event::load($event);
222 $eventold->delete();
225 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
227 // Set the common parameters for one of the events we will be triggering.
228 $params = array(
229 'objectid' => $override->id,
230 'context' => context_module::instance($quiz->cmid),
231 'other' => array(
232 'quizid' => $override->quiz
235 // Determine which override deleted event to fire.
236 if (!empty($override->userid)) {
237 $params['relateduserid'] = $override->userid;
238 $event = \mod_quiz\event\user_override_deleted::create($params);
239 } else {
240 $params['other']['groupid'] = $override->groupid;
241 $event = \mod_quiz\event\group_override_deleted::create($params);
244 // Trigger the override deleted event.
245 $event->add_record_snapshot('quiz_overrides', $override);
246 $event->trigger();
248 return true;
252 * Deletes all quiz overrides from the database and clears any corresponding calendar events
254 * @param object $quiz The quiz object.
256 function quiz_delete_all_overrides($quiz) {
257 global $DB;
259 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
260 foreach ($overrides as $override) {
261 quiz_delete_override($quiz, $override->id);
266 * Updates a quiz object with override information for a user.
268 * Algorithm: For each quiz setting, if there is a matching user-specific override,
269 * then use that otherwise, if there are group-specific overrides, return the most
270 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
272 * Special case: if there is more than one password that applies to the user, then
273 * quiz->extrapasswords will contain an array of strings giving the remaining
274 * passwords.
276 * @param object $quiz The quiz object.
277 * @param int $userid The userid.
278 * @return object $quiz The updated quiz object.
280 function quiz_update_effective_access($quiz, $userid) {
281 global $DB;
283 // Check for user override.
284 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
286 if (!$override) {
287 $override = new stdClass();
288 $override->timeopen = null;
289 $override->timeclose = null;
290 $override->timelimit = null;
291 $override->attempts = null;
292 $override->password = null;
295 // Check for group overrides.
296 $groupings = groups_get_user_groups($quiz->course, $userid);
298 if (!empty($groupings[0])) {
299 // Select all overrides that apply to the User's groups.
300 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
301 $sql = "SELECT * FROM {quiz_overrides}
302 WHERE groupid $extra AND quiz = ?";
303 $params[] = $quiz->id;
304 $records = $DB->get_records_sql($sql, $params);
306 // Combine the overrides.
307 $opens = array();
308 $closes = array();
309 $limits = array();
310 $attempts = array();
311 $passwords = array();
313 foreach ($records as $gpoverride) {
314 if (isset($gpoverride->timeopen)) {
315 $opens[] = $gpoverride->timeopen;
317 if (isset($gpoverride->timeclose)) {
318 $closes[] = $gpoverride->timeclose;
320 if (isset($gpoverride->timelimit)) {
321 $limits[] = $gpoverride->timelimit;
323 if (isset($gpoverride->attempts)) {
324 $attempts[] = $gpoverride->attempts;
326 if (isset($gpoverride->password)) {
327 $passwords[] = $gpoverride->password;
330 // If there is a user override for a setting, ignore the group override.
331 if (is_null($override->timeopen) && count($opens)) {
332 $override->timeopen = min($opens);
334 if (is_null($override->timeclose) && count($closes)) {
335 if (in_array(0, $closes)) {
336 $override->timeclose = 0;
337 } else {
338 $override->timeclose = max($closes);
341 if (is_null($override->timelimit) && count($limits)) {
342 if (in_array(0, $limits)) {
343 $override->timelimit = 0;
344 } else {
345 $override->timelimit = max($limits);
348 if (is_null($override->attempts) && count($attempts)) {
349 if (in_array(0, $attempts)) {
350 $override->attempts = 0;
351 } else {
352 $override->attempts = max($attempts);
355 if (is_null($override->password) && count($passwords)) {
356 $override->password = array_shift($passwords);
357 if (count($passwords)) {
358 $override->extrapasswords = $passwords;
364 // Merge with quiz defaults.
365 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
366 foreach ($keys as $key) {
367 if (isset($override->{$key})) {
368 $quiz->{$key} = $override->{$key};
372 return $quiz;
376 * Delete all the attempts belonging to a quiz.
378 * @param object $quiz The quiz object.
380 function quiz_delete_all_attempts($quiz) {
381 global $CFG, $DB;
382 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
383 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
384 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
385 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
389 * Get the best current grade for a particular user in a quiz.
391 * @param object $quiz the quiz settings.
392 * @param int $userid the id of the user.
393 * @return float the user's current grade for this quiz, or null if this user does
394 * not have a grade on this quiz.
396 function quiz_get_best_grade($quiz, $userid) {
397 global $DB;
398 $grade = $DB->get_field('quiz_grades', 'grade',
399 array('quiz' => $quiz->id, 'userid' => $userid));
401 // Need to detect errors/no result, without catching 0 grades.
402 if ($grade === false) {
403 return null;
406 return $grade + 0; // Convert to number.
410 * Is this a graded quiz? If this method returns true, you can assume that
411 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
412 * divide by them).
414 * @param object $quiz a row from the quiz table.
415 * @return bool whether this is a graded quiz.
417 function quiz_has_grades($quiz) {
418 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
422 * Does this quiz allow multiple tries?
424 * @return bool
426 function quiz_allows_multiple_tries($quiz) {
427 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
428 return $bt->allows_multiple_submitted_responses();
432 * Return a small object with summary information about what a
433 * user has done with a given particular instance of this module
434 * Used for user activity reports.
435 * $return->time = the time they did it
436 * $return->info = a short text description
438 * @param object $course
439 * @param object $user
440 * @param object $mod
441 * @param object $quiz
442 * @return object|null
444 function quiz_user_outline($course, $user, $mod, $quiz) {
445 global $DB, $CFG;
446 require_once($CFG->libdir . '/gradelib.php');
447 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
449 if (empty($grades->items[0]->grades)) {
450 return null;
451 } else {
452 $grade = reset($grades->items[0]->grades);
455 $result = new stdClass();
456 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
458 // Datesubmitted == time created. dategraded == time modified or time overridden
459 // if grade was last modified by the user themselves use date graded. Otherwise use
460 // date submitted.
461 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
462 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
463 $result->time = $grade->dategraded;
464 } else {
465 $result->time = $grade->datesubmitted;
468 return $result;
472 * Print a detailed representation of what a user has done with
473 * a given particular instance of this module, for user activity reports.
475 * @param object $course
476 * @param object $user
477 * @param object $mod
478 * @param object $quiz
479 * @return bool
481 function quiz_user_complete($course, $user, $mod, $quiz) {
482 global $DB, $CFG, $OUTPUT;
483 require_once($CFG->libdir . '/gradelib.php');
484 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
486 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
487 if (!empty($grades->items[0]->grades)) {
488 $grade = reset($grades->items[0]->grades);
489 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
490 if ($grade->str_feedback) {
491 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
495 if ($attempts = $DB->get_records('quiz_attempts',
496 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
497 foreach ($attempts as $attempt) {
498 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
499 if ($attempt->state != quiz_attempt::FINISHED) {
500 echo quiz_attempt_state_name($attempt->state);
501 } else {
502 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
503 quiz_format_grade($quiz, $quiz->sumgrades);
505 echo ' - '.userdate($attempt->timemodified).'<br />';
507 } else {
508 print_string('noattempts', 'quiz');
511 return true;
515 * Quiz periodic clean-up tasks.
517 function quiz_cron() {
518 global $CFG;
520 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
521 mtrace('');
523 $timenow = time();
524 $overduehander = new mod_quiz_overdue_attempt_updater();
526 $processto = $timenow - get_config('quiz', 'graceperiodmin');
528 mtrace(' Looking for quiz overdue quiz attempts...');
530 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
532 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
534 // Run cron for our sub-plugin types.
535 cron_execute_plugin_type('quiz', 'quiz reports');
536 cron_execute_plugin_type('quizaccess', 'quiz access rules');
538 return true;
542 * @param int $quizid the quiz id.
543 * @param int $userid the userid.
544 * @param string $status 'all', 'finished' or 'unfinished' to control
545 * @param bool $includepreviews
546 * @return an array of all the user's attempts at this quiz. Returns an empty
547 * array if there are none.
549 function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
550 global $DB, $CFG;
551 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
552 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
553 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
554 // MDL-33048.
555 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
557 $params = array();
558 switch ($status) {
559 case 'all':
560 $statuscondition = '';
561 break;
563 case 'finished':
564 $statuscondition = ' AND state IN (:state1, :state2)';
565 $params['state1'] = quiz_attempt::FINISHED;
566 $params['state2'] = quiz_attempt::ABANDONED;
567 break;
569 case 'unfinished':
570 $statuscondition = ' AND state IN (:state1, :state2)';
571 $params['state1'] = quiz_attempt::IN_PROGRESS;
572 $params['state2'] = quiz_attempt::OVERDUE;
573 break;
576 $previewclause = '';
577 if (!$includepreviews) {
578 $previewclause = ' AND preview = 0';
581 $params['quizid'] = $quizid;
582 $params['userid'] = $userid;
583 return $DB->get_records_select('quiz_attempts',
584 'quiz = :quizid AND userid = :userid' . $previewclause . $statuscondition,
585 $params, 'attempt ASC');
589 * Return grade for given user or all users.
591 * @param int $quizid id of quiz
592 * @param int $userid optional user id, 0 means all users
593 * @return array array of grades, false if none. These are raw grades. They should
594 * be processed with quiz_format_grade for display.
596 function quiz_get_user_grades($quiz, $userid = 0) {
597 global $CFG, $DB;
599 $params = array($quiz->id);
600 $usertest = '';
601 if ($userid) {
602 $params[] = $userid;
603 $usertest = 'AND u.id = ?';
605 return $DB->get_records_sql("
606 SELECT
607 u.id,
608 u.id AS userid,
609 qg.grade AS rawgrade,
610 qg.timemodified AS dategraded,
611 MAX(qa.timefinish) AS datesubmitted
613 FROM {user} u
614 JOIN {quiz_grades} qg ON u.id = qg.userid
615 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
617 WHERE qg.quiz = ?
618 $usertest
619 GROUP BY u.id, qg.grade, qg.timemodified", $params);
623 * Round a grade to to the correct number of decimal places, and format it for display.
625 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
626 * @param float $grade The grade to round.
627 * @return float
629 function quiz_format_grade($quiz, $grade) {
630 if (is_null($grade)) {
631 return get_string('notyetgraded', 'quiz');
633 return format_float($grade, $quiz->decimalpoints);
637 * Round a grade to to the correct number of decimal places, and format it for display.
639 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
640 * @param float $grade The grade to round.
641 * @return float
643 function quiz_format_question_grade($quiz, $grade) {
644 if (empty($quiz->questiondecimalpoints)) {
645 $quiz->questiondecimalpoints = -1;
647 if ($quiz->questiondecimalpoints == -1) {
648 return format_float($grade, $quiz->decimalpoints);
649 } else {
650 return format_float($grade, $quiz->questiondecimalpoints);
655 * Update grades in central gradebook
657 * @category grade
658 * @param object $quiz the quiz settings.
659 * @param int $userid specific user only, 0 means all users.
660 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
662 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
663 global $CFG, $DB;
664 require_once($CFG->libdir . '/gradelib.php');
666 if ($quiz->grade == 0) {
667 quiz_grade_item_update($quiz);
669 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
670 quiz_grade_item_update($quiz, $grades);
672 } else if ($userid && $nullifnone) {
673 $grade = new stdClass();
674 $grade->userid = $userid;
675 $grade->rawgrade = null;
676 quiz_grade_item_update($quiz, $grade);
678 } else {
679 quiz_grade_item_update($quiz);
684 * Update all grades in gradebook.
686 function quiz_upgrade_grades() {
687 global $DB;
689 $sql = "SELECT COUNT('x')
690 FROM {quiz} a, {course_modules} cm, {modules} m
691 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
692 $count = $DB->count_records_sql($sql);
694 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
695 FROM {quiz} a, {course_modules} cm, {modules} m
696 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
697 $rs = $DB->get_recordset_sql($sql);
698 if ($rs->valid()) {
699 $pbar = new progress_bar('quizupgradegrades', 500, true);
700 $i=0;
701 foreach ($rs as $quiz) {
702 $i++;
703 upgrade_set_timeout(60*5); // Set up timeout, may also abort execution.
704 quiz_update_grades($quiz, 0, false);
705 $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
708 $rs->close();
712 * Create or update the grade item for given quiz
714 * @category grade
715 * @param object $quiz object with extra cmidnumber
716 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
717 * @return int 0 if ok, error code otherwise
719 function quiz_grade_item_update($quiz, $grades = null) {
720 global $CFG, $OUTPUT;
721 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
722 require_once($CFG->libdir . '/gradelib.php');
724 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
725 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
726 } else {
727 $params = array('itemname' => $quiz->name);
730 if ($quiz->grade > 0) {
731 $params['gradetype'] = GRADE_TYPE_VALUE;
732 $params['grademax'] = $quiz->grade;
733 $params['grademin'] = 0;
735 } else {
736 $params['gradetype'] = GRADE_TYPE_NONE;
739 // What this is trying to do:
740 // 1. If the quiz is set to not show grades while the quiz is still open,
741 // and is set to show grades after the quiz is closed, then create the
742 // grade_item with a show-after date that is the quiz close date.
743 // 2. If the quiz is set to not show grades at either of those times,
744 // create the grade_item as hidden.
745 // 3. If the quiz is set to show grades, create the grade_item visible.
746 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
747 mod_quiz_display_options::LATER_WHILE_OPEN);
748 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
749 mod_quiz_display_options::AFTER_CLOSE);
750 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
751 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
752 $params['hidden'] = 1;
754 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
755 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
756 if ($quiz->timeclose) {
757 $params['hidden'] = $quiz->timeclose;
758 } else {
759 $params['hidden'] = 1;
762 } else {
763 // Either
764 // a) both open and closed enabled
765 // b) open enabled, closed disabled - we can not "hide after",
766 // grades are kept visible even after closing.
767 $params['hidden'] = 0;
770 if (!$params['hidden']) {
771 // If the grade item is not hidden by the quiz logic, then we need to
772 // hide it if the quiz is hidden from students.
773 if (property_exists($quiz, 'visible')) {
774 // Saving the quiz form, and cm not yet updated in the database.
775 $params['hidden'] = !$quiz->visible;
776 } else {
777 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
778 $params['hidden'] = !$cm->visible;
782 if ($grades === 'reset') {
783 $params['reset'] = true;
784 $grades = null;
787 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
788 if (!empty($gradebook_grades->items)) {
789 $grade_item = $gradebook_grades->items[0];
790 if ($grade_item->locked) {
791 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
792 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
793 if (!$confirm_regrade) {
794 if (!AJAX_SCRIPT) {
795 $message = get_string('gradeitemislocked', 'grades');
796 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
797 '&amp;mode=overview';
798 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
799 echo $OUTPUT->box_start('generalbox', 'notice');
800 echo '<p>'. $message .'</p>';
801 echo $OUTPUT->container_start('buttons');
802 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
803 echo $OUTPUT->single_button($back_link, get_string('cancel'));
804 echo $OUTPUT->container_end();
805 echo $OUTPUT->box_end();
807 return GRADE_UPDATE_ITEM_LOCKED;
812 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
816 * Delete grade item for given quiz
818 * @category grade
819 * @param object $quiz object
820 * @return object quiz
822 function quiz_grade_item_delete($quiz) {
823 global $CFG;
824 require_once($CFG->libdir . '/gradelib.php');
826 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
827 null, array('deleted' => 1));
831 * This standard function will check all instances of this module
832 * and make sure there are up-to-date events created for each of them.
833 * If courseid = 0, then every quiz event in the site is checked, else
834 * only quiz events belonging to the course specified are checked.
835 * This function is used, in its new format, by restore_refresh_events()
837 * @param int $courseid
838 * @return bool
840 function quiz_refresh_events($courseid = 0) {
841 global $DB;
843 if ($courseid == 0) {
844 if (!$quizzes = $DB->get_records('quiz')) {
845 return true;
847 } else {
848 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
849 return true;
853 foreach ($quizzes as $quiz) {
854 quiz_update_events($quiz);
857 return true;
861 * Returns all quiz graded users since a given time for specified quiz
863 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
864 $courseid, $cmid, $userid = 0, $groupid = 0) {
865 global $CFG, $USER, $DB;
866 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
868 $course = get_course($courseid);
869 $modinfo = get_fast_modinfo($course);
871 $cm = $modinfo->cms[$cmid];
872 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
874 if ($userid) {
875 $userselect = "AND u.id = :userid";
876 $params['userid'] = $userid;
877 } else {
878 $userselect = '';
881 if ($groupid) {
882 $groupselect = 'AND gm.groupid = :groupid';
883 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
884 $params['groupid'] = $groupid;
885 } else {
886 $groupselect = '';
887 $groupjoin = '';
890 $params['timestart'] = $timestart;
891 $params['quizid'] = $quiz->id;
893 $ufields = user_picture::fields('u', null, 'useridagain');
894 if (!$attempts = $DB->get_records_sql("
895 SELECT qa.*,
896 {$ufields}
897 FROM {quiz_attempts} qa
898 JOIN {user} u ON u.id = qa.userid
899 $groupjoin
900 WHERE qa.timefinish > :timestart
901 AND qa.quiz = :quizid
902 AND qa.preview = 0
903 $userselect
904 $groupselect
905 ORDER BY qa.timefinish ASC", $params)) {
906 return;
909 $context = context_module::instance($cm->id);
910 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
911 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
912 $grader = has_capability('mod/quiz:viewreports', $context);
913 $groupmode = groups_get_activity_groupmode($cm, $course);
915 $usersgroups = null;
916 $aname = format_string($cm->name, true);
917 foreach ($attempts as $attempt) {
918 if ($attempt->userid != $USER->id) {
919 if (!$grader) {
920 // Grade permission required.
921 continue;
924 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
925 $usersgroups = groups_get_all_groups($course->id,
926 $attempt->userid, $cm->groupingid);
927 $usersgroups = array_keys($usersgroups);
928 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
929 continue;
934 $options = quiz_get_review_options($quiz, $attempt, $context);
936 $tmpactivity = new stdClass();
938 $tmpactivity->type = 'quiz';
939 $tmpactivity->cmid = $cm->id;
940 $tmpactivity->name = $aname;
941 $tmpactivity->sectionnum = $cm->sectionnum;
942 $tmpactivity->timestamp = $attempt->timefinish;
944 $tmpactivity->content = new stdClass();
945 $tmpactivity->content->attemptid = $attempt->id;
946 $tmpactivity->content->attempt = $attempt->attempt;
947 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
948 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
949 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
950 } else {
951 $tmpactivity->content->sumgrades = null;
952 $tmpactivity->content->maxgrade = null;
955 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
956 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
958 $activities[$index++] = $tmpactivity;
962 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
963 global $CFG, $OUTPUT;
965 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
967 echo '<tr><td class="userpicture" valign="top">';
968 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
969 echo '</td><td>';
971 if ($detail) {
972 $modname = $modnames[$activity->type];
973 echo '<div class="title">';
974 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
975 'class="icon" alt="' . $modname . '" />';
976 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
977 $activity->cmid . '">' . $activity->name . '</a>';
978 echo '</div>';
981 echo '<div class="grade">';
982 echo get_string('attempt', 'quiz', $activity->content->attempt);
983 if (isset($activity->content->maxgrade)) {
984 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
985 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
986 $activity->content->attemptid . '">' . $grades . '</a>)';
988 echo '</div>';
990 echo '<div class="user">';
991 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
992 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
993 '</a> - ' . userdate($activity->timestamp);
994 echo '</div>';
996 echo '</td></tr></table>';
998 return;
1002 * Pre-process the quiz options form data, making any necessary adjustments.
1003 * Called by add/update instance in this file.
1005 * @param object $quiz The variables set on the form.
1007 function quiz_process_options($quiz) {
1008 global $CFG;
1009 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1010 require_once($CFG->libdir . '/questionlib.php');
1012 $quiz->timemodified = time();
1014 // Quiz name.
1015 if (!empty($quiz->name)) {
1016 $quiz->name = trim($quiz->name);
1019 // Password field - different in form to stop browsers that remember passwords
1020 // getting confused.
1021 $quiz->password = $quiz->quizpassword;
1022 unset($quiz->quizpassword);
1024 // Quiz feedback.
1025 if (isset($quiz->feedbacktext)) {
1026 // Clean up the boundary text.
1027 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1028 if (empty($quiz->feedbacktext[$i]['text'])) {
1029 $quiz->feedbacktext[$i]['text'] = '';
1030 } else {
1031 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1035 // Check the boundary value is a number or a percentage, and in range.
1036 $i = 0;
1037 while (!empty($quiz->feedbackboundaries[$i])) {
1038 $boundary = trim($quiz->feedbackboundaries[$i]);
1039 if (!is_numeric($boundary)) {
1040 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1041 $boundary = trim(substr($boundary, 0, -1));
1042 if (is_numeric($boundary)) {
1043 $boundary = $boundary * $quiz->grade / 100.0;
1044 } else {
1045 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1049 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1050 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1052 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1053 return get_string('feedbackerrororder', 'quiz', $i + 1);
1055 $quiz->feedbackboundaries[$i] = $boundary;
1056 $i += 1;
1058 $numboundaries = $i;
1060 // Check there is nothing in the remaining unused fields.
1061 if (!empty($quiz->feedbackboundaries)) {
1062 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1063 if (!empty($quiz->feedbackboundaries[$i]) &&
1064 trim($quiz->feedbackboundaries[$i]) != '') {
1065 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1069 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1070 if (!empty($quiz->feedbacktext[$i]['text']) &&
1071 trim($quiz->feedbacktext[$i]['text']) != '') {
1072 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1075 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1076 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1077 $quiz->feedbackboundaries[$numboundaries] = 0;
1078 $quiz->feedbackboundarycount = $numboundaries;
1079 } else {
1080 $quiz->feedbackboundarycount = -1;
1083 // Combing the individual settings into the review columns.
1084 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1085 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1086 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1087 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1088 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1089 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1090 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1091 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1092 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1096 * Helper function for {@link quiz_process_options()}.
1097 * @param object $fromform the sumbitted form date.
1098 * @param string $field one of the review option field names.
1100 function quiz_review_option_form_to_db($fromform, $field) {
1101 static $times = array(
1102 'during' => mod_quiz_display_options::DURING,
1103 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1104 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1105 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1108 $review = 0;
1109 foreach ($times as $whenname => $when) {
1110 $fieldname = $field . $whenname;
1111 if (isset($fromform->$fieldname)) {
1112 $review |= $when;
1113 unset($fromform->$fieldname);
1117 return $review;
1121 * This function is called at the end of quiz_add_instance
1122 * and quiz_update_instance, to do the common processing.
1124 * @param object $quiz the quiz object.
1126 function quiz_after_add_or_update($quiz) {
1127 global $DB;
1128 $cmid = $quiz->coursemodule;
1130 // We need to use context now, so we need to make sure all needed info is already in db.
1131 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1132 $context = context_module::instance($cmid);
1134 // Save the feedback.
1135 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1137 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1138 $feedback = new stdClass();
1139 $feedback->quizid = $quiz->id;
1140 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1141 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1142 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1143 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1144 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1145 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1146 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1147 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1148 $quiz->feedbacktext[$i]['text']);
1149 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1150 array('id' => $feedback->id));
1153 // Store any settings belonging to the access rules.
1154 quiz_access_manager::save_settings($quiz);
1156 // Update the events relating to this quiz.
1157 quiz_update_events($quiz);
1159 // Update related grade item.
1160 quiz_grade_item_update($quiz);
1164 * This function updates the events associated to the quiz.
1165 * If $override is non-zero, then it updates only the events
1166 * associated with the specified override.
1168 * @uses QUIZ_MAX_EVENT_LENGTH
1169 * @param object $quiz the quiz object.
1170 * @param object optional $override limit to a specific override
1172 function quiz_update_events($quiz, $override = null) {
1173 global $DB;
1175 // Load the old events relating to this quiz.
1176 $conds = array('modulename'=>'quiz',
1177 'instance'=>$quiz->id);
1178 if (!empty($override)) {
1179 // Only load events for this override.
1180 $conds['groupid'] = isset($override->groupid)? $override->groupid : 0;
1181 $conds['userid'] = isset($override->userid)? $override->userid : 0;
1183 $oldevents = $DB->get_records('event', $conds);
1185 // Now make a todo list of all that needs to be updated.
1186 if (empty($override)) {
1187 // We are updating the primary settings for the quiz, so we
1188 // need to add all the overrides.
1189 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
1190 // As well as the original quiz (empty override).
1191 $overrides[] = new stdClass();
1192 } else {
1193 // Just do the one override.
1194 $overrides = array($override);
1197 foreach ($overrides as $current) {
1198 $groupid = isset($current->groupid)? $current->groupid : 0;
1199 $userid = isset($current->userid)? $current->userid : 0;
1200 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1201 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1203 // Only add open/close events for an override if they differ from the quiz default.
1204 $addopen = empty($current->id) || !empty($current->timeopen);
1205 $addclose = empty($current->id) || !empty($current->timeclose);
1207 if (!empty($quiz->coursemodule)) {
1208 $cmid = $quiz->coursemodule;
1209 } else {
1210 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1213 $event = new stdClass();
1214 $event->description = format_module_intro('quiz', $quiz, $cmid);
1215 // Events module won't show user events when the courseid is nonzero.
1216 $event->courseid = ($userid) ? 0 : $quiz->course;
1217 $event->groupid = $groupid;
1218 $event->userid = $userid;
1219 $event->modulename = 'quiz';
1220 $event->instance = $quiz->id;
1221 $event->timestart = $timeopen;
1222 $event->timeduration = max($timeclose - $timeopen, 0);
1223 $event->visible = instance_is_visible('quiz', $quiz);
1224 $event->eventtype = 'open';
1226 // Determine the event name.
1227 if ($groupid) {
1228 $params = new stdClass();
1229 $params->quiz = $quiz->name;
1230 $params->group = groups_get_group_name($groupid);
1231 if ($params->group === false) {
1232 // Group doesn't exist, just skip it.
1233 continue;
1235 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1236 } else if ($userid) {
1237 $params = new stdClass();
1238 $params->quiz = $quiz->name;
1239 $eventname = get_string('overrideusereventname', 'quiz', $params);
1240 } else {
1241 $eventname = $quiz->name;
1243 if ($addopen or $addclose) {
1244 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1245 // Single event for the whole quiz.
1246 if ($oldevent = array_shift($oldevents)) {
1247 $event->id = $oldevent->id;
1248 } else {
1249 unset($event->id);
1251 $event->name = $eventname;
1252 // The method calendar_event::create will reuse a db record if the id field is set.
1253 calendar_event::create($event);
1254 } else {
1255 // Separate start and end events.
1256 $event->timeduration = 0;
1257 if ($timeopen && $addopen) {
1258 if ($oldevent = array_shift($oldevents)) {
1259 $event->id = $oldevent->id;
1260 } else {
1261 unset($event->id);
1263 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
1264 // The method calendar_event::create will reuse a db record if the id field is set.
1265 calendar_event::create($event);
1267 if ($timeclose && $addclose) {
1268 if ($oldevent = array_shift($oldevents)) {
1269 $event->id = $oldevent->id;
1270 } else {
1271 unset($event->id);
1273 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1274 $event->timestart = $timeclose;
1275 $event->eventtype = 'close';
1276 calendar_event::create($event);
1282 // Delete any leftover events.
1283 foreach ($oldevents as $badevent) {
1284 $badevent = calendar_event::load($badevent);
1285 $badevent->delete();
1290 * List the actions that correspond to a view of this module.
1291 * This is used by the participation report.
1293 * Note: This is not used by new logging system. Event with
1294 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1295 * be considered as view action.
1297 * @return array
1299 function quiz_get_view_actions() {
1300 return array('view', 'view all', 'report', 'review');
1304 * List the actions that correspond to a post of this module.
1305 * This is used by the participation report.
1307 * Note: This is not used by new logging system. Event with
1308 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1309 * will be considered as post action.
1311 * @return array
1313 function quiz_get_post_actions() {
1314 return array('attempt', 'close attempt', 'preview', 'editquestions',
1315 'delete attempt', 'manualgrade');
1319 * @param array $questionids of question ids.
1320 * @return bool whether any of these questions are used by any instance of this module.
1322 function quiz_questions_in_use($questionids) {
1323 global $DB, $CFG;
1324 require_once($CFG->libdir . '/questionlib.php');
1325 list($test, $params) = $DB->get_in_or_equal($questionids);
1326 return $DB->record_exists_select('quiz_slots',
1327 'questionid ' . $test, $params) || question_engine::questions_in_use(
1328 $questionids, new qubaid_join('{quiz_attempts} quiza',
1329 'quiza.uniqueid', 'quiza.preview = 0'));
1333 * Implementation of the function for printing the form elements that control
1334 * whether the course reset functionality affects the quiz.
1336 * @param $mform the course reset form that is being built.
1338 function quiz_reset_course_form_definition($mform) {
1339 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1340 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1341 get_string('removeallquizattempts', 'quiz'));
1345 * Course reset form defaults.
1346 * @return array the defaults.
1348 function quiz_reset_course_form_defaults($course) {
1349 return array('reset_quiz_attempts' => 1);
1353 * Removes all grades from gradebook
1355 * @param int $courseid
1356 * @param string optional type
1358 function quiz_reset_gradebook($courseid, $type='') {
1359 global $CFG, $DB;
1361 $quizzes = $DB->get_records_sql("
1362 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1363 FROM {modules} m
1364 JOIN {course_modules} cm ON m.id = cm.module
1365 JOIN {quiz} q ON cm.instance = q.id
1366 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1368 foreach ($quizzes as $quiz) {
1369 quiz_grade_item_update($quiz, 'reset');
1374 * Actual implementation of the reset course functionality, delete all the
1375 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1376 * set and true.
1378 * Also, move the quiz open and close dates, if the course start date is changing.
1380 * @param object $data the data submitted from the reset course.
1381 * @return array status array
1383 function quiz_reset_userdata($data) {
1384 global $CFG, $DB;
1385 require_once($CFG->libdir . '/questionlib.php');
1387 $componentstr = get_string('modulenameplural', 'quiz');
1388 $status = array();
1390 // Delete attempts.
1391 if (!empty($data->reset_quiz_attempts)) {
1392 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1393 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1394 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1395 array('quizcourseid' => $data->courseid)));
1397 $DB->delete_records_select('quiz_attempts',
1398 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1399 $status[] = array(
1400 'component' => $componentstr,
1401 'item' => get_string('attemptsdeleted', 'quiz'),
1402 'error' => false);
1404 // Remove all grades from gradebook.
1405 $DB->delete_records_select('quiz_grades',
1406 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1407 if (empty($data->reset_gradebook_grades)) {
1408 quiz_reset_gradebook($data->courseid);
1410 $status[] = array(
1411 'component' => $componentstr,
1412 'item' => get_string('gradesdeleted', 'quiz'),
1413 'error' => false);
1416 // Updating dates - shift may be negative too.
1417 if ($data->timeshift) {
1418 $DB->execute("UPDATE {quiz_overrides}
1419 SET timeopen = timeopen + ?
1420 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1421 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1422 $DB->execute("UPDATE {quiz_overrides}
1423 SET timeclose = timeclose + ?
1424 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1425 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1427 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1428 $data->timeshift, $data->courseid);
1430 $status[] = array(
1431 'component' => $componentstr,
1432 'item' => get_string('openclosedatesupdated', 'quiz'),
1433 'error' => false);
1436 return $status;
1440 * Prints quiz summaries on MyMoodle Page
1441 * @param arry $courses
1442 * @param array $htmlarray
1444 function quiz_print_overview($courses, &$htmlarray) {
1445 global $USER, $CFG;
1446 // These next 6 Lines are constant in all modules (just change module name).
1447 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1448 return array();
1451 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1452 return;
1455 // Fetch some language strings outside the main loop.
1456 $strquiz = get_string('modulename', 'quiz');
1457 $strnoattempts = get_string('noattempts', 'quiz');
1459 // We want to list quizzes that are currently available, and which have a close date.
1460 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1461 $now = time();
1462 foreach ($quizzes as $quiz) {
1463 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1464 // Give a link to the quiz, and the deadline.
1465 $str = '<div class="quiz overview">' .
1466 '<div class="name">' . $strquiz . ': <a ' .
1467 ($quiz->visible ? '' : ' class="dimmed"') .
1468 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1469 $quiz->coursemodule . '">' .
1470 $quiz->name . '</a></div>';
1471 $str .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1472 userdate($quiz->timeclose)) . '</div>';
1474 // Now provide more information depending on the uers's role.
1475 $context = context_module::instance($quiz->coursemodule);
1476 if (has_capability('mod/quiz:viewreports', $context)) {
1477 // For teacher-like people, show a summary of the number of student attempts.
1478 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1479 // fields set to make the following call work.
1480 $str .= '<div class="info">' .
1481 quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1482 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'),
1483 $context)) { // Student
1484 // For student-like people, tell them how many attempts they have made.
1485 if (isset($USER->id) &&
1486 ($attempts = quiz_get_user_attempts($quiz->id, $USER->id))) {
1487 $numattempts = count($attempts);
1488 $str .= '<div class="info">' .
1489 get_string('numattemptsmade', 'quiz', $numattempts) . '</div>';
1490 } else {
1491 $str .= '<div class="info">' . $strnoattempts . '</div>';
1493 } else {
1494 // For ayone else, there is no point listing this quiz, so stop processing.
1495 continue;
1498 // Add the output for this quiz to the rest.
1499 $str .= '</div>';
1500 if (empty($htmlarray[$quiz->course]['quiz'])) {
1501 $htmlarray[$quiz->course]['quiz'] = $str;
1502 } else {
1503 $htmlarray[$quiz->course]['quiz'] .= $str;
1510 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1511 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1513 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1514 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1515 * $cm->groupingid fields are used at the moment.
1516 * @param bool $returnzero if false (default), when no attempts have been
1517 * made '' is returned instead of 'Attempts: 0'.
1518 * @param int $currentgroup if there is a concept of current group where this method is being called
1519 * (e.g. a report) pass it in here. Default 0 which means no current group.
1520 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1521 * "Attemtps 123 (45 from this group)".
1523 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1524 global $DB, $USER;
1525 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1526 if ($numattempts || $returnzero) {
1527 if (groups_get_activity_groupmode($cm)) {
1528 $a = new stdClass();
1529 $a->total = $numattempts;
1530 if ($currentgroup) {
1531 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1532 '{quiz_attempts} qa JOIN ' .
1533 '{groups_members} gm ON qa.userid = gm.userid ' .
1534 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1535 array($quiz->id, $currentgroup));
1536 return get_string('attemptsnumthisgroup', 'quiz', $a);
1537 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1538 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1539 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1540 '{quiz_attempts} qa JOIN ' .
1541 '{groups_members} gm ON qa.userid = gm.userid ' .
1542 'WHERE quiz = ? AND preview = 0 AND ' .
1543 "groupid $usql", array_merge(array($quiz->id), $params));
1544 return get_string('attemptsnumyourgroups', 'quiz', $a);
1547 return get_string('attemptsnum', 'quiz', $numattempts);
1549 return '';
1553 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1554 * to the quiz reports.
1556 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1557 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1558 * $cm->groupingid fields are used at the moment.
1559 * @param object $context the quiz context.
1560 * @param bool $returnzero if false (default), when no attempts have been made
1561 * '' is returned instead of 'Attempts: 0'.
1562 * @param int $currentgroup if there is a concept of current group where this method is being called
1563 * (e.g. a report) pass it in here. Default 0 which means no current group.
1564 * @return string HTML fragment for the link.
1566 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1567 $currentgroup = 0) {
1568 global $CFG;
1569 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1570 if (!$summary) {
1571 return '';
1574 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1575 $url = new moodle_url('/mod/quiz/report.php', array(
1576 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1577 return html_writer::link($url, $summary);
1581 * @param string $feature FEATURE_xx constant for requested feature
1582 * @return bool True if quiz supports feature
1584 function quiz_supports($feature) {
1585 switch($feature) {
1586 case FEATURE_GROUPS: return true;
1587 case FEATURE_GROUPINGS: return true;
1588 case FEATURE_GROUPMEMBERSONLY: return true;
1589 case FEATURE_MOD_INTRO: return true;
1590 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1591 case FEATURE_GRADE_HAS_GRADE: return true;
1592 case FEATURE_GRADE_OUTCOMES: return true;
1593 case FEATURE_BACKUP_MOODLE2: return true;
1594 case FEATURE_SHOW_DESCRIPTION: return true;
1595 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1596 case FEATURE_USES_QUESTIONS: return true;
1598 default: return null;
1603 * @return array all other caps used in module
1605 function quiz_get_extra_capabilities() {
1606 global $CFG;
1607 require_once($CFG->libdir . '/questionlib.php');
1608 $caps = question_get_all_capabilities();
1609 $caps[] = 'moodle/site:accessallgroups';
1610 return $caps;
1614 * This function extends the settings navigation block for the site.
1616 * It is safe to rely on PAGE here as we will only ever be within the module
1617 * context when this is called
1619 * @param settings_navigation $settings
1620 * @param navigation_node $quiznode
1621 * @return void
1623 function quiz_extend_settings_navigation($settings, $quiznode) {
1624 global $PAGE, $CFG;
1626 // Require {@link questionlib.php}
1627 // Included here as we only ever want to include this file if we really need to.
1628 require_once($CFG->libdir . '/questionlib.php');
1630 // We want to add these new nodes after the Edit settings node, and before the
1631 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1632 $keys = $quiznode->get_children_key_list();
1633 $beforekey = null;
1634 $i = array_search('modedit', $keys);
1635 if ($i === false and array_key_exists(0, $keys)) {
1636 $beforekey = $keys[0];
1637 } else if (array_key_exists($i + 1, $keys)) {
1638 $beforekey = $keys[$i + 1];
1641 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1642 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1643 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1644 new moodle_url($url, array('mode'=>'group')),
1645 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1646 $quiznode->add_node($node, $beforekey);
1648 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1649 new moodle_url($url, array('mode'=>'user')),
1650 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1651 $quiznode->add_node($node, $beforekey);
1654 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1655 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1656 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1657 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1658 new pix_icon('t/edit', ''));
1659 $quiznode->add_node($node, $beforekey);
1662 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1663 $url = new moodle_url('/mod/quiz/startattempt.php',
1664 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1665 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1666 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1667 new pix_icon('i/preview', ''));
1668 $quiznode->add_node($node, $beforekey);
1671 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1672 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1673 $reportlist = quiz_report_list($PAGE->cm->context);
1675 $url = new moodle_url('/mod/quiz/report.php',
1676 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1677 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1678 navigation_node::TYPE_SETTING,
1679 null, null, new pix_icon('i/report', '')), $beforekey);
1681 foreach ($reportlist as $report) {
1682 $url = new moodle_url('/mod/quiz/report.php',
1683 array('id' => $PAGE->cm->id, 'mode' => $report));
1684 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1685 navigation_node::TYPE_SETTING,
1686 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1690 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1694 * Serves the quiz files.
1696 * @package mod_quiz
1697 * @category files
1698 * @param stdClass $course course object
1699 * @param stdClass $cm course module object
1700 * @param stdClass $context context object
1701 * @param string $filearea file area
1702 * @param array $args extra arguments
1703 * @param bool $forcedownload whether or not force download
1704 * @param array $options additional options affecting the file serving
1705 * @return bool false if file not found, does not return if found - justsend the file
1707 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1708 global $CFG, $DB;
1710 if ($context->contextlevel != CONTEXT_MODULE) {
1711 return false;
1714 require_login($course, false, $cm);
1716 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1717 return false;
1720 // The 'intro' area is served by pluginfile.php.
1721 $fileareas = array('feedback');
1722 if (!in_array($filearea, $fileareas)) {
1723 return false;
1726 $feedbackid = (int)array_shift($args);
1727 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1728 return false;
1731 $fs = get_file_storage();
1732 $relativepath = implode('/', $args);
1733 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1734 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1735 return false;
1737 send_stored_file($file, 0, 0, true, $options);
1741 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1742 * a question in a question_attempt when that attempt is a quiz attempt.
1744 * @package mod_quiz
1745 * @category files
1746 * @param stdClass $course course settings object
1747 * @param stdClass $context context object
1748 * @param string $component the name of the component we are serving files for.
1749 * @param string $filearea the name of the file area.
1750 * @param int $qubaid the attempt usage id.
1751 * @param int $slot the id of a question in this quiz attempt.
1752 * @param array $args the remaining bits of the file path.
1753 * @param bool $forcedownload whether the user must be forced to download the file.
1754 * @param array $options additional options affecting the file serving
1755 * @return bool false if file not found, does not return if found - justsend the file
1757 function quiz_question_pluginfile($course, $context, $component,
1758 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
1759 global $CFG;
1760 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1762 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1763 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1765 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1766 // In the middle of an attempt.
1767 if (!$attemptobj->is_preview_user()) {
1768 $attemptobj->require_capability('mod/quiz:attempt');
1770 $isreviewing = false;
1772 } else {
1773 // Reviewing an attempt.
1774 $attemptobj->check_review_capability();
1775 $isreviewing = true;
1778 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1779 $component, $filearea, $args, $forcedownload)) {
1780 send_file_not_found();
1783 $fs = get_file_storage();
1784 $relativepath = implode('/', $args);
1785 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1786 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1787 send_file_not_found();
1790 send_stored_file($file, 0, 0, $forcedownload, $options);
1794 * Return a list of page types
1795 * @param string $pagetype current page type
1796 * @param stdClass $parentcontext Block's parent context
1797 * @param stdClass $currentcontext Current context of block
1799 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1800 $module_pagetype = array(
1801 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1802 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1803 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1804 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1805 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1806 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1807 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1809 return $module_pagetype;
1813 * @return the options for quiz navigation.
1815 function quiz_get_navigation_options() {
1816 return array(
1817 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1818 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')