MDL-55956 mod: New function *_get_group_override_priorities()
[moodle.git] / mod / quiz / lib.php
CommitLineData
8cc86111 1<?php
8cc86111 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.
13//
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/>.
84e628a0 16
ee1fb969 17/**
84e628a0 18 * Library of functions for the quiz module.
19 *
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}
22 *
01773a6d 23 * @package mod_quiz
ba643847
TH
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
84e628a0 26 */
730fd187 27
25302dee 28
a17b297d
TH
29defined('MOODLE_INTERNAL') || die();
30
84e628a0 31require_once($CFG->libdir . '/eventslib.php');
f81a8247 32require_once($CFG->dirroot . '/calendar/lib.php');
8966a111 33
75cd257b 34
e2249afe 35/**#@+
25302dee 36 * Option controlling what options are offered on the quiz settings form.
e2249afe 37 */
84e628a0 38define('QUIZ_MAX_ATTEMPT_OPTION', 10);
39define('QUIZ_MAX_QPP_OPTION', 50);
40define('QUIZ_MAX_DECIMAL_OPTION', 5);
41define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
75cd257b 42/**#@-*/
43
4344c5d5
TH
44/**#@+
45 * Options determining how the grades from individual attempts are combined to give
46 * the overall grade for a user
47 */
48define('QUIZ_GRADEHIGHEST', '1');
49define('QUIZ_GRADEAVERAGE', '2');
50define('QUIZ_ATTEMPTFIRST', '3');
51define('QUIZ_ATTEMPTLAST', '4');
52/**#@-*/
53
75cd257b 54/**
9e83f3d1 55 * @var int If start and end date for the quiz are more than this many seconds apart
75cd257b 56 * they will be represented by two separate events in the calendar
57 */
9e83f3d1 58define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
ee1fb969 59
33c8d37b
CF
60/**#@+
61 * Options for navigation method within quizzes.
62 */
63define('QUIZ_NAVMETHOD_FREE', 'free');
64define('QUIZ_NAVMETHOD_SEQ', 'sequential');
65/**#@-*/
66
920b93d1 67/**
68 * Given an object containing all the necessary data,
7cac0c4b 69 * (defined by the form in mod_form.php) this function
920b93d1 70 * will create a new instance and return the id number
71 * of the new instance.
a23f0aaf 72 *
920b93d1 73 * @param object $quiz the data that came from the form.
212b7b8c 74 * @return mixed the id of the new instance on success,
75 * false or a string error message on failure.
920b93d1 76 */
730fd187 77function quiz_add_instance($quiz) {
c18269c7 78 global $DB;
fe6ce234 79 $cmid = $quiz->coursemodule;
730fd187 80
920b93d1 81 // Process the options from the form.
82 $quiz->created = time();
212b7b8c 83 $result = quiz_process_options($quiz);
84 if ($result && is_string($result)) {
85 return $result;
86 }
6f797013 87
920b93d1 88 // Try to store it in the database.
eeab18f0 89 $quiz->id = $DB->insert_record('quiz', $quiz);
7bd1aa1d 90
5d949702
K
91 // Create the first section for this quiz.
92 $DB->insert_record('quiz_sections', array('quizid' => $quiz->id,
93 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0));
94
920b93d1 95 // Do the processing required after an add or an update.
96 quiz_after_add_or_update($quiz);
a23f0aaf 97
7bd1aa1d 98 return $quiz->id;
730fd187 99}
100
920b93d1 101/**
102 * Given an object containing all the necessary data,
7cac0c4b 103 * (defined by the form in mod_form.php) this function
920b93d1 104 * will update an existing instance with new data.
a23f0aaf 105 *
920b93d1 106 * @param object $quiz the data that came from the form.
212b7b8c 107 * @return mixed true on success, false or a string error message on failure.
920b93d1 108 */
eeab18f0 109function quiz_update_instance($quiz, $mform) {
110 global $CFG, $DB;
475225a1 111 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
730fd187 112
920b93d1 113 // Process the options from the form.
212b7b8c 114 $result = quiz_process_options($quiz);
115 if ($result && is_string($result)) {
116 return $result;
117 }
ee1fb969 118
475225a1 119 // Get the current value, so we can see what changed.
f2557823 120 $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
25302dee 121
475225a1
TH
122 // We need two values from the existing DB record that are not in the form,
123 // in some of the function calls below.
124 $quiz->sumgrades = $oldquiz->sumgrades;
125 $quiz->grade = $oldquiz->grade;
126
920b93d1 127 // Update the database.
730fd187 128 $quiz->id = $quiz->instance;
eeab18f0 129 $DB->update_record('quiz', $quiz);
730fd187 130
920b93d1 131 // Do the processing required after an add or an update.
132 quiz_after_add_or_update($quiz);
ee1fb969 133
25302dee 134 if ($oldquiz->grademethod != $quiz->grademethod) {
25302dee
TH
135 quiz_update_all_final_grades($quiz);
136 quiz_update_grades($quiz);
137 }
138
475225a1
TH
139 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
140 || $oldquiz->timeclose != $quiz->timeclose
141 || $oldquiz->graceperiod != $quiz->graceperiod;
142 if ($quizdateschanged) {
143 quiz_update_open_attempts(array('quizid' => $quiz->id));
8e771aed
MP
144 }
145
9e83f3d1 146 // Delete any previous preview attempts.
53004e48 147 quiz_delete_previews($quiz);
d2f308c0 148
ccba5b88 149 // Repaginate, if asked to.
5d949702 150 if (!empty($quiz->repaginatenow)) {
ccba5b88
TH
151 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
152 }
153
7bd1aa1d 154 return true;
730fd187 155}
156
8cc86111 157/**
158 * Given an ID of an instance of this module,
159 * this function will permanently delete the instance
160 * and any data that depends on it.
161 *
25302dee 162 * @param int $id the id of the quiz to delete.
f7970e3c 163 * @return bool success or failure.
8cc86111 164 */
730fd187 165function quiz_delete_instance($id) {
c18269c7 166 global $DB;
730fd187 167
25302dee 168 $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
730fd187 169
53004e48 170 quiz_delete_all_attempts($quiz);
990650f9 171 quiz_delete_all_overrides($quiz);
730fd187 172
828a4e9f
EM
173 // Look for random questions that may no longer be used when this quiz is gone.
174 $sql = "SELECT q.id
175 FROM {quiz_slots} slot
176 JOIN {question} q ON q.id = slot.questionid
177 WHERE slot.quizid = ? AND q.qtype = ?";
178 $questionids = $DB->get_fieldset_sql($sql, array($quiz->id, 'random'));
179
180 // We need to do this before we try and delete randoms, otherwise they would still be 'in use'.
ccba5b88 181 $DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
5d949702 182 $DB->delete_records('quiz_sections', array('quizid' => $quiz->id));
828a4e9f
EM
183
184 foreach ($questionids as $questionid) {
185 question_delete_question($questionid);
186 }
187
53004e48 188 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
730fd187 189
35cbe84b
TH
190 quiz_access_manager::delete_settings($quiz);
191
53004e48 192 $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
25a03faa 193 foreach ($events as $event) {
f81a8247
SH
194 $event = calendar_event::load($event);
195 $event->delete();
b2a3cd2d 196 }
197
d6dd2108 198 quiz_grade_item_delete($quiz);
53004e48 199 $DB->delete_records('quiz', array('id' => $quiz->id));
d6dd2108 200
53004e48 201 return true;
202}
203
990650f9
TH
204/**
205 * Deletes a quiz override from the database and clears any corresponding calendar events
206 *
207 * @param object $quiz The quiz object.
f7970e3c 208 * @param int $overrideid The id of the override being deleted
990650f9
TH
209 * @return bool true on success
210 */
211function quiz_delete_override($quiz, $overrideid) {
212 global $DB;
213
92089e0e
MN
214 if (!isset($quiz->cmid)) {
215 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
216 $quiz->cmid = $cm->id;
217 }
218
25302dee 219 $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
990650f9 220
9e83f3d1 221 // Delete the events.
25302dee
TH
222 $events = $DB->get_records('event', array('modulename' => 'quiz',
223 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
224 'userid' => (int)$override->userid));
225 foreach ($events as $event) {
990650f9
TH
226 $eventold = calendar_event::load($event);
227 $eventold->delete();
228 }
229
230 $DB->delete_records('quiz_overrides', array('id' => $overrideid));
8de2eb35
MN
231
232 // Set the common parameters for one of the events we will be triggering.
233 $params = array(
234 'objectid' => $override->id,
235 'context' => context_module::instance($quiz->cmid),
236 'other' => array(
237 'quizid' => $override->quiz
238 )
239 );
240 // Determine which override deleted event to fire.
241 if (!empty($override->userid)) {
242 $params['relateduserid'] = $override->userid;
243 $event = \mod_quiz\event\user_override_deleted::create($params);
244 } else {
245 $params['other']['groupid'] = $override->groupid;
246 $event = \mod_quiz\event\group_override_deleted::create($params);
247 }
248
249 // Trigger the override deleted event.
250 $event->add_record_snapshot('quiz_overrides', $override);
251 $event->trigger();
252
990650f9
TH
253 return true;
254}
255
256/**
257 * Deletes all quiz overrides from the database and clears any corresponding calendar events
258 *
259 * @param object $quiz The quiz object.
260 */
261function quiz_delete_all_overrides($quiz) {
262 global $DB;
263
264 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
265 foreach ($overrides as $override) {
266 quiz_delete_override($quiz, $override->id);
267 }
268}
269
270/**
271 * Updates a quiz object with override information for a user.
272 *
273 * Algorithm: For each quiz setting, if there is a matching user-specific override,
274 * then use that otherwise, if there are group-specific overrides, return the most
275 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
276 *
277 * Special case: if there is more than one password that applies to the user, then
278 * quiz->extrapasswords will contain an array of strings giving the remaining
279 * passwords.
280 *
281 * @param object $quiz The quiz object.
f7970e3c 282 * @param int $userid The userid.
990650f9
TH
283 * @return object $quiz The updated quiz object.
284 */
285function quiz_update_effective_access($quiz, $userid) {
286 global $DB;
287
9e83f3d1 288 // Check for user override.
990650f9
TH
289 $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
290
291 if (!$override) {
6bdfef5d 292 $override = new stdClass();
990650f9
TH
293 $override->timeopen = null;
294 $override->timeclose = null;
295 $override->timelimit = null;
296 $override->attempts = null;
297 $override->password = null;
298 }
299
9e83f3d1 300 // Check for group overrides.
990650f9 301 $groupings = groups_get_user_groups($quiz->course, $userid);
990650f9 302
7bc488dc 303 if (!empty($groupings[0])) {
9e83f3d1 304 // Select all overrides that apply to the User's groups.
7bc488dc 305 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
990650f9
TH
306 $sql = "SELECT * FROM {quiz_overrides}
307 WHERE groupid $extra AND quiz = ?";
ac250ad5 308 $params[] = $quiz->id;
990650f9
TH
309 $records = $DB->get_records_sql($sql, $params);
310
9e83f3d1 311 // Combine the overrides.
990650f9
TH
312 $opens = array();
313 $closes = array();
314 $limits = array();
315 $attempts = array();
316 $passwords = array();
317
318 foreach ($records as $gpoverride) {
319 if (isset($gpoverride->timeopen)) {
320 $opens[] = $gpoverride->timeopen;
321 }
322 if (isset($gpoverride->timeclose)) {
323 $closes[] = $gpoverride->timeclose;
324 }
325 if (isset($gpoverride->timelimit)) {
326 $limits[] = $gpoverride->timelimit;
327 }
328 if (isset($gpoverride->attempts)) {
329 $attempts[] = $gpoverride->attempts;
330 }
331 if (isset($gpoverride->password)) {
332 $passwords[] = $gpoverride->password;
333 }
334 }
9e83f3d1 335 // If there is a user override for a setting, ignore the group override.
990650f9 336 if (is_null($override->timeopen) && count($opens)) {
25302dee 337 $override->timeopen = min($opens);
990650f9
TH
338 }
339 if (is_null($override->timeclose) && count($closes)) {
8e771aed
MP
340 if (in_array(0, $closes)) {
341 $override->timeclose = 0;
342 } else {
343 $override->timeclose = max($closes);
344 }
990650f9
TH
345 }
346 if (is_null($override->timelimit) && count($limits)) {
8e771aed
MP
347 if (in_array(0, $limits)) {
348 $override->timelimit = 0;
349 } else {
350 $override->timelimit = max($limits);
351 }
990650f9
TH
352 }
353 if (is_null($override->attempts) && count($attempts)) {
8e771aed
MP
354 if (in_array(0, $attempts)) {
355 $override->attempts = 0;
356 } else {
357 $override->attempts = max($attempts);
358 }
990650f9
TH
359 }
360 if (is_null($override->password) && count($passwords)) {
25302dee 361 $override->password = array_shift($passwords);
990650f9 362 if (count($passwords)) {
25302dee 363 $override->extrapasswords = $passwords;
990650f9
TH
364 }
365 }
366
367 }
368
9e83f3d1 369 // Merge with quiz defaults.
25302dee 370 $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
990650f9
TH
371 foreach ($keys as $key) {
372 if (isset($override->{$key})) {
373 $quiz->{$key} = $override->{$key};
374 }
375 }
376
377 return $quiz;
378}
379
53004e48 380/**
381 * Delete all the attempts belonging to a quiz.
8cc86111 382 *
8cc86111 383 * @param object $quiz The quiz object.
53004e48 384 */
385function quiz_delete_all_attempts($quiz) {
386 global $CFG, $DB;
6b5f24d3
TH
387 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
388 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
53004e48 389 $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
390 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
730fd187 391}
392
25302dee
TH
393/**
394 * Get the best current grade for a particular user in a quiz.
395 *
396 * @param object $quiz the quiz settings.
f7970e3c 397 * @param int $userid the id of the user.
25a03faa 398 * @return float the user's current grade for this quiz, or null if this user does
25302dee
TH
399 * not have a grade on this quiz.
400 */
401function quiz_get_best_grade($quiz, $userid) {
402 global $DB;
25a03faa
TH
403 $grade = $DB->get_field('quiz_grades', 'grade',
404 array('quiz' => $quiz->id, 'userid' => $userid));
25302dee 405
b2607ccc 406 // Need to detect errors/no result, without catching 0 grades.
25302dee
TH
407 if ($grade === false) {
408 return null;
409 }
410
411 return $grade + 0; // Convert to number.
412}
413
414/**
415 * Is this a graded quiz? If this method returns true, you can assume that
416 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
417 * divide by them).
418 *
419 * @param object $quiz a row from the quiz table.
f7970e3c 420 * @return bool whether this is a graded quiz.
25302dee
TH
421 */
422function quiz_has_grades($quiz) {
423 return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
424}
425
99caa248
JP
426/**
427 * Does this quiz allow multiple tries?
428 *
429 * @return bool
430 */
431function quiz_allows_multiple_tries($quiz) {
432 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
433 return $bt->allows_multiple_submitted_responses();
434}
435
8cc86111 436/**
437 * Return a small object with summary information about what a
438 * user has done with a given particular instance of this module
439 * Used for user activity reports.
440 * $return->time = the time they did it
441 * $return->info = a short text description
442 *
8cc86111 443 * @param object $course
444 * @param object $user
445 * @param object $mod
446 * @param object $quiz
447 * @return object|null
448 */
730fd187 449function quiz_user_outline($course, $user, $mod, $quiz) {
1a96363a 450 global $DB, $CFG;
172238f4 451 require_once($CFG->libdir . '/gradelib.php');
1a96363a
NC
452 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
453
454 if (empty($grades->items[0]->grades)) {
455 return null;
456 } else {
457 $grade = reset($grades->items[0]->grades);
5ecfab51 458 }
459
0ff4bd08 460 $result = new stdClass();
930570b4
MC
461 // If the user can't see hidden grades, don't return that information.
462 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
463 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
464 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
465 } else {
466 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
467 }
4433f871 468
9e83f3d1
TH
469 // Datesubmitted == time created. dategraded == time modified or time overridden
470 // if grade was last modified by the user themselves use date graded. Otherwise use
471 // date submitted.
472 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
4433f871
AD
473 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
474 $result->time = $grade->dategraded;
475 } else {
476 $result->time = $grade->datesubmitted;
477 }
478
5ecfab51 479 return $result;
1a96363a 480}
730fd187 481
8cc86111 482/**
483 * Print a detailed representation of what a user has done with
484 * a given particular instance of this module, for user activity reports.
485 *
8cc86111 486 * @param object $course
487 * @param object $user
488 * @param object $mod
489 * @param object $quiz
490 * @return bool
491 */
730fd187 492function quiz_user_complete($course, $user, $mod, $quiz) {
1a14a14b 493 global $DB, $CFG, $OUTPUT;
be18f589 494 require_once($CFG->libdir . '/gradelib.php');
172238f4 495 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
25302dee 496
1a96363a
NC
497 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
498 if (!empty($grades->items[0]->grades)) {
499 $grade = reset($grades->items[0]->grades);
930570b4
MC
500 // If the user can't see hidden grades, don't return that information.
501 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
502 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
503 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
504 if ($grade->str_feedback) {
505 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
506 }
507 } else {
508 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
509 if ($grade->str_feedback) {
510 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
511 }
1a96363a
NC
512 }
513 }
730fd187 514
25a03faa
TH
515 if ($attempts = $DB->get_records('quiz_attempts',
516 array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
ee1fb969 517 foreach ($attempts as $attempt) {
9378c99b 518 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
be18f589
TH
519 if ($attempt->state != quiz_attempt::FINISHED) {
520 echo quiz_attempt_state_name($attempt->state);
ee1fb969 521 } else {
930570b4
MC
522 if (!isset($gitem)) {
523 if (!empty($grades->items[0]->grades)) {
524 $gitem = grade_item::fetch(array('id' => $grades->items[0]->id));
525 } else {
526 $gitem = new stdClass();
527 $gitem->hidden = true;
528 }
529 }
530 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
531 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
532 } else {
533 echo get_string('hidden', 'grades');
534 }
ee1fb969 535 }
536 echo ' - '.userdate($attempt->timemodified).'<br />';
537 }
538 } else {
25a03faa 539 print_string('noattempts', 'quiz');
ee1fb969 540 }
541
730fd187 542 return true;
543}
544
8cc86111 545/**
c2f5e2ab 546 * Quiz periodic clean-up tasks.
8cc86111 547 */
be0ba083 548function quiz_cron() {
be18f589 549 global $CFG;
c2f5e2ab 550
8e771aed
MP
551 require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
552 mtrace('');
e1bf1619
TH
553
554 $timenow = time();
8e771aed 555 $overduehander = new mod_quiz_overdue_attempt_updater();
e1bf1619 556
8e771aed 557 $processto = $timenow - get_config('quiz', 'graceperiodmin');
e1bf1619 558
8e771aed 559 mtrace(' Looking for quiz overdue quiz attempts...');
815fcecc 560
8e771aed 561 list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
815fcecc 562
8e771aed 563 mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
e1bf1619 564
c2f5e2ab
TH
565 // Run cron for our sub-plugin types.
566 cron_execute_plugin_type('quiz', 'quiz reports');
567 cron_execute_plugin_type('quizaccess', 'quiz access rules');
7b0f4a37
DM
568
569 return true;
730fd187 570}
571
b5a16eb7 572/**
ac032e0e 573 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
f7970e3c 574 * @param int $userid the userid.
b5a16eb7 575 * @param string $status 'all', 'finished' or 'unfinished' to control
8cc86111 576 * @param bool $includepreviews
25a03faa
TH
577 * @return an array of all the user's attempts at this quiz. Returns an empty
578 * array if there are none.
b5a16eb7 579 */
ac032e0e 580function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
36e48cb8
TH
581 global $DB, $CFG;
582 // TODO MDL-33071 it is very annoying to have to included all of locallib.php
583 // just to get the quiz_attempt::FINISHED constants, but I will try to sort
584 // that out properly for Moodle 2.4. For now, I will just do a quick fix for
585 // MDL-33048.
586 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
34b7d838
TH
587
588 $params = array();
589 switch ($status) {
590 case 'all':
591 $statuscondition = '';
592 break;
593
594 case 'finished':
595 $statuscondition = ' AND state IN (:state1, :state2)';
596 $params['state1'] = quiz_attempt::FINISHED;
597 $params['state2'] = quiz_attempt::ABANDONED;
598 break;
599
600 case 'unfinished':
601 $statuscondition = ' AND state IN (:state1, :state2)';
602 $params['state1'] = quiz_attempt::IN_PROGRESS;
603 $params['state2'] = quiz_attempt::OVERDUE;
604 break;
605 }
606
ac032e0e
FM
607 $quizids = (array) $quizids;
608 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
609 $params += $inparams;
610 $params['userid'] = $userid;
611
b5a16eb7 612 $previewclause = '';
613 if (!$includepreviews) {
614 $previewclause = ' AND preview = 0';
615 }
34b7d838 616
25302dee 617 return $DB->get_records_select('quiz_attempts',
ac032e0e 618 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
8675453e 619 $params, 'quiz, attempt ASC');
b5a16eb7 620}
858deff0 621
d6dd2108 622/**
623 * Return grade for given user or all users.
624 *
625 * @param int $quizid id of quiz
626 * @param int $userid optional user id, 0 means all users
f88fb62c 627 * @return array array of grades, false if none. These are raw grades. They should
628 * be processed with quiz_format_grade for display.
d6dd2108 629 */
25302dee 630function quiz_get_user_grades($quiz, $userid = 0) {
9cf4a18b 631 global $CFG, $DB;
d6dd2108 632
9cf4a18b 633 $params = array($quiz->id);
25302dee 634 $usertest = '';
9cf4a18b 635 if ($userid) {
636 $params[] = $userid;
25302dee
TH
637 $usertest = 'AND u.id = ?';
638 }
8f37f7fb 639 return $DB->get_records_sql("
25302dee
TH
640 SELECT
641 u.id,
642 u.id AS userid,
643 qg.grade AS rawgrade,
644 qg.timemodified AS dategraded,
645 MAX(qa.timefinish) AS datesubmitted
646
647 FROM {user} u
648 JOIN {quiz_grades} qg ON u.id = qg.userid
649 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
650
8f37f7fb
TH
651 WHERE qg.quiz = ?
652 $usertest
653 GROUP BY u.id, qg.grade, qg.timemodified", $params);
d6dd2108 654}
655
f88fb62c 656/**
657 * Round a grade to to the correct number of decimal places, and format it for display.
658 *
659 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
660 * @param float $grade The grade to round.
8cc86111 661 * @return float
f88fb62c 662 */
663function quiz_format_grade($quiz, $grade) {
25302dee
TH
664 if (is_null($grade)) {
665 return get_string('notyetgraded', 'quiz');
666 }
f88fb62c 667 return format_float($grade, $quiz->decimalpoints);
668}
669
84e628a0 670/**
e1a2d0d9 671 * Determine the correct number of decimal places required to format a grade.
84e628a0 672 *
673 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
e1a2d0d9 674 * @return integer
84e628a0 675 */
e1a2d0d9 676function quiz_get_grade_format($quiz) {
25302dee
TH
677 if (empty($quiz->questiondecimalpoints)) {
678 $quiz->questiondecimalpoints = -1;
679 }
e1a2d0d9 680
84e628a0 681 if ($quiz->questiondecimalpoints == -1) {
e1a2d0d9 682 return $quiz->decimalpoints;
84e628a0 683 }
e1a2d0d9
CC
684
685 return $quiz->questiondecimalpoints;
686}
687
688/**
689 * Round a grade to the correct number of decimal places, and format it for display.
690 *
691 * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
692 * @param float $grade The grade to round.
693 * @return float
694 */
695function quiz_format_question_grade($quiz, $grade) {
696 return format_float($grade, quiz_get_grade_format($quiz));
84e628a0 697}
698
d6dd2108 699/**
700 * Update grades in central gradebook
701 *
a153c9f2 702 * @category grade
25302dee
TH
703 * @param object $quiz the quiz settings.
704 * @param int $userid specific user only, 0 means all users.
a153c9f2 705 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
d6dd2108 706 */
25302dee 707function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
9cf4a18b 708 global $CFG, $DB;
172238f4 709 require_once($CFG->libdir . '/gradelib.php');
ed1daaa9 710
775f811a 711 if ($quiz->grade == 0) {
712 quiz_grade_item_update($quiz);
d6dd2108 713
775f811a 714 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
715 quiz_grade_item_update($quiz, $grades);
eafb9d9e 716
25302dee 717 } else if ($userid && $nullifnone) {
39790bd8 718 $grade = new stdClass();
25302dee
TH
719 $grade->userid = $userid;
720 $grade->rawgrade = null;
775f811a 721 quiz_grade_item_update($quiz, $grade);
d6dd2108 722
723 } else {
775f811a 724 quiz_grade_item_update($quiz);
725 }
726}
3b1d5cc4 727
d6dd2108 728/**
a153c9f2 729 * Create or update the grade item for given quiz
d6dd2108 730 *
a153c9f2 731 * @category grade
d6dd2108 732 * @param object $quiz object with extra cmidnumber
8cc86111 733 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
d6dd2108 734 * @return int 0 if ok, error code otherwise
735 */
25a03faa 736function quiz_grade_item_update($quiz, $grades = null) {
3b1d5cc4 737 global $CFG, $OUTPUT;
609c0d6b 738 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
172238f4 739 require_once($CFG->libdir . '/gradelib.php');
d6dd2108 740
9e83f3d1 741 if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
25302dee 742 $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
d6dd2108 743 } else {
25302dee 744 $params = array('itemname' => $quiz->name);
d6dd2108 745 }
746
747 if ($quiz->grade > 0) {
748 $params['gradetype'] = GRADE_TYPE_VALUE;
749 $params['grademax'] = $quiz->grade;
750 $params['grademin'] = 0;
751
752 } else {
753 $params['gradetype'] = GRADE_TYPE_NONE;
754 }
755
9e83f3d1 756 // What this is trying to do:
25a03faa
TH
757 // 1. If the quiz is set to not show grades while the quiz is still open,
758 // and is set to show grades after the quiz is closed, then create the
759 // grade_item with a show-after date that is the quiz close date.
760 // 2. If the quiz is set to not show grades at either of those times,
761 // create the grade_item as hidden.
762 // 3. If the quiz is set to show grades, create the grade_item visible.
25302dee
TH
763 $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
764 mod_quiz_display_options::LATER_WHILE_OPEN);
765 $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
766 mod_quiz_display_options::AFTER_CLOSE);
6d03fd98
TH
767 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
768 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
1223d24a 769 $params['hidden'] = 1;
770
6d03fd98
TH
771 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
772 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
1223d24a 773 if ($quiz->timeclose) {
774 $params['hidden'] = $quiz->timeclose;
775 } else {
776 $params['hidden'] = 1;
777 }
778
779 } else {
9e83f3d1 780 // Either
1223d24a 781 // a) both open and closed enabled
25a03faa 782 // b) open enabled, closed disabled - we can not "hide after",
9e83f3d1 783 // grades are kept visible even after closing.
1223d24a 784 $params['hidden'] = 0;
785 }
786
39873128
TH
787 if (!$params['hidden']) {
788 // If the grade item is not hidden by the quiz logic, then we need to
789 // hide it if the quiz is hidden from students.
1c73df9e
TH
790 if (property_exists($quiz, 'visible')) {
791 // Saving the quiz form, and cm not yet updated in the database.
792 $params['hidden'] = !$quiz->visible;
793 } else {
794 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
795 $params['hidden'] = !$cm->visible;
796 }
39873128
TH
797 }
798
0b5a80a1 799 if ($grades === 'reset') {
800 $params['reset'] = true;
25a03faa 801 $grades = null;
0b5a80a1 802 }
9cf4a18b 803
49460d84 804 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
d45459b7 805 if (!empty($gradebook_grades->items)) {
806 $grade_item = $gradebook_grades->items[0];
807 if ($grade_item->locked) {
9e83f3d1 808 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
d45459b7 809 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
810 if (!$confirm_regrade) {
f5f36584
MP
811 if (!AJAX_SCRIPT) {
812 $message = get_string('gradeitemislocked', 'grades');
813 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
814 '&amp;mode=overview';
815 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
816 echo $OUTPUT->box_start('generalbox', 'notice');
817 echo '<p>'. $message .'</p>';
818 echo $OUTPUT->container_start('buttons');
819 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
820 echo $OUTPUT->single_button($back_link, get_string('cancel'));
821 echo $OUTPUT->container_end();
822 echo $OUTPUT->box_end();
823 }
d45459b7 824 return GRADE_UPDATE_ITEM_LOCKED;
825 }
49460d84 826 }
827 }
0b5a80a1 828
ced5ee59 829 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
d6dd2108 830}
831
832/**
833 * Delete grade item for given quiz
834 *
a153c9f2 835 * @category grade
d6dd2108 836 * @param object $quiz object
837 * @return object quiz
838 */
839function quiz_grade_item_delete($quiz) {
840 global $CFG;
53004e48 841 require_once($CFG->libdir . '/gradelib.php');
d6dd2108 842
25a03faa
TH
843 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
844 null, array('deleted' => 1));
d6dd2108 845}
846
8cc86111 847/**
848 * This standard function will check all instances of this module
849 * and make sure there are up-to-date events created for each of them.
850 * If courseid = 0, then every quiz event in the site is checked, else
851 * only quiz events belonging to the course specified are checked.
852 * This function is used, in its new format, by restore_refresh_events()
853 *
8cc86111 854 * @param int $courseid
855 * @return bool
856 */
d2f308c0 857function quiz_refresh_events($courseid = 0) {
9cf4a18b 858 global $DB;
d2f308c0 859
860 if ($courseid == 0) {
25302dee 861 if (!$quizzes = $DB->get_records('quiz')) {
d2f308c0 862 return true;
863 }
864 } else {
25302dee 865 if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
d2f308c0 866 return true;
867 }
868 }
f41e824f 869
d2f308c0 870 foreach ($quizzes as $quiz) {
990650f9 871 quiz_update_events($quiz);
d2f308c0 872 }
990650f9 873
d2f308c0 874 return true;
875}
876
dd97c328 877/**
878 * Returns all quiz graded users since a given time for specified quiz
879 */
8d297188
TH
880function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
881 $courseid, $cmid, $userid = 0, $groupid = 0) {
e19c086c 882 global $CFG, $USER, $DB;
172238f4 883 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
6710ec87 884
e19c086c 885 $course = get_course($courseid);
f20edd52 886 $modinfo = get_fast_modinfo($course);
6710ec87 887
dd97c328 888 $cm = $modinfo->cms[$cmid];
8d297188 889 $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
9cf4a18b 890
dd97c328 891 if ($userid) {
8d297188
TH
892 $userselect = "AND u.id = :userid";
893 $params['userid'] = $userid;
dd97c328 894 } else {
8d297188 895 $userselect = '';
dd97c328 896 }
ac21ad39 897
dd97c328 898 if ($groupid) {
8d297188
TH
899 $groupselect = 'AND gm.groupid = :groupid';
900 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
901 $params['groupid'] = $groupid;
dd97c328 902 } else {
8d297188
TH
903 $groupselect = '';
904 $groupjoin = '';
905 }
906
122fc5d9
DM
907 $params['timestart'] = $timestart;
908 $params['quizid'] = $quiz->id;
909
21d22803 910 $ufields = user_picture::fields('u', null, 'useridagain');
8d297188
TH
911 if (!$attempts = $DB->get_records_sql("
912 SELECT qa.*,
3047f140 913 {$ufields}
8d297188
TH
914 FROM {quiz_attempts} qa
915 JOIN {user} u ON u.id = qa.userid
916 $groupjoin
917 WHERE qa.timefinish > :timestart
918 AND qa.quiz = :quizid
919 AND qa.preview = 0
920 $userselect
921 $groupselect
922 ORDER BY qa.timefinish ASC", $params)) {
923 return;
924 }
925
c492a78e 926 $context = context_module::instance($cm->id);
8d297188
TH
927 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
928 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
cb323d02 929 $grader = has_capability('mod/quiz:viewreports', $context);
dd97c328 930 $groupmode = groups_get_activity_groupmode($cm, $course);
6710ec87 931
8d297188 932 $usersgroups = null;
25a03faa 933 $aname = format_string($cm->name, true);
dd97c328 934 foreach ($attempts as $attempt) {
935 if ($attempt->userid != $USER->id) {
936 if (!$grader) {
9e83f3d1 937 // Grade permission required.
dd97c328 938 continue;
939 }
6710ec87 940
9cf4a18b 941 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
e19c086c
MG
942 $usersgroups = groups_get_all_groups($course->id,
943 $attempt->userid, $cm->groupingid);
944 $usersgroups = array_keys($usersgroups);
945 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
dd97c328 946 continue;
947 }
948 }
8d297188
TH
949 }
950
7ee80cab 951 $options = quiz_get_review_options($quiz, $attempt, $context);
dd97c328 952
0ff4bd08 953 $tmpactivity = new stdClass();
dd97c328 954
8d297188
TH
955 $tmpactivity->type = 'quiz';
956 $tmpactivity->cmid = $cm->id;
957 $tmpactivity->name = $aname;
958 $tmpactivity->sectionnum = $cm->sectionnum;
959 $tmpactivity->timestamp = $attempt->timefinish;
9cf4a18b 960
a957e97f 961 $tmpactivity->content = new stdClass();
dd97c328 962 $tmpactivity->content->attemptid = $attempt->id;
dd97c328 963 $tmpactivity->content->attempt = $attempt->attempt;
6d03fd98 964 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
8d297188
TH
965 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
966 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
967 } else {
968 $tmpactivity->content->sumgrades = null;
969 $tmpactivity->content->maxgrade = null;
970 }
9cf4a18b 971
21d22803 972 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
3047f140 973 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
9cf4a18b 974
dd97c328 975 $activities[$index++] = $tmpactivity;
6710ec87 976 }
6710ec87 977}
978
dd97c328 979function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
e63f88c9 980 global $CFG, $OUTPUT;
6710ec87 981
dd97c328 982 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
6710ec87 983
8d297188
TH
984 echo '<tr><td class="userpicture" valign="top">';
985 echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
986 echo '</td><td>';
6710ec87 987
988 if ($detail) {
dd97c328 989 $modname = $modnames[$activity->type];
990 echo '<div class="title">';
8d297188
TH
991 echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
992 'class="icon" alt="' . $modname . '" />';
993 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
994 $activity->cmid . '">' . $activity->name . '</a>';
dd97c328 995 echo '</div>';
6710ec87 996 }
997
dd97c328 998 echo '<div class="grade">';
8d297188
TH
999 echo get_string('attempt', 'quiz', $activity->content->attempt);
1000 if (isset($activity->content->maxgrade)) {
1001 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1002 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1003 $activity->content->attemptid . '">' . $grades . '</a>)';
1004 }
dd97c328 1005 echo '</div>';
6710ec87 1006
dd97c328 1007 echo '<div class="user">';
8d297188
TH
1008 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1009 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
1010 '</a> - ' . userdate($activity->timestamp);
dd97c328 1011 echo '</div>';
6710ec87 1012
8d297188 1013 echo '</td></tr></table>';
6710ec87 1014
1015 return;
1016}
1017
ee1fb969 1018/**
920b93d1 1019 * Pre-process the quiz options form data, making any necessary adjustments.
ad4cd837 1020 * Called by add/update instance in this file.
b159da78 1021 *
920b93d1 1022 * @param object $quiz The variables set on the form.
1023 */
25302dee
TH
1024function quiz_process_options($quiz) {
1025 global $CFG;
1026 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1027 require_once($CFG->libdir . '/questionlib.php');
1028
920b93d1 1029 $quiz->timemodified = time();
ee1fb969 1030
dc5c6851 1031 // Quiz name.
1032 if (!empty($quiz->name)) {
1033 $quiz->name = trim($quiz->name);
1034 }
a23f0aaf 1035
ab0a8ff2 1036 // Password field - different in form to stop browsers that remember passwords
1037 // getting confused.
1038 $quiz->password = $quiz->quizpassword;
1039 unset($quiz->quizpassword);
1040
9e83f3d1 1041 // Quiz feedback.
a0807a00 1042 if (isset($quiz->feedbacktext)) {
1043 // Clean up the boundary text.
1044 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
fe6ce234
DC
1045 if (empty($quiz->feedbacktext[$i]['text'])) {
1046 $quiz->feedbacktext[$i]['text'] = '';
a0807a00 1047 } else {
fe6ce234 1048 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
a0807a00 1049 }
212b7b8c 1050 }
b159da78 1051
a0807a00 1052 // Check the boundary value is a number or a percentage, and in range.
1053 $i = 0;
1054 while (!empty($quiz->feedbackboundaries[$i])) {
1055 $boundary = trim($quiz->feedbackboundaries[$i]);
1056 if (!is_numeric($boundary)) {
1057 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1058 $boundary = trim(substr($boundary, 0, -1));
1059 if (is_numeric($boundary)) {
1060 $boundary = $boundary * $quiz->grade / 100.0;
1061 } else {
1062 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1063 }
212b7b8c 1064 }
1065 }
a0807a00 1066 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1067 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1068 }
1069 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1070 return get_string('feedbackerrororder', 'quiz', $i + 1);
1071 }
1072 $quiz->feedbackboundaries[$i] = $boundary;
1073 $i += 1;
212b7b8c 1074 }
a0807a00 1075 $numboundaries = $i;
b159da78 1076
a0807a00 1077 // Check there is nothing in the remaining unused fields.
e0b7cfcb 1078 if (!empty($quiz->feedbackboundaries)) {
1079 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
25a03faa
TH
1080 if (!empty($quiz->feedbackboundaries[$i]) &&
1081 trim($quiz->feedbackboundaries[$i]) != '') {
e0b7cfcb 1082 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1083 }
a0807a00 1084 }
212b7b8c 1085 }
a0807a00 1086 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
25a03faa
TH
1087 if (!empty($quiz->feedbacktext[$i]['text']) &&
1088 trim($quiz->feedbacktext[$i]['text']) != '') {
a0807a00 1089 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1090 }
212b7b8c 1091 }
25a03faa
TH
1092 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1093 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
a0807a00 1094 $quiz->feedbackboundaries[$numboundaries] = 0;
1095 $quiz->feedbackboundarycount = $numboundaries;
2cf5ab10
TH
1096 } else {
1097 $quiz->feedbackboundarycount = -1;
212b7b8c 1098 }
a23f0aaf 1099
25302dee
TH
1100 // Combing the individual settings into the review columns.
1101 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1102 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1103 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1104 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1105 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1106 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1107 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1108 $quiz->reviewattempt |= mod_quiz_display_options::DURING;
1109 $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
1110}
ee1fb969 1111
25302dee
TH
1112/**
1113 * Helper function for {@link quiz_process_options()}.
1114 * @param object $fromform the sumbitted form date.
1115 * @param string $field one of the review option field names.
1116 */
1117function quiz_review_option_form_to_db($fromform, $field) {
1118 static $times = array(
1119 'during' => mod_quiz_display_options::DURING,
1120 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
1121 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
1122 'closed' => mod_quiz_display_options::AFTER_CLOSE,
1123 );
00719c02 1124
25302dee
TH
1125 $review = 0;
1126 foreach ($times as $whenname => $when) {
1127 $fieldname = $field . $whenname;
1128 if (isset($fromform->$fieldname)) {
1129 $review |= $when;
1130 unset($fromform->$fieldname);
1131 }
1b8a7434 1132 }
1133
25302dee 1134 return $review;
920b93d1 1135}
1136
1137/**
1138 * This function is called at the end of quiz_add_instance
1139 * and quiz_update_instance, to do the common processing.
a23f0aaf 1140 *
920b93d1 1141 * @param object $quiz the quiz object.
1142 */
1143function quiz_after_add_or_update($quiz) {
c18269c7 1144 global $DB;
fe6ce234
DC
1145 $cmid = $quiz->coursemodule;
1146
9e83f3d1 1147 // We need to use context now, so we need to make sure all needed info is already in db.
fe6ce234 1148 $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
c492a78e 1149 $context = context_module::instance($cmid);
920b93d1 1150
9e83f3d1 1151 // Save the feedback.
53004e48 1152 $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
a23f0aaf 1153
fe6ce234 1154 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
0ff4bd08 1155 $feedback = new stdClass();
212b7b8c 1156 $feedback->quizid = $quiz->id;
fe6ce234
DC
1157 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1158 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
212b7b8c 1159 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1160 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
fe6ce234 1161 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
25a03faa
TH
1162 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1163 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1164 array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
1165 $quiz->feedbacktext[$i]['text']);
1166 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1167 array('id' => $feedback->id));
212b7b8c 1168 }
1169
b83c32d3
TH
1170 // Store any settings belonging to the access rules.
1171 quiz_access_manager::save_settings($quiz);
1172
920b93d1 1173 // Update the events relating to this quiz.
990650f9
TH
1174 quiz_update_events($quiz);
1175
9e83f3d1 1176 // Update related grade item.
990650f9 1177 quiz_grade_item_update($quiz);
990650f9
TH
1178}
1179
1180/**
1181 * This function updates the events associated to the quiz.
1182 * If $override is non-zero, then it updates only the events
1183 * associated with the specified override.
1184 *
1185 * @uses QUIZ_MAX_EVENT_LENGTH
1186 * @param object $quiz the quiz object.
1187 * @param object optional $override limit to a specific override
1188 */
1189function quiz_update_events($quiz, $override = null) {
1190 global $DB;
1191
1192 // Load the old events relating to this quiz.
1193 $conds = array('modulename'=>'quiz',
1194 'instance'=>$quiz->id);
1195 if (!empty($override)) {
9e83f3d1 1196 // Only load events for this override.
cc4fba86
MN
1197 if (isset($override->userid)) {
1198 $conds['userid'] = $override->userid;
1199 } else {
1200 $conds['groupid'] = $override->groupid;
1201 }
990650f9
TH
1202 }
1203 $oldevents = $DB->get_records('event', $conds);
1204
9e83f3d1 1205 // Now make a todo list of all that needs to be updated.
990650f9
TH
1206 if (empty($override)) {
1207 // We are updating the primary settings for the quiz, so we
9e83f3d1 1208 // need to add all the overrides.
990650f9 1209 $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
9e83f3d1 1210 // As well as the original quiz (empty override).
0ff4bd08 1211 $overrides[] = new stdClass();
25a03faa 1212 } else {
9e83f3d1 1213 // Just do the one override.
990650f9 1214 $overrides = array($override);
920b93d1 1215 }
1216
990650f9
TH
1217 foreach ($overrides as $current) {
1218 $groupid = isset($current->groupid)? $current->groupid : 0;
1219 $userid = isset($current->userid)? $current->userid : 0;
1220 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1221 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1222
9e83f3d1 1223 // Only add open/close events for an override if they differ from the quiz default.
990650f9
TH
1224 $addopen = empty($current->id) || !empty($current->timeopen);
1225 $addclose = empty($current->id) || !empty($current->timeclose);
1226
2079c732
TH
1227 if (!empty($quiz->coursemodule)) {
1228 $cmid = $quiz->coursemodule;
1229 } else {
393cadf2 1230 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
2079c732
TH
1231 }
1232
0ff4bd08 1233 $event = new stdClass();
2079c732 1234 $event->description = format_module_intro('quiz', $quiz, $cmid);
9e83f3d1 1235 // Events module won't show user events when the courseid is nonzero.
25a03faa 1236 $event->courseid = ($userid) ? 0 : $quiz->course;
990650f9
TH
1237 $event->groupid = $groupid;
1238 $event->userid = $userid;
1239 $event->modulename = 'quiz';
1240 $event->instance = $quiz->id;
1241 $event->timestart = $timeopen;
1242 $event->timeduration = max($timeclose - $timeopen, 0);
1243 $event->visible = instance_is_visible('quiz', $quiz);
1244 $event->eventtype = 'open';
1245
9e83f3d1 1246 // Determine the event name.
990650f9 1247 if ($groupid) {
0ff4bd08 1248 $params = new stdClass();
990650f9
TH
1249 $params->quiz = $quiz->name;
1250 $params->group = groups_get_group_name($groupid);
1251 if ($params->group === false) {
9e83f3d1 1252 // Group doesn't exist, just skip it.
990650f9
TH
1253 continue;
1254 }
1255 $eventname = get_string('overridegroupeventname', 'quiz', $params);
25a03faa 1256 } else if ($userid) {
0ff4bd08 1257 $params = new stdClass();
990650f9
TH
1258 $params->quiz = $quiz->name;
1259 $eventname = get_string('overrideusereventname', 'quiz', $params);
1260 } else {
1261 $eventname = $quiz->name;
1262 }
1263 if ($addopen or $addclose) {
1264 if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
1265 // Single event for the whole quiz.
1266 if ($oldevent = array_shift($oldevents)) {
1267 $event->id = $oldevent->id;
25a03faa 1268 } else {
990650f9
TH
1269 unset($event->id);
1270 }
1271 $event->name = $eventname;
9e83f3d1 1272 // The method calendar_event::create will reuse a db record if the id field is set.
990650f9
TH
1273 calendar_event::create($event);
1274 } else {
1275 // Separate start and end events.
1276 $event->timeduration = 0;
1277 if ($timeopen && $addopen) {
1278 if ($oldevent = array_shift($oldevents)) {
1279 $event->id = $oldevent->id;
25a03faa 1280 } else {
990650f9
TH
1281 unset($event->id);
1282 }
1283 $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
9e83f3d1 1284 // The method calendar_event::create will reuse a db record if the id field is set.
990650f9
TH
1285 calendar_event::create($event);
1286 }
1287 if ($timeclose && $addclose) {
1288 if ($oldevent = array_shift($oldevents)) {
1289 $event->id = $oldevent->id;
25a03faa 1290 } else {
990650f9
TH
1291 unset($event->id);
1292 }
1293 $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
1294 $event->timestart = $timeclose;
1295 $event->eventtype = 'close';
1296 calendar_event::create($event);
1297 }
1298 }
920b93d1 1299 }
1300 }
d6dd2108 1301
9e83f3d1 1302 // Delete any leftover events.
990650f9
TH
1303 foreach ($oldevents as $badevent) {
1304 $badevent = calendar_event::load($badevent);
1305 $badevent->delete();
1306 }
ee1fb969 1307}
1308
efe24976
JP
1309/**
1310 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1311 *
1312 * @param int $quizid The quiz ID.
1313 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1314 */
1315function quiz_get_group_override_priorities($quizid) {
1316 global $DB;
1317
1318 // Fetch group overrides.
1319 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1320 $params = ['quiz' => $quizid];
1321 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1322 if (!$overrides) {
1323 return null;
1324 }
1325
1326 $grouptimeopen = [];
1327 $grouptimeclose = [];
1328 foreach ($overrides as $override) {
1329 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1330 $grouptimeopen[] = $override->timeopen;
1331 }
1332 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1333 $grouptimeclose[] = $override->timeclose;
1334 }
1335 }
1336
1337 // Sort open times in descending manner. The earlier open time gets higher priority.
1338 rsort($grouptimeopen);
1339 // Set priorities.
1340 $opengrouppriorities = [];
1341 $openpriority = 1;
1342 foreach ($grouptimeopen as $timeopen) {
1343 $opengrouppriorities[$timeopen] = $openpriority++;
1344 }
1345
1346 // Sort close times in ascending manner. The later close time gets higher priority.
1347 sort($grouptimeclose);
1348 // Set priorities.
1349 $closegrouppriorities = [];
1350 $closepriority = 1;
1351 foreach ($grouptimeclose as $timeclose) {
1352 $closegrouppriorities[$timeclose] = $closepriority++;
1353 }
1354
1355 return [
1356 'open' => $opengrouppriorities,
1357 'close' => $closegrouppriorities
1358 ];
1359}
1360
8cc86111 1361/**
b2b4ec30
RT
1362 * List the actions that correspond to a view of this module.
1363 * This is used by the participation report.
1364 *
1365 * Note: This is not used by new logging system. Event with
1366 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1367 * be considered as view action.
1368 *
8cc86111 1369 * @return array
1370 */
f3221af9 1371function quiz_get_view_actions() {
cf051cc4 1372 return array('view', 'view all', 'report', 'review');
f3221af9 1373}
ee1fb969 1374
8cc86111 1375/**
b2b4ec30
RT
1376 * List the actions that correspond to a post of this module.
1377 * This is used by the participation report.
1378 *
1379 * Note: This is not used by new logging system. Event with
1380 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1381 * will be considered as post action.
1382 *
8cc86111 1383 * @return array
1384 */
f3221af9 1385function quiz_get_post_actions() {
25a03faa
TH
1386 return array('attempt', 'close attempt', 'preview', 'editquestions',
1387 'delete attempt', 'manualgrade');
f3221af9 1388}
ee1fb969 1389
f67172b6 1390/**
25302dee 1391 * @param array $questionids of question ids.
f7970e3c 1392 * @return bool whether any of these questions are used by any instance of this module.
f67172b6 1393 */
25302dee 1394function quiz_questions_in_use($questionids) {
07f88584
TH
1395 global $DB, $CFG;
1396 require_once($CFG->libdir . '/questionlib.php');
25302dee 1397 list($test, $params) = $DB->get_in_or_equal($questionids);
ccba5b88 1398 return $DB->record_exists_select('quiz_slots',
dc4a3ea1 1399 'questionid ' . $test, $params) || question_engine::questions_in_use(
6b5f24d3 1400 $questionids, new qubaid_join('{quiz_attempts} quiza',
07f88584 1401 'quiza.uniqueid', 'quiza.preview = 0'));
f67172b6 1402}
1403
7a6f4066 1404/**
1405 * Implementation of the function for printing the form elements that control
1406 * whether the course reset functionality affects the quiz.
3b1d5cc4 1407 *
25302dee 1408 * @param $mform the course reset form that is being built.
0b5a80a1 1409 */
25302dee 1410function quiz_reset_course_form_definition($mform) {
c159da4c 1411 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
25a03faa
TH
1412 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1413 get_string('removeallquizattempts', 'quiz'));
113486d2
SB
1414 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1415 get_string('removealluseroverrides', 'quiz'));
1416 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1417 get_string('removeallgroupoverrides', 'quiz'));
0b5a80a1 1418}
1419
1420/**
1421 * Course reset form defaults.
25302dee 1422 * @return array the defaults.
0b5a80a1 1423 */
1424function quiz_reset_course_form_defaults($course) {
113486d2
SB
1425 return array('reset_quiz_attempts' => 1,
1426 'reset_quiz_group_overrides' => 1,
1427 'reset_quiz_user_overrides' => 1);
0b5a80a1 1428}
1429
1430/**
1431 * Removes all grades from gradebook
8cc86111 1432 *
0b5a80a1 1433 * @param int $courseid
1434 * @param string optional type
7a6f4066 1435 */
0b5a80a1 1436function quiz_reset_gradebook($courseid, $type='') {
9cf4a18b 1437 global $CFG, $DB;
0b5a80a1 1438
25302dee
TH
1439 $quizzes = $DB->get_records_sql("
1440 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1441 FROM {modules} m
1442 JOIN {course_modules} cm ON m.id = cm.module
1443 JOIN {quiz} q ON cm.instance = q.id
1444 WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
0b5a80a1 1445
25302dee
TH
1446 foreach ($quizzes as $quiz) {
1447 quiz_grade_item_update($quiz, 'reset');
0b5a80a1 1448 }
7a6f4066 1449}
1450
1451/**
72d2982e 1452 * Actual implementation of the reset course functionality, delete all the
7a6f4066 1453 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1454 * set and true.
6ef56c99 1455 *
1456 * Also, move the quiz open and close dates, if the course start date is changing.
8cc86111 1457 *
8cc86111 1458 * @param object $data the data submitted from the reset course.
0b5a80a1 1459 * @return array status array
7a6f4066 1460 */
0b5a80a1 1461function quiz_reset_userdata($data) {
53004e48 1462 global $CFG, $DB;
172238f4 1463 require_once($CFG->libdir . '/questionlib.php');
be0ba083 1464
0b5a80a1 1465 $componentstr = get_string('modulenameplural', 'quiz');
1466 $status = array();
b159da78 1467
25a03faa 1468 // Delete attempts.
6ef56c99 1469 if (!empty($data->reset_quiz_attempts)) {
6b5f24d3
TH
1470 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1471 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1472 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1473 array('quizcourseid' => $data->courseid)));
25302dee
TH
1474
1475 $DB->delete_records_select('quiz_attempts',
1476 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
1477 $status[] = array(
1478 'component' => $componentstr,
25a03faa 1479 'item' => get_string('attemptsdeleted', 'quiz'),
25302dee
TH
1480 'error' => false);
1481
9e83f3d1 1482 // Remove all grades from gradebook.
8dd9ccf4
TH
1483 $DB->delete_records_select('quiz_grades',
1484 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
0b5a80a1 1485 if (empty($data->reset_gradebook_grades)) {
1486 quiz_reset_gradebook($data->courseid);
7a6f4066 1487 }
25302dee
TH
1488 $status[] = array(
1489 'component' => $componentstr,
8dd9ccf4 1490 'item' => get_string('gradesdeleted', 'quiz'),
25302dee 1491 'error' => false);
7a6f4066 1492 }
6ef56c99 1493
113486d2
SB
1494 // Remove user overrides.
1495 if (!empty($data->reset_quiz_user_overrides)) {
1496 $DB->delete_records_select('quiz_overrides',
1497 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1498 $status[] = array(
1499 'component' => $componentstr,
1500 'item' => get_string('useroverridesdeleted', 'quiz'),
1501 'error' => false);
1502 }
1503 // Remove group overrides.
1504 if (!empty($data->reset_quiz_group_overrides)) {
1505 $DB->delete_records_select('quiz_overrides',
1506 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1507 $status[] = array(
1508 'component' => $componentstr,
1509 'item' => get_string('groupoverridesdeleted', 'quiz'),
1510 'error' => false);
1511 }
1512
9e83f3d1 1513 // Updating dates - shift may be negative too.
0b5a80a1 1514 if ($data->timeshift) {
2079c732
TH
1515 $DB->execute("UPDATE {quiz_overrides}
1516 SET timeopen = timeopen + ?
1517 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1518 AND timeopen <> 0", array($data->timeshift, $data->courseid));
1519 $DB->execute("UPDATE {quiz_overrides}
1520 SET timeclose = timeclose + ?
1521 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1522 AND timeclose <> 0", array($data->timeshift, $data->courseid));
1523
25a03faa
TH
1524 shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
1525 $data->timeshift, $data->courseid);
2079c732 1526
25302dee
TH
1527 $status[] = array(
1528 'component' => $componentstr,
1529 'item' => get_string('openclosedatesupdated', 'quiz'),
1530 'error' => false);
7a6f4066 1531 }
0b5a80a1 1532
1533 return $status;
7a6f4066 1534}
14e6dc79 1535
b5a16eb7 1536/**
1537 * Prints quiz summaries on MyMoodle Page
8cc86111 1538 * @param arry $courses
1539 * @param array $htmlarray
b5a16eb7 1540 */
1541function quiz_print_overview($courses, &$htmlarray) {
1542 global $USER, $CFG;
9e83f3d1 1543 // These next 6 Lines are constant in all modules (just change module name).
b5a16eb7 1544 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1545 return array();
1546 }
1547
2a13e454 1548 if (!$quizzes = get_all_instances_in_courses('quiz', $courses)) {
b5a16eb7 1549 return;
1550 }
1551
ac032e0e
FM
1552 // Get the quizzes attempts.
1553 $attemptsinfo = [];
1554 $quizids = [];
1555 foreach ($quizzes as $quiz) {
1556 $quizids[] = $quiz->id;
1557 $attemptsinfo[$quiz->id] = ['count' => 0, 'hasfinished' => false];
1558 }
1559 $attempts = quiz_get_user_attempts($quizids, $USER->id);
1560 foreach ($attempts as $attempt) {
1561 $attemptsinfo[$attempt->quiz]['count']++;
1562 $attemptsinfo[$attempt->quiz]['hasfinished'] = true;
1563 }
1564 unset($attempts);
1565
25a03faa 1566 // Fetch some language strings outside the main loop.
b5a16eb7 1567 $strquiz = get_string('modulename', 'quiz');
1568 $strnoattempts = get_string('noattempts', 'quiz');
1569
25a03faa
TH
1570 // We want to list quizzes that are currently available, and which have a close date.
1571 // This is the same as what the lesson does, and the dabate is in MDL-10568.
6c58e198 1572 $now = time();
2a13e454 1573 foreach ($quizzes as $quiz) {
b5a16eb7 1574 if ($quiz->timeclose >= $now && $quiz->timeopen < $now) {
ac032e0e 1575 $str = '';
b5a16eb7 1576
25a03faa 1577 // Now provide more information depending on the uers's role.
c492a78e 1578 $context = context_module::instance($quiz->coursemodule);
b5a16eb7 1579 if (has_capability('mod/quiz:viewreports', $context)) {
25a03faa 1580 // For teacher-like people, show a summary of the number of student attempts.
9cf4a18b 1581 // The $quiz objects returned by get_all_instances_in_course have the necessary $cm
2a13e454 1582 // fields set to make the following call work.
ac032e0e
FM
1583 $str .= '<div class="info">' . quiz_num_attempt_summary($quiz, $quiz, true) . '</div>';
1584
1585 } else if (has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $context)) { // Student
25a03faa 1586 // For student-like people, tell them how many attempts they have made.
ac032e0e
FM
1587
1588 if (isset($USER->id)) {
1589 if ($attemptsinfo[$quiz->id]['hasfinished']) {
1590 // The student's last attempt is finished.
1591 continue;
1592 }
1593
1594 if ($attemptsinfo[$quiz->id]['count'] > 0) {
1595 $str .= '<div class="info">' .
1596 get_string('numattemptsmade', 'quiz', $attemptsinfo[$quiz->id]['count']) . '</div>';
1597 } else {
1598 $str .= '<div class="info">' . $strnoattempts . '</div>';
1599 }
1600
b5a16eb7 1601 } else {
1602 $str .= '<div class="info">' . $strnoattempts . '</div>';
1603 }
ac032e0e 1604
b5a16eb7 1605 } else {
25a03faa 1606 // For ayone else, there is no point listing this quiz, so stop processing.
b5a16eb7 1607 continue;
1608 }
1609
ac032e0e
FM
1610 // Give a link to the quiz, and the deadline.
1611 $html = '<div class="quiz overview">' .
1612 '<div class="name">' . $strquiz . ': <a ' .
1613 ($quiz->visible ? '' : ' class="dimmed"') .
1614 ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1615 $quiz->coursemodule . '">' .
1616 $quiz->name . '</a></div>';
1617 $html .= '<div class="info">' . get_string('quizcloseson', 'quiz',
1618 userdate($quiz->timeclose)) . '</div>';
1619 $html .= $str;
1620 $html .= '</div>';
b5a16eb7 1621 if (empty($htmlarray[$quiz->course]['quiz'])) {
ac032e0e 1622 $htmlarray[$quiz->course]['quiz'] = $html;
b5a16eb7 1623 } else {
ac032e0e 1624 $htmlarray[$quiz->course]['quiz'] .= $html;
b5a16eb7 1625 }
1626 }
1627 }
1628}
6c58e198 1629
1630/**
25302dee 1631 * Return a textual summary of the number of attempts that have been made at a particular quiz,
cd300cf3 1632 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
8cc86111 1633 *
6c58e198 1634 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
25a03faa
TH
1635 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1636 * $cm->groupingid fields are used at the moment.
1637 * @param bool $returnzero if false (default), when no attempts have been
1638 * made '' is returned instead of 'Attempts: 0'.
2a13e454 1639 * @param int $currentgroup if there is a concept of current group where this method is being called
1640 * (e.g. a report) pass it in here. Default 0 which means no current group.
1641 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1642 * "Attemtps 123 (45 from this group)".
6c58e198 1643 */
2a13e454 1644function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
a49cb927 1645 global $DB, $USER;
9cf4a18b 1646 $numattempts = $DB->count_records('quiz_attempts', array('quiz'=> $quiz->id, 'preview'=>0));
6c58e198 1647 if ($numattempts || $returnzero) {
2a13e454 1648 if (groups_get_activity_groupmode($cm)) {
92701024 1649 $a = new stdClass();
2a13e454 1650 $a->total = $numattempts;
1651 if ($currentgroup) {
3f11d7f9 1652 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
9cf4a18b 1653 '{quiz_attempts} qa JOIN ' .
1654 '{groups_members} gm ON qa.userid = gm.userid ' .
25a03faa
TH
1655 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1656 array($quiz->id, $currentgroup));
2a13e454 1657 return get_string('attemptsnumthisgroup', 'quiz', $a);
9cf4a18b 1658 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1659 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
3f11d7f9 1660 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
9cf4a18b 1661 '{quiz_attempts} qa JOIN ' .
1662 '{groups_members} gm ON qa.userid = gm.userid ' .
1663 'WHERE quiz = ? AND preview = 0 AND ' .
1664 "groupid $usql", array_merge(array($quiz->id), $params));
2a13e454 1665 return get_string('attemptsnumyourgroups', 'quiz', $a);
1666 }
1667 }
6c58e198 1668 return get_string('attemptsnum', 'quiz', $numattempts);
1669 }
1670 return '';
1671}
f432bebf 1672
4e781c7b 1673/**
a49cb927
TH
1674 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1675 * to the quiz reports.
1676 *
1677 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
25a03faa
TH
1678 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and
1679 * $cm->groupingid fields are used at the moment.
a49cb927 1680 * @param object $context the quiz context.
25a03faa
TH
1681 * @param bool $returnzero if false (default), when no attempts have been made
1682 * '' is returned instead of 'Attempts: 0'.
a49cb927
TH
1683 * @param int $currentgroup if there is a concept of current group where this method is being called
1684 * (e.g. a report) pass it in here. Default 0 which means no current group.
1685 * @return string HTML fragment for the link.
1686 */
25a03faa
TH
1687function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1688 $currentgroup = 0) {
a49cb927
TH
1689 global $CFG;
1690 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1691 if (!$summary) {
1692 return '';
1693 }
1694
1695 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1696 $url = new moodle_url('/mod/quiz/report.php', array(
1697 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1698 return html_writer::link($url, $summary);
1699}
1700
1701/**
4e781c7b 1702 * @param string $feature FEATURE_xx constant for requested feature
1703 * @return bool True if quiz supports feature
1704 */
1705function quiz_supports($feature) {
1706 switch($feature) {
455dc0de
FM
1707 case FEATURE_GROUPS: return true;
1708 case FEATURE_GROUPINGS: return true;
455dc0de
FM
1709 case FEATURE_MOD_INTRO: return true;
1710 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
349c9303 1711 case FEATURE_COMPLETION_HAS_RULES: return true;
455dc0de 1712 case FEATURE_GRADE_HAS_GRADE: return true;
7e48778b 1713 case FEATURE_GRADE_OUTCOMES: return true;
455dc0de
FM
1714 case FEATURE_BACKUP_MOODLE2: return true;
1715 case FEATURE_SHOW_DESCRIPTION: return true;
1716 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
b07ef13b 1717 case FEATURE_USES_QUESTIONS: return true;
42f103be 1718
49f6e5f4 1719 default: return null;
4e781c7b 1720 }
1721}
1722
f432bebf 1723/**
cca6e300 1724 * @return array all other caps used in module
f432bebf 1725 */
1726function quiz_get_extra_capabilities() {
d774e817 1727 global $CFG;
172238f4 1728 require_once($CFG->libdir . '/questionlib.php');
cca6e300 1729 $caps = question_get_all_capabilities();
1730 $caps[] = 'moodle/site:accessallgroups';
1731 return $caps;
f432bebf 1732}
55f599f0 1733
55f599f0 1734/**
1735 * This function extends the settings navigation block for the site.
1736 *
1737 * It is safe to rely on PAGE here as we will only ever be within the module
1738 * context when this is called
1739 *
0b29477b
SH
1740 * @param settings_navigation $settings
1741 * @param navigation_node $quiznode
ebd9ae65 1742 * @return void
55f599f0 1743 */
0b29477b
SH
1744function quiz_extend_settings_navigation($settings, $quiznode) {
1745 global $PAGE, $CFG;
55f599f0 1746
9e83f3d1
TH
1747 // Require {@link questionlib.php}
1748 // Included here as we only ever want to include this file if we really need to.
56ed242b 1749 require_once($CFG->libdir . '/questionlib.php');
55f599f0 1750
bc502c16
TH
1751 // We want to add these new nodes after the Edit settings node, and before the
1752 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1753 $keys = $quiznode->get_children_key_list();
1b8655ab 1754 $beforekey = null;
bc502c16 1755 $i = array_search('modedit', $keys);
1b8655ab 1756 if ($i === false and array_key_exists(0, $keys)) {
bc502c16
TH
1757 $beforekey = $keys[0];
1758 } else if (array_key_exists($i + 1, $keys)) {
1759 $beforekey = $keys[$i + 1];
bc502c16
TH
1760 }
1761
56ed242b 1762 if (has_capability('mod/quiz:manageoverrides', $PAGE->cm->context)) {
56ed242b 1763 $url = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$PAGE->cm->id));
bc502c16 1764 $node = navigation_node::create(get_string('groupoverrides', 'quiz'),
25a03faa 1765 new moodle_url($url, array('mode'=>'group')),
bc502c16
TH
1766 navigation_node::TYPE_SETTING, null, 'mod_quiz_groupoverrides');
1767 $quiznode->add_node($node, $beforekey);
1768
1769 $node = navigation_node::create(get_string('useroverrides', 'quiz'),
25a03faa 1770 new moodle_url($url, array('mode'=>'user')),
bc502c16
TH
1771 navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1772 $quiznode->add_node($node, $beforekey);
55f599f0 1773 }
56ed242b 1774
55f599f0 1775 if (has_capability('mod/quiz:manage', $PAGE->cm->context)) {
bc502c16
TH
1776 $node = navigation_node::create(get_string('editquiz', 'quiz'),
1777 new moodle_url('/mod/quiz/edit.php', array('cmid'=>$PAGE->cm->id)),
1778 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit',
1779 new pix_icon('t/edit', ''));
1780 $quiznode->add_node($node, $beforekey);
55f599f0 1781 }
56ed242b
SH
1782
1783 if (has_capability('mod/quiz:preview', $PAGE->cm->context)) {
25a03faa
TH
1784 $url = new moodle_url('/mod/quiz/startattempt.php',
1785 array('cmid'=>$PAGE->cm->id, 'sesskey'=>sesskey()));
bc502c16
TH
1786 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1787 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
c3847443 1788 new pix_icon('i/preview', ''));
bc502c16 1789 $quiznode->add_node($node, $beforekey);
55f599f0 1790 }
56ed242b 1791
ebd9ae65
FM
1792 if (has_any_capability(array('mod/quiz:viewreports', 'mod/quiz:grade'), $PAGE->cm->context)) {
1793 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1794 $reportlist = quiz_report_list($PAGE->cm->context);
1795
1796 $url = new moodle_url('/mod/quiz/report.php',
1797 array('id' => $PAGE->cm->id, 'mode' => reset($reportlist)));
1798 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1799 navigation_node::TYPE_SETTING,
1800 null, null, new pix_icon('i/report', '')), $beforekey);
1801
1802 foreach ($reportlist as $report) {
1803 $url = new moodle_url('/mod/quiz/report.php',
1804 array('id' => $PAGE->cm->id, 'mode' => $report));
1805 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1806 navigation_node::TYPE_SETTING,
1807 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1808 }
1809 }
1810
2a8a78c3 1811 question_extend_settings_navigation($quiznode, $PAGE->cm->context)->trim_if_empty();
56ed242b 1812}
fe6ce234
DC
1813
1814/**
1815 * Serves the quiz files.
1816 *
d2b7803e
DC
1817 * @package mod_quiz
1818 * @category files
1819 * @param stdClass $course course object
1820 * @param stdClass $cm course module object
1821 * @param stdClass $context context object
1822 * @param string $filearea file area
1823 * @param array $args extra arguments
1824 * @param bool $forcedownload whether or not force download
261cbbac 1825 * @param array $options additional options affecting the file serving
fe6ce234
DC
1826 * @return bool false if file not found, does not return if found - justsend the file
1827 */
261cbbac 1828function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
fe6ce234
DC
1829 global $CFG, $DB;
1830
1831 if ($context->contextlevel != CONTEXT_MODULE) {
1832 return false;
1833 }
1834
1835 require_login($course, false, $cm);
1836
1837 if (!$quiz = $DB->get_record('quiz', array('id'=>$cm->instance))) {
1838 return false;
1839 }
1840
9e83f3d1 1841 // The 'intro' area is served by pluginfile.php.
fe6ce234
DC
1842 $fileareas = array('feedback');
1843 if (!in_array($filearea, $fileareas)) {
1844 return false;
1845 }
1846
1847 $feedbackid = (int)array_shift($args);
1848 if (!$feedback = $DB->get_record('quiz_feedback', array('id'=>$feedbackid))) {
1849 return false;
1850 }
1851
1852 $fs = get_file_storage();
1853 $relativepath = implode('/', $args);
1854 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1855 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1856 return false;
1857 }
261cbbac 1858 send_stored_file($file, 0, 0, true, $options);
fe6ce234
DC
1859}
1860
1861/**
1862 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1863 * a question in a question_attempt when that attempt is a quiz attempt.
1864 *
d2b7803e
DC
1865 * @package mod_quiz
1866 * @category files
1867 * @param stdClass $course course settings object
1868 * @param stdClass $context context object
fe6ce234
DC
1869 * @param string $component the name of the component we are serving files for.
1870 * @param string $filearea the name of the file area.
d2b7803e
DC
1871 * @param int $qubaid the attempt usage id.
1872 * @param int $slot the id of a question in this quiz attempt.
fe6ce234
DC
1873 * @param array $args the remaining bits of the file path.
1874 * @param bool $forcedownload whether the user must be forced to download the file.
261cbbac 1875 * @param array $options additional options affecting the file serving
fe6ce234
DC
1876 * @return bool false if file not found, does not return if found - justsend the file
1877 */
6b8b0b2e 1878function quiz_question_pluginfile($course, $context, $component,
261cbbac 1879 $filearea, $qubaid, $slot, $args, $forcedownload, array $options=array()) {
cef18275 1880 global $CFG;
fe6ce234
DC
1881 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1882
56e82d99 1883 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
cdbea7ee 1884 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
fe6ce234
DC
1885
1886 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1887 // In the middle of an attempt.
1888 if (!$attemptobj->is_preview_user()) {
1889 $attemptobj->require_capability('mod/quiz:attempt');
1890 }
1891 $isreviewing = false;
1892
1893 } else {
1894 // Reviewing an attempt.
1895 $attemptobj->check_review_capability();
1896 $isreviewing = true;
1897 }
1898
56e82d99 1899 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
fe6ce234
DC
1900 $component, $filearea, $args, $forcedownload)) {
1901 send_file_not_found();
1902 }
1903
1904 $fs = get_file_storage();
1905 $relativepath = implode('/', $args);
1906 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1907 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1908 send_file_not_found();
1909 }
1910
261cbbac 1911 send_stored_file($file, 0, 0, $forcedownload, $options);
fe6ce234 1912}
b1627a92
DC
1913
1914/**
1915 * Return a list of page types
1916 * @param string $pagetype current page type
1917 * @param stdClass $parentcontext Block's parent context
1918 * @param stdClass $currentcontext Current context of block
1919 */
b38e2e28 1920function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
346a32a7 1921 $module_pagetype = array(
f38965db
TH
1922 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1923 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1924 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1925 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1926 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1927 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1928 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1929 );
b1627a92
DC
1930 return $module_pagetype;
1931}
33c8d37b
CF
1932
1933/**
1934 * @return the options for quiz navigation.
1935 */
1936function quiz_get_navigation_options() {
1937 return array(
1938 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1939 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1940 );
1941}
349c9303 1942
349c9303
RM
1943/**
1944 * Obtains the automatic completion state for this quiz on any conditions
1945 * in quiz settings, such as if all attempts are used or a certain grade is achieved.
1946 *
1947 * @param object $course Course
1948 * @param object $cm Course-module
1949 * @param int $userid User ID
1950 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1951 * @return bool True if completed, false if not. (If no conditions, then return
1952 * value depends on comparison type)
1953 */
1954function quiz_get_completion_state($course, $cm, $userid, $type) {
1955 global $DB;
1956 global $CFG;
1957
1958 $quiz = $DB->get_record('quiz', array('id' => $cm->instance), '*', MUST_EXIST);
1959 if (!$quiz->completionattemptsexhausted && !$quiz->completionpass) {
1960 return $type;
1961 }
1962
1963 // Check if the user has used up all attempts.
1964 if ($quiz->completionattemptsexhausted) {
1965 $attempts = quiz_get_user_attempts($quiz->id, $userid, 'finished', true);
1966 if ($attempts) {
1967 $lastfinishedattempt = end($attempts);
1968 $context = context_module::instance($cm->id);
1969 $quizobj = quiz::create($quiz->id, $userid);
1970 $accessmanager = new quiz_access_manager($quizobj, time(),
1971 has_capability('mod/quiz:ignoretimelimits', $context, $userid, false));
1972 if ($accessmanager->is_finished(count($attempts), $lastfinishedattempt)) {
1973 return true;
1974 }
1975 }
1976 }
1977
1978 // Check for passing grade.
1979 if ($quiz->completionpass) {
1980 require_once($CFG->libdir . '/gradelib.php');
1981 $item = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod',
1245bfd5 1982 'itemmodule' => 'quiz', 'iteminstance' => $cm->instance, 'outcomeid' => null));
349c9303
RM
1983 if ($item) {
1984 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
1985 if (!empty($grades[$userid])) {
1986 return $grades[$userid]->is_passed($item);
1987 }
1988 }
1989 }
1990 return false;
1991}
02a73d76
JL
1992
1993/**
1994 * Check if the module has any update that affects the current user since a given time.
1995 *
1996 * @param cm_info $cm course module data
1997 * @param int $from the time to check updates from
1998 * @param array $filter if we need to check only specific updates
1999 * @return stdClass an object with the different type of areas indicating if they were updated or not
2000 * @since Moodle 3.2
2001 */
2002function quiz_check_updates_since(cm_info $cm, $from, $filter = array()) {
2003 global $DB, $USER, $CFG;
2004 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2005
2006 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2007
2008 // Check if questions were updated.
65b2669d 2009 $updates->questions = (object) array('updated' => false);
02a73d76
JL
2010 $quizobj = quiz::create($cm->instance, $USER->id);
2011 $quizobj->preload_questions();
2012 $quizobj->load_questions();
2013 $questionids = array_keys($quizobj->get_questions());
2014 if (!empty($questionids)) {
2015 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
2016 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
2017 $params['time1'] = $from;
2018 $params['time2'] = $from;
8abfb7b1 2019 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
65b2669d
JL
2020 if (!empty($questions)) {
2021 $updates->questions->updated = true;
2022 $updates->questions->itemids = array_keys($questions);
2023 }
02a73d76
JL
2024 }
2025
2026 // Check for new attempts or grades.
65b2669d
JL
2027 $updates->attempts = (object) array('updated' => false);
2028 $updates->grades = (object) array('updated' => false);
02a73d76
JL
2029 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
2030 $params = array($cm->instance, $USER->id, $from);
65b2669d
JL
2031
2032 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
2033 if (!empty($attempts)) {
2034 $updates->attempts->updated = true;
2035 $updates->attempts->itemids = array_keys($attempts);
2036 }
2037 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2038 if (!empty($grades)) {
2039 $updates->grades->updated = true;
2040 $updates->grades->itemids = array_keys($grades);
2041 }
02a73d76
JL
2042
2043 return $updates;
2044}