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($oldquiz->questions, $quiz->questionsperpage);
106 unset($quiz->repaginatenow);
108 // Update the database.
109 $quiz->id = $quiz->instance;
110 $DB->update_record('quiz', $quiz);
112 // Do the processing required after an add or an update.
113 quiz_after_add_or_update($quiz);
115 if ($oldquiz->grademethod != $quiz->grademethod) {
116 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
117 $quiz->sumgrades = $oldquiz->sumgrades;
118 $quiz->grade = $oldquiz->grade;
119 quiz_update_all_final_grades($quiz);
120 quiz_update_grades($quiz);
123 // Delete any previous preview attempts
124 quiz_delete_previews($quiz);
130 * Given an ID of an instance of this module,
131 * this function will permanently delete the instance
132 * and any data that depends on it.
134 * @param int $id the id of the quiz to delete.
135 * @return bool success or failure.
137 function quiz_delete_instance($id) {
140 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
142 quiz_delete_all_attempts($quiz);
143 quiz_delete_all_overrides($quiz);
145 $DB->delete_records('quiz_question_instances', array('quiz' => $quiz->id));
146 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
148 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
149 foreach ($events as $event) {
150 $event = calendar_event::load($event);
154 quiz_grade_item_delete($quiz);
155 $DB->delete_records('quiz', array('id' => $quiz->id));
161 * Deletes a quiz override from the database and clears any corresponding calendar events
163 * @param object $quiz The quiz object.
164 * @param int $overrideid The id of the override being deleted
165 * @return bool true on success
167 function quiz_delete_override($quiz, $overrideid) {
170 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
173 $events = $DB->get_records('event', array('modulename' => 'quiz',
174 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
175 'userid' => (int)$override->userid));
176 foreach ($events as $event) {
177 $eventold = calendar_event::load($event);
181 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
186 * Deletes all quiz overrides from the database and clears any corresponding calendar events
188 * @param object $quiz The quiz object.
190 function quiz_delete_all_overrides($quiz) {
193 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
194 foreach ($overrides as $override) {
195 quiz_delete_override($quiz, $override->id);
200 * Updates a quiz object with override information for a user.
202 * Algorithm: For each quiz setting, if there is a matching user-specific override,
203 * then use that otherwise, if there are group-specific overrides, return the most
204 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
206 * Special case: if there is more than one password that applies to the user, then
207 * quiz->extrapasswords will contain an array of strings giving the remaining
210 * @param object $quiz The quiz object.
211 * @param int $userid The userid.
212 * @return object $quiz The updated quiz object.
214 function quiz_update_effective_access($quiz, $userid) {
217 // check for user override
218 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
221 $override = new stdClass();
222 $override->timeopen = null;
223 $override->timeclose = null;
224 $override->timelimit = null;
225 $override->attempts = null;
226 $override->password = null;
229 // check for group overrides
230 $groupings = groups_get_user_groups($quiz->course, $userid);
232 if (!empty($groupings[0])) {
233 // Select all overrides that apply to the User's groups
234 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
235 $sql = "SELECT * FROM {quiz_overrides}
236 WHERE groupid $extra AND quiz = ?";
237 $params[] = $quiz->id;
238 $records = $DB->get_records_sql($sql, $params);
240 // Combine the overrides
245 $passwords = array();
247 foreach ($records as $gpoverride) {
248 if (isset($gpoverride->timeopen)) {
249 $opens[] = $gpoverride->timeopen;
251 if (isset($gpoverride->timeclose)) {
252 $closes[] = $gpoverride->timeclose;
254 if (isset($gpoverride->timelimit)) {
255 $limits[] = $gpoverride->timelimit;
257 if (isset($gpoverride->attempts)) {
258 $attempts[] = $gpoverride->attempts;
260 if (isset($gpoverride->password)) {
261 $passwords[] = $gpoverride->password;
264 // If there is a user override for a setting, ignore the group override
265 if (is_null($override->timeopen) && count($opens)) {
266 $override->timeopen = min($opens);
268 if (is_null($override->timeclose) && count($closes)) {
269 $override->timeclose = max($closes);
271 if (is_null($override->timelimit) && count($limits)) {
272 $override->timelimit = max($limits);
274 if (is_null($override->attempts) && count($attempts)) {
275 $override->attempts = max($attempts);
277 if (is_null($override->password) && count($passwords)) {
278 $override->password = array_shift($passwords);
279 if (count($passwords)) {
280 $override->extrapasswords = $passwords;
286 // merge with quiz defaults
287 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
288 foreach ($keys as $key) {
289 if (isset($override->{$key})) {
290 $quiz->{$key} = $override->{$key};
298 * Delete all the attempts belonging to a quiz.
300 * @param object $quiz The quiz object.
302 function quiz_delete_all_attempts($quiz) {
304 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
305 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
306 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
307 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
311 * Get the best current grade for a particular user in a quiz.
313 * @param object $quiz the quiz settings.
314 * @param int $userid the id of the user.
315 * @return float the user's current grade for this quiz, or null if this user does
316 * not have a grade on this quiz.
318 function quiz_get_best_grade($quiz, $userid) {
320 $grade = $DB->get_field('quiz_grades', 'grade',
321 array('quiz' => $quiz->id, 'userid' => $userid));
323 // Need to detect errors/no result, without catching 0 grades.
324 if ($grade === false) {
328 return $grade + 0; // Convert to number.
332 * Is this a graded quiz? If this method returns true, you can assume that
333 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
336 * @param object $quiz a row from the quiz table.
337 * @return bool whether this is a graded quiz.
339 function quiz_has_grades($quiz) {
340 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
344 * Return a small object with summary information about what a
345 * user has done with a given particular instance of this module
346 * Used for user activity reports.
347 * $return->time = the time they did it
348 * $return->info = a short text description
350 * @param object $course
351 * @param object $user
353 * @param object $quiz
354 * @return object|null
356 function quiz_user_outline($course, $user, $mod, $quiz) {
358 require_once("$CFG->libdir/gradelib.php");
359 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
361 if (empty($grades->items[0]->grades)) {
364 $grade = reset($grades->items[0]->grades);
367 $result = new stdClass();
368 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
369 $result->time = $grade->dategraded;
374 * Print a detailed representation of what a user has done with
375 * a given particular instance of this module, for user activity reports.
378 * @param object $course
379 * @param object $user
381 * @param object $quiz
384 function quiz_user_complete($course, $user, $mod, $quiz) {
385 global $DB, $CFG, $OUTPUT;
386 require_once("$CFG->libdir/gradelib.php");
388 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
389 if (!empty($grades->items[0]->grades)) {
390 $grade = reset($grades->items[0]->grades);
391 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
392 if ($grade->str_feedback) {
393 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
397 if ($attempts = $DB->get_records('quiz_attempts',
398 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
399 foreach ($attempts as $attempt) {
400 echo get_string('attempt', 'quiz').' '.$attempt->attempt.': ';
401 if ($attempt->timefinish == 0) {
402 print_string('unfinished');
404 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
405 quiz_format_grade($quiz, $quiz->sumgrades);
407 echo ' - '.userdate($attempt->timemodified).'<br />';
410 print_string('noattempts', 'quiz');
417 * Function to be run periodically according to the moodle cron
418 * This function searches for things that need to be done, such
419 * as sending out mail, toggling flags etc ...
423 function quiz_cron() {
428 * @param int $quizid the quiz id.
429 * @param int $userid the userid.
430 * @param string $status 'all', 'finished' or 'unfinished' to control
431 * @param bool $includepreviews
432 * @return an array of all the user's attempts at this quiz. Returns an empty
433 * array if there are none.
435 function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
437 $status_condition = array(
439 'finished' => ' AND timefinish > 0',
440 'unfinished' => ' AND timefinish = 0'
443 if (!$includepreviews) {
444 $previewclause = ' AND preview = 0';
446 return $DB->get_records_select('quiz_attempts',
447 'quiz = ? AND userid = ?' . $previewclause . $status_condition[$status],
448 array($quizid, $userid), 'attempt ASC');
452 * Return grade for given user or all users.
454 * @param int $quizid id of quiz
455 * @param int $userid optional user id, 0 means all users
456 * @return array array of grades, false if none. These are raw grades. They should
457 * be processed with quiz_format_grade for display.
459 function quiz_get_user_grades($quiz, $userid = 0) {
462 $params = array($quiz->id);
466 $usertest = 'AND u.id = ?';
468 return $DB->get_records_sql("
472 qg.grade AS rawgrade,
473 qg.timemodified AS dategraded,
474 MAX(qa.timefinish) AS datesubmitted
477 JOIN {quiz_grades} qg ON u.id = qg.userid
478 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
482 GROUP BY u.id, qg.grade, qg.timemodified", $params);
486 * Round a grade to to the correct number of decimal places, and format it for display.
488 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
489 * @param float $grade The grade to round.
492 function quiz_format_grade($quiz, $grade) {
493 if (is_null($grade)) {
494 return get_string('notyetgraded', 'quiz');
496 return format_float($grade, $quiz->decimalpoints);
500 * Round a grade to to the correct number of decimal places, and format it for display.
502 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
503 * @param float $grade The grade to round.
506 function quiz_format_question_grade($quiz, $grade) {
507 if (empty($quiz->questiondecimalpoints)) {
508 $quiz->questiondecimalpoints = -1;
510 if ($quiz->questiondecimalpoints == -1) {
511 return format_float($grade, $quiz->decimalpoints);
513 return format_float($grade, $quiz->questiondecimalpoints);
518 * Update grades in central gradebook
520 * @param object $quiz the quiz settings.
521 * @param int $userid specific user only, 0 means all users.
523 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
525 require_once($CFG->libdir.'/gradelib.php');
527 if ($quiz->grade == 0) {
528 quiz_grade_item_update($quiz);
530 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
531 quiz_grade_item_update($quiz, $grades);
533 } else if ($userid && $nullifnone) {
534 $grade = new stdClass();
535 $grade->userid = $userid;
536 $grade->rawgrade = null;
537 quiz_grade_item_update($quiz, $grade);
540 quiz_grade_item_update($quiz);
545 * Update all grades in gradebook.
547 function quiz_upgrade_grades() {
550 $sql = "SELECT COUNT('x')
551 FROM {quiz} a, {course_modules} cm, {modules} m
552 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
553 $count = $DB->count_records_sql($sql);
555 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
556 FROM {quiz} a, {course_modules} cm, {modules} m
557 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
558 $rs = $DB->get_recordset_sql($sql);
560 $pbar = new progress_bar('quizupgradegrades', 500, true);
562 foreach ($rs as $quiz) {
564 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
565 quiz_update_grades($quiz, 0, false);
566 $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
573 * Create grade item for given quiz
575 * @param object $quiz object with extra cmidnumber
576 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
577 * @return int 0 if ok, error code otherwise
579 function quiz_grade_item_update($quiz, $grades = null) {
580 global $CFG, $OUTPUT;
581 require_once($CFG->libdir.'/gradelib.php');
583 if (array_key_exists('cmidnumber', $quiz)) { // may not be always present
584 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
586 $params = array('itemname' => $quiz->name);
589 if ($quiz->grade > 0) {
590 $params['gradetype'] = GRADE_TYPE_VALUE;
591 $params['grademax'] = $quiz->grade;
592 $params['grademin'] = 0;
595 $params['gradetype'] = GRADE_TYPE_NONE;
598 // description by TJ:
599 // 1. If the quiz is set to not show grades while the quiz is still open,
600 // and is set to show grades after the quiz is closed, then create the
601 // grade_item with a show-after date that is the quiz close date.
602 // 2. If the quiz is set to not show grades at either of those times,
603 // create the grade_item as hidden.
604 // 3. If the quiz is set to show grades, create the grade_item visible.
605 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
606 mod_quiz_display_options::LATER_WHILE_OPEN);
607 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
608 mod_quiz_display_options::AFTER_CLOSE);
609 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
610 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
611 $params['hidden'] = 1;
613 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
614 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
615 if ($quiz->timeclose) {
616 $params['hidden'] = $quiz->timeclose;
618 $params['hidden'] = 1;
622 // a) both open and closed enabled
623 // b) open enabled, closed disabled - we can not "hide after",
624 // grades are kept visible even after closing
625 $params['hidden'] = 0;
628 if ($grades === 'reset') {
629 $params['reset'] = true;
633 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
634 if (!empty($gradebook_grades->items)) {
635 $grade_item = $gradebook_grades->items[0];
636 if ($grade_item->locked) {
637 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
638 if (!$confirm_regrade) {
639 $message = get_string('gradeitemislocked', 'grades');
640 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
641 '&mode=overview';
642 $regrade_link = qualified_me() . '&confirm_regrade=1';
643 echo $OUTPUT->box_start('generalbox', 'notice');
644 echo '<p>'. $message .'</p>';
645 echo $OUTPUT->container_start('buttons');
646 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
647 echo $OUTPUT->single_button($back_link, get_string('cancel'));
648 echo $OUTPUT->container_end();
649 echo $OUTPUT->box_end();
651 return GRADE_UPDATE_ITEM_LOCKED;
656 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
660 * Delete grade item for given quiz
662 * @param object $quiz object
663 * @return object quiz
665 function quiz_grade_item_delete($quiz) {
667 require_once($CFG->libdir . '/gradelib.php');
669 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
670 null, array('deleted' => 1));
674 * Returns an array of users who have data in a given quiz
676 * @todo: deprecated - to be deleted in 2.2
678 * @param int $quizid the quiz id.
679 * @return array of userids.
681 function quiz_get_participants($quizid) {
684 return $DB->get_records_sql('
685 SELECT DISTINCT userid, userid
686 JOIN {quiz_attempts} qa
687 WHERE a.quiz = ?', array($quizid));
691 * This standard function will check all instances of this module
692 * and make sure there are up-to-date events created for each of them.
693 * If courseid = 0, then every quiz event in the site is checked, else
694 * only quiz events belonging to the course specified are checked.
695 * This function is used, in its new format, by restore_refresh_events()
697 * @param int $courseid
700 function quiz_refresh_events($courseid = 0) {
703 if ($courseid == 0) {
704 if (!$quizzes = $DB->get_records('quiz')) {
708 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
713 foreach ($quizzes as $quiz) {
714 quiz_update_events($quiz);
721 * Returns all quiz graded users since a given time for specified quiz
723 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
724 $courseid, $cmid, $userid = 0, $groupid = 0) {
725 global $CFG, $COURSE, $USER, $DB;
726 require_once('locallib.php');
728 if ($COURSE->id == $courseid) {
731 $course = $DB->get_record('course', array('id' => $courseid));
734 $modinfo =& get_fast_modinfo($course);
736 $cm = $modinfo->cms[$cmid];
737 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
740 $userselect = "AND u.id = :userid";
741 $params['userid'] = $userid;
747 $groupselect = 'AND gm.groupid = :groupid';
748 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
749 $params['groupid'] = $groupid;
755 $params['timestart'] = $timestart;
756 $params['quizid'] = $quiz->id;
758 if (!$attempts = $DB->get_records_sql("
760 u.firstname, u.lastname, u.email, u.picture, u.imagealt
761 FROM {quiz_attempts} qa
762 JOIN {user} u ON u.id = qa.userid
764 WHERE qa.timefinish > :timestart
765 AND qa.quiz = :quizid
769 ORDER BY qa.timefinish ASC", $params)) {
773 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
774 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
775 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
776 $grader = has_capability('mod/quiz:viewreports', $context);
777 $groupmode = groups_get_activity_groupmode($cm, $course);
779 if (is_null($modinfo->groups)) {
780 // load all my groups and cache it in modinfo
781 $modinfo->groups = groups_get_user_groups($course->id);
785 $aname = format_string($cm->name, true);
786 foreach ($attempts as $attempt) {
787 if ($attempt->userid != $USER->id) {
789 // Grade permission required
793 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
794 if (is_null($usersgroups)) {
795 $usersgroups = groups_get_all_groups($course->id,
796 $attempt->userid, $cm->groupingid);
797 if (is_array($usersgroups)) {
798 $usersgroups = array_keys($usersgroups);
800 $usersgroups = array();
803 if (!array_intersect($usersgroups, $modinfo->groups[$cm->id])) {
809 $options = quiz_get_review_options($quiz, $attempt, $context);
811 $tmpactivity = new stdClass();
813 $tmpactivity->type = 'quiz';
814 $tmpactivity->cmid = $cm->id;
815 $tmpactivity->name = $aname;
816 $tmpactivity->sectionnum = $cm->sectionnum;
817 $tmpactivity->timestamp = $attempt->timefinish;
819 $tmpactivity->content->attemptid = $attempt->id;
820 $tmpactivity->content->attempt = $attempt->attempt;
821 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
822 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
823 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
825 $tmpactivity->content->sumgrades = null;
826 $tmpactivity->content->maxgrade = null;
829 $tmpactivity->user->id = $attempt->userid;
830 $tmpactivity->user->firstname = $attempt->firstname;
831 $tmpactivity->user->lastname = $attempt->lastname;
832 $tmpactivity->user->fullname = fullname($attempt, $viewfullnames);
833 $tmpactivity->user->picture = $attempt->picture;
834 $tmpactivity->user->imagealt = $attempt->imagealt;
835 $tmpactivity->user->email = $attempt->email;
837 $activities[$index++] = $tmpactivity;
841 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
842 global $CFG, $OUTPUT;
844 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
846 echo '<tr><td class="userpicture" valign="top">';
847 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
851 $modname = $modnames[$activity->type];
852 echo '<div class="title">';
853 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
854 'class="icon" alt="' . $modname . '" />';
855 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
856 $activity->cmid . '">' . $activity->name . '</a>';
860 echo '<div class="grade">';
861 echo get_string('attempt', 'quiz', $activity->content->attempt);
862 if (isset($activity->content->maxgrade)) {
863 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
864 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
865 $activity->content->attemptid . '">' . $grades . '</a>)';
869 echo '<div class="user">';
870 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
871 '&course=' . $courseid . '">' . $activity->user->fullname .
872 '</a> - ' . userdate($activity->timestamp);
875 echo '</td></tr></table>';
881 * Pre-process the quiz options form data, making any necessary adjustments.
882 * Called by add/update instance in this file.
884 * @param object $quiz The variables set on the form.
886 function quiz_process_options($quiz) {
888 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
889 require_once($CFG->libdir . '/questionlib.php');
891 $quiz->timemodified = time();
894 if (!empty($quiz->name)) {
895 $quiz->name = trim($quiz->name);
898 // Password field - different in form to stop browsers that remember passwords
900 $quiz->password = $quiz->quizpassword;
901 unset($quiz->quizpassword);
904 if (isset($quiz->feedbacktext)) {
905 // Clean up the boundary text.
906 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
907 if (empty($quiz->feedbacktext[$i]['text'])) {
908 $quiz->feedbacktext[$i]['text'] = '';
910 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
914 // Check the boundary value is a number or a percentage, and in range.
916 while (!empty($quiz->feedbackboundaries[$i])) {
917 $boundary = trim($quiz->feedbackboundaries[$i]);
918 if (!is_numeric($boundary)) {
919 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
920 $boundary = trim(substr($boundary, 0, -1));
921 if (is_numeric($boundary)) {
922 $boundary = $boundary * $quiz->grade / 100.0;
924 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
928 if ($boundary <= 0 || $boundary >= $quiz->grade) {
929 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
931 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
932 return get_string('feedbackerrororder', 'quiz', $i + 1);
934 $quiz->feedbackboundaries[$i] = $boundary;
939 // Check there is nothing in the remaining unused fields.
940 if (!empty($quiz->feedbackboundaries)) {
941 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
942 if (!empty($quiz->feedbackboundaries[$i]) &&
943 trim($quiz->feedbackboundaries[$i]) != '') {
944 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
948 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
949 if (!empty($quiz->feedbacktext[$i]['text']) &&
950 trim($quiz->feedbacktext[$i]['text']) != '') {
951 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
954 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
955 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
956 $quiz->feedbackboundaries[$numboundaries] = 0;
957 $quiz->feedbackboundarycount = $numboundaries;
960 // Combing the individual settings into the review columns.
961 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
962 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
963 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
964 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
965 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
966 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
967 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
968 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
969 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
973 * Helper function for {@link quiz_process_options()}.
974 * @param object $fromform the sumbitted form date.
975 * @param string $field one of the review option field names.
977 function quiz_review_option_form_to_db($fromform, $field) {
978 static $times = array(
979 'during' => mod_quiz_display_options::DURING,
980 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
981 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
982 'closed' => mod_quiz_display_options::AFTER_CLOSE,
986 foreach ($times as $whenname => $when) {
987 $fieldname = $field . $whenname;
988 if (isset($fromform->$fieldname)) {
990 unset($fromform->$fieldname);
998 * This function is called at the end of quiz_add_instance
999 * and quiz_update_instance, to do the common processing.
1001 * @param object $quiz the quiz object.
1003 function quiz_after_add_or_update($quiz) {
1005 $cmid = $quiz->coursemodule;
1007 // we need to use context now, so we need to make sure all needed info is already in db
1008 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1009 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1011 // Save the feedback
1012 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1014 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1015 $feedback = new stdClass();
1016 $feedback->quizid = $quiz->id;
1017 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1018 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1019 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1020 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1021 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1022 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1023 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1024 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1025 $quiz->feedbacktext[$i]['text']);
1026 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1027 array('id' => $feedback->id));
1030 // Update the events relating to this quiz.
1031 quiz_update_events($quiz);
1033 //update related grade item
1034 quiz_grade_item_update($quiz);
1038 * This function updates the events associated to the quiz.
1039 * If $override is non-zero, then it updates only the events
1040 * associated with the specified override.
1042 * @uses QUIZ_MAX_EVENT_LENGTH
1043 * @param object $quiz the quiz object.
1044 * @param object optional $override limit to a specific override
1046 function quiz_update_events($quiz, $override = null) {
1049 // Load the old events relating to this quiz.
1050 $conds = array('modulename'=>'quiz',
1051 'instance'=>$quiz->id);
1052 if (!empty($override)) {
1053 // only load events for this override
1054 $conds['groupid'] = isset($override->groupid)? $override->groupid : 0;
1055 $conds['userid'] = isset($override->userid)? $override->userid : 0;
1057 $oldevents = $DB->get_records('event', $conds);
1059 // Now make a todo list of all that needs to be updated
1060 if (empty($override)) {
1061 // We are updating the primary settings for the quiz, so we
1062 // need to add all the overrides
1063 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
1064 // as well as the original quiz (empty override)
1065 $overrides[] = new stdClass();
1067 // Just do the one override
1068 $overrides = array($override);
1071 foreach ($overrides as $current) {
1072 $groupid = isset($current->groupid)? $current->groupid : 0;
1073 $userid = isset($current->userid)? $current->userid : 0;
1074 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1075 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1077 // only add open/close events for an override if they differ from the quiz default
1078 $addopen = empty($current->id) || !empty($current->timeopen);
1079 $addclose = empty($current->id) || !empty($current->timeclose);
1081 $event = new stdClass();
1082 $event->description = $quiz->intro;
1083 // Events module won't show user events when the courseid is nonzero
1084 $event->courseid = ($userid) ? 0 : $quiz->course;
1085 $event->groupid = $groupid;
1086 $event->userid = $userid;
1087 $event->modulename = 'quiz';
1088 $event->instance = $quiz->id;
1089 $event->timestart = $timeopen;
1090 $event->timeduration = max($timeclose - $timeopen, 0);
1091 $event->visible = instance_is_visible('quiz', $quiz);
1092 $event->eventtype = 'open';
1094 // Determine the event name
1096 $params = new stdClass();
1097 $params->quiz = $quiz->name;
1098 $params->group = groups_get_group_name($groupid);
1099 if ($params->group === false) {
1100 // group doesn't exist, just skip it
1103 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1104 } else if ($userid) {
1105 $params = new stdClass();
1106 $params->quiz = $quiz->name;
1107 $eventname = get_string('overrideusereventname', 'quiz', $params);
1109 $eventname = $quiz->name;
1111 if ($addopen or $addclose) {
1112 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1113 // Single event for the whole quiz.
1114 if ($oldevent = array_shift($oldevents)) {
1115 $event->id = $oldevent->id;
1119 $event->name = $eventname;
1120 // calendar_event::create will reuse a db record if the id field is set
1121 calendar_event::create($event);
1123 // Separate start and end events.
1124 $event->timeduration = 0;
1125 if ($timeopen && $addopen) {
1126 if ($oldevent = array_shift($oldevents)) {
1127 $event->id = $oldevent->id;
1131 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
1132 // calendar_event::create will reuse a db record if the id field is set
1133 calendar_event::create($event);
1135 if ($timeclose && $addclose) {
1136 if ($oldevent = array_shift($oldevents)) {
1137 $event->id = $oldevent->id;
1141 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1142 $event->timestart = $timeclose;
1143 $event->eventtype = 'close';
1144 calendar_event::create($event);
1150 // Delete any leftover events
1151 foreach ($oldevents as $badevent) {
1152 $badevent = calendar_event::load($badevent);
1153 $badevent->delete();
1160 function quiz_get_view_actions() {
1161 return array('view', 'view all', 'report', 'review');
1167 function quiz_get_post_actions() {
1168 return array('attempt', 'close attempt', 'preview', 'editquestions',
1169 'delete attempt', 'manualgrade');
1173 * @param array $questionids of question ids.
1174 * @return bool whether any of these questions are used by any instance of this module.
1176 function quiz_questions_in_use($questionids) {
1178 require_once($CFG->libdir . '/questionlib.php');
1179 list($test, $params) = $DB->get_in_or_equal($questionids);
1180 return $DB->record_exists_select('quiz_question_instances',
1181 'question ' . $test, $params) || question_engine::questions_in_use(
1182 $questionids, new qubaid_join('{quiz_attempts} quiza',
1183 'quiza.uniqueid', 'quiza.preview = 0'));
1187 * Implementation of the function for printing the form elements that control
1188 * whether the course reset functionality affects the quiz.
1190 * @param $mform the course reset form that is being built.
1192 function quiz_reset_course_form_definition($mform) {
1193 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1194 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1195 get_string('removeallquizattempts', 'quiz'));
1199 * Course reset form defaults.
1200 * @return array the defaults.
1202 function quiz_reset_course_form_defaults($course) {
1203 return array('reset_quiz_attempts' => 1);
1207 * Removes all grades from gradebook
1209 * @param int $courseid
1210 * @param string optional type
1212 function quiz_reset_gradebook($courseid, $type='') {
1215 $quizzes = $DB->get_records_sql("
1216 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1218 JOIN {course_modules} cm ON m.id = cm.module
1219 JOIN {quiz} q ON cm.instance = q.id
1220 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1222 foreach ($quizzes as $quiz) {
1223 quiz_grade_item_update($quiz, 'reset');
1228 * Actual implementation of the reset course functionality, delete all the
1229 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1232 * Also, move the quiz open and close dates, if the course start date is changing.
1234 * @param object $data the data submitted from the reset course.
1235 * @return array status array
1237 function quiz_reset_userdata($data) {
1239 require_once($CFG->libdir.'/questionlib.php');
1241 $componentstr = get_string('modulenameplural', 'quiz');
1245 if (!empty($data->reset_quiz_attempts)) {
1246 require_once($CFG->libdir . '/questionlib.php');
1248 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1249 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1250 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1251 array('quizcourseid' => $data->courseid)));
1253 $DB->delete_records_select('quiz_attempts',
1254 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1256 'component' => $componentstr,
1257 'item' => get_string('attemptsdeleted', 'quiz'),
1260 // Remove all grades from gradebook
1261 if (empty($data->reset_gradebook_grades)) {
1262 quiz_reset_gradebook($data->courseid);
1265 'component' => $componentstr,
1266 'item' => get_string('attemptsdeleted', 'quiz'),
1270 // Updating dates - shift may be negative too
1271 if ($data->timeshift) {
1272 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1273 $data->timeshift, $data->courseid);
1275 'component' => $componentstr,
1276 'item' => get_string('openclosedatesupdated', 'quiz'),
1284 * Checks whether the current user is allowed to view a file uploaded in a quiz.
1285 * Teachers can view any from their courses, students can only view their own.
1287 * @param int $attemptuniqueid int attempt id
1288 * @param int $questionid int question id
1289 * @return bool to indicate access granted or denied
1291 function quiz_check_file_access($attemptuniqueid, $questionid, $context = null) {
1292 global $USER, $DB, $CFG;
1293 require_once(dirname(__FILE__).'/attemptlib.php');
1294 require_once(dirname(__FILE__).'/locallib.php');
1296 $attempt = $DB->get_record('quiz_attempts', array('uniqueid' => $attemptuniqueid));
1297 $attemptobj = quiz_attempt::create($attempt->id);
1299 // does question exist?
1300 if (!$question = $DB->get_record('question', array('id' => $questionid))) {
1304 if ($context === null) {
1305 $quiz = $DB->get_record('quiz', array('id' => $attempt->quiz));
1306 $cm = get_coursemodule_from_id('quiz', $quiz->id);
1307 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1310 // Load those questions and the associated states.
1311 $attemptobj->load_questions(array($questionid));
1312 $attemptobj->load_question_states(array($questionid));
1315 $state = $attemptobj->get_question_state($questionid);
1317 $question = $attemptobj->get_question($questionid);
1319 // access granted if the current user submitted this file
1320 if ($attempt->userid != $USER->id) {
1323 // access granted if the current user has permission to grade quizzes in this course
1324 if (!(has_capability('mod/quiz:viewreports', $context) ||
1325 has_capability('mod/quiz:grade', $context))) {
1329 return array($question, $state, array());
1333 * Prints quiz summaries on MyMoodle Page
1334 * @param arry $courses
1335 * @param array $htmlarray
1337 function quiz_print_overview($courses, &$htmlarray) {
1339 // These next 6 Lines are constant in all modules (just change module name)
1340 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1344 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1348 // Fetch some language strings outside the main loop.
1349 $strquiz = get_string('modulename', 'quiz');
1350 $strnoattempts = get_string('noattempts', 'quiz');
1352 // We want to list quizzes that are currently available, and which have a close date.
1353 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1355 foreach ($quizzes as $quiz) {
1356 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1357 // Give a link to the quiz, and the deadline.
1358 $str = '<div class="quiz overview">' .
1359 '<div class="name">' . $strquiz . ': <a ' .
1360 ($quiz->visible ? '' : ' class="dimmed"') .
1361 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1362 $quiz->coursemodule . '">' .
1363 $quiz->name . '</a></div>';
1364 $str .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1365 userdate($quiz->timeclose)) . '</div>';
1367 // Now provide more information depending on the uers's role.
1368 $context = get_context_instance(CONTEXT_MODULE, $quiz->coursemodule);
1369 if (has_capability('mod/quiz:viewreports', $context)) {
1370 // For teacher-like people, show a summary of the number of student attempts.
1371 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1372 // fields set to make the following call work.
1373 $str .= '<div class="info">' .
1374 quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1375 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'),
1376 $context)) { // Student
1377 // For student-like people, tell them how many attempts they have made.
1378 if (isset($USER->id) &&
1379 ($attempts = quiz_get_user_attempts($quiz->id, $USER->id))) {
1380 $numattempts = count($attempts);
1381 $str .= '<div class="info">' .
1382 get_string('numattemptsmade', 'quiz', $numattempts) . '</div>';
1384 $str .= '<div class="info">' . $strnoattempts . '</div>';
1387 // For ayone else, there is no point listing this quiz, so stop processing.
1391 // Add the output for this quiz to the rest.
1393 if (empty($htmlarray[$quiz->course]['quiz'])) {
1394 $htmlarray[$quiz->course]['quiz'] = $str;
1396 $htmlarray[$quiz->course]['quiz'] .= $str;
1403 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1404 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1406 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1407 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1408 * $cm->groupingid fields are used at the moment.
1409 * @param bool $returnzero if false (default), when no attempts have been
1410 * made '' is returned instead of 'Attempts: 0'.
1411 * @param int $currentgroup if there is a concept of current group where this method is being called
1412 * (e.g. a report) pass it in here. Default 0 which means no current group.
1413 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1414 * "Attemtps 123 (45 from this group)".
1416 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1418 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1419 if ($numattempts || $returnzero) {
1420 if (groups_get_activity_groupmode($cm)) {
1421 $a->total = $numattempts;
1422 if ($currentgroup) {
1423 $a->group = $DB->count_records_sql('SELECT count(1) FROM ' .
1424 '{quiz_attempts} qa JOIN ' .
1425 '{groups_members} gm ON qa.userid = gm.userid ' .
1426 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1427 array($quiz->id, $currentgroup));
1428 return get_string('attemptsnumthisgroup', 'quiz', $a);
1429 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1430 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1431 $a->group = $DB->count_records_sql('SELECT count(1) FROM ' .
1432 '{quiz_attempts} qa JOIN ' .
1433 '{groups_members} gm ON qa.userid = gm.userid ' .
1434 'WHERE quiz = ? AND preview = 0 AND ' .
1435 "groupid $usql", array_merge(array($quiz->id), $params));
1436 return get_string('attemptsnumyourgroups', 'quiz', $a);
1439 return get_string('attemptsnum', 'quiz', $numattempts);
1445 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1446 * to the quiz reports.
1448 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1449 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1450 * $cm->groupingid fields are used at the moment.
1451 * @param object $context the quiz context.
1452 * @param bool $returnzero if false (default), when no attempts have been made
1453 * '' is returned instead of 'Attempts: 0'.
1454 * @param int $currentgroup if there is a concept of current group where this method is being called
1455 * (e.g. a report) pass it in here. Default 0 which means no current group.
1456 * @return string HTML fragment for the link.
1458 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1459 $currentgroup = 0) {
1461 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1466 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1467 $url = new moodle_url('/mod/quiz/report.php', array(
1468 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1469 return html_writer::link($url, $summary);
1473 * @param string $feature FEATURE_xx constant for requested feature
1474 * @return bool True if quiz supports feature
1476 function quiz_supports($feature) {
1478 case FEATURE_GROUPS: return true;
1479 case FEATURE_GROUPINGS: return true;
1480 case FEATURE_GROUPMEMBERSONLY: return true;
1481 case FEATURE_MOD_INTRO: return true;
1482 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1483 case FEATURE_GRADE_HAS_GRADE: return true;
1484 case FEATURE_GRADE_OUTCOMES: return true;
1485 case FEATURE_BACKUP_MOODLE2: return true;
1487 default: return null;
1492 * @return array all other caps used in module
1494 function quiz_get_extra_capabilities() {
1496 require_once($CFG->libdir.'/questionlib.php');
1497 $caps = question_get_all_capabilities();
1498 $caps[] = 'moodle/site:accessallgroups';
1503 * This fucntion extends the global navigation for the site.
1504 * It is important to note that you should not rely on PAGE objects within this
1505 * body of code as there is no guarantee that during an AJAX request they are
1508 * @param navigation_node $quiznode The quiz node within the global navigation
1509 * @param object $course The course object returned from the DB
1510 * @param object $module The module object returned from the DB
1511 * @param object $cm The course module instance returned from the DB
1513 function quiz_extend_navigation($quiznode, $course, $module, $cm) {
1516 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1518 if (has_capability('mod/quiz:view', $context)) {
1519 $url = new moodle_url('/mod/quiz/view.php', array('id'=>$cm->id));
1520 $quiznode->add(get_string('info', 'quiz'), $url, navigation_node::TYPE_SETTING,
1521 null, null, new pix_icon('i/info', ''));
1524 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $context)) {
1525 require_once($CFG->dirroot.'/mod/quiz/report/reportlib.php');
1526 $reportlist = quiz_report_list($context);
1528 $url = new moodle_url('/mod/quiz/report.php',
1529 array('id' => $cm->id, 'mode' => reset($reportlist)));
1530 $reportnode = $quiznode->add(get_string('results', 'quiz'), $url,
1531 navigation_node::TYPE_SETTING,
1532 null, null, new pix_icon('i/report', ''));
1534 foreach ($reportlist as $report) {
1535 $url = new moodle_url('/mod/quiz/report.php',
1536 array('id' => $cm->id, 'mode' => $report));
1537 $reportnode->add(get_string($report, 'quiz_'.$report), $url,
1538 navigation_node::TYPE_SETTING,
1539 null, 'quiz_report_' . $report, new pix_icon('i/item', ''));
1545 * This function extends the settings navigation block for the site.
1547 * It is safe to rely on PAGE here as we will only ever be within the module
1548 * context when this is called
1550 * @param settings_navigation $settings
1551 * @param navigation_node $quiznode
1553 function quiz_extend_settings_navigation($settings, $quiznode) {
1557 * Require {@link questionlib.php}
1558 * Included here as we only ever want to include this file if we really need to.
1560 require_once($CFG->libdir . '/questionlib.php');
1562 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1563 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1564 $quiznode->add(get_string('groupoverrides', 'quiz'),
1565 new moodle_url($url, array('mode'=>'group')),
1566 navigation_node::TYPE_SETTING, null, 'groupoverrides');
1567 $quiznode->add(get_string('useroverrides', 'quiz'),
1568 new moodle_url($url, array('mode'=>'user')),
1569 navigation_node::TYPE_SETTING, null, 'useroverrides');
1572 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1573 $url = new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id));
1574 $text = get_string('editquiz', 'quiz');
1575 $quiznode->add($text, $url, navigation_node::TYPE_SETTING, null,
1576 'mod_quiz_edit', new pix_icon('t/edit', ''));
1579 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1580 $url = new moodle_url('/mod/quiz/startattempt.php',
1581 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1582 $quiznode->add(get_string('preview', 'quiz'), $url, navigation_node::TYPE_SETTING,
1583 null, 'mod_quiz_preview', new pix_icon('t/preview', ''));
1586 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1590 * Serves the quiz files.
1592 * @param object $course
1594 * @param object $context
1595 * @param string $filearea
1596 * @param array $args
1597 * @param bool $forcedownload
1598 * @return bool false if file not found, does not return if found - justsend the file
1600 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
1603 if ($context->contextlevel != CONTEXT_MODULE) {
1607 require_login($course, false, $cm);
1609 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1613 // 'intro' area is served by pluginfile.php
1614 $fileareas = array('feedback');
1615 if (!in_array($filearea, $fileareas)) {
1619 $feedbackid = (int)array_shift($args);
1620 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1624 $fs = get_file_storage();
1625 $relativepath = implode('/', $args);
1626 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1627 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1630 send_stored_file($file, 0, 0, true);
1634 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1635 * a question in a question_attempt when that attempt is a quiz attempt.
1637 * @param object $course course settings object
1638 * @param object $context context object
1639 * @param string $component the name of the component we are serving files for.
1640 * @param string $filearea the name of the file area.
1641 * @param array $args the remaining bits of the file path.
1642 * @param bool $forcedownload whether the user must be forced to download the file.
1643 * @return bool false if file not found, does not return if found - justsend the file
1645 function mod_quiz_question_pluginfile($course, $context, $component,
1646 $filearea, $qubaid, $slot, $args, $forcedownload) {
1648 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1650 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1651 require_login($attemptobj->get_courseid(), false, $attemptobj->get_cm());
1653 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1654 // In the middle of an attempt.
1655 if (!$attemptobj->is_preview_user()) {
1656 $attemptobj->require_capability('mod/quiz:attempt');
1658 $isreviewing = false;
1661 // Reviewing an attempt.
1662 $attemptobj->check_review_capability();
1663 $isreviewing = true;
1666 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1667 $component, $filearea, $args, $forcedownload)) {
1668 send_file_not_found();
1671 $fs = get_file_storage();
1672 $relativepath = implode('/', $args);
1673 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1674 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1675 send_file_not_found();
1678 send_stored_file($file, 0, 0, $forcedownload);