2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of functions for the quiz module.
20 * This contains functions that are called also from outside the quiz module
21 * Functions that are only called by the quiz module itself are in {@link locallib.php}
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 require_once($CFG->libdir . '/eventslib.php');
33 require_once($CFG->dirroot . '/calendar/lib.php');
37 * Option controlling what options are offered on the quiz settings form.
39 define('QUIZ_MAX_ATTEMPT_OPTION', 10);
40 define('QUIZ_MAX_QPP_OPTION', 50);
41 define('QUIZ_MAX_DECIMAL_OPTION', 5);
42 define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
46 * If start and end date for the quiz are more than this many seconds apart
47 * they will be represented by two separate events in the calendar
49 define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days
52 * Given an object containing all the necessary data,
53 * (defined by the form in mod_form.php) this function
54 * will create a new instance and return the id number
55 * of the new instance.
57 * @param object $quiz the data that came from the form.
58 * @return mixed the id of the new instance on success,
59 * false or a string error message on failure.
61 function quiz_add_instance($quiz) {
63 $cmid = $quiz->coursemodule;
65 // Process the options from the form.
66 $quiz->created = time();
67 $quiz->questions = '';
68 $result = quiz_process_options($quiz);
69 if ($result && is_string($result)) {
73 // Try to store it in the database.
74 $quiz->id = $DB->insert_record('quiz', $quiz);
76 // Do the processing required after an add or an update.
77 quiz_after_add_or_update($quiz);
83 * Given an object containing all the necessary data,
84 * (defined by the form in mod_form.php) this function
85 * will update an existing instance with new data.
87 * @param object $quiz the data that came from the form.
88 * @return mixed true on success, false or a string error message on failure.
90 function quiz_update_instance($quiz, $mform) {
93 // Process the options from the form.
94 $result = quiz_process_options($quiz);
95 if ($result && is_string($result)) {
99 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
101 // Repaginate, if asked to.
102 if (!$quiz->shufflequestions && !empty($quiz->repaginatenow)) {
103 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
104 $quiz->questions = quiz_repaginate(quiz_clean_layout($oldquiz->questions, true),
105 $quiz->questionsperpage);
107 unset($quiz->repaginatenow);
109 // Update the database.
110 $quiz->id = $quiz->instance;
111 $DB->update_record('quiz', $quiz);
113 // Do the processing required after an add or an update.
114 quiz_after_add_or_update($quiz);
116 if ($oldquiz->grademethod != $quiz->grademethod) {
117 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
118 $quiz->sumgrades = $oldquiz->sumgrades;
119 $quiz->grade = $oldquiz->grade;
120 quiz_update_all_final_grades($quiz);
121 quiz_update_grades($quiz);
124 // Delete any previous preview attempts
125 quiz_delete_previews($quiz);
131 * Given an ID of an instance of this module,
132 * this function will permanently delete the instance
133 * and any data that depends on it.
135 * @param int $id the id of the quiz to delete.
136 * @return bool success or failure.
138 function quiz_delete_instance($id) {
141 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
143 quiz_delete_all_attempts($quiz);
144 quiz_delete_all_overrides($quiz);
146 $DB->delete_records('quiz_question_instances', array('quiz' => $quiz->id));
147 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
149 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
150 foreach ($events as $event) {
151 $event = calendar_event::load($event);
155 quiz_grade_item_delete($quiz);
156 $DB->delete_records('quiz', array('id' => $quiz->id));
162 * Deletes a quiz override from the database and clears any corresponding calendar events
164 * @param object $quiz The quiz object.
165 * @param int $overrideid The id of the override being deleted
166 * @return bool true on success
168 function quiz_delete_override($quiz, $overrideid) {
171 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
174 $events = $DB->get_records('event', array('modulename' => 'quiz',
175 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
176 'userid' => (int)$override->userid));
177 foreach ($events as $event) {
178 $eventold = calendar_event::load($event);
182 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
187 * Deletes all quiz overrides from the database and clears any corresponding calendar events
189 * @param object $quiz The quiz object.
191 function quiz_delete_all_overrides($quiz) {
194 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
195 foreach ($overrides as $override) {
196 quiz_delete_override($quiz, $override->id);
201 * Updates a quiz object with override information for a user.
203 * Algorithm: For each quiz setting, if there is a matching user-specific override,
204 * then use that otherwise, if there are group-specific overrides, return the most
205 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
207 * Special case: if there is more than one password that applies to the user, then
208 * quiz->extrapasswords will contain an array of strings giving the remaining
211 * @param object $quiz The quiz object.
212 * @param int $userid The userid.
213 * @return object $quiz The updated quiz object.
215 function quiz_update_effective_access($quiz, $userid) {
218 // check for user override
219 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
222 $override = new stdClass();
223 $override->timeopen = null;
224 $override->timeclose = null;
225 $override->timelimit = null;
226 $override->attempts = null;
227 $override->password = null;
230 // check for group overrides
231 $groupings = groups_get_user_groups($quiz->course, $userid);
233 if (!empty($groupings[0])) {
234 // Select all overrides that apply to the User's groups
235 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
236 $sql = "SELECT * FROM {quiz_overrides}
237 WHERE groupid $extra AND quiz = ?";
238 $params[] = $quiz->id;
239 $records = $DB->get_records_sql($sql, $params);
241 // Combine the overrides
246 $passwords = array();
248 foreach ($records as $gpoverride) {
249 if (isset($gpoverride->timeopen)) {
250 $opens[] = $gpoverride->timeopen;
252 if (isset($gpoverride->timeclose)) {
253 $closes[] = $gpoverride->timeclose;
255 if (isset($gpoverride->timelimit)) {
256 $limits[] = $gpoverride->timelimit;
258 if (isset($gpoverride->attempts)) {
259 $attempts[] = $gpoverride->attempts;
261 if (isset($gpoverride->password)) {
262 $passwords[] = $gpoverride->password;
265 // If there is a user override for a setting, ignore the group override
266 if (is_null($override->timeopen) && count($opens)) {
267 $override->timeopen = min($opens);
269 if (is_null($override->timeclose) && count($closes)) {
270 $override->timeclose = max($closes);
272 if (is_null($override->timelimit) && count($limits)) {
273 $override->timelimit = max($limits);
275 if (is_null($override->attempts) && count($attempts)) {
276 $override->attempts = max($attempts);
278 if (is_null($override->password) && count($passwords)) {
279 $override->password = array_shift($passwords);
280 if (count($passwords)) {
281 $override->extrapasswords = $passwords;
287 // merge with quiz defaults
288 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
289 foreach ($keys as $key) {
290 if (isset($override->{$key})) {
291 $quiz->{$key} = $override->{$key};
299 * Delete all the attempts belonging to a quiz.
301 * @param object $quiz The quiz object.
303 function quiz_delete_all_attempts($quiz) {
305 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
306 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
307 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
308 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
312 * Get the best current grade for a particular user in a quiz.
314 * @param object $quiz the quiz settings.
315 * @param int $userid the id of the user.
316 * @return float the user's current grade for this quiz, or null if this user does
317 * not have a grade on this quiz.
319 function quiz_get_best_grade($quiz, $userid) {
321 $grade = $DB->get_field('quiz_grades', 'grade',
322 array('quiz' => $quiz->id, 'userid' => $userid));
324 // Need to detect errors/no result, without catching 0 grades.
325 if ($grade === false) {
329 return $grade + 0; // Convert to number.
333 * Is this a graded quiz? If this method returns true, you can assume that
334 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
337 * @param object $quiz a row from the quiz table.
338 * @return bool whether this is a graded quiz.
340 function quiz_has_grades($quiz) {
341 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
345 * Return a small object with summary information about what a
346 * user has done with a given particular instance of this module
347 * Used for user activity reports.
348 * $return->time = the time they did it
349 * $return->info = a short text description
351 * @param object $course
352 * @param object $user
354 * @param object $quiz
355 * @return object|null
357 function quiz_user_outline($course, $user, $mod, $quiz) {
359 require_once("$CFG->libdir/gradelib.php");
360 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
362 if (empty($grades->items[0]->grades)) {
365 $grade = reset($grades->items[0]->grades);
368 $result = new stdClass();
369 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
371 //datesubmitted == time created. dategraded == time modified or time overridden
372 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
373 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
374 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
375 $result->time = $grade->dategraded;
377 $result->time = $grade->datesubmitted;
384 * Print a detailed representation of what a user has done with
385 * a given particular instance of this module, for user activity reports.
388 * @param object $course
389 * @param object $user
391 * @param object $quiz
394 function quiz_user_complete($course, $user, $mod, $quiz) {
395 global $DB, $CFG, $OUTPUT;
396 require_once("$CFG->libdir/gradelib.php");
398 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
399 if (!empty($grades->items[0]->grades)) {
400 $grade = reset($grades->items[0]->grades);
401 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
402 if ($grade->str_feedback) {
403 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
407 if ($attempts = $DB->get_records('quiz_attempts',
408 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
409 foreach ($attempts as $attempt) {
410 echo get_string('attempt', 'quiz').' '.$attempt->attempt.': ';
411 if ($attempt->timefinish == 0) {
412 print_string('unfinished');
414 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
415 quiz_format_grade($quiz, $quiz->sumgrades);
417 echo ' - '.userdate($attempt->timemodified).'<br />';
420 print_string('noattempts', 'quiz');
427 * Function to be run periodically according to the moodle cron
428 * This function searches for things that need to be done, such
429 * as sending out mail, toggling flags etc ...
433 function quiz_cron() {
438 * @param int $quizid the quiz id.
439 * @param int $userid the userid.
440 * @param string $status 'all', 'finished' or 'unfinished' to control
441 * @param bool $includepreviews
442 * @return an array of all the user's attempts at this quiz. Returns an empty
443 * array if there are none.
445 function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
447 $status_condition = array(
449 'finished' => ' AND timefinish > 0',
450 'unfinished' => ' AND timefinish = 0'
453 if (!$includepreviews) {
454 $previewclause = ' AND preview = 0';
456 return $DB->get_records_select('quiz_attempts',
457 'quiz = ? AND userid = ?' . $previewclause . $status_condition[$status],
458 array($quizid, $userid), 'attempt ASC');
462 * Return grade for given user or all users.
464 * @param int $quizid id of quiz
465 * @param int $userid optional user id, 0 means all users
466 * @return array array of grades, false if none. These are raw grades. They should
467 * be processed with quiz_format_grade for display.
469 function quiz_get_user_grades($quiz, $userid = 0) {
472 $params = array($quiz->id);
476 $usertest = 'AND u.id = ?';
478 return $DB->get_records_sql("
482 qg.grade AS rawgrade,
483 qg.timemodified AS dategraded,
484 MAX(qa.timefinish) AS datesubmitted
487 JOIN {quiz_grades} qg ON u.id = qg.userid
488 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
492 GROUP BY u.id, qg.grade, qg.timemodified", $params);
496 * Round a grade to to the correct number of decimal places, and format it for display.
498 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
499 * @param float $grade The grade to round.
502 function quiz_format_grade($quiz, $grade) {
503 if (is_null($grade)) {
504 return get_string('notyetgraded', 'quiz');
506 return format_float($grade, $quiz->decimalpoints);
510 * Round a grade to to the correct number of decimal places, and format it for display.
512 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
513 * @param float $grade The grade to round.
516 function quiz_format_question_grade($quiz, $grade) {
517 if (empty($quiz->questiondecimalpoints)) {
518 $quiz->questiondecimalpoints = -1;
520 if ($quiz->questiondecimalpoints == -1) {
521 return format_float($grade, $quiz->decimalpoints);
523 return format_float($grade, $quiz->questiondecimalpoints);
528 * Update grades in central gradebook
530 * @param object $quiz the quiz settings.
531 * @param int $userid specific user only, 0 means all users.
533 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
535 require_once($CFG->libdir.'/gradelib.php');
537 if ($quiz->grade == 0) {
538 quiz_grade_item_update($quiz);
540 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
541 quiz_grade_item_update($quiz, $grades);
543 } else if ($userid && $nullifnone) {
544 $grade = new stdClass();
545 $grade->userid = $userid;
546 $grade->rawgrade = null;
547 quiz_grade_item_update($quiz, $grade);
550 quiz_grade_item_update($quiz);
555 * Update all grades in gradebook.
557 function quiz_upgrade_grades() {
560 $sql = "SELECT COUNT('x')
561 FROM {quiz} a, {course_modules} cm, {modules} m
562 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
563 $count = $DB->count_records_sql($sql);
565 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
566 FROM {quiz} a, {course_modules} cm, {modules} m
567 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
568 $rs = $DB->get_recordset_sql($sql);
570 $pbar = new progress_bar('quizupgradegrades', 500, true);
572 foreach ($rs as $quiz) {
574 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
575 quiz_update_grades($quiz, 0, false);
576 $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
583 * Create grade item for given quiz
585 * @param object $quiz object with extra cmidnumber
586 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
587 * @return int 0 if ok, error code otherwise
589 function quiz_grade_item_update($quiz, $grades = null) {
590 global $CFG, $OUTPUT;
591 require_once($CFG->libdir.'/gradelib.php');
593 if (array_key_exists('cmidnumber', $quiz)) { // may not be always present
594 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
596 $params = array('itemname' => $quiz->name);
599 if ($quiz->grade > 0) {
600 $params['gradetype'] = GRADE_TYPE_VALUE;
601 $params['grademax'] = $quiz->grade;
602 $params['grademin'] = 0;
605 $params['gradetype'] = GRADE_TYPE_NONE;
608 // description by TJ:
609 // 1. If the quiz is set to not show grades while the quiz is still open,
610 // and is set to show grades after the quiz is closed, then create the
611 // grade_item with a show-after date that is the quiz close date.
612 // 2. If the quiz is set to not show grades at either of those times,
613 // create the grade_item as hidden.
614 // 3. If the quiz is set to show grades, create the grade_item visible.
615 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
616 mod_quiz_display_options::LATER_WHILE_OPEN);
617 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
618 mod_quiz_display_options::AFTER_CLOSE);
619 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
620 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
621 $params['hidden'] = 1;
623 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
624 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
625 if ($quiz->timeclose) {
626 $params['hidden'] = $quiz->timeclose;
628 $params['hidden'] = 1;
632 // a) both open and closed enabled
633 // b) open enabled, closed disabled - we can not "hide after",
634 // grades are kept visible even after closing
635 $params['hidden'] = 0;
638 if ($grades === 'reset') {
639 $params['reset'] = true;
643 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
644 if (!empty($gradebook_grades->items)) {
645 $grade_item = $gradebook_grades->items[0];
646 if ($grade_item->locked) {
647 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
648 if (!$confirm_regrade) {
649 $message = get_string('gradeitemislocked', 'grades');
650 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
651 '&mode=overview';
652 $regrade_link = qualified_me() . '&confirm_regrade=1';
653 echo $OUTPUT->box_start('generalbox', 'notice');
654 echo '<p>'. $message .'</p>';
655 echo $OUTPUT->container_start('buttons');
656 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
657 echo $OUTPUT->single_button($back_link, get_string('cancel'));
658 echo $OUTPUT->container_end();
659 echo $OUTPUT->box_end();
661 return GRADE_UPDATE_ITEM_LOCKED;
666 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
670 * Delete grade item for given quiz
672 * @param object $quiz object
673 * @return object quiz
675 function quiz_grade_item_delete($quiz) {
677 require_once($CFG->libdir . '/gradelib.php');
679 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
680 null, array('deleted' => 1));
684 * Returns an array of users who have data in a given quiz
686 * @todo: deprecated - to be deleted in 2.2
688 * @param int $quizid the quiz id.
689 * @return array of userids.
691 function quiz_get_participants($quizid) {
694 return $DB->get_records_sql('
695 SELECT DISTINCT userid, userid
696 JOIN {quiz_attempts} qa
697 WHERE a.quiz = ?', array($quizid));
701 * This standard function will check all instances of this module
702 * and make sure there are up-to-date events created for each of them.
703 * If courseid = 0, then every quiz event in the site is checked, else
704 * only quiz events belonging to the course specified are checked.
705 * This function is used, in its new format, by restore_refresh_events()
707 * @param int $courseid
710 function quiz_refresh_events($courseid = 0) {
713 if ($courseid == 0) {
714 if (!$quizzes = $DB->get_records('quiz')) {
718 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
723 foreach ($quizzes as $quiz) {
724 quiz_update_events($quiz);
731 * Returns all quiz graded users since a given time for specified quiz
733 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
734 $courseid, $cmid, $userid = 0, $groupid = 0) {
735 global $CFG, $COURSE, $USER, $DB;
736 require_once('locallib.php');
738 if ($COURSE->id == $courseid) {
741 $course = $DB->get_record('course', array('id' => $courseid));
744 $modinfo =& get_fast_modinfo($course);
746 $cm = $modinfo->cms[$cmid];
747 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
750 $userselect = "AND u.id = :userid";
751 $params['userid'] = $userid;
757 $groupselect = 'AND gm.groupid = :groupid';
758 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
759 $params['groupid'] = $groupid;
765 $params['timestart'] = $timestart;
766 $params['quizid'] = $quiz->id;
768 if (!$attempts = $DB->get_records_sql("
770 u.firstname, u.lastname, u.email, u.picture, u.imagealt
771 FROM {quiz_attempts} qa
772 JOIN {user} u ON u.id = qa.userid
774 WHERE qa.timefinish > :timestart
775 AND qa.quiz = :quizid
779 ORDER BY qa.timefinish ASC", $params)) {
783 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
784 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
785 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
786 $grader = has_capability('mod/quiz:viewreports', $context);
787 $groupmode = groups_get_activity_groupmode($cm, $course);
789 if (is_null($modinfo->groups)) {
790 // load all my groups and cache it in modinfo
791 $modinfo->groups = groups_get_user_groups($course->id);
795 $aname = format_string($cm->name, true);
796 foreach ($attempts as $attempt) {
797 if ($attempt->userid != $USER->id) {
799 // Grade permission required
803 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
804 if (is_null($usersgroups)) {
805 $usersgroups = groups_get_all_groups($course->id,
806 $attempt->userid, $cm->groupingid);
807 if (is_array($usersgroups)) {
808 $usersgroups = array_keys($usersgroups);
810 $usersgroups = array();
813 if (!array_intersect($usersgroups, $modinfo->groups[$cm->id])) {
819 $options = quiz_get_review_options($quiz, $attempt, $context);
821 $tmpactivity = new stdClass();
823 $tmpactivity->type = 'quiz';
824 $tmpactivity->cmid = $cm->id;
825 $tmpactivity->name = $aname;
826 $tmpactivity->sectionnum = $cm->sectionnum;
827 $tmpactivity->timestamp = $attempt->timefinish;
829 $tmpactivity->content->attemptid = $attempt->id;
830 $tmpactivity->content->attempt = $attempt->attempt;
831 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
832 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
833 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
835 $tmpactivity->content->sumgrades = null;
836 $tmpactivity->content->maxgrade = null;
839 $tmpactivity->user->id = $attempt->userid;
840 $tmpactivity->user->firstname = $attempt->firstname;
841 $tmpactivity->user->lastname = $attempt->lastname;
842 $tmpactivity->user->fullname = fullname($attempt, $viewfullnames);
843 $tmpactivity->user->picture = $attempt->picture;
844 $tmpactivity->user->imagealt = $attempt->imagealt;
845 $tmpactivity->user->email = $attempt->email;
847 $activities[$index++] = $tmpactivity;
851 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
852 global $CFG, $OUTPUT;
854 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
856 echo '<tr><td class="userpicture" valign="top">';
857 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
861 $modname = $modnames[$activity->type];
862 echo '<div class="title">';
863 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
864 'class="icon" alt="' . $modname . '" />';
865 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
866 $activity->cmid . '">' . $activity->name . '</a>';
870 echo '<div class="grade">';
871 echo get_string('attempt', 'quiz', $activity->content->attempt);
872 if (isset($activity->content->maxgrade)) {
873 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
874 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
875 $activity->content->attemptid . '">' . $grades . '</a>)';
879 echo '<div class="user">';
880 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
881 '&course=' . $courseid . '">' . $activity->user->fullname .
882 '</a> - ' . userdate($activity->timestamp);
885 echo '</td></tr></table>';
891 * Pre-process the quiz options form data, making any necessary adjustments.
892 * Called by add/update instance in this file.
894 * @param object $quiz The variables set on the form.
896 function quiz_process_options($quiz) {
898 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
899 require_once($CFG->libdir . '/questionlib.php');
901 $quiz->timemodified = time();
904 if (!empty($quiz->name)) {
905 $quiz->name = trim($quiz->name);
908 // Password field - different in form to stop browsers that remember passwords
910 $quiz->password = $quiz->quizpassword;
911 unset($quiz->quizpassword);
914 if (isset($quiz->feedbacktext)) {
915 // Clean up the boundary text.
916 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
917 if (empty($quiz->feedbacktext[$i]['text'])) {
918 $quiz->feedbacktext[$i]['text'] = '';
920 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
924 // Check the boundary value is a number or a percentage, and in range.
926 while (!empty($quiz->feedbackboundaries[$i])) {
927 $boundary = trim($quiz->feedbackboundaries[$i]);
928 if (!is_numeric($boundary)) {
929 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
930 $boundary = trim(substr($boundary, 0, -1));
931 if (is_numeric($boundary)) {
932 $boundary = $boundary * $quiz->grade / 100.0;
934 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
938 if ($boundary <= 0 || $boundary >= $quiz->grade) {
939 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
941 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
942 return get_string('feedbackerrororder', 'quiz', $i + 1);
944 $quiz->feedbackboundaries[$i] = $boundary;
949 // Check there is nothing in the remaining unused fields.
950 if (!empty($quiz->feedbackboundaries)) {
951 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
952 if (!empty($quiz->feedbackboundaries[$i]) &&
953 trim($quiz->feedbackboundaries[$i]) != '') {
954 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
958 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
959 if (!empty($quiz->feedbacktext[$i]['text']) &&
960 trim($quiz->feedbacktext[$i]['text']) != '') {
961 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
964 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
965 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
966 $quiz->feedbackboundaries[$numboundaries] = 0;
967 $quiz->feedbackboundarycount = $numboundaries;
970 // Combing the individual settings into the review columns.
971 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
972 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
973 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
974 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
975 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
976 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
977 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
978 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
979 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
983 * Helper function for {@link quiz_process_options()}.
984 * @param object $fromform the sumbitted form date.
985 * @param string $field one of the review option field names.
987 function quiz_review_option_form_to_db($fromform, $field) {
988 static $times = array(
989 'during' => mod_quiz_display_options::DURING,
990 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
991 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
992 'closed' => mod_quiz_display_options::AFTER_CLOSE,
996 foreach ($times as $whenname => $when) {
997 $fieldname = $field . $whenname;
998 if (isset($fromform->$fieldname)) {
1000 unset($fromform->$fieldname);
1008 * This function is called at the end of quiz_add_instance
1009 * and quiz_update_instance, to do the common processing.
1011 * @param object $quiz the quiz object.
1013 function quiz_after_add_or_update($quiz) {
1015 $cmid = $quiz->coursemodule;
1017 // we need to use context now, so we need to make sure all needed info is already in db
1018 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1019 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1021 // Save the feedback
1022 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1024 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1025 $feedback = new stdClass();
1026 $feedback->quizid = $quiz->id;
1027 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1028 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1029 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1030 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1031 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1032 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1033 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1034 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1035 $quiz->feedbacktext[$i]['text']);
1036 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1037 array('id' => $feedback->id));
1040 // Update the events relating to this quiz.
1041 quiz_update_events($quiz);
1043 //update related grade item
1044 quiz_grade_item_update($quiz);
1048 * This function updates the events associated to the quiz.
1049 * If $override is non-zero, then it updates only the events
1050 * associated with the specified override.
1052 * @uses QUIZ_MAX_EVENT_LENGTH
1053 * @param object $quiz the quiz object.
1054 * @param object optional $override limit to a specific override
1056 function quiz_update_events($quiz, $override = null) {
1059 // Load the old events relating to this quiz.
1060 $conds = array('modulename'=>'quiz',
1061 'instance'=>$quiz->id);
1062 if (!empty($override)) {
1063 // only load events for this override
1064 $conds['groupid'] = isset($override->groupid)? $override->groupid : 0;
1065 $conds['userid'] = isset($override->userid)? $override->userid : 0;
1067 $oldevents = $DB->get_records('event', $conds);
1069 // Now make a todo list of all that needs to be updated
1070 if (empty($override)) {
1071 // We are updating the primary settings for the quiz, so we
1072 // need to add all the overrides
1073 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
1074 // as well as the original quiz (empty override)
1075 $overrides[] = new stdClass();
1077 // Just do the one override
1078 $overrides = array($override);
1081 foreach ($overrides as $current) {
1082 $groupid = isset($current->groupid)? $current->groupid : 0;
1083 $userid = isset($current->userid)? $current->userid : 0;
1084 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1085 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1087 // only add open/close events for an override if they differ from the quiz default
1088 $addopen = empty($current->id) || !empty($current->timeopen);
1089 $addclose = empty($current->id) || !empty($current->timeclose);
1091 $event = new stdClass();
1092 $event->description = $quiz->intro;
1093 // Events module won't show user events when the courseid is nonzero
1094 $event->courseid = ($userid) ? 0 : $quiz->course;
1095 $event->groupid = $groupid;
1096 $event->userid = $userid;
1097 $event->modulename = 'quiz';
1098 $event->instance = $quiz->id;
1099 $event->timestart = $timeopen;
1100 $event->timeduration = max($timeclose - $timeopen, 0);
1101 $event->visible = instance_is_visible('quiz', $quiz);
1102 $event->eventtype = 'open';
1104 // Determine the event name
1106 $params = new stdClass();
1107 $params->quiz = $quiz->name;
1108 $params->group = groups_get_group_name($groupid);
1109 if ($params->group === false) {
1110 // group doesn't exist, just skip it
1113 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1114 } else if ($userid) {
1115 $params = new stdClass();
1116 $params->quiz = $quiz->name;
1117 $eventname = get_string('overrideusereventname', 'quiz', $params);
1119 $eventname = $quiz->name;
1121 if ($addopen or $addclose) {
1122 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1123 // Single event for the whole quiz.
1124 if ($oldevent = array_shift($oldevents)) {
1125 $event->id = $oldevent->id;
1129 $event->name = $eventname;
1130 // calendar_event::create will reuse a db record if the id field is set
1131 calendar_event::create($event);
1133 // Separate start and end events.
1134 $event->timeduration = 0;
1135 if ($timeopen && $addopen) {
1136 if ($oldevent = array_shift($oldevents)) {
1137 $event->id = $oldevent->id;
1141 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
1142 // calendar_event::create will reuse a db record if the id field is set
1143 calendar_event::create($event);
1145 if ($timeclose && $addclose) {
1146 if ($oldevent = array_shift($oldevents)) {
1147 $event->id = $oldevent->id;
1151 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1152 $event->timestart = $timeclose;
1153 $event->eventtype = 'close';
1154 calendar_event::create($event);
1160 // Delete any leftover events
1161 foreach ($oldevents as $badevent) {
1162 $badevent = calendar_event::load($badevent);
1163 $badevent->delete();
1170 function quiz_get_view_actions() {
1171 return array('view', 'view all', 'report', 'review');
1177 function quiz_get_post_actions() {
1178 return array('attempt', 'close attempt', 'preview', 'editquestions',
1179 'delete attempt', 'manualgrade');
1183 * @param array $questionids of question ids.
1184 * @return bool whether any of these questions are used by any instance of this module.
1186 function quiz_questions_in_use($questionids) {
1188 require_once($CFG->libdir . '/questionlib.php');
1189 list($test, $params) = $DB->get_in_or_equal($questionids);
1190 return $DB->record_exists_select('quiz_question_instances',
1191 'question ' . $test, $params) || question_engine::questions_in_use(
1192 $questionids, new qubaid_join('{quiz_attempts} quiza',
1193 'quiza.uniqueid', 'quiza.preview = 0'));
1197 * Implementation of the function for printing the form elements that control
1198 * whether the course reset functionality affects the quiz.
1200 * @param $mform the course reset form that is being built.
1202 function quiz_reset_course_form_definition($mform) {
1203 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1204 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1205 get_string('removeallquizattempts', 'quiz'));
1209 * Course reset form defaults.
1210 * @return array the defaults.
1212 function quiz_reset_course_form_defaults($course) {
1213 return array('reset_quiz_attempts' => 1);
1217 * Removes all grades from gradebook
1219 * @param int $courseid
1220 * @param string optional type
1222 function quiz_reset_gradebook($courseid, $type='') {
1225 $quizzes = $DB->get_records_sql("
1226 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1228 JOIN {course_modules} cm ON m.id = cm.module
1229 JOIN {quiz} q ON cm.instance = q.id
1230 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1232 foreach ($quizzes as $quiz) {
1233 quiz_grade_item_update($quiz, 'reset');
1238 * Actual implementation of the reset course functionality, delete all the
1239 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1242 * Also, move the quiz open and close dates, if the course start date is changing.
1244 * @param object $data the data submitted from the reset course.
1245 * @return array status array
1247 function quiz_reset_userdata($data) {
1249 require_once($CFG->libdir.'/questionlib.php');
1251 $componentstr = get_string('modulenameplural', 'quiz');
1255 if (!empty($data->reset_quiz_attempts)) {
1256 require_once($CFG->libdir . '/questionlib.php');
1258 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1259 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1260 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1261 array('quizcourseid' => $data->courseid)));
1263 $DB->delete_records_select('quiz_attempts',
1264 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1266 'component' => $componentstr,
1267 'item' => get_string('attemptsdeleted', 'quiz'),
1270 // Remove all grades from gradebook
1271 if (empty($data->reset_gradebook_grades)) {
1272 quiz_reset_gradebook($data->courseid);
1275 'component' => $componentstr,
1276 'item' => get_string('attemptsdeleted', 'quiz'),
1280 // Updating dates - shift may be negative too
1281 if ($data->timeshift) {
1282 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1283 $data->timeshift, $data->courseid);
1285 'component' => $componentstr,
1286 'item' => get_string('openclosedatesupdated', 'quiz'),
1294 * Checks whether the current user is allowed to view a file uploaded in a quiz.
1295 * Teachers can view any from their courses, students can only view their own.
1297 * @param int $attemptuniqueid int attempt id
1298 * @param int $questionid int question id
1299 * @return bool to indicate access granted or denied
1301 function quiz_check_file_access($attemptuniqueid, $questionid, $context = null) {
1302 global $USER, $DB, $CFG;
1303 require_once(dirname(__FILE__).'/attemptlib.php');
1304 require_once(dirname(__FILE__).'/locallib.php');
1306 $attempt = $DB->get_record('quiz_attempts', array('uniqueid' => $attemptuniqueid));
1307 $attemptobj = quiz_attempt::create($attempt->id);
1309 // does question exist?
1310 if (!$question = $DB->get_record('question', array('id' => $questionid))) {
1314 if ($context === null) {
1315 $quiz = $DB->get_record('quiz', array('id' => $attempt->quiz));
1316 $cm = get_coursemodule_from_id('quiz', $quiz->id);
1317 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1320 // Load those questions and the associated states.
1321 $attemptobj->load_questions(array($questionid));
1322 $attemptobj->load_question_states(array($questionid));
1325 $state = $attemptobj->get_question_state($questionid);
1327 $question = $attemptobj->get_question($questionid);
1329 // access granted if the current user submitted this file
1330 if ($attempt->userid != $USER->id) {
1333 // access granted if the current user has permission to grade quizzes in this course
1334 if (!(has_capability('mod/quiz:viewreports', $context) ||
1335 has_capability('mod/quiz:grade', $context))) {
1339 return array($question, $state, array());
1343 * Prints quiz summaries on MyMoodle Page
1344 * @param arry $courses
1345 * @param array $htmlarray
1347 function quiz_print_overview($courses, &$htmlarray) {
1349 // These next 6 Lines are constant in all modules (just change module name)
1350 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1354 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1358 // Fetch some language strings outside the main loop.
1359 $strquiz = get_string('modulename', 'quiz');
1360 $strnoattempts = get_string('noattempts', 'quiz');
1362 // We want to list quizzes that are currently available, and which have a close date.
1363 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1365 foreach ($quizzes as $quiz) {
1366 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1367 // Give a link to the quiz, and the deadline.
1368 $str = '<div class="quiz overview">' .
1369 '<div class="name">' . $strquiz . ': <a ' .
1370 ($quiz->visible ? '' : ' class="dimmed"') .
1371 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1372 $quiz->coursemodule . '">' .
1373 $quiz->name . '</a></div>';
1374 $str .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1375 userdate($quiz->timeclose)) . '</div>';
1377 // Now provide more information depending on the uers's role.
1378 $context = get_context_instance(CONTEXT_MODULE, $quiz->coursemodule);
1379 if (has_capability('mod/quiz:viewreports', $context)) {
1380 // For teacher-like people, show a summary of the number of student attempts.
1381 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1382 // fields set to make the following call work.
1383 $str .= '<div class="info">' .
1384 quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1385 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'),
1386 $context)) { // Student
1387 // For student-like people, tell them how many attempts they have made.
1388 if (isset($USER->id) &&
1389 ($attempts = quiz_get_user_attempts($quiz->id, $USER->id))) {
1390 $numattempts = count($attempts);
1391 $str .= '<div class="info">' .
1392 get_string('numattemptsmade', 'quiz', $numattempts) . '</div>';
1394 $str .= '<div class="info">' . $strnoattempts . '</div>';
1397 // For ayone else, there is no point listing this quiz, so stop processing.
1401 // Add the output for this quiz to the rest.
1403 if (empty($htmlarray[$quiz->course]['quiz'])) {
1404 $htmlarray[$quiz->course]['quiz'] = $str;
1406 $htmlarray[$quiz->course]['quiz'] .= $str;
1413 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1414 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1416 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1417 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1418 * $cm->groupingid fields are used at the moment.
1419 * @param bool $returnzero if false (default), when no attempts have been
1420 * made '' is returned instead of 'Attempts: 0'.
1421 * @param int $currentgroup if there is a concept of current group where this method is being called
1422 * (e.g. a report) pass it in here. Default 0 which means no current group.
1423 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1424 * "Attemtps 123 (45 from this group)".
1426 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1428 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1429 if ($numattempts || $returnzero) {
1430 if (groups_get_activity_groupmode($cm)) {
1431 $a->total = $numattempts;
1432 if ($currentgroup) {
1433 $a->group = $DB->count_records_sql('SELECT count(1) FROM ' .
1434 '{quiz_attempts} qa JOIN ' .
1435 '{groups_members} gm ON qa.userid = gm.userid ' .
1436 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1437 array($quiz->id, $currentgroup));
1438 return get_string('attemptsnumthisgroup', 'quiz', $a);
1439 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1440 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1441 $a->group = $DB->count_records_sql('SELECT count(1) FROM ' .
1442 '{quiz_attempts} qa JOIN ' .
1443 '{groups_members} gm ON qa.userid = gm.userid ' .
1444 'WHERE quiz = ? AND preview = 0 AND ' .
1445 "groupid $usql", array_merge(array($quiz->id), $params));
1446 return get_string('attemptsnumyourgroups', 'quiz', $a);
1449 return get_string('attemptsnum', 'quiz', $numattempts);
1455 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1456 * to the quiz reports.
1458 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1459 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1460 * $cm->groupingid fields are used at the moment.
1461 * @param object $context the quiz context.
1462 * @param bool $returnzero if false (default), when no attempts have been made
1463 * '' is returned instead of 'Attempts: 0'.
1464 * @param int $currentgroup if there is a concept of current group where this method is being called
1465 * (e.g. a report) pass it in here. Default 0 which means no current group.
1466 * @return string HTML fragment for the link.
1468 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1469 $currentgroup = 0) {
1471 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1476 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1477 $url = new moodle_url('/mod/quiz/report.php', array(
1478 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1479 return html_writer::link($url, $summary);
1483 * @param string $feature FEATURE_xx constant for requested feature
1484 * @return bool True if quiz supports feature
1486 function quiz_supports($feature) {
1488 case FEATURE_GROUPS: return true;
1489 case FEATURE_GROUPINGS: return true;
1490 case FEATURE_GROUPMEMBERSONLY: return true;
1491 case FEATURE_MOD_INTRO: return true;
1492 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1493 case FEATURE_GRADE_HAS_GRADE: return true;
1494 case FEATURE_GRADE_OUTCOMES: return true;
1495 case FEATURE_BACKUP_MOODLE2: return true;
1497 default: return null;
1502 * @return array all other caps used in module
1504 function quiz_get_extra_capabilities() {
1506 require_once($CFG->libdir.'/questionlib.php');
1507 $caps = question_get_all_capabilities();
1508 $caps[] = 'moodle/site:accessallgroups';
1513 * This fucntion extends the global navigation for the site.
1514 * It is important to note that you should not rely on PAGE objects within this
1515 * body of code as there is no guarantee that during an AJAX request they are
1518 * @param navigation_node $quiznode The quiz node within the global navigation
1519 * @param object $course The course object returned from the DB
1520 * @param object $module The module object returned from the DB
1521 * @param object $cm The course module instance returned from the DB
1523 function quiz_extend_navigation($quiznode, $course, $module, $cm) {
1526 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1528 if (has_capability('mod/quiz:view', $context)) {
1529 $url = new moodle_url('/mod/quiz/view.php', array('id'=>$cm->id));
1530 $quiznode->add(get_string('info', 'quiz'), $url, navigation_node::TYPE_SETTING,
1531 null, null, new pix_icon('i/info', ''));
1534 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $context)) {
1535 require_once($CFG->dirroot.'/mod/quiz/report/reportlib.php');
1536 $reportlist = quiz_report_list($context);
1538 $url = new moodle_url('/mod/quiz/report.php',
1539 array('id' => $cm->id, 'mode' => reset($reportlist)));
1540 $reportnode = $quiznode->add(get_string('results', 'quiz'), $url,
1541 navigation_node::TYPE_SETTING,
1542 null, null, new pix_icon('i/report', ''));
1544 foreach ($reportlist as $report) {
1545 $url = new moodle_url('/mod/quiz/report.php',
1546 array('id' => $cm->id, 'mode' => $report));
1547 $reportnode->add(get_string($report, 'quiz_'.$report), $url,
1548 navigation_node::TYPE_SETTING,
1549 null, 'quiz_report_' . $report, new pix_icon('i/item', ''));
1555 * This function extends the settings navigation block for the site.
1557 * It is safe to rely on PAGE here as we will only ever be within the module
1558 * context when this is called
1560 * @param settings_navigation $settings
1561 * @param navigation_node $quiznode
1563 function quiz_extend_settings_navigation($settings, $quiznode) {
1567 * Require {@link questionlib.php}
1568 * Included here as we only ever want to include this file if we really need to.
1570 require_once($CFG->libdir . '/questionlib.php');
1572 // We want to add these new nodes after the Edit settings node, and before the
1573 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1574 $keys = $quiznode->get_children_key_list();
1576 $i = array_search('modedit', $keys);
1577 if ($i === false and array_key_exists(0, $keys)) {
1578 $beforekey = $keys[0];
1579 } else if (array_key_exists($i + 1, $keys)) {
1580 $beforekey = $keys[$i + 1];
1583 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1584 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1585 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1586 new moodle_url($url, array('mode'=>'group')),
1587 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1588 $quiznode->add_node($node, $beforekey);
1590 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1591 new moodle_url($url, array('mode'=>'user')),
1592 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1593 $quiznode->add_node($node, $beforekey);
1596 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1597 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1598 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1599 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1600 new pix_icon('t/edit', ''));
1601 $quiznode->add_node($node, $beforekey);
1604 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1605 $url = new moodle_url('/mod/quiz/startattempt.php',
1606 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1607 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1608 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1609 new pix_icon('t/preview', ''));
1610 $quiznode->add_node($node, $beforekey);
1613 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1617 * Serves the quiz files.
1619 * @param object $course
1621 * @param object $context
1622 * @param string $filearea
1623 * @param array $args
1624 * @param bool $forcedownload
1625 * @return bool false if file not found, does not return if found - justsend the file
1627 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
1630 if ($context->contextlevel != CONTEXT_MODULE) {
1634 require_login($course, false, $cm);
1636 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1640 // 'intro' area is served by pluginfile.php
1641 $fileareas = array('feedback');
1642 if (!in_array($filearea, $fileareas)) {
1646 $feedbackid = (int)array_shift($args);
1647 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1651 $fs = get_file_storage();
1652 $relativepath = implode('/', $args);
1653 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1654 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1657 send_stored_file($file, 0, 0, true);
1661 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1662 * a question in a question_attempt when that attempt is a quiz attempt.
1664 * @param object $course course settings object
1665 * @param object $context context object
1666 * @param string $component the name of the component we are serving files for.
1667 * @param string $filearea the name of the file area.
1668 * @param array $args the remaining bits of the file path.
1669 * @param bool $forcedownload whether the user must be forced to download the file.
1670 * @return bool false if file not found, does not return if found - justsend the file
1672 function mod_quiz_question_pluginfile($course, $context, $component,
1673 $filearea, $qubaid, $slot, $args, $forcedownload) {
1675 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1677 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1678 require_login($attemptobj->get_courseid(), false, $attemptobj->get_cm());
1680 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1681 // In the middle of an attempt.
1682 if (!$attemptobj->is_preview_user()) {
1683 $attemptobj->require_capability('mod/quiz:attempt');
1685 $isreviewing = false;
1688 // Reviewing an attempt.
1689 $attemptobj->check_review_capability();
1690 $isreviewing = true;
1693 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1694 $component, $filearea, $args, $forcedownload)) {
1695 send_file_not_found();
1698 $fs = get_file_storage();
1699 $relativepath = implode('/', $args);
1700 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1701 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1702 send_file_not_found();
1705 send_stored_file($file, 0, 0, $forcedownload);
1709 * Return a list of page types
1710 * @param string $pagetype current page type
1711 * @param stdClass $parentcontext Block's parent context
1712 * @param stdClass $currentcontext Current context of block
1714 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1715 $module_pagetype = array(
1716 'mod-quiz-*'=>get_string('page-mod-quiz-x', 'quiz'),
1717 'mod-quiz-edit'=>get_string('page-mod-quiz-edit', 'quiz'));
1718 return $module_pagetype;