weekly release 2.2dev
[moodle.git] / mod / quiz / locallib.php
CommitLineData
83192608 1<?php
25302dee
TH
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/**
26d12a0c 18 * Library of functions used by the quiz module.
19 *
20 * This contains functions that are called from within the quiz module only
21 * Functions that are also called by core Moodle are in {@link lib.php}
22 * This script also loads the code in {@link questionlib.php} which holds
23 * the module-indpendent code for handling questions and which in turn
24 * initialises all the questiontype classes.
f63a4ff2 25 *
ba643847 26 * @package mod
25302dee 27 * @subpackage quiz
ba643847
TH
28 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26d12a0c 30 */
76cacec8 31
66d07f81 32
a17b297d
TH
33defined('MOODLE_INTERNAL') || die();
34
26d12a0c 35require_once($CFG->dirroot . '/mod/quiz/lib.php');
c52c62d1 36require_once($CFG->dirroot . '/mod/quiz/accessrules.php');
39759ac4 37require_once($CFG->dirroot . '/mod/quiz/renderer.php');
78e7a3dd 38require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
84e628a0 39require_once($CFG->dirroot . '/question/editlib.php');
3b120e46 40require_once($CFG->libdir . '/eventslib.php');
99d19c13 41require_once($CFG->libdir . '/filelib.php');
76cacec8 42
76cacec8 43
a4faed69 44/**#@+
25302dee
TH
45 * Options determining how the grades from individual attempts are combined to give
46 * the overall grade for a user
a4faed69 47 */
7c5bd5bf
TH
48define('QUIZ_GRADEHIGHEST', '1');
49define('QUIZ_GRADEAVERAGE', '2');
50define('QUIZ_ATTEMPTFIRST', '3');
51define('QUIZ_ATTEMPTLAST', '4');
a4faed69 52/**#@-*/
53
c52c62d1 54/**
55 * We show the countdown timer if there is less than this amount of time left before the
56 * the quiz close date. (1 hour)
57 */
58define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
59
26d12a0c 60/// Functions related to attempts /////////////////////////////////////////
ee1fb969 61
62/**
26d12a0c 63 * Creates an object to represent a new attempt at a quiz
64 *
65 * Creates an attempt object to represent an attempt at the quiz by the current
66 * user starting at the current time. The ->id field is not set. The object is
67 * NOT written to the database.
c52c62d1 68 *
69 * @param object $quiz the quiz to create an attempt for.
f7970e3c 70 * @param int $attemptnumber the sequence number for the attempt.
c52c62d1 71 * @param object $lastattempt the previous attempt by this user, if any. Only needed
72 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
f7970e3c
TH
73 * @param int $timenow the time the attempt was started at.
74 * @param bool $ispreview whether this new attempt is a preview.
c52c62d1 75 *
76 * @return object the newly created attempt object.
26d12a0c 77 */
c52c62d1 78function quiz_create_attempt($quiz, $attemptnumber, $lastattempt, $timenow, $ispreview = false) {
79 global $USER;
ee1fb969 80
e89e09d2 81 if ($attemptnumber == 1 || !$quiz->attemptonlast) {
25a03faa 82 // We are not building on last attempt so create a new attempt.
0ff4bd08 83 $attempt = new stdClass();
75e1df6f 84 $attempt->quiz = $quiz->id;
85 $attempt->userid = $USER->id;
86 $attempt->preview = 0;
87 if ($quiz->shufflequestions) {
25a03faa
TH
88 $attempt->layout = quiz_clean_layout(quiz_repaginate(
89 $quiz->questions, $quiz->questionsperpage, true), true);
75e1df6f 90 } else {
25a03faa 91 $attempt->layout = quiz_clean_layout($quiz->questions, true);
75e1df6f 92 }
c52c62d1 93 } else {
25a03faa 94 // Build on last attempt.
c52c62d1 95 if (empty($lastattempt)) {
5a2a5331 96 print_error('cannotfindprevattempt', 'quiz');
c52c62d1 97 }
98 $attempt = $lastattempt;
75e1df6f 99 }
100
ee1fb969 101 $attempt->attempt = $attemptnumber;
ee1fb969 102 $attempt->timestart = $timenow;
103 $attempt->timefinish = 0;
104 $attempt->timemodified = $timenow;
75e1df6f 105
25a03faa 106 // If this is a preview, mark it as such.
c52c62d1 107 if ($ispreview) {
108 $attempt->preview = 1;
109 }
110
ee1fb969 111 return $attempt;
112}
113
cd06115f 114/**
25302dee
TH
115 * Returns an unfinished attempt (if there is one) for the given
116 * user on the given quiz. This function does not return preview attempts.
77ed3ba5 117 *
f7970e3c
TH
118 * @param int $quizid the id of the quiz.
119 * @param int $userid the id of the user.
77ed3ba5 120 *
121 * @return mixed the unfinished attempt if there is one, false if not.
cd06115f 122 */
0d156caa 123function quiz_get_user_attempt_unfinished($quizid, $userid) {
ed8bebce 124 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
77ed3ba5 125 if ($attempts) {
126 return array_shift($attempts);
127 } else {
128 return false;
129 }
920fb237 130}
131
ff51d646 132/**
133 * Delete a quiz attempt.
25a03faa
TH
134 * @param mixed $attempt an integer attempt id or an attempt object
135 * (row of the quiz_attempts table).
97344ae3 136 * @param object $quiz the quiz object.
ff51d646 137 */
138function quiz_delete_attempt($attempt, $quiz) {
9cf4a18b 139 global $DB;
ff51d646 140 if (is_numeric($attempt)) {
9cf4a18b 141 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
ff51d646 142 return;
143 }
144 }
271e6dec 145
ff51d646 146 if ($attempt->quiz != $quiz->id) {
147 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
148 "but was passed quiz $quiz->id.");
149 return;
150 }
271e6dec 151
25302dee 152 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
6b5f24d3 153 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
ff51d646 154
155 // Search quiz_attempts for other instances by this user.
156 // If none, then delete record for this quiz, this user from quiz_grades
157 // else recalculate best grade
ff51d646 158 $userid = $attempt->userid;
9cf4a18b 159 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
25a03faa 160 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
ff51d646 161 } else {
162 quiz_save_best_grade($quiz, $userid);
163 }
07a7d859 164
165 quiz_update_grades($quiz, $userid);
ff51d646 166}
167
4299df1d 168/**
169 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
170 * to one user.
171 * @param object $quiz the quiz object.
f7970e3c 172 * @param int $userid (optional) if given, only delete the previews belonging to this user.
4299df1d 173 */
174function quiz_delete_previews($quiz, $userid = null) {
175 global $DB;
176 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
177 if (!empty($userid)) {
178 $conditions['userid'] = $userid;
179 }
180 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
181 foreach ($previewattempts as $attempt) {
182 quiz_delete_attempt($attempt, $quiz);
183 }
184}
185
84e628a0 186/**
f7970e3c
TH
187 * @param int $quizid The quiz id.
188 * @return bool whether this quiz has any (non-preview) attempts.
84e628a0 189 */
190function quiz_has_attempts($quizid) {
191 global $DB;
192 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
193}
194
26d12a0c 195/// Functions to do with quiz layout and pages ////////////////////////////////
0d156caa 196
ee1fb969 197/**
26d12a0c 198 * Returns a comma separated list of question ids for the quiz
199 *
1332ce53 200 * @param string $layout The string representing the quiz layout. Each page is
201 * represented as a comma separated list of question ids and 0 indicating
202 * page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
203 * 3 on page 2
204 * @return string comma separated list of question ids, without page breaks.
26d12a0c 205 */
ee1fb969 206function quiz_questions_in_quiz($layout) {
167f1562
TH
207 $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
208 if ($questions === '0') {
209 return '';
210 } else {
211 return $questions;
212 }
ee1fb969 213}
76cacec8 214
ee1fb969 215/**
1332ce53 216 * Returns the number of pages in a quiz layout
26d12a0c 217 *
1332ce53 218 * @param string $layout The string representing the quiz layout. Always ends in ,0
f7970e3c 219 * @return int The number of pages in the quiz.
26d12a0c 220 */
ee1fb969 221function quiz_number_of_pages($layout) {
167f1562 222 return substr_count(',' . $layout, ',0');
fa583f5f 223}
25302dee 224
fa583f5f 225/**
226 * Returns the number of questions in the quiz layout
227 *
1332ce53 228 * @param string $layout the string representing the quiz layout.
f7970e3c 229 * @return int The number of questions in the quiz.
fa583f5f 230 */
231function quiz_number_of_questions_in_quiz($layout) {
78634f1e 232 $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
1332ce53 233 $count = substr_count($layout, ',');
234 if ($layout !== '') {
fa583f5f 235 $count++;
236 }
237 return $count;
ee1fb969 238}
76cacec8 239
ee1fb969 240/**
26d12a0c 241 * Re-paginates the quiz layout
242 *
26d12a0c 243 * @param string $layout The string representing the quiz layout.
f7970e3c
TH
244 * @param int $perpage The number of questions per page
245 * @param bool $shuffle Should the questions be reordered randomly?
1332ce53 246 * @return string the new layout string
26d12a0c 247 */
4299df1d 248function quiz_repaginate($layout, $perpage, $shuffle = false) {
ee1fb969 249 $layout = str_replace(',0', '', $layout); // remove existing page breaks
250 $questions = explode(',', $layout);
251 if ($shuffle) {
ee1fb969 252 shuffle($questions);
253 }
254 $i = 1;
255 $layout = '';
256 foreach ($questions as $question) {
257 if ($perpage and $i > $perpage) {
258 $layout .= '0,';
259 $i = 1;
76cacec8 260 }
ee1fb969 261 $layout .= $question.',';
262 $i++;
76cacec8 263 }
ee1fb969 264 return $layout.'0';
265}
76cacec8 266
26d12a0c 267/// Functions to do with quiz grades //////////////////////////////////////////
76cacec8 268
ee1fb969 269/**
26d12a0c 270 * Creates an array of maximum grades for a quiz
83192608 271 *
25302dee
TH
272 * The grades are extracted from the quiz_question_instances table.
273 * @param object $quiz The quiz settings.
274 * @return array of grades indexed by question id. These are the maximum
4e6f553d 275 * possible grades that students can achieve for each of the questions.
26d12a0c 276 */
ee1fb969 277function quiz_get_all_question_grades($quiz) {
9cf4a18b 278 global $CFG, $DB;
76cacec8 279
ee1fb969 280 $questionlist = quiz_questions_in_quiz($quiz->questions);
76cacec8 281 if (empty($questionlist)) {
282 return array();
283 }
284
9cf4a18b 285 $params = array($quiz->id);
286 $wheresql = '';
287 if (!is_null($questionlist)) {
288 list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
289 $wheresql = " AND question $usql ";
290 $params = array_merge($params, $question_params);
291 }
292
25a03faa 293 $instances = $DB->get_records_sql("SELECT question, grade, id
9cf4a18b 294 FROM {quiz_question_instances}
295 WHERE quiz = ? $wheresql", $params);
76cacec8 296
297 $list = explode(",", $questionlist);
298 $grades = array();
299
300 foreach ($list as $qid) {
ee1fb969 301 if (isset($instances[$qid])) {
302 $grades[$qid] = $instances[$qid]->grade;
76cacec8 303 } else {
304 $grades[$qid] = 1;
305 }
306 }
307 return $grades;
308}
309
212b7b8c 310/**
311 * Convert the raw grade stored in $attempt into a grade out of the maximum
312 * grade for this quiz.
77ed3ba5 313 *
212b7b8c 314 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
25302dee 315 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
f7970e3c 316 * @param bool|string $format whether to format the results for display
25302dee 317 * or 'question' to format a question grade (different number of decimal places.
25a03faa
TH
318 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
319 * if the $grade is null.
212b7b8c 320 */
25302dee
TH
321function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
322 if (is_null($rawgrade)) {
323 $grade = null;
324 } else if ($quiz->sumgrades >= 0.000005) {
b7b4f8bd 325 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
212b7b8c 326 } else {
b7b4f8bd 327 $grade = 0;
212b7b8c 328 }
25302dee
TH
329 if ($format === 'question') {
330 $grade = quiz_format_question_grade($quiz, $grade);
331 } else if ($format) {
332 $grade = quiz_format_grade($quiz, $grade);
333 }
b7b4f8bd 334 return $grade;
76cacec8 335}
336
ee1fb969 337/**
212b7b8c 338 * Get the feedback text that should be show to a student who
de266537 339 * got this grade on this quiz. The feedback is processed ready for diplay.
77ed3ba5 340 *
212b7b8c 341 * @param float $grade a grade on this quiz.
2709ee45
TH
342 * @param object $quiz the quiz settings.
343 * @param object $context the quiz context.
212b7b8c 344 * @return string the comment that corresponds to this grade (empty string if there is not one.
345 */
2709ee45 346function quiz_feedback_for_grade($grade, $quiz, $context) {
9cf4a18b 347 global $DB;
212b7b8c 348
25302dee
TH
349 if (is_null($grade)) {
350 return '';
351 }
352
2709ee45
TH
353 $feedback = $DB->get_record_select('quiz_feedback',
354 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
fe6ce234
DC
355
356 if (empty($feedback->feedbacktext)) {
2709ee45 357 return '';
212b7b8c 358 }
77ed3ba5 359
de266537 360 // Clean the text, ready for display.
0ff4bd08 361 $formatoptions = new stdClass();
de266537 362 $formatoptions->noclean = true;
25a03faa
TH
363 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
364 $context->id, 'mod_quiz', 'feedback', $feedback->id);
fe6ce234 365 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
de266537 366
fe6ce234 367 return $feedbacktext;
212b7b8c 368}
369
370/**
8ce3e17f 371 * @param object $quiz the quiz database row.
f7970e3c 372 * @return bool Whether this quiz has any non-blank feedback text.
212b7b8c 373 */
739b0711 374function quiz_has_feedback($quiz) {
9cf4a18b 375 global $DB;
212b7b8c 376 static $cache = array();
739b0711 377 if (!array_key_exists($quiz->id, $cache)) {
378 $cache[$quiz->id] = quiz_has_grades($quiz) &&
379 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
380 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
381 array($quiz->id));
212b7b8c 382 }
739b0711 383 return $cache[$quiz->id];
212b7b8c 384}
385
3c6185e9
TH
386function quiz_no_questions_message($quiz, $cm, $context) {
387 global $OUTPUT;
388
389 $output = '';
390 $output .= $OUTPUT->notification(get_string('noquestions', 'quiz'));
391 if (has_capability('mod/quiz:manage', $context)) {
392 $output .= $OUTPUT->single_button(new moodle_url('/mod/quiz/edit.php',
393 array('cmid' => $cm->id)), get_string('editquiz', 'quiz'), 'get');
394 }
395
396 return $output;
397}
398
25302dee
TH
399/**
400 * Update the sumgrades field of the quiz. This needs to be called whenever
401 * the grading structure of the quiz is changed. For example if a question is
402 * added or removed, or a question weight is changed.
403 *
404 * @param object $quiz a quiz.
405 */
406function quiz_update_sumgrades($quiz) {
407 global $DB;
408 $sql = 'UPDATE {quiz}
409 SET sumgrades = COALESCE((
410 SELECT SUM(grade)
411 FROM {quiz_question_instances}
412 WHERE quiz = {quiz}.id
413 ), 0)
414 WHERE id = ?';
a13d4fbd
TH
415 $DB->execute($sql, array($quiz->id));
416 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
25302dee
TH
417 if ($quiz->sumgrades < 0.000005) {
418 quiz_set_grade(0, $quiz);
419 }
420}
421
422function quiz_update_all_attempt_sumgrades($quiz) {
423 global $DB;
424 $dm = new question_engine_data_mapper();
425 $timenow = time();
426
427 $sql = "UPDATE {quiz_attempts}
428 SET
429 timemodified = :timenow,
430 sumgrades = (
431 {$dm->sum_usage_marks_subquery('uniqueid')}
432 )
433 WHERE quiz = :quizid AND timefinish <> 0";
434 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id));
435}
436
212b7b8c 437/**
b2607ccc 438 * The quiz grade is the maximum that student's results are marked out of. When it
212b7b8c 439 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
25302dee
TH
440 * rescaled. After calling this function, you probably need to call
441 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
442 * quiz_update_grades.
77ed3ba5 443 *
212b7b8c 444 * @param float $newgrade the new maximum grade for the quiz.
25a03faa
TH
445 * @param object $quiz the quiz we are updating. Passed by reference so its
446 * grade field can be updated too.
f7970e3c 447 * @return bool indicating success or failure.
212b7b8c 448 */
25302dee 449function quiz_set_grade($newgrade, $quiz) {
9cf4a18b 450 global $DB;
212b7b8c 451 // This is potentially expensive, so only do it if necessary.
452 if (abs($quiz->grade - $newgrade) < 1e-7) {
453 // Nothing to do.
454 return true;
455 }
b22fc901 456
212b7b8c 457 // Use a transaction, so that on those databases that support it, this is safer.
d5a8d9aa
PS
458 $transaction = $DB->start_delegated_transaction();
459
0f1c59c5
TH
460 // Update the quiz table.
461 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
462
463 // Rescaling the other data is only possible if the old grade was non-zero.
464 if ($quiz->grade > 1e-7) {
465 global $CFG;
466
467 $factor = $newgrade/$quiz->grade;
468 $quiz->grade = $newgrade;
469
470 // Update the quiz_grades table.
471 $timemodified = time();
472 $DB->execute("
473 UPDATE {quiz_grades}
474 SET grade = ? * grade, timemodified = ?
475 WHERE quiz = ?
476 ", array($factor, $timemodified, $quiz->id));
477
478 // Update the quiz_feedback table.
479 $DB->execute("
480 UPDATE {quiz_feedback}
481 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
482 WHERE quizid = ?
483 ", array($factor, $factor, $quiz->id));
484 }
77ed3ba5 485
0f1c59c5
TH
486 // update grade item and send all grades to gradebook
487 quiz_grade_item_update($quiz);
488 quiz_update_grades($quiz);
d6dd2108 489
0f1c59c5
TH
490 $transaction->allow_commit();
491 return true;
212b7b8c 492}
493
494/**
495 * Save the overall grade for a user at a quiz in the quiz_grades table
496 *
497 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
f7970e3c 498 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
98f38217 499 * @param array $attempts The attempts of this user. Useful if you are
500 * looping through many users. Attempts can be fetched in one master query to
501 * avoid repeated querying.
f7970e3c 502 * @return bool Indicates success or failure.
212b7b8c 503 */
98f38217 504function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
9cf4a18b 505 global $DB;
825116fb 506 global $USER, $OUTPUT;
ee1fb969 507
212b7b8c 508 if (empty($userid)) {
ee1fb969 509 $userid = $USER->id;
510 }
76cacec8 511
25a03faa 512 if (!$attempts) {
98f38217 513 // Get all the attempts made by the user
25302dee 514 $attempts = quiz_get_user_attempts($quiz->id, $userid);
76cacec8 515 }
516
ee1fb969 517 // Calculate the best grade
76cacec8 518 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
84e628a0 519 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
77ed3ba5 520
ee1fb969 521 // Save the best grade in the database
25302dee
TH
522 if (is_null($bestgrade)) {
523 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
524
25a03faa
TH
525 } else if ($grade = $DB->get_record('quiz_grades',
526 array('quiz' => $quiz->id, 'userid' => $userid))) {
fc44ee0d 527 $grade->grade = $bestgrade;
76cacec8 528 $grade->timemodified = time();
a8c31db2 529 $DB->update_record('quiz_grades', $grade);
25302dee 530
76cacec8 531 } else {
532 $grade->quiz = $quiz->id;
533 $grade->userid = $userid;
fc44ee0d 534 $grade->grade = $bestgrade;
76cacec8 535 $grade->timemodified = time();
a8c31db2 536 $DB->insert_record('quiz_grades', $grade);
76cacec8 537 }
d6dd2108 538
539 quiz_update_grades($quiz, $userid);
76cacec8 540}
541
fc44ee0d 542/**
26d12a0c 543 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
544 *
545 * @return float The overall grade
546 * @param object $quiz The quiz for which the best grade is to be calculated
547 * @param array $attempts An array of all the attempts of the user at the quiz
548 */
76cacec8 549function quiz_calculate_best_grade($quiz, $attempts) {
76cacec8 550
551 switch ($quiz->grademethod) {
552
ee1fb969 553 case QUIZ_ATTEMPTFIRST:
76cacec8 554 foreach ($attempts as $attempt) {
555 return $attempt->sumgrades;
556 }
25302dee 557 return $final;
76cacec8 558
ee1fb969 559 case QUIZ_ATTEMPTLAST:
76cacec8 560 foreach ($attempts as $attempt) {
561 $final = $attempt->sumgrades;
562 }
563 return $final;
564
ee1fb969 565 case QUIZ_GRADEAVERAGE:
76cacec8 566 $sum = 0;
567 $count = 0;
568 foreach ($attempts as $attempt) {
25302dee
TH
569 if (!is_null($attempt->sumgrades)) {
570 $sum += $attempt->sumgrades;
571 $count++;
572 }
76cacec8 573 }
25302dee
TH
574 if ($count == 0) {
575 return null;
576 }
577 return $sum / $count;
76cacec8 578
579 default:
ee1fb969 580 case QUIZ_GRADEHIGHEST:
25302dee 581 $max = null;
76cacec8 582 foreach ($attempts as $attempt) {
583 if ($attempt->sumgrades > $max) {
584 $max = $attempt->sumgrades;
585 }
586 }
587 return $max;
588 }
589}
590
25302dee
TH
591/**
592 * Update the final grade at this quiz for all students.
593 *
594 * This function is equivalent to calling quiz_save_best_grade for all
595 * users, but much more efficient.
596 *
597 * @param object $quiz the quiz settings.
598 */
599function quiz_update_all_final_grades($quiz) {
600 global $DB;
601
602 if (!$quiz->sumgrades) {
603 return;
604 }
605
606 $param = array('iquizid' => $quiz->id);
607 $firstlastattemptjoin = "JOIN (
608 SELECT
609 iquiza.userid,
610 MIN(attempt) AS firstattempt,
611 MAX(attempt) AS lastattempt
612
e50a5813 613 FROM {quiz_attempts} iquiza
25302dee
TH
614
615 WHERE
616 iquiza.timefinish <> 0 AND
617 iquiza.preview = 0 AND
618 iquiza.quiz = :iquizid
619
620 GROUP BY iquiza.userid
621 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
622
623 switch ($quiz->grademethod) {
624 case QUIZ_ATTEMPTFIRST:
625 // Becuase of the where clause, there will only be one row, but we
626 // must still use an aggregate function.
627 $select = 'MAX(quiza.sumgrades)';
628 $join = $firstlastattemptjoin;
629 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
630 break;
631
632 case QUIZ_ATTEMPTLAST:
633 // Becuase of the where clause, there will only be one row, but we
634 // must still use an aggregate function.
635 $select = 'MAX(quiza.sumgrades)';
636 $join = $firstlastattemptjoin;
637 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
638 break;
639
640 case QUIZ_GRADEAVERAGE:
641 $select = 'AVG(quiza.sumgrades)';
642 $join = '';
643 $where = '';
644 break;
645
646 default:
647 case QUIZ_GRADEHIGHEST:
648 $select = 'MAX(quiza.sumgrades)';
649 $join = '';
650 $where = '';
651 break;
652 }
653
654 if ($quiz->sumgrades >= 0.000005) {
655 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
656 } else {
657 $finalgrade = '0';
658 }
659 $param['quizid'] = $quiz->id;
660 $param['quizid2'] = $quiz->id;
661 $param['quizid3'] = $quiz->id;
662 $param['quizid4'] = $quiz->id;
663 $finalgradesubquery = "
664 SELECT quiza.userid, $finalgrade AS newgrade
665 FROM {quiz_attempts} quiza
666 $join
667 WHERE
668 $where
669 quiza.timefinish <> 0 AND
670 quiza.preview = 0 AND
671 quiza.quiz = :quizid3
672 GROUP BY quiza.userid";
673
674 $changedgrades = $DB->get_records_sql("
675 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
676
677 FROM (
678 SELECT userid
679 FROM {quiz_grades} qg
680 WHERE quiz = :quizid
681 UNION
682 SELECT DISTINCT userid
683 FROM {quiz_attempts} quiza2
684 WHERE
685 quiza2.timefinish <> 0 AND
686 quiza2.preview = 0 AND
687 quiza2.quiz = :quizid2
688 ) users
689
690 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
691
692 LEFT JOIN (
693 $finalgradesubquery
694 ) newgrades ON newgrades.userid = users.userid
695
696 WHERE
697 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
698 (newgrades.newgrade IS NULL) <> (qg.grade IS NULL)",
a13d4fbd 699 $param);
25302dee
TH
700
701 $timenow = time();
702 $todelete = array();
703 foreach ($changedgrades as $changedgrade) {
704
705 if (is_null($changedgrade->newgrade)) {
706 $todelete[] = $changedgrade->userid;
707
708 } else if (is_null($changedgrade->grade)) {
0ff4bd08 709 $toinsert = new stdClass();
25302dee
TH
710 $toinsert->quiz = $quiz->id;
711 $toinsert->userid = $changedgrade->userid;
712 $toinsert->timemodified = $timenow;
713 $toinsert->grade = $changedgrade->newgrade;
714 $DB->insert_record('quiz_grades', $toinsert);
715
716 } else {
0ff4bd08 717 $toupdate = new stdClass();
25302dee
TH
718 $toupdate->id = $changedgrade->id;
719 $toupdate->grade = $changedgrade->newgrade;
720 $toupdate->timemodified = $timenow;
721 $DB->update_record('quiz_grades', $toupdate);
722 }
723 }
724
725 if (!empty($todelete)) {
e65f89b9 726 list($test, $params) = $DB->get_in_or_equal($todelete);
8d13ea83
TH
727 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
728 array_merge(array($quiz->id), $params));
25302dee
TH
729 }
730}
731
fc44ee0d 732/**
26d12a0c 733 * Return the attempt with the best grade for a quiz
734 *
735 * Which attempt is the best depends on $quiz->grademethod. If the grade
736 * method is GRADEAVERAGE then this function simply returns the last attempt.
737 * @return object The attempt with the best grade
738 * @param object $quiz The quiz for which the best grade is to be calculated
739 * @param array $attempts An array of all the attempts of the user at the quiz
740 */
76cacec8 741function quiz_calculate_best_attempt($quiz, $attempts) {
76cacec8 742
743 switch ($quiz->grademethod) {
744
ee1fb969 745 case QUIZ_ATTEMPTFIRST:
76cacec8 746 foreach ($attempts as $attempt) {
747 return $attempt;
748 }
749 break;
750
ee1fb969 751 case QUIZ_GRADEAVERAGE: // need to do something with it :-)
752 case QUIZ_ATTEMPTLAST:
76cacec8 753 foreach ($attempts as $attempt) {
754 $final = $attempt;
755 }
756 return $final;
757
758 default:
ee1fb969 759 case QUIZ_GRADEHIGHEST:
76cacec8 760 $max = -1;
761 foreach ($attempts as $attempt) {
762 if ($attempt->sumgrades > $max) {
763 $max = $attempt->sumgrades;
764 $maxattempt = $attempt;
765 }
766 }
767 return $maxattempt;
768 }
769}
770
25302dee
TH
771/**
772 * @return the options for calculating the quiz grade from the individual attempt grades.
773 */
774function quiz_get_grading_options() {
775 return array(
776 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
777 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
778 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
779 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
780 );
781}
782
0675e5eb 783/**
25a03faa
TH
784 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
785 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
0675e5eb 786 * @return the lang string for that option.
787 */
788function quiz_get_grading_option_name($option) {
789 $strings = quiz_get_grading_options();
790 return $strings[$option];
791}
792
26d12a0c 793/// Other quiz functions ////////////////////////////////////////////////////
ee1fb969 794
26a29b1a 795/**
2a874d65 796 * @param object $quiz the quiz.
f7970e3c 797 * @param int $cmid the course_module object for this quiz.
2a874d65 798 * @param object $question the question.
26a29b1a 799 * @param string $returnurl url to return to after action is done.
800 * @return string html for a number of icons linked to action pages for a
801 * question - preview and edit / view icons depending on user capabilities.
802 */
2a874d65 803function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
804 $html = quiz_question_preview_button($quiz, $question) . ' ' .
805 quiz_question_edit_button($cmid, $question, $returnurl);
806 return $html;
807}
808
809/**
f7970e3c 810 * @param int $cmid the course_module.id for this quiz.
2a874d65 811 * @param object $question the question.
812 * @param string $returnurl url to return to after action is done.
813 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
25a03faa
TH
814 * @return the HTML for an edit icon, view icon, or nothing for a question
815 * (depending on permissions).
2a874d65 816 */
d04f623b 817function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
d436d197 818 global $CFG, $OUTPUT;
2a874d65 819
820 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
26a29b1a 821 static $stredit = null;
822 static $strview = null;
25a03faa 823 if ($stredit === null) {
26a29b1a 824 $stredit = get_string('edit');
825 $strview = get_string('view');
826 }
2a874d65 827
828 // What sort of icon should we show?
829 $action = '';
25a03faa
TH
830 if (!empty($question->id) &&
831 (question_has_capability_on($question, 'edit', $question->category) ||
832 question_has_capability_on($question, 'move', $question->category))) {
2a874d65 833 $action = $stredit;
834 $icon = '/t/edit';
25a03faa
TH
835 } else if (!empty($question->id) &&
836 question_has_capability_on($question, 'view', $question->category)) {
2a874d65 837 $action = $strview;
838 $icon = '/i/info';
839 }
840
841 // Build the icon.
842 if ($action) {
47678d60
TH
843 if ($returnurl instanceof moodle_url) {
844 $returnurl = str_replace($CFG->wwwroot, '', $returnurl->out(false));
845 }
2a874d65 846 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
847 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
d04f623b
TH
848 return '<a title="' . $action . '" href="' . $questionurl->out() . '"><img src="' .
849 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
850 '</a>';
2a874d65 851 } else {
d04f623b 852 return $contentaftericon;
26a29b1a 853 }
26a29b1a 854}
855
7d87171b 856/**
612106b3
TH
857 * @param object $quiz the quiz settings
858 * @param object $question the question
859 * @return moodle_url to preview this question with the options from this quiz.
860 */
861function quiz_question_preview_url($quiz, $question) {
862 // Get the appropriate display options.
863 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
864 mod_quiz_display_options::DURING);
865
866 $maxmark = null;
867 if (isset($question->maxmark)) {
868 $maxmark = $question->maxmark;
869 }
870
871 // Work out the correcte preview URL.
872 return question_preview_url($question->id, $quiz->preferredbehaviour,
873 $maxmark, $displayoptions);
874}
875
876/**
877 * @param object $quiz the quiz settings
7d87171b 878 * @param object $question the question
f7970e3c 879 * @param bool $label if true, show the preview question label after the icon
7d87171b 880 * @return the HTML for a preview question icon.
881 */
2a874d65 882function quiz_question_preview_button($quiz, $question, $label = false) {
56a4ae46 883 global $CFG, $OUTPUT;
2a874d65 884 if (!question_has_capability_on($question, 'use', $question->category)) {
271e6dec 885 return '';
886 }
2a874d65 887
612106b3 888 $url = quiz_question_preview_url($quiz, $question);
2a874d65 889
890 // Do we want a label?
25302dee 891 $strpreviewlabel = '';
2a874d65 892 if ($label) {
25302dee 893 $strpreviewlabel = get_string('preview', 'quiz');
fa583f5f 894 }
2a874d65 895
896 // Build the icon.
f9b0500f 897 $strpreviewquestion = get_string('previewquestion', 'quiz');
000c278c 898 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
ca4b4f8f 899
612106b3
TH
900 $action = new popup_action('click', $url, 'questionpreview',
901 question_preview_popup_params());
4bcc5118 902
25302dee 903 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
ad7e7ba8 904}
0d156caa 905
62e76c67 906/**
907 * @param object $attempt the attempt.
908 * @param object $context the quiz context.
f7970e3c 909 * @return int whether flags should be shown/editable to the current user for this attempt.
62e76c67 910 */
911function quiz_get_flag_option($attempt, $context) {
912 global $USER;
25302dee
TH
913 if (!has_capability('moodle/question:flag', $context)) {
914 return question_display_options::HIDDEN;
915 } else if ($attempt->userid == $USER->id) {
916 return question_display_options::EDITABLE;
917 } else {
918 return question_display_options::VISIBLE;
62e76c67 919 }
62e76c67 920}
921
4f48fb42 922/**
25302dee
TH
923 * Work out what state this quiz attempt is in.
924 * @param object $quiz the quiz settings
925 * @param object $attempt the quiz_attempt database row.
f7970e3c 926 * @return int one of the mod_quiz_display_options::DURING,
25302dee 927 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
4dca7e51 928 */
25302dee
TH
929function quiz_attempt_state($quiz, $attempt) {
930 if ($attempt->timefinish == 0) {
931 return mod_quiz_display_options::DURING;
932 } else if (time() < $attempt->timefinish + 120) {
933 return mod_quiz_display_options::IMMEDIATELY_AFTER;
934 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
935 return mod_quiz_display_options::LATER_WHILE_OPEN;
936 } else {
937 return mod_quiz_display_options::AFTER_CLOSE;
938 }
4f48fb42 939}
940
4f48fb42 941/**
25302dee
TH
942 * The the appropraite mod_quiz_display_options object for this attempt at this
943 * quiz right now.
77ed3ba5 944 *
cd06115f 945 * @param object $quiz the quiz instance.
946 * @param object $attempt the attempt in question.
25302dee 947 * @param $context the quiz context.
77ed3ba5 948 *
25302dee 949 * @return mod_quiz_display_options
cd06115f 950 */
7ee80cab 951function quiz_get_review_options($quiz, $attempt, $context) {
25302dee 952 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
62e76c67 953
4f48fb42 954 $options->readonly = true;
62e76c67 955 $options->flags = quiz_get_flag_option($attempt, $context);
2709ee45
TH
956 if (!empty($attempt->id)) {
957 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
958 array('attempt' => $attempt->id));
959 }
b6e907a2 960
e2833e87 961 // Show a link to the comment box only for closed attempts
2709ee45
TH
962 if (!empty($attempt->id) && $attempt->timefinish && !$attempt->preview &&
963 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
25302dee 964 $options->manualcomment = question_display_options::VISIBLE;
7ee80cab
TH
965 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
966 array('attempt' => $attempt->id));
01600b51 967 }
968
25a03faa
TH
969 if (!is_null($context) && !$attempt->preview &&
970 has_capability('mod/quiz:viewreports', $context) &&
25302dee 971 has_capability('moodle/grade:viewhidden', $context)) {
e2833e87 972 // People who can see reports and hidden grades should be shown everything,
973 // except during preview when teachers want to see what students see.
25302dee
TH
974 $options->attempt = question_display_options::VISIBLE;
975 $options->correctness = question_display_options::VISIBLE;
976 $options->marks = question_display_options::MARK_AND_MAX;
977 $options->feedback = question_display_options::VISIBLE;
978 $options->numpartscorrect = question_display_options::VISIBLE;
979 $options->generalfeedback = question_display_options::VISIBLE;
980 $options->rightanswer = question_display_options::VISIBLE;
981 $options->overallfeedback = question_display_options::VISIBLE;
982 $options->history = question_display_options::VISIBLE;
e2833e87 983
4f48fb42 984 }
77ed3ba5 985
4f48fb42 986 return $options;
987}
77ed3ba5 988
40377b18 989/**
77ed3ba5 990 * Combines the review options from a number of different quiz attempts.
25302dee 991 * Returns an array of two ojects, so the suggested way of calling this
77ed3ba5 992 * funciton is:
993 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
994 *
995 * @param object $quiz the quiz instance.
996 * @param array $attempts an array of attempt objects.
997 * @param $context the roles and permissions context,
998 * normally the context for the quiz module instance.
999 *
1000 * @return array of two options objects, one showing which options are true for
1001 * at least one of the attempts, the other showing which options are true
1002 * for all attempts.
1003 */
25302dee 1004function quiz_get_combined_reviewoptions($quiz, $attempts) {
6d03fd98 1005 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
0ff4bd08
TH
1006 $someoptions = new stdClass();
1007 $alloptions = new stdClass();
77ed3ba5 1008 foreach ($fields as $field) {
1009 $someoptions->$field = false;
1010 $alloptions->$field = true;
40377b18 1011 }
6d03fd98
TH
1012 $someoptions->marks = question_display_options::HIDDEN;
1013 $alloptions->marks = question_display_options::MARK_AND_MAX;
1014
77ed3ba5 1015 foreach ($attempts as $attempt) {
25302dee
TH
1016 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1017 quiz_attempt_state($quiz, $attempt));
7d014bf5 1018 foreach ($fields as $field) {
1019 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1020 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1021 }
6d03fd98
TH
1022 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1023 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
77ed3ba5 1024 }
1025 return array($someoptions, $alloptions);
40377b18 1026}
ac48e43a 1027
25302dee
TH
1028/**
1029 * Clean the question layout from various possible anomalies:
1030 * - Remove consecutive ","'s
1031 * - Remove duplicate question id's
1032 * - Remove extra "," from beginning and end
1033 * - Finally, add a ",0" in the end if there is none
1034 *
1035 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
f7970e3c 1036 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
25302dee
TH
1037 * @return $string the cleaned-up layout
1038 */
1039function quiz_clean_layout($layout, $removeemptypages = false) {
1040 // Remove repeated ','s. This can happen when a restore fails to find the right
1041 // id to relink to.
1042 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1043
1044 // Remove duplicate question ids
1045 $layout = explode(',', $layout);
1046 $cleanerlayout = array();
1047 $seen = array();
1048 foreach ($layout as $item) {
1049 if ($item == 0) {
1050 $cleanerlayout[] = '0';
1051 } else if (!in_array($item, $seen)) {
1052 $cleanerlayout[] = $item;
1053 $seen[] = $item;
1054 }
1055 }
1056
1057 if ($removeemptypages) {
1058 // Avoid duplicate page breaks
1059 $layout = $cleanerlayout;
1060 $cleanerlayout = array();
1061 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1062 foreach ($layout as $item) {
1063 if ($stripfollowingbreaks && $item == 0) {
1064 continue;
1065 }
1066 $cleanerlayout[] = $item;
1067 $stripfollowingbreaks = $item == 0;
1068 }
1069 }
1070
1071 // Add a page break at the end if there is none
1072 if (end($cleanerlayout) !== '0') {
1073 $cleanerlayout[] = '0';
1074 }
1075
1076 return implode(',', $cleanerlayout);
1077}
1078
1079/**
1080 * Get the slot for a question with a particular id.
1081 * @param object $quiz the quiz settings.
f7970e3c
TH
1082 * @param int $questionid the of a question in the quiz.
1083 * @return int the corresponding slot. Null if the question is not in the quiz.
25302dee
TH
1084 */
1085function quiz_get_slot_for_question($quiz, $questionid) {
1086 $questionids = quiz_questions_in_quiz($quiz->questions);
1087 foreach (explode(',', $questionids) as $key => $id) {
1088 if ($id == $questionid) {
1089 return $key + 1;
1090 }
1091 }
1092 return null;
1093}
1094
ac48e43a 1095/// FUNCTIONS FOR SENDING NOTIFICATION EMAILS ///////////////////////////////
1096
1097/**
1098 * Sends confirmation email to the student taking the course
1099 *
0ff4bd08 1100 * @param object $a associative array of replaceable fields for the templates
ac48e43a 1101 *
d83bad41 1102 * @return bool
ac48e43a 1103 */
1104function quiz_send_confirmation($a) {
1105
1106 global $USER;
1107
1108 // recipient is self
1109 $a->useridnumber = $USER->idnumber;
1110 $a->username = fullname($USER);
1111 $a->userusername = $USER->username;
1112
1113 // fetch the subject and body from strings
1114 $subject = get_string('emailconfirmsubject', 'quiz', $a);
1115 $body = get_string('emailconfirmbody', 'quiz', $a);
1116
1117 // send email and analyse result
39790bd8 1118 $eventdata = new stdClass();
94263cca
AD
1119 $eventdata->component = 'mod_quiz';
1120 $eventdata->name = 'confirmation';
1121 $eventdata->notification = 1;
1122
3b120e46 1123 $eventdata->userfrom = get_admin();
1124 $eventdata->userto = $USER;
1125 $eventdata->subject = $subject;
1126 $eventdata->fullmessage = $body;
1127 $eventdata->fullmessageformat = FORMAT_PLAIN;
1128 $eventdata->fullmessagehtml = '';
94263cca
AD
1129
1130 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1131 $eventdata->contexturl = $a->quizurl;
1132 $eventdata->contexturlname = $a->quizname;
99d19c13 1133
d83bad41 1134 return (bool)message_send($eventdata); // returns message id or false
ac48e43a 1135}
1136
1137/**
bc68fc9a 1138 * Sends notification messages to the interested parties that assign the role capability
ac48e43a 1139 *
1140 * @param object $recipient user object of the intended recipient
0ff4bd08 1141 * @param object $a associative array of replaceable fields for the templates
ac48e43a 1142 *
d83bad41 1143 * @return bool
ac48e43a 1144 */
1145function quiz_send_notification($recipient, $a) {
1146
1147 global $USER;
1148
1149 // recipient info for template
1150 $a->username = fullname($recipient);
1151 $a->userusername = $recipient->username;
ac48e43a 1152
1153 // fetch the subject and body from strings
1154 $subject = get_string('emailnotifysubject', 'quiz', $a);
1155 $body = get_string('emailnotifybody', 'quiz', $a);
1156
1157 // send email and analyse result
39790bd8 1158 $eventdata = new stdClass();
bc68fc9a
AD
1159 $eventdata->component = 'mod_quiz';
1160 $eventdata->name = 'submission';
1161 $eventdata->notification = 1;
1162
3b120e46 1163 $eventdata->userfrom = $USER;
1164 $eventdata->userto = $recipient;
1165 $eventdata->subject = $subject;
1166 $eventdata->fullmessage = $body;
1167 $eventdata->fullmessageformat = FORMAT_PLAIN;
1168 $eventdata->fullmessagehtml = '';
bc68fc9a
AD
1169
1170 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1171 $eventdata->contexturl = $a->quizreviewurl;
1172 $eventdata->contexturlname = $a->quizname;
1173
d83bad41 1174 return (bool)message_send($eventdata);
ac48e43a 1175}
1176
1177/**
1178 * Takes a bunch of information to format into an email and send
1179 * to the specified recipient.
1180 *
1181 * @param object $course the course
1182 * @param object $quiz the quiz
1183 * @param object $attempt this attempt just finished
1184 * @param object $context the quiz context
1185 * @param object $cm the coursemodule for this quiz
1186 *
1187 * @return int number of emails sent
1188 */
1189function quiz_send_notification_emails($course, $quiz, $attempt, $context, $cm) {
1190 global $CFG, $USER;
1191 // we will count goods and bads for error logging
46505ee7 1192 $emailresult = array('good' => 0, 'fail' => 0);
ac48e43a 1193
1194 // do nothing if required objects not present
1195 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1196 debugging('quiz_send_notification_emails: Email(s) not sent due to program error.',
1197 DEBUG_DEVELOPER);
1198 return $emailresult['fail'];
1199 }
1200
1201 // check for confirmation required
1202 $sendconfirm = false;
1203 $notifyexcludeusers = '';
25a03faa 1204 if (has_capability('mod/quiz:emailconfirmsubmission', $context, null, false)) {
ac48e43a 1205 // exclude from notify emails later
1206 $notifyexcludeusers = $USER->id;
1207 // send the email
1208 $sendconfirm = true;
1209 }
1210
1211 // check for notifications required
25a03faa
TH
1212 $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.email, u.lang, ' .
1213 'u.timezone, u.mailformat, u.maildisplay';
5a128471 1214 $groups = groups_get_all_groups($course->id, $USER->id);
1215 if (is_array($groups) && count($groups) > 0) {
1216 $groups = array_keys($groups);
255985f1 1217 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1218 // If the user is not in a group, and the quiz is set to group mode,
1219 // then set $gropus to a non-existant id so that only users with
1220 // 'moodle/site:accessallgroups' get notified.
1221 $groups = -1;
5a128471 1222 } else {
1223 $groups = '';
1224 }
ac48e43a 1225 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
5a128471 1226 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
ac48e43a 1227
1228 // if something to send, then build $a
1229 if (! empty($userstonotify) or $sendconfirm) {
0ff4bd08 1230 $a = new stdClass();
ac48e43a 1231 // course info
1232 $a->coursename = $course->fullname;
1233 $a->courseshortname = $course->shortname;
1234 // quiz info
1235 $a->quizname = $quiz->name;
a49cb927 1236 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
25a03faa
TH
1237 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1238 format_string($quiz->name) . ' report</a>';
ac48e43a 1239 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
25a03faa
TH
1240 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1241 format_string($quiz->name) . ' review</a>';
a49cb927 1242 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
4f67bf8c 1243 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
ac48e43a 1244 // attempt info
b0972c05 1245 $a->submissiontime = userdate($attempt->timefinish);
1246 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
ac48e43a 1247 // student who sat the quiz info
1248 $a->studentidnumber = $USER->idnumber;
1249 $a->studentname = fullname($USER);
1250 $a->studentusername = $USER->username;
1251 }
1252
1253 // send confirmation if required
1254 if ($sendconfirm) {
1255 // send the email and update stats
1256 switch (quiz_send_confirmation($a)) {
1257 case true:
1258 $emailresult['good']++;
1259 break;
1260 case false:
1261 $emailresult['fail']++;
1262 break;
ac48e43a 1263 }
1264 }
1265
1266 // send notifications if required
1267 if (!empty($userstonotify)) {
1268 // loop through recipients and send an email to each and update stats
1269 foreach ($userstonotify as $recipient) {
1270 switch (quiz_send_notification($recipient, $a)) {
1271 case true:
1272 $emailresult['good']++;
1273 break;
1274 case false:
1275 $emailresult['fail']++;
1276 break;
ac48e43a 1277 }
1278 }
1279 }
1280
1281 // log errors sending emails if any
1282 if (! empty($emailresult['fail'])) {
25a03faa
TH
1283 debugging('quiz_send_notification_emails:: ' . $emailresult['fail'] .
1284 ' email(s) failed to be sent.', DEBUG_DEVELOPER);
ac48e43a 1285 }
ac48e43a 1286
1287 // return the number of successfully sent emails
1288 return $emailresult['good'];
1289}
fa583f5f 1290
7d4dfc48 1291/**
1292 * Checks if browser is safe browser
83192608 1293 *
7d4dfc48 1294 * @return true, if browser is safe browser else false
25302dee 1295 */
7d4dfc48 1296function quiz_check_safe_browser() {
1297 return strpos($_SERVER['HTTP_USER_AGENT'], "SEB") !== false;
1298}
ff065f96
TH
1299
1300function quiz_get_js_module() {
157434a5 1301 global $PAGE;
ff065f96
TH
1302 return array(
1303 'name' => 'mod_quiz',
1304 'fullpath' => '/mod/quiz/module.js',
25a03faa
TH
1305 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1306 'core_question_engine'),
ff065f96
TH
1307 'strings' => array(
1308 array('timesup', 'quiz'),
1309 array('functiondisabledbysecuremode', 'quiz'),
a26246ea 1310 array('flagged', 'question'),
ff065f96
TH
1311 ),
1312 );
fe6ce234 1313}
25302dee
TH
1314
1315
1316/**
1317 * An extension of question_display_options that includes the extra options used
1318 * by the quiz.
1319 *
f7970e3c
TH
1320 * @copyright 2010 The Open University
1321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee
TH
1322 */
1323class mod_quiz_display_options extends question_display_options {
1324 /**#@+
1325 * @var integer bits used to indicate various times in relation to a
1326 * quiz attempt.
1327 */
1328 const DURING = 0x10000;
1329 const IMMEDIATELY_AFTER = 0x01000;
1330 const LATER_WHILE_OPEN = 0x00100;
1331 const AFTER_CLOSE = 0x00010;
1332 /**#@-*/
1333
1334 /**
1335 * @var boolean if this is false, then the student is not allowed to review
1336 * anything about the attempt.
1337 */
1338 public $attempt = true;
1339
1340 /**
1341 * @var boolean if this is false, then the student is not allowed to review
1342 * anything about the attempt.
1343 */
1344 public $overallfeedback = self::VISIBLE;
1345
1346 /**
1347 * Set up the various options from the quiz settings, and a time constant.
0ff4bd08 1348 * @param object $quiz the quiz settings.
f7970e3c 1349 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
25302dee
TH
1350 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1351 * @return mod_quiz_display_options set up appropriately.
1352 */
1353 public static function make_from_quiz($quiz, $when) {
1354 $options = new self();
1355
1356 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1357 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
25a03faa
TH
1358 $options->marks = self::extract($quiz->reviewmarks, $when,
1359 self::MARK_AND_MAX, self::MAX_ONLY);
25302dee
TH
1360 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1361 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1362 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1363 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1364
1365 $options->numpartscorrect = $options->feedback;
1366
1367 if ($quiz->questiondecimalpoints != -1) {
1368 $options->markdp = $quiz->questiondecimalpoints;
1369 } else {
1370 $options->markdp = $quiz->decimalpoints;
1371 }
1372
1373 return $options;
1374 }
1375
25a03faa
TH
1376 protected static function extract($bitmask, $bit,
1377 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
25302dee
TH
1378 if ($bitmask & $bit) {
1379 return $whenset;
1380 } else {
1381 return $whennotset;
1382 }
1383 }
1384}
1385
1386
1387/**
1388 * A {@link qubaid_condition} for finding all the question usages belonging to
1389 * a particular quiz.
1390 *
f7970e3c
TH
1391 * @copyright 2010 The Open University
1392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee 1393 */
6b5f24d3 1394class qubaids_for_quiz extends qubaid_join {
25302dee 1395 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
6b5f24d3 1396 $where = 'quiza.quiz = :quizaquiz';
25302dee
TH
1397 if (!$includepreviews) {
1398 $where .= ' AND preview = 0';
1399 }
25302dee
TH
1400 if ($onlyfinished) {
1401 $where .= ' AND timefinish <> 0';
1402 }
1403
6b5f24d3
TH
1404 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where,
1405 array('quizaquiz' => $quizid));
25302dee
TH
1406 }
1407}