MDL-45565 core_message: Fixed strangers array
[moodle.git] / mod / quiz / lib.php
blob6ed0e3f5012b7716a105f8b146ee46516b39dde4
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for the quiz module.
20 * This contains functions that are called also from outside the quiz module
21 * Functions that are only called by the quiz module itself are in {@link locallib.php}
23 * @package mod_quiz
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir . '/eventslib.php');
32 require_once($CFG->dirroot . '/calendar/lib.php');
35 /**#@+
36 * Option controlling what options are offered on the quiz settings form.
38 define('QUIZ_MAX_ATTEMPT_OPTION', 10);
39 define('QUIZ_MAX_QPP_OPTION', 50);
40 define('QUIZ_MAX_DECIMAL_OPTION', 5);
41 define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
42 /**#@-*/
44 /**#@+
45 * Options determining how the grades from individual attempts are combined to give
46 * the overall grade for a user
48 define('QUIZ_GRADEHIGHEST', '1');
49 define('QUIZ_GRADEAVERAGE', '2');
50 define('QUIZ_ATTEMPTFIRST', '3');
51 define('QUIZ_ATTEMPTLAST', '4');
52 /**#@-*/
54 /**
55 * @var int If start and end date for the quiz are more than this many seconds apart
56 * they will be represented by two separate events in the calendar
58 define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
60 /**#@+
61 * Options for navigation method within quizzes.
63 define('QUIZ_NAVMETHOD_FREE', 'free');
64 define('QUIZ_NAVMETHOD_SEQ', 'sequential');
65 /**#@-*/
67 /**
68 * Given an object containing all the necessary data,
69 * (defined by the form in mod_form.php) this function
70 * will create a new instance and return the id number
71 * of the new instance.
73 * @param object $quiz the data that came from the form.
74 * @return mixed the id of the new instance on success,
75 * false or a string error message on failure.
77 function quiz_add_instance($quiz) {
78 global $DB;
79 $cmid = $quiz->coursemodule;
81 // Process the options from the form.
82 $quiz->created = time();
83 $result = quiz_process_options($quiz);
84 if ($result && is_string($result)) {
85 return $result;
88 // Try to store it in the database.
89 $quiz->id = $DB->insert_record('quiz', $quiz);
91 // Do the processing required after an add or an update.
92 quiz_after_add_or_update($quiz);
94 return $quiz->id;
97 /**
98 * Given an object containing all the necessary data,
99 * (defined by the form in mod_form.php) this function
100 * will update an existing instance with new data.
102 * @param object $quiz the data that came from the form.
103 * @return mixed true on success, false or a string error message on failure.
105 function quiz_update_instance($quiz, $mform) {
106 global $CFG, $DB;
107 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
109 // Process the options from the form.
110 $result = quiz_process_options($quiz);
111 if ($result && is_string($result)) {
112 return $result;
115 // Get the current value, so we can see what changed.
116 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
118 // We need two values from the existing DB record that are not in the form,
119 // in some of the function calls below.
120 $quiz->sumgrades = $oldquiz->sumgrades;
121 $quiz->grade = $oldquiz->grade;
123 // Update the database.
124 $quiz->id = $quiz->instance;
125 $DB->update_record('quiz', $quiz);
127 // Do the processing required after an add or an update.
128 quiz_after_add_or_update($quiz);
130 if ($oldquiz->grademethod != $quiz->grademethod) {
131 quiz_update_all_final_grades($quiz);
132 quiz_update_grades($quiz);
135 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
136 || $oldquiz->timeclose != $quiz->timeclose
137 || $oldquiz->graceperiod != $quiz->graceperiod;
138 if ($quizdateschanged) {
139 quiz_update_open_attempts(array('quizid' => $quiz->id));
142 // Delete any previous preview attempts.
143 quiz_delete_previews($quiz);
145 // Repaginate, if asked to.
146 if (!$quiz->shufflequestions && !empty($quiz->repaginatenow)) {
147 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
150 return true;
154 * Given an ID of an instance of this module,
155 * this function will permanently delete the instance
156 * and any data that depends on it.
158 * @param int $id the id of the quiz to delete.
159 * @return bool success or failure.
161 function quiz_delete_instance($id) {
162 global $DB;
164 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
166 quiz_delete_all_attempts($quiz);
167 quiz_delete_all_overrides($quiz);
169 $DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
170 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
172 quiz_access_manager::delete_settings($quiz);
174 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
175 foreach ($events as $event) {
176 $event = calendar_event::load($event);
177 $event->delete();
180 quiz_grade_item_delete($quiz);
181 $DB->delete_records('quiz', array('id' => $quiz->id));
183 return true;
187 * Deletes a quiz override from the database and clears any corresponding calendar events
189 * @param object $quiz The quiz object.
190 * @param int $overrideid The id of the override being deleted
191 * @return bool true on success
193 function quiz_delete_override($quiz, $overrideid) {
194 global $DB;
196 if (!isset($quiz->cmid)) {
197 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
198 $quiz->cmid = $cm->id;
201 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
203 // Delete the events.
204 $events = $DB->get_records('event', array('modulename' => 'quiz',
205 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
206 'userid' => (int)$override->userid));
207 foreach ($events as $event) {
208 $eventold = calendar_event::load($event);
209 $eventold->delete();
212 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
214 // Set the common parameters for one of the events we will be triggering.
215 $params = array(
216 'objectid' => $override->id,
217 'context' => context_module::instance($quiz->cmid),
218 'other' => array(
219 'quizid' => $override->quiz
222 // Determine which override deleted event to fire.
223 if (!empty($override->userid)) {
224 $params['relateduserid'] = $override->userid;
225 $event = \mod_quiz\event\user_override_deleted::create($params);
226 } else {
227 $params['other']['groupid'] = $override->groupid;
228 $event = \mod_quiz\event\group_override_deleted::create($params);
231 // Trigger the override deleted event.
232 $event->add_record_snapshot('quiz_overrides', $override);
233 $event->trigger();
235 return true;
239 * Deletes all quiz overrides from the database and clears any corresponding calendar events
241 * @param object $quiz The quiz object.
243 function quiz_delete_all_overrides($quiz) {
244 global $DB;
246 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
247 foreach ($overrides as $override) {
248 quiz_delete_override($quiz, $override->id);
253 * Updates a quiz object with override information for a user.
255 * Algorithm: For each quiz setting, if there is a matching user-specific override,
256 * then use that otherwise, if there are group-specific overrides, return the most
257 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
259 * Special case: if there is more than one password that applies to the user, then
260 * quiz->extrapasswords will contain an array of strings giving the remaining
261 * passwords.
263 * @param object $quiz The quiz object.
264 * @param int $userid The userid.
265 * @return object $quiz The updated quiz object.
267 function quiz_update_effective_access($quiz, $userid) {
268 global $DB;
270 // Check for user override.
271 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
273 if (!$override) {
274 $override = new stdClass();
275 $override->timeopen = null;
276 $override->timeclose = null;
277 $override->timelimit = null;
278 $override->attempts = null;
279 $override->password = null;
282 // Check for group overrides.
283 $groupings = groups_get_user_groups($quiz->course, $userid);
285 if (!empty($groupings[0])) {
286 // Select all overrides that apply to the User's groups.
287 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
288 $sql = "SELECT * FROM {quiz_overrides}
289 WHERE groupid $extra AND quiz = ?";
290 $params[] = $quiz->id;
291 $records = $DB->get_records_sql($sql, $params);
293 // Combine the overrides.
294 $opens = array();
295 $closes = array();
296 $limits = array();
297 $attempts = array();
298 $passwords = array();
300 foreach ($records as $gpoverride) {
301 if (isset($gpoverride->timeopen)) {
302 $opens[] = $gpoverride->timeopen;
304 if (isset($gpoverride->timeclose)) {
305 $closes[] = $gpoverride->timeclose;
307 if (isset($gpoverride->timelimit)) {
308 $limits[] = $gpoverride->timelimit;
310 if (isset($gpoverride->attempts)) {
311 $attempts[] = $gpoverride->attempts;
313 if (isset($gpoverride->password)) {
314 $passwords[] = $gpoverride->password;
317 // If there is a user override for a setting, ignore the group override.
318 if (is_null($override->timeopen) && count($opens)) {
319 $override->timeopen = min($opens);
321 if (is_null($override->timeclose) && count($closes)) {
322 if (in_array(0, $closes)) {
323 $override->timeclose = 0;
324 } else {
325 $override->timeclose = max($closes);
328 if (is_null($override->timelimit) && count($limits)) {
329 if (in_array(0, $limits)) {
330 $override->timelimit = 0;
331 } else {
332 $override->timelimit = max($limits);
335 if (is_null($override->attempts) && count($attempts)) {
336 if (in_array(0, $attempts)) {
337 $override->attempts = 0;
338 } else {
339 $override->attempts = max($attempts);
342 if (is_null($override->password) && count($passwords)) {
343 $override->password = array_shift($passwords);
344 if (count($passwords)) {
345 $override->extrapasswords = $passwords;
351 // Merge with quiz defaults.
352 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
353 foreach ($keys as $key) {
354 if (isset($override->{$key})) {
355 $quiz->{$key} = $override->{$key};
359 return $quiz;
363 * Delete all the attempts belonging to a quiz.
365 * @param object $quiz The quiz object.
367 function quiz_delete_all_attempts($quiz) {
368 global $CFG, $DB;
369 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
370 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
371 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
372 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
376 * Get the best current grade for a particular user in a quiz.
378 * @param object $quiz the quiz settings.
379 * @param int $userid the id of the user.
380 * @return float the user's current grade for this quiz, or null if this user does
381 * not have a grade on this quiz.
383 function quiz_get_best_grade($quiz, $userid) {
384 global $DB;
385 $grade = $DB->get_field('quiz_grades', 'grade',
386 array('quiz' => $quiz->id, 'userid' => $userid));
388 // Need to detect errors/no result, without catching 0 grades.
389 if ($grade === false) {
390 return null;
393 return $grade + 0; // Convert to number.
397 * Is this a graded quiz? If this method returns true, you can assume that
398 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
399 * divide by them).
401 * @param object $quiz a row from the quiz table.
402 * @return bool whether this is a graded quiz.
404 function quiz_has_grades($quiz) {
405 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
409 * Does this quiz allow multiple tries?
411 * @return bool
413 function quiz_allows_multiple_tries($quiz) {
414 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
415 return $bt->allows_multiple_submitted_responses();
419 * Return a small object with summary information about what a
420 * user has done with a given particular instance of this module
421 * Used for user activity reports.
422 * $return->time = the time they did it
423 * $return->info = a short text description
425 * @param object $course
426 * @param object $user
427 * @param object $mod
428 * @param object $quiz
429 * @return object|null
431 function quiz_user_outline($course, $user, $mod, $quiz) {
432 global $DB, $CFG;
433 require_once($CFG->libdir . '/gradelib.php');
434 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
436 if (empty($grades->items[0]->grades)) {
437 return null;
438 } else {
439 $grade = reset($grades->items[0]->grades);
442 $result = new stdClass();
443 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
445 // Datesubmitted == time created. dategraded == time modified or time overridden
446 // if grade was last modified by the user themselves use date graded. Otherwise use
447 // date submitted.
448 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
449 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
450 $result->time = $grade->dategraded;
451 } else {
452 $result->time = $grade->datesubmitted;
455 return $result;
459 * Print a detailed representation of what a user has done with
460 * a given particular instance of this module, for user activity reports.
462 * @param object $course
463 * @param object $user
464 * @param object $mod
465 * @param object $quiz
466 * @return bool
468 function quiz_user_complete($course, $user, $mod, $quiz) {
469 global $DB, $CFG, $OUTPUT;
470 require_once($CFG->libdir . '/gradelib.php');
471 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
473 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
474 if (!empty($grades->items[0]->grades)) {
475 $grade = reset($grades->items[0]->grades);
476 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
477 if ($grade->str_feedback) {
478 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
482 if ($attempts = $DB->get_records('quiz_attempts',
483 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
484 foreach ($attempts as $attempt) {
485 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
486 if ($attempt->state != quiz_attempt::FINISHED) {
487 echo quiz_attempt_state_name($attempt->state);
488 } else {
489 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
490 quiz_format_grade($quiz, $quiz->sumgrades);
492 echo ' - '.userdate($attempt->timemodified).'<br />';
494 } else {
495 print_string('noattempts', 'quiz');
498 return true;
502 * Quiz periodic clean-up tasks.
504 function quiz_cron() {
505 global $CFG;
507 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
508 mtrace('');
510 $timenow = time();
511 $overduehander = new mod_quiz_overdue_attempt_updater();
513 $processto = $timenow - get_config('quiz', 'graceperiodmin');
515 mtrace(' Looking for quiz overdue quiz attempts...');
517 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
519 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
521 // Run cron for our sub-plugin types.
522 cron_execute_plugin_type('quiz', 'quiz reports');
523 cron_execute_plugin_type('quizaccess', 'quiz access rules');
525 return true;
529 * @param int $quizid the quiz id.
530 * @param int $userid the userid.
531 * @param string $status 'all', 'finished' or 'unfinished' to control
532 * @param bool $includepreviews
533 * @return an array of all the user's attempts at this quiz. Returns an empty
534 * array if there are none.
536 function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
537 global $DB, $CFG;
538 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
539 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
540 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
541 // MDL-33048.
542 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
544 $params = array();
545 switch ($status) {
546 case 'all':
547 $statuscondition = '';
548 break;
550 case 'finished':
551 $statuscondition = ' AND state IN (:state1, :state2)';
552 $params['state1'] = quiz_attempt::FINISHED;
553 $params['state2'] = quiz_attempt::ABANDONED;
554 break;
556 case 'unfinished':
557 $statuscondition = ' AND state IN (:state1, :state2)';
558 $params['state1'] = quiz_attempt::IN_PROGRESS;
559 $params['state2'] = quiz_attempt::OVERDUE;
560 break;
563 $previewclause = '';
564 if (!$includepreviews) {
565 $previewclause = ' AND preview = 0';
568 $params['quizid'] = $quizid;
569 $params['userid'] = $userid;
570 return $DB->get_records_select('quiz_attempts',
571 'quiz = :quizid AND userid = :userid' . $previewclause . $statuscondition,
572 $params, 'attempt ASC');
576 * Return grade for given user or all users.
578 * @param int $quizid id of quiz
579 * @param int $userid optional user id, 0 means all users
580 * @return array array of grades, false if none. These are raw grades. They should
581 * be processed with quiz_format_grade for display.
583 function quiz_get_user_grades($quiz, $userid = 0) {
584 global $CFG, $DB;
586 $params = array($quiz->id);
587 $usertest = '';
588 if ($userid) {
589 $params[] = $userid;
590 $usertest = 'AND u.id = ?';
592 return $DB->get_records_sql("
593 SELECT
594 u.id,
595 u.id AS userid,
596 qg.grade AS rawgrade,
597 qg.timemodified AS dategraded,
598 MAX(qa.timefinish) AS datesubmitted
600 FROM {user} u
601 JOIN {quiz_grades} qg ON u.id = qg.userid
602 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
604 WHERE qg.quiz = ?
605 $usertest
606 GROUP BY u.id, qg.grade, qg.timemodified", $params);
610 * Round a grade to to the correct number of decimal places, and format it for display.
612 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
613 * @param float $grade The grade to round.
614 * @return float
616 function quiz_format_grade($quiz, $grade) {
617 if (is_null($grade)) {
618 return get_string('notyetgraded', 'quiz');
620 return format_float($grade, $quiz->decimalpoints);
624 * Round a grade to to the correct number of decimal places, and format it for display.
626 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
627 * @param float $grade The grade to round.
628 * @return float
630 function quiz_format_question_grade($quiz, $grade) {
631 if (empty($quiz->questiondecimalpoints)) {
632 $quiz->questiondecimalpoints = -1;
634 if ($quiz->questiondecimalpoints == -1) {
635 return format_float($grade, $quiz->decimalpoints);
636 } else {
637 return format_float($grade, $quiz->questiondecimalpoints);
642 * Update grades in central gradebook
644 * @category grade
645 * @param object $quiz the quiz settings.
646 * @param int $userid specific user only, 0 means all users.
647 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
649 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
650 global $CFG, $DB;
651 require_once($CFG->libdir . '/gradelib.php');
653 if ($quiz->grade == 0) {
654 quiz_grade_item_update($quiz);
656 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
657 quiz_grade_item_update($quiz, $grades);
659 } else if ($userid && $nullifnone) {
660 $grade = new stdClass();
661 $grade->userid = $userid;
662 $grade->rawgrade = null;
663 quiz_grade_item_update($quiz, $grade);
665 } else {
666 quiz_grade_item_update($quiz);
671 * Update all grades in gradebook.
673 function quiz_upgrade_grades() {
674 global $DB;
676 $sql = "SELECT COUNT('x')
677 FROM {quiz} a, {course_modules} cm, {modules} m
678 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
679 $count = $DB->count_records_sql($sql);
681 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
682 FROM {quiz} a, {course_modules} cm, {modules} m
683 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
684 $rs = $DB->get_recordset_sql($sql);
685 if ($rs->valid()) {
686 $pbar = new progress_bar('quizupgradegrades', 500, true);
687 $i=0;
688 foreach ($rs as $quiz) {
689 $i++;
690 upgrade_set_timeout(60*5); // Set up timeout, may also abort execution.
691 quiz_update_grades($quiz, 0, false);
692 $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
695 $rs->close();
699 * Create or update the grade item for given quiz
701 * @category grade
702 * @param object $quiz object with extra cmidnumber
703 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
704 * @return int 0 if ok, error code otherwise
706 function quiz_grade_item_update($quiz, $grades = null) {
707 global $CFG, $OUTPUT;
708 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
709 require_once($CFG->libdir . '/gradelib.php');
711 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
712 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
713 } else {
714 $params = array('itemname' => $quiz->name);
717 if ($quiz->grade > 0) {
718 $params['gradetype'] = GRADE_TYPE_VALUE;
719 $params['grademax'] = $quiz->grade;
720 $params['grademin'] = 0;
722 } else {
723 $params['gradetype'] = GRADE_TYPE_NONE;
726 // What this is trying to do:
727 // 1. If the quiz is set to not show grades while the quiz is still open,
728 // and is set to show grades after the quiz is closed, then create the
729 // grade_item with a show-after date that is the quiz close date.
730 // 2. If the quiz is set to not show grades at either of those times,
731 // create the grade_item as hidden.
732 // 3. If the quiz is set to show grades, create the grade_item visible.
733 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
734 mod_quiz_display_options::LATER_WHILE_OPEN);
735 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
736 mod_quiz_display_options::AFTER_CLOSE);
737 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
738 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
739 $params['hidden'] = 1;
741 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
742 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
743 if ($quiz->timeclose) {
744 $params['hidden'] = $quiz->timeclose;
745 } else {
746 $params['hidden'] = 1;
749 } else {
750 // Either
751 // a) both open and closed enabled
752 // b) open enabled, closed disabled - we can not "hide after",
753 // grades are kept visible even after closing.
754 $params['hidden'] = 0;
757 if (!$params['hidden']) {
758 // If the grade item is not hidden by the quiz logic, then we need to
759 // hide it if the quiz is hidden from students.
760 if (property_exists($quiz, 'visible')) {
761 // Saving the quiz form, and cm not yet updated in the database.
762 $params['hidden'] = !$quiz->visible;
763 } else {
764 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
765 $params['hidden'] = !$cm->visible;
769 if ($grades === 'reset') {
770 $params['reset'] = true;
771 $grades = null;
774 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
775 if (!empty($gradebook_grades->items)) {
776 $grade_item = $gradebook_grades->items[0];
777 if ($grade_item->locked) {
778 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
779 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
780 if (!$confirm_regrade) {
781 if (!AJAX_SCRIPT) {
782 $message = get_string('gradeitemislocked', 'grades');
783 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
784 '&amp;mode=overview';
785 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
786 echo $OUTPUT->box_start('generalbox', 'notice');
787 echo '<p>'. $message .'</p>';
788 echo $OUTPUT->container_start('buttons');
789 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
790 echo $OUTPUT->single_button($back_link, get_string('cancel'));
791 echo $OUTPUT->container_end();
792 echo $OUTPUT->box_end();
794 return GRADE_UPDATE_ITEM_LOCKED;
799 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
803 * Delete grade item for given quiz
805 * @category grade
806 * @param object $quiz object
807 * @return object quiz
809 function quiz_grade_item_delete($quiz) {
810 global $CFG;
811 require_once($CFG->libdir . '/gradelib.php');
813 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
814 null, array('deleted' => 1));
818 * This standard function will check all instances of this module
819 * and make sure there are up-to-date events created for each of them.
820 * If courseid = 0, then every quiz event in the site is checked, else
821 * only quiz events belonging to the course specified are checked.
822 * This function is used, in its new format, by restore_refresh_events()
824 * @param int $courseid
825 * @return bool
827 function quiz_refresh_events($courseid = 0) {
828 global $DB;
830 if ($courseid == 0) {
831 if (!$quizzes = $DB->get_records('quiz')) {
832 return true;
834 } else {
835 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
836 return true;
840 foreach ($quizzes as $quiz) {
841 quiz_update_events($quiz);
844 return true;
848 * Returns all quiz graded users since a given time for specified quiz
850 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
851 $courseid, $cmid, $userid = 0, $groupid = 0) {
852 global $CFG, $USER, $DB;
853 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
855 $course = get_course($courseid);
856 $modinfo = get_fast_modinfo($course);
858 $cm = $modinfo->cms[$cmid];
859 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
861 if ($userid) {
862 $userselect = "AND u.id = :userid";
863 $params['userid'] = $userid;
864 } else {
865 $userselect = '';
868 if ($groupid) {
869 $groupselect = 'AND gm.groupid = :groupid';
870 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
871 $params['groupid'] = $groupid;
872 } else {
873 $groupselect = '';
874 $groupjoin = '';
877 $params['timestart'] = $timestart;
878 $params['quizid'] = $quiz->id;
880 $ufields = user_picture::fields('u', null, 'useridagain');
881 if (!$attempts = $DB->get_records_sql("
882 SELECT qa.*,
883 {$ufields}
884 FROM {quiz_attempts} qa
885 JOIN {user} u ON u.id = qa.userid
886 $groupjoin
887 WHERE qa.timefinish > :timestart
888 AND qa.quiz = :quizid
889 AND qa.preview = 0
890 $userselect
891 $groupselect
892 ORDER BY qa.timefinish ASC", $params)) {
893 return;
896 $context = context_module::instance($cm->id);
897 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
898 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
899 $grader = has_capability('mod/quiz:viewreports', $context);
900 $groupmode = groups_get_activity_groupmode($cm, $course);
902 $usersgroups = null;
903 $aname = format_string($cm->name, true);
904 foreach ($attempts as $attempt) {
905 if ($attempt->userid != $USER->id) {
906 if (!$grader) {
907 // Grade permission required.
908 continue;
911 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
912 $usersgroups = groups_get_all_groups($course->id,
913 $attempt->userid, $cm->groupingid);
914 $usersgroups = array_keys($usersgroups);
915 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
916 continue;
921 $options = quiz_get_review_options($quiz, $attempt, $context);
923 $tmpactivity = new stdClass();
925 $tmpactivity->type = 'quiz';
926 $tmpactivity->cmid = $cm->id;
927 $tmpactivity->name = $aname;
928 $tmpactivity->sectionnum = $cm->sectionnum;
929 $tmpactivity->timestamp = $attempt->timefinish;
931 $tmpactivity->content = new stdClass();
932 $tmpactivity->content->attemptid = $attempt->id;
933 $tmpactivity->content->attempt = $attempt->attempt;
934 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
935 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
936 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
937 } else {
938 $tmpactivity->content->sumgrades = null;
939 $tmpactivity->content->maxgrade = null;
942 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
943 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
945 $activities[$index++] = $tmpactivity;
949 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
950 global $CFG, $OUTPUT;
952 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
954 echo '<tr><td class="userpicture" valign="top">';
955 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
956 echo '</td><td>';
958 if ($detail) {
959 $modname = $modnames[$activity->type];
960 echo '<div class="title">';
961 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
962 'class="icon" alt="' . $modname . '" />';
963 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
964 $activity->cmid . '">' . $activity->name . '</a>';
965 echo '</div>';
968 echo '<div class="grade">';
969 echo get_string('attempt', 'quiz', $activity->content->attempt);
970 if (isset($activity->content->maxgrade)) {
971 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
972 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
973 $activity->content->attemptid . '">' . $grades . '</a>)';
975 echo '</div>';
977 echo '<div class="user">';
978 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
979 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
980 '</a> - ' . userdate($activity->timestamp);
981 echo '</div>';
983 echo '</td></tr></table>';
985 return;
989 * Pre-process the quiz options form data, making any necessary adjustments.
990 * Called by add/update instance in this file.
992 * @param object $quiz The variables set on the form.
994 function quiz_process_options($quiz) {
995 global $CFG;
996 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
997 require_once($CFG->libdir . '/questionlib.php');
999 $quiz->timemodified = time();
1001 // Quiz name.
1002 if (!empty($quiz->name)) {
1003 $quiz->name = trim($quiz->name);
1006 // Password field - different in form to stop browsers that remember passwords
1007 // getting confused.
1008 $quiz->password = $quiz->quizpassword;
1009 unset($quiz->quizpassword);
1011 // Quiz feedback.
1012 if (isset($quiz->feedbacktext)) {
1013 // Clean up the boundary text.
1014 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1015 if (empty($quiz->feedbacktext[$i]['text'])) {
1016 $quiz->feedbacktext[$i]['text'] = '';
1017 } else {
1018 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1022 // Check the boundary value is a number or a percentage, and in range.
1023 $i = 0;
1024 while (!empty($quiz->feedbackboundaries[$i])) {
1025 $boundary = trim($quiz->feedbackboundaries[$i]);
1026 if (!is_numeric($boundary)) {
1027 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1028 $boundary = trim(substr($boundary, 0, -1));
1029 if (is_numeric($boundary)) {
1030 $boundary = $boundary * $quiz->grade / 100.0;
1031 } else {
1032 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1036 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1037 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1039 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1040 return get_string('feedbackerrororder', 'quiz', $i + 1);
1042 $quiz->feedbackboundaries[$i] = $boundary;
1043 $i += 1;
1045 $numboundaries = $i;
1047 // Check there is nothing in the remaining unused fields.
1048 if (!empty($quiz->feedbackboundaries)) {
1049 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1050 if (!empty($quiz->feedbackboundaries[$i]) &&
1051 trim($quiz->feedbackboundaries[$i]) != '') {
1052 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1056 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1057 if (!empty($quiz->feedbacktext[$i]['text']) &&
1058 trim($quiz->feedbacktext[$i]['text']) != '') {
1059 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1062 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1063 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1064 $quiz->feedbackboundaries[$numboundaries] = 0;
1065 $quiz->feedbackboundarycount = $numboundaries;
1066 } else {
1067 $quiz->feedbackboundarycount = -1;
1070 // Combing the individual settings into the review columns.
1071 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1072 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1073 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1074 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1075 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1076 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1077 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1078 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1079 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1083 * Helper function for {@link quiz_process_options()}.
1084 * @param object $fromform the sumbitted form date.
1085 * @param string $field one of the review option field names.
1087 function quiz_review_option_form_to_db($fromform, $field) {
1088 static $times = array(
1089 'during' => mod_quiz_display_options::DURING,
1090 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1091 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1092 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1095 $review = 0;
1096 foreach ($times as $whenname => $when) {
1097 $fieldname = $field . $whenname;
1098 if (isset($fromform->$fieldname)) {
1099 $review |= $when;
1100 unset($fromform->$fieldname);
1104 return $review;
1108 * This function is called at the end of quiz_add_instance
1109 * and quiz_update_instance, to do the common processing.
1111 * @param object $quiz the quiz object.
1113 function quiz_after_add_or_update($quiz) {
1114 global $DB;
1115 $cmid = $quiz->coursemodule;
1117 // We need to use context now, so we need to make sure all needed info is already in db.
1118 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
1119 $context = context_module::instance($cmid);
1121 // Save the feedback.
1122 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
1124 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1125 $feedback = new stdClass();
1126 $feedback->quizid = $quiz->id;
1127 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1128 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1129 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1130 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1131 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1132 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1133 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1134 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1135 $quiz->feedbacktext[$i]['text']);
1136 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1137 array('id' => $feedback->id));
1140 // Store any settings belonging to the access rules.
1141 quiz_access_manager::save_settings($quiz);
1143 // Update the events relating to this quiz.
1144 quiz_update_events($quiz);
1146 // Update related grade item.
1147 quiz_grade_item_update($quiz);
1151 * This function updates the events associated to the quiz.
1152 * If $override is non-zero, then it updates only the events
1153 * associated with the specified override.
1155 * @uses QUIZ_MAX_EVENT_LENGTH
1156 * @param object $quiz the quiz object.
1157 * @param object optional $override limit to a specific override
1159 function quiz_update_events($quiz, $override = null) {
1160 global $DB;
1162 // Load the old events relating to this quiz.
1163 $conds = array('modulename'=>'quiz',
1164 'instance'=>$quiz->id);
1165 if (!empty($override)) {
1166 // Only load events for this override.
1167 $conds['groupid'] = isset($override->groupid)? $override->groupid : 0;
1168 $conds['userid'] = isset($override->userid)? $override->userid : 0;
1170 $oldevents = $DB->get_records('event', $conds);
1172 // Now make a todo list of all that needs to be updated.
1173 if (empty($override)) {
1174 // We are updating the primary settings for the quiz, so we
1175 // need to add all the overrides.
1176 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
1177 // As well as the original quiz (empty override).
1178 $overrides[] = new stdClass();
1179 } else {
1180 // Just do the one override.
1181 $overrides = array($override);
1184 foreach ($overrides as $current) {
1185 $groupid = isset($current->groupid)? $current->groupid : 0;
1186 $userid = isset($current->userid)? $current->userid : 0;
1187 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1188 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1190 // Only add open/close events for an override if they differ from the quiz default.
1191 $addopen = empty($current->id) || !empty($current->timeopen);
1192 $addclose = empty($current->id) || !empty($current->timeclose);
1194 if (!empty($quiz->coursemodule)) {
1195 $cmid = $quiz->coursemodule;
1196 } else {
1197 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1200 $event = new stdClass();
1201 $event->description = format_module_intro('quiz', $quiz, $cmid);
1202 // Events module won't show user events when the courseid is nonzero.
1203 $event->courseid = ($userid) ? 0 : $quiz->course;
1204 $event->groupid = $groupid;
1205 $event->userid = $userid;
1206 $event->modulename = 'quiz';
1207 $event->instance = $quiz->id;
1208 $event->timestart = $timeopen;
1209 $event->timeduration = max($timeclose - $timeopen, 0);
1210 $event->visible = instance_is_visible('quiz', $quiz);
1211 $event->eventtype = 'open';
1213 // Determine the event name.
1214 if ($groupid) {
1215 $params = new stdClass();
1216 $params->quiz = $quiz->name;
1217 $params->group = groups_get_group_name($groupid);
1218 if ($params->group === false) {
1219 // Group doesn't exist, just skip it.
1220 continue;
1222 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1223 } else if ($userid) {
1224 $params = new stdClass();
1225 $params->quiz = $quiz->name;
1226 $eventname = get_string('overrideusereventname', 'quiz', $params);
1227 } else {
1228 $eventname = $quiz->name;
1230 if ($addopen or $addclose) {
1231 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1232 // Single event for the whole quiz.
1233 if ($oldevent = array_shift($oldevents)) {
1234 $event->id = $oldevent->id;
1235 } else {
1236 unset($event->id);
1238 $event->name = $eventname;
1239 // The method calendar_event::create will reuse a db record if the id field is set.
1240 calendar_event::create($event);
1241 } else {
1242 // Separate start and end events.
1243 $event->timeduration = 0;
1244 if ($timeopen && $addopen) {
1245 if ($oldevent = array_shift($oldevents)) {
1246 $event->id = $oldevent->id;
1247 } else {
1248 unset($event->id);
1250 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
1251 // The method calendar_event::create will reuse a db record if the id field is set.
1252 calendar_event::create($event);
1254 if ($timeclose && $addclose) {
1255 if ($oldevent = array_shift($oldevents)) {
1256 $event->id = $oldevent->id;
1257 } else {
1258 unset($event->id);
1260 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1261 $event->timestart = $timeclose;
1262 $event->eventtype = 'close';
1263 calendar_event::create($event);
1269 // Delete any leftover events.
1270 foreach ($oldevents as $badevent) {
1271 $badevent = calendar_event::load($badevent);
1272 $badevent->delete();
1277 * List the actions that correspond to a view of this module.
1278 * This is used by the participation report.
1280 * Note: This is not used by new logging system. Event with
1281 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1282 * be considered as view action.
1284 * @return array
1286 function quiz_get_view_actions() {
1287 return array('view', 'view all', 'report', 'review');
1291 * List the actions that correspond to a post of this module.
1292 * This is used by the participation report.
1294 * Note: This is not used by new logging system. Event with
1295 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1296 * will be considered as post action.
1298 * @return array
1300 function quiz_get_post_actions() {
1301 return array('attempt', 'close attempt', 'preview', 'editquestions',
1302 'delete attempt', 'manualgrade');
1306 * @param array $questionids of question ids.
1307 * @return bool whether any of these questions are used by any instance of this module.
1309 function quiz_questions_in_use($questionids) {
1310 global $DB, $CFG;
1311 require_once($CFG->libdir . '/questionlib.php');
1312 list($test, $params) = $DB->get_in_or_equal($questionids);
1313 return $DB->record_exists_select('quiz_slots',
1314 'questionid ' . $test, $params) || question_engine::questions_in_use(
1315 $questionids, new qubaid_join('{quiz_attempts} quiza',
1316 'quiza.uniqueid', 'quiza.preview = 0'));
1320 * Implementation of the function for printing the form elements that control
1321 * whether the course reset functionality affects the quiz.
1323 * @param $mform the course reset form that is being built.
1325 function quiz_reset_course_form_definition($mform) {
1326 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1327 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1328 get_string('removeallquizattempts', 'quiz'));
1332 * Course reset form defaults.
1333 * @return array the defaults.
1335 function quiz_reset_course_form_defaults($course) {
1336 return array('reset_quiz_attempts' => 1);
1340 * Removes all grades from gradebook
1342 * @param int $courseid
1343 * @param string optional type
1345 function quiz_reset_gradebook($courseid, $type='') {
1346 global $CFG, $DB;
1348 $quizzes = $DB->get_records_sql("
1349 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1350 FROM {modules} m
1351 JOIN {course_modules} cm ON m.id = cm.module
1352 JOIN {quiz} q ON cm.instance = q.id
1353 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
1355 foreach ($quizzes as $quiz) {
1356 quiz_grade_item_update($quiz, 'reset');
1361 * Actual implementation of the reset course functionality, delete all the
1362 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1363 * set and true.
1365 * Also, move the quiz open and close dates, if the course start date is changing.
1367 * @param object $data the data submitted from the reset course.
1368 * @return array status array
1370 function quiz_reset_userdata($data) {
1371 global $CFG, $DB;
1372 require_once($CFG->libdir . '/questionlib.php');
1374 $componentstr = get_string('modulenameplural', 'quiz');
1375 $status = array();
1377 // Delete attempts.
1378 if (!empty($data->reset_quiz_attempts)) {
1379 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1380 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1381 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1382 array('quizcourseid' => $data->courseid)));
1384 $DB->delete_records_select('quiz_attempts',
1385 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1386 $status[] = array(
1387 'component' => $componentstr,
1388 'item' => get_string('attemptsdeleted', 'quiz'),
1389 'error' => false);
1391 // Remove all grades from gradebook.
1392 $DB->delete_records_select('quiz_grades',
1393 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1394 if (empty($data->reset_gradebook_grades)) {
1395 quiz_reset_gradebook($data->courseid);
1397 $status[] = array(
1398 'component' => $componentstr,
1399 'item' => get_string('gradesdeleted', 'quiz'),
1400 'error' => false);
1403 // Updating dates - shift may be negative too.
1404 if ($data->timeshift) {
1405 $DB->execute("UPDATE {quiz_overrides}
1406 SET timeopen = timeopen + ?
1407 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1408 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1409 $DB->execute("UPDATE {quiz_overrides}
1410 SET timeclose = timeclose + ?
1411 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1412 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1414 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1415 $data->timeshift, $data->courseid);
1417 $status[] = array(
1418 'component' => $componentstr,
1419 'item' => get_string('openclosedatesupdated', 'quiz'),
1420 'error' => false);
1423 return $status;
1427 * Prints quiz summaries on MyMoodle Page
1428 * @param arry $courses
1429 * @param array $htmlarray
1431 function quiz_print_overview($courses, &$htmlarray) {
1432 global $USER, $CFG;
1433 // These next 6 Lines are constant in all modules (just change module name).
1434 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1435 return array();
1438 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
1439 return;
1442 // Fetch some language strings outside the main loop.
1443 $strquiz = get_string('modulename', 'quiz');
1444 $strnoattempts = get_string('noattempts', 'quiz');
1446 // We want to list quizzes that are currently available, and which have a close date.
1447 // This is the same as what the lesson does, and the dabate is in MDL-10568.
1448 $now = time();
1449 foreach ($quizzes as $quiz) {
1450 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
1451 // Give a link to the quiz, and the deadline.
1452 $str = '<div class="quiz overview">' .
1453 '<div class="name">' . $strquiz . ': <a ' .
1454 ($quiz->visible ? '' : ' class="dimmed"') .
1455 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1456 $quiz->coursemodule . '">' .
1457 $quiz->name . '</a></div>';
1458 $str .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1459 userdate($quiz->timeclose)) . '</div>';
1461 // Now provide more information depending on the uers's role.
1462 $context = context_module::instance($quiz->coursemodule);
1463 if (has_capability('mod/quiz:viewreports', $context)) {
1464 // For teacher-like people, show a summary of the number of student attempts.
1465 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
1466 // fields set to make the following call work.
1467 $str .= '<div class="info">' .
1468 quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1469 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'),
1470 $context)) { // Student
1471 // For student-like people, tell them how many attempts they have made.
1472 if (isset($USER->id) &&
1473 ($attempts = quiz_get_user_attempts($quiz->id, $USER->id))) {
1474 $numattempts = count($attempts);
1475 $str .= '<div class="info">' .
1476 get_string('numattemptsmade', 'quiz', $numattempts) . '</div>';
1477 } else {
1478 $str .= '<div class="info">' . $strnoattempts . '</div>';
1480 } else {
1481 // For ayone else, there is no point listing this quiz, so stop processing.
1482 continue;
1485 // Add the output for this quiz to the rest.
1486 $str .= '</div>';
1487 if (empty($htmlarray[$quiz->course]['quiz'])) {
1488 $htmlarray[$quiz->course]['quiz'] = $str;
1489 } else {
1490 $htmlarray[$quiz->course]['quiz'] .= $str;
1497 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1498 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1500 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1501 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1502 * $cm->groupingid fields are used at the moment.
1503 * @param bool $returnzero if false (default), when no attempts have been
1504 * made '' is returned instead of 'Attempts: 0'.
1505 * @param int $currentgroup if there is a concept of current group where this method is being called
1506 * (e.g. a report) pass it in here. Default 0 which means no current group.
1507 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1508 * "Attemtps 123 (45 from this group)".
1510 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1511 global $DB, $USER;
1512 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
1513 if ($numattempts || $returnzero) {
1514 if (groups_get_activity_groupmode($cm)) {
1515 $a = new stdClass();
1516 $a->total = $numattempts;
1517 if ($currentgroup) {
1518 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1519 '{quiz_attempts} qa JOIN ' .
1520 '{groups_members} gm ON qa.userid = gm.userid ' .
1521 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1522 array($quiz->id, $currentgroup));
1523 return get_string('attemptsnumthisgroup', 'quiz', $a);
1524 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1525 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1526 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1527 '{quiz_attempts} qa JOIN ' .
1528 '{groups_members} gm ON qa.userid = gm.userid ' .
1529 'WHERE quiz = ? AND preview = 0 AND ' .
1530 "groupid $usql", array_merge(array($quiz->id), $params));
1531 return get_string('attemptsnumyourgroups', 'quiz', $a);
1534 return get_string('attemptsnum', 'quiz', $numattempts);
1536 return '';
1540 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1541 * to the quiz reports.
1543 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1544 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1545 * $cm->groupingid fields are used at the moment.
1546 * @param object $context the quiz context.
1547 * @param bool $returnzero if false (default), when no attempts have been made
1548 * '' is returned instead of 'Attempts: 0'.
1549 * @param int $currentgroup if there is a concept of current group where this method is being called
1550 * (e.g. a report) pass it in here. Default 0 which means no current group.
1551 * @return string HTML fragment for the link.
1553 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1554 $currentgroup = 0) {
1555 global $CFG;
1556 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1557 if (!$summary) {
1558 return '';
1561 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1562 $url = new moodle_url('/mod/quiz/report.php', array(
1563 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1564 return html_writer::link($url, $summary);
1568 * @param string $feature FEATURE_xx constant for requested feature
1569 * @return bool True if quiz supports feature
1571 function quiz_supports($feature) {
1572 switch($feature) {
1573 case FEATURE_GROUPS: return true;
1574 case FEATURE_GROUPINGS: return true;
1575 case FEATURE_GROUPMEMBERSONLY: return true;
1576 case FEATURE_MOD_INTRO: return true;
1577 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1578 case FEATURE_GRADE_HAS_GRADE: return true;
1579 case FEATURE_GRADE_OUTCOMES: return true;
1580 case FEATURE_BACKUP_MOODLE2: return true;
1581 case FEATURE_SHOW_DESCRIPTION: return true;
1582 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1583 case FEATURE_USES_QUESTIONS: return true;
1585 default: return null;
1590 * @return array all other caps used in module
1592 function quiz_get_extra_capabilities() {
1593 global $CFG;
1594 require_once($CFG->libdir . '/questionlib.php');
1595 $caps = question_get_all_capabilities();
1596 $caps[] = 'moodle/site:accessallgroups';
1597 return $caps;
1601 * This function extends the settings navigation block for the site.
1603 * It is safe to rely on PAGE here as we will only ever be within the module
1604 * context when this is called
1606 * @param settings_navigation $settings
1607 * @param navigation_node $quiznode
1608 * @return void
1610 function quiz_extend_settings_navigation($settings, $quiznode) {
1611 global $PAGE, $CFG;
1613 // Require {@link questionlib.php}
1614 // Included here as we only ever want to include this file if we really need to.
1615 require_once($CFG->libdir . '/questionlib.php');
1617 // We want to add these new nodes after the Edit settings node, and before the
1618 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1619 $keys = $quiznode->get_children_key_list();
1620 $beforekey = null;
1621 $i = array_search('modedit', $keys);
1622 if ($i === false and array_key_exists(0, $keys)) {
1623 $beforekey = $keys[0];
1624 } else if (array_key_exists($i + 1, $keys)) {
1625 $beforekey = $keys[$i + 1];
1628 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
1629 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
1630 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
1631 new moodle_url($url, array('mode'=>'group')),
1632 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1633 $quiznode->add_node($node, $beforekey);
1635 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
1636 new moodle_url($url, array('mode'=>'user')),
1637 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1638 $quiznode->add_node($node, $beforekey);
1641 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
1642 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1643 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1644 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1645 new pix_icon('t/edit', ''));
1646 $quiznode->add_node($node, $beforekey);
1649 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
1650 $url = new moodle_url('/mod/quiz/startattempt.php',
1651 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
1652 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1653 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1654 new pix_icon('i/preview', ''));
1655 $quiznode->add_node($node, $beforekey);
1658 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1659 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1660 $reportlist = quiz_report_list($PAGE->cm->context);
1662 $url = new moodle_url('/mod/quiz/report.php',
1663 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1664 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1665 navigation_node::TYPE_SETTING,
1666 null, null, new pix_icon('i/report', '')), $beforekey);
1668 foreach ($reportlist as $report) {
1669 $url = new moodle_url('/mod/quiz/report.php',
1670 array('id' => $PAGE->cm->id, 'mode' => $report));
1671 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1672 navigation_node::TYPE_SETTING,
1673 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1677 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
1681 * Serves the quiz files.
1683 * @package mod_quiz
1684 * @category files
1685 * @param stdClass $course course object
1686 * @param stdClass $cm course module object
1687 * @param stdClass $context context object
1688 * @param string $filearea file area
1689 * @param array $args extra arguments
1690 * @param bool $forcedownload whether or not force download
1691 * @param array $options additional options affecting the file serving
1692 * @return bool false if file not found, does not return if found - justsend the file
1694 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1695 global $CFG, $DB;
1697 if ($context->contextlevel != CONTEXT_MODULE) {
1698 return false;
1701 require_login($course, false, $cm);
1703 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1704 return false;
1707 // The 'intro' area is served by pluginfile.php.
1708 $fileareas = array('feedback');
1709 if (!in_array($filearea, $fileareas)) {
1710 return false;
1713 $feedbackid = (int)array_shift($args);
1714 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1715 return false;
1718 $fs = get_file_storage();
1719 $relativepath = implode('/', $args);
1720 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1721 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1722 return false;
1724 send_stored_file($file, 0, 0, true, $options);
1728 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1729 * a question in a question_attempt when that attempt is a quiz attempt.
1731 * @package mod_quiz
1732 * @category files
1733 * @param stdClass $course course settings object
1734 * @param stdClass $context context object
1735 * @param string $component the name of the component we are serving files for.
1736 * @param string $filearea the name of the file area.
1737 * @param int $qubaid the attempt usage id.
1738 * @param int $slot the id of a question in this quiz attempt.
1739 * @param array $args the remaining bits of the file path.
1740 * @param bool $forcedownload whether the user must be forced to download the file.
1741 * @param array $options additional options affecting the file serving
1742 * @return bool false if file not found, does not return if found - justsend the file
1744 function quiz_question_pluginfile($course, $context, $component,
1745 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
1746 global $CFG;
1747 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1749 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1750 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1752 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1753 // In the middle of an attempt.
1754 if (!$attemptobj->is_preview_user()) {
1755 $attemptobj->require_capability('mod/quiz:attempt');
1757 $isreviewing = false;
1759 } else {
1760 // Reviewing an attempt.
1761 $attemptobj->check_review_capability();
1762 $isreviewing = true;
1765 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1766 $component, $filearea, $args, $forcedownload)) {
1767 send_file_not_found();
1770 $fs = get_file_storage();
1771 $relativepath = implode('/', $args);
1772 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1773 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1774 send_file_not_found();
1777 send_stored_file($file, 0, 0, $forcedownload, $options);
1781 * Return a list of page types
1782 * @param string $pagetype current page type
1783 * @param stdClass $parentcontext Block's parent context
1784 * @param stdClass $currentcontext Current context of block
1786 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1787 $module_pagetype = array(
1788 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1789 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1790 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1791 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1792 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1793 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1794 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1796 return $module_pagetype;
1800 * @return the options for quiz navigation.
1802 function quiz_get_navigation_options() {
1803 return array(
1804 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1805 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')