PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/mod/quiz/locallib.php

https://bitbucket.org/ngmares/moodle
PHP | 1565 lines | 893 code | 196 blank | 476 comment | 148 complexity | 6d3ac39731ff659fb268ea585ff2e3e4 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-3.0, Apache-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  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/>.
  16. /**
  17. * Library of functions used by the quiz module.
  18. *
  19. * This contains functions that are called from within the quiz module only
  20. * Functions that are also called by core Moodle are in {@link lib.php}
  21. * This script also loads the code in {@link questionlib.php} which holds
  22. * the module-indpendent code for handling questions and which in turn
  23. * initialises all the questiontype classes.
  24. *
  25. * @package mod
  26. * @subpackage quiz
  27. * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
  28. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  29. */
  30. defined('MOODLE_INTERNAL') || die();
  31. require_once($CFG->dirroot . '/mod/quiz/lib.php');
  32. require_once($CFG->dirroot . '/mod/quiz/accessmanager.php');
  33. require_once($CFG->dirroot . '/mod/quiz/accessmanager_form.php');
  34. require_once($CFG->dirroot . '/mod/quiz/renderer.php');
  35. require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
  36. require_once($CFG->dirroot . '/question/editlib.php');
  37. require_once($CFG->libdir . '/eventslib.php');
  38. require_once($CFG->libdir . '/filelib.php');
  39. /**
  40. * @var int We show the countdown timer if there is less than this amount of time left before the
  41. * the quiz close date. (1 hour)
  42. */
  43. define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
  44. /**
  45. * @var int If there are fewer than this many seconds left when the student submits
  46. * a page of the quiz, then do not take them to the next page of the quiz. Instead
  47. * close the quiz immediately.
  48. */
  49. define('QUIZ_MIN_TIME_TO_CONTINUE', '2');
  50. // Functions related to attempts ///////////////////////////////////////////////
  51. /**
  52. * Creates an object to represent a new attempt at a quiz
  53. *
  54. * Creates an attempt object to represent an attempt at the quiz by the current
  55. * user starting at the current time. The ->id field is not set. The object is
  56. * NOT written to the database.
  57. *
  58. * @param object $quiz the quiz to create an attempt for.
  59. * @param int $attemptnumber the sequence number for the attempt.
  60. * @param object $lastattempt the previous attempt by this user, if any. Only needed
  61. * if $attemptnumber > 1 and $quiz->attemptonlast is true.
  62. * @param int $timenow the time the attempt was started at.
  63. * @param bool $ispreview whether this new attempt is a preview.
  64. *
  65. * @return object the newly created attempt object.
  66. */
  67. function quiz_create_attempt($quiz, $attemptnumber, $lastattempt, $timenow, $ispreview = false) {
  68. global $USER;
  69. if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
  70. throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
  71. new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id)),
  72. array('grade' => quiz_format_grade($quiz, $quiz->grade)));
  73. }
  74. if ($attemptnumber == 1 || !$quiz->attemptonlast) {
  75. // We are not building on last attempt so create a new attempt.
  76. $attempt = new stdClass();
  77. $attempt->quiz = $quiz->id;
  78. $attempt->userid = $USER->id;
  79. $attempt->preview = 0;
  80. $attempt->layout = quiz_clean_layout($quiz->questions, true);
  81. if ($quiz->shufflequestions) {
  82. $attempt->layout = quiz_repaginate($attempt->layout, $quiz->questionsperpage, true);
  83. }
  84. } else {
  85. // Build on last attempt.
  86. if (empty($lastattempt)) {
  87. print_error('cannotfindprevattempt', 'quiz');
  88. }
  89. $attempt = $lastattempt;
  90. }
  91. $attempt->attempt = $attemptnumber;
  92. $attempt->timestart = $timenow;
  93. $attempt->timefinish = 0;
  94. $attempt->timemodified = $timenow;
  95. $attempt->state = quiz_attempt::IN_PROGRESS;
  96. // If this is a preview, mark it as such.
  97. if ($ispreview) {
  98. $attempt->preview = 1;
  99. }
  100. return $attempt;
  101. }
  102. /**
  103. * Returns an unfinished attempt (if there is one) for the given
  104. * user on the given quiz. This function does not return preview attempts.
  105. *
  106. * @param int $quizid the id of the quiz.
  107. * @param int $userid the id of the user.
  108. *
  109. * @return mixed the unfinished attempt if there is one, false if not.
  110. */
  111. function quiz_get_user_attempt_unfinished($quizid, $userid) {
  112. $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
  113. if ($attempts) {
  114. return array_shift($attempts);
  115. } else {
  116. return false;
  117. }
  118. }
  119. /**
  120. * Delete a quiz attempt.
  121. * @param mixed $attempt an integer attempt id or an attempt object
  122. * (row of the quiz_attempts table).
  123. * @param object $quiz the quiz object.
  124. */
  125. function quiz_delete_attempt($attempt, $quiz) {
  126. global $DB;
  127. if (is_numeric($attempt)) {
  128. if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
  129. return;
  130. }
  131. }
  132. if ($attempt->quiz != $quiz->id) {
  133. debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
  134. "but was passed quiz $quiz->id.");
  135. return;
  136. }
  137. question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
  138. $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
  139. // Search quiz_attempts for other instances by this user.
  140. // If none, then delete record for this quiz, this user from quiz_grades
  141. // else recalculate best grade.
  142. $userid = $attempt->userid;
  143. if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
  144. $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
  145. } else {
  146. quiz_save_best_grade($quiz, $userid);
  147. }
  148. quiz_update_grades($quiz, $userid);
  149. }
  150. /**
  151. * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
  152. * to one user.
  153. * @param object $quiz the quiz object.
  154. * @param int $userid (optional) if given, only delete the previews belonging to this user.
  155. */
  156. function quiz_delete_previews($quiz, $userid = null) {
  157. global $DB;
  158. $conditions = array('quiz' => $quiz->id, 'preview' => 1);
  159. if (!empty($userid)) {
  160. $conditions['userid'] = $userid;
  161. }
  162. $previewattempts = $DB->get_records('quiz_attempts', $conditions);
  163. foreach ($previewattempts as $attempt) {
  164. quiz_delete_attempt($attempt, $quiz);
  165. }
  166. }
  167. /**
  168. * @param int $quizid The quiz id.
  169. * @return bool whether this quiz has any (non-preview) attempts.
  170. */
  171. function quiz_has_attempts($quizid) {
  172. global $DB;
  173. return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
  174. }
  175. // Functions to do with quiz layout and pages //////////////////////////////////
  176. /**
  177. * Returns a comma separated list of question ids for the quiz
  178. *
  179. * @param string $layout The string representing the quiz layout. Each page is
  180. * represented as a comma separated list of question ids and 0 indicating
  181. * page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
  182. * 3 on page 2
  183. * @return string comma separated list of question ids, without page breaks.
  184. */
  185. function quiz_questions_in_quiz($layout) {
  186. $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
  187. if ($questions === '0') {
  188. return '';
  189. } else {
  190. return $questions;
  191. }
  192. }
  193. /**
  194. * Returns the number of pages in a quiz layout
  195. *
  196. * @param string $layout The string representing the quiz layout. Always ends in ,0
  197. * @return int The number of pages in the quiz.
  198. */
  199. function quiz_number_of_pages($layout) {
  200. return substr_count(',' . $layout, ',0');
  201. }
  202. /**
  203. * Returns the number of questions in the quiz layout
  204. *
  205. * @param string $layout the string representing the quiz layout.
  206. * @return int The number of questions in the quiz.
  207. */
  208. function quiz_number_of_questions_in_quiz($layout) {
  209. $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
  210. $count = substr_count($layout, ',');
  211. if ($layout !== '') {
  212. $count++;
  213. }
  214. return $count;
  215. }
  216. /**
  217. * Re-paginates the quiz layout
  218. *
  219. * @param string $layout The string representing the quiz layout. If there is
  220. * if there is any doubt about the quality of the input data, call
  221. * quiz_clean_layout before you call this function.
  222. * @param int $perpage The number of questions per page
  223. * @param bool $shuffle Should the questions be reordered randomly?
  224. * @return string the new layout string
  225. */
  226. function quiz_repaginate($layout, $perpage, $shuffle = false) {
  227. $questions = quiz_questions_in_quiz($layout);
  228. if (!$questions) {
  229. return '0';
  230. }
  231. $questions = explode(',', quiz_questions_in_quiz($layout));
  232. if ($shuffle) {
  233. shuffle($questions);
  234. }
  235. $onthispage = 0;
  236. $layout = array();
  237. foreach ($questions as $question) {
  238. if ($perpage and $onthispage >= $perpage) {
  239. $layout[] = 0;
  240. $onthispage = 0;
  241. }
  242. $layout[] = $question;
  243. $onthispage += 1;
  244. }
  245. $layout[] = 0;
  246. return implode(',', $layout);
  247. }
  248. // Functions to do with quiz grades ////////////////////////////////////////////
  249. /**
  250. * Creates an array of maximum grades for a quiz
  251. *
  252. * The grades are extracted from the quiz_question_instances table.
  253. * @param object $quiz The quiz settings.
  254. * @return array of grades indexed by question id. These are the maximum
  255. * possible grades that students can achieve for each of the questions.
  256. */
  257. function quiz_get_all_question_grades($quiz) {
  258. global $CFG, $DB;
  259. $questionlist = quiz_questions_in_quiz($quiz->questions);
  260. if (empty($questionlist)) {
  261. return array();
  262. }
  263. $params = array($quiz->id);
  264. $wheresql = '';
  265. if (!is_null($questionlist)) {
  266. list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
  267. $wheresql = " AND question $usql ";
  268. $params = array_merge($params, $question_params);
  269. }
  270. $instances = $DB->get_records_sql("SELECT question, grade, id
  271. FROM {quiz_question_instances}
  272. WHERE quiz = ? $wheresql", $params);
  273. $list = explode(",", $questionlist);
  274. $grades = array();
  275. foreach ($list as $qid) {
  276. if (isset($instances[$qid])) {
  277. $grades[$qid] = $instances[$qid]->grade;
  278. } else {
  279. $grades[$qid] = 1;
  280. }
  281. }
  282. return $grades;
  283. }
  284. /**
  285. * Convert the raw grade stored in $attempt into a grade out of the maximum
  286. * grade for this quiz.
  287. *
  288. * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
  289. * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
  290. * @param bool|string $format whether to format the results for display
  291. * or 'question' to format a question grade (different number of decimal places.
  292. * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
  293. * if the $grade is null.
  294. */
  295. function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
  296. if (is_null($rawgrade)) {
  297. $grade = null;
  298. } else if ($quiz->sumgrades >= 0.000005) {
  299. $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
  300. } else {
  301. $grade = 0;
  302. }
  303. if ($format === 'question') {
  304. $grade = quiz_format_question_grade($quiz, $grade);
  305. } else if ($format) {
  306. $grade = quiz_format_grade($quiz, $grade);
  307. }
  308. return $grade;
  309. }
  310. /**
  311. * Get the feedback text that should be show to a student who
  312. * got this grade on this quiz. The feedback is processed ready for diplay.
  313. *
  314. * @param float $grade a grade on this quiz.
  315. * @param object $quiz the quiz settings.
  316. * @param object $context the quiz context.
  317. * @return string the comment that corresponds to this grade (empty string if there is not one.
  318. */
  319. function quiz_feedback_for_grade($grade, $quiz, $context) {
  320. global $DB;
  321. if (is_null($grade)) {
  322. return '';
  323. }
  324. // With CBM etc, it is possible to get -ve grades, which would then not match
  325. // any feedback. Therefore, we replace -ve grades with 0.
  326. $grade = max($grade, 0);
  327. $feedback = $DB->get_record_select('quiz_feedback',
  328. 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
  329. if (empty($feedback->feedbacktext)) {
  330. return '';
  331. }
  332. // Clean the text, ready for display.
  333. $formatoptions = new stdClass();
  334. $formatoptions->noclean = true;
  335. $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
  336. $context->id, 'mod_quiz', 'feedback', $feedback->id);
  337. $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
  338. return $feedbacktext;
  339. }
  340. /**
  341. * @param object $quiz the quiz database row.
  342. * @return bool Whether this quiz has any non-blank feedback text.
  343. */
  344. function quiz_has_feedback($quiz) {
  345. global $DB;
  346. static $cache = array();
  347. if (!array_key_exists($quiz->id, $cache)) {
  348. $cache[$quiz->id] = quiz_has_grades($quiz) &&
  349. $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
  350. $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
  351. array($quiz->id));
  352. }
  353. return $cache[$quiz->id];
  354. }
  355. /**
  356. * Update the sumgrades field of the quiz. This needs to be called whenever
  357. * the grading structure of the quiz is changed. For example if a question is
  358. * added or removed, or a question weight is changed.
  359. *
  360. * You should call {@link quiz_delete_previews()} before you call this function.
  361. *
  362. * @param object $quiz a quiz.
  363. */
  364. function quiz_update_sumgrades($quiz) {
  365. global $DB;
  366. $sql = 'UPDATE {quiz}
  367. SET sumgrades = COALESCE((
  368. SELECT SUM(grade)
  369. FROM {quiz_question_instances}
  370. WHERE quiz = {quiz}.id
  371. ), 0)
  372. WHERE id = ?';
  373. $DB->execute($sql, array($quiz->id));
  374. $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
  375. if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
  376. // If the quiz has been attempted, and the sumgrades has been
  377. // set to 0, then we must also set the maximum possible grade to 0, or
  378. // we will get a divide by zero error.
  379. quiz_set_grade(0, $quiz);
  380. }
  381. }
  382. /**
  383. * Update the sumgrades field of the attempts at a quiz.
  384. *
  385. * @param object $quiz a quiz.
  386. */
  387. function quiz_update_all_attempt_sumgrades($quiz) {
  388. global $DB;
  389. $dm = new question_engine_data_mapper();
  390. $timenow = time();
  391. $sql = "UPDATE {quiz_attempts}
  392. SET
  393. timemodified = :timenow,
  394. sumgrades = (
  395. {$dm->sum_usage_marks_subquery('uniqueid')}
  396. )
  397. WHERE quiz = :quizid AND state = :finishedstate";
  398. $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
  399. 'finishedstate' => quiz_attempt::FINISHED));
  400. }
  401. /**
  402. * The quiz grade is the maximum that student's results are marked out of. When it
  403. * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
  404. * rescaled. After calling this function, you probably need to call
  405. * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
  406. * quiz_update_grades.
  407. *
  408. * @param float $newgrade the new maximum grade for the quiz.
  409. * @param object $quiz the quiz we are updating. Passed by reference so its
  410. * grade field can be updated too.
  411. * @return bool indicating success or failure.
  412. */
  413. function quiz_set_grade($newgrade, $quiz) {
  414. global $DB;
  415. // This is potentially expensive, so only do it if necessary.
  416. if (abs($quiz->grade - $newgrade) < 1e-7) {
  417. // Nothing to do.
  418. return true;
  419. }
  420. $oldgrade = $quiz->grade;
  421. $quiz->grade = $newgrade;
  422. // Use a transaction, so that on those databases that support it, this is safer.
  423. $transaction = $DB->start_delegated_transaction();
  424. // Update the quiz table.
  425. $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
  426. if ($oldgrade < 1) {
  427. // If the old grade was zero, we cannot rescale, we have to recompute.
  428. // We also recompute if the old grade was too small to avoid underflow problems.
  429. quiz_update_all_final_grades($quiz);
  430. } else {
  431. // We can rescale the grades efficiently.
  432. $timemodified = time();
  433. $DB->execute("
  434. UPDATE {quiz_grades}
  435. SET grade = ? * grade, timemodified = ?
  436. WHERE quiz = ?
  437. ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
  438. }
  439. if ($oldgrade > 1e-7) {
  440. // Update the quiz_feedback table.
  441. $factor = $newgrade/$oldgrade;
  442. $DB->execute("
  443. UPDATE {quiz_feedback}
  444. SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
  445. WHERE quizid = ?
  446. ", array($factor, $factor, $quiz->id));
  447. }
  448. // Update grade item and send all grades to gradebook.
  449. quiz_grade_item_update($quiz);
  450. quiz_update_grades($quiz);
  451. $transaction->allow_commit();
  452. return true;
  453. }
  454. /**
  455. * Save the overall grade for a user at a quiz in the quiz_grades table
  456. *
  457. * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
  458. * @param int $userid The userid to calculate the grade for. Defaults to the current user.
  459. * @param array $attempts The attempts of this user. Useful if you are
  460. * looping through many users. Attempts can be fetched in one master query to
  461. * avoid repeated querying.
  462. * @return bool Indicates success or failure.
  463. */
  464. function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
  465. global $DB, $OUTPUT, $USER;
  466. if (empty($userid)) {
  467. $userid = $USER->id;
  468. }
  469. if (!$attempts) {
  470. // Get all the attempts made by the user.
  471. $attempts = quiz_get_user_attempts($quiz->id, $userid);
  472. }
  473. // Calculate the best grade.
  474. $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
  475. $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
  476. // Save the best grade in the database.
  477. if (is_null($bestgrade)) {
  478. $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
  479. } else if ($grade = $DB->get_record('quiz_grades',
  480. array('quiz' => $quiz->id, 'userid' => $userid))) {
  481. $grade->grade = $bestgrade;
  482. $grade->timemodified = time();
  483. $DB->update_record('quiz_grades', $grade);
  484. } else {
  485. $grade = new stdClass();
  486. $grade->quiz = $quiz->id;
  487. $grade->userid = $userid;
  488. $grade->grade = $bestgrade;
  489. $grade->timemodified = time();
  490. $DB->insert_record('quiz_grades', $grade);
  491. }
  492. quiz_update_grades($quiz, $userid);
  493. }
  494. /**
  495. * Calculate the overall grade for a quiz given a number of attempts by a particular user.
  496. *
  497. * @param object $quiz the quiz settings object.
  498. * @param array $attempts an array of all the user's attempts at this quiz in order.
  499. * @return float the overall grade
  500. */
  501. function quiz_calculate_best_grade($quiz, $attempts) {
  502. switch ($quiz->grademethod) {
  503. case QUIZ_ATTEMPTFIRST:
  504. $firstattempt = reset($attempts);
  505. return $firstattempt->sumgrades;
  506. case QUIZ_ATTEMPTLAST:
  507. $lastattempt = end($attempts);
  508. return $lastattempt->sumgrades;
  509. case QUIZ_GRADEAVERAGE:
  510. $sum = 0;
  511. $count = 0;
  512. foreach ($attempts as $attempt) {
  513. if (!is_null($attempt->sumgrades)) {
  514. $sum += $attempt->sumgrades;
  515. $count++;
  516. }
  517. }
  518. if ($count == 0) {
  519. return null;
  520. }
  521. return $sum / $count;
  522. case QUIZ_GRADEHIGHEST:
  523. default:
  524. $max = null;
  525. foreach ($attempts as $attempt) {
  526. if ($attempt->sumgrades > $max) {
  527. $max = $attempt->sumgrades;
  528. }
  529. }
  530. return $max;
  531. }
  532. }
  533. /**
  534. * Update the final grade at this quiz for all students.
  535. *
  536. * This function is equivalent to calling quiz_save_best_grade for all
  537. * users, but much more efficient.
  538. *
  539. * @param object $quiz the quiz settings.
  540. */
  541. function quiz_update_all_final_grades($quiz) {
  542. global $DB;
  543. if (!$quiz->sumgrades) {
  544. return;
  545. }
  546. $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
  547. $firstlastattemptjoin = "JOIN (
  548. SELECT
  549. iquiza.userid,
  550. MIN(attempt) AS firstattempt,
  551. MAX(attempt) AS lastattempt
  552. FROM {quiz_attempts} iquiza
  553. WHERE
  554. iquiza.state = :istatefinished AND
  555. iquiza.preview = 0 AND
  556. iquiza.quiz = :iquizid
  557. GROUP BY iquiza.userid
  558. ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
  559. switch ($quiz->grademethod) {
  560. case QUIZ_ATTEMPTFIRST:
  561. // Because of the where clause, there will only be one row, but we
  562. // must still use an aggregate function.
  563. $select = 'MAX(quiza.sumgrades)';
  564. $join = $firstlastattemptjoin;
  565. $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
  566. break;
  567. case QUIZ_ATTEMPTLAST:
  568. // Because of the where clause, there will only be one row, but we
  569. // must still use an aggregate function.
  570. $select = 'MAX(quiza.sumgrades)';
  571. $join = $firstlastattemptjoin;
  572. $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
  573. break;
  574. case QUIZ_GRADEAVERAGE:
  575. $select = 'AVG(quiza.sumgrades)';
  576. $join = '';
  577. $where = '';
  578. break;
  579. default:
  580. case QUIZ_GRADEHIGHEST:
  581. $select = 'MAX(quiza.sumgrades)';
  582. $join = '';
  583. $where = '';
  584. break;
  585. }
  586. if ($quiz->sumgrades >= 0.000005) {
  587. $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
  588. } else {
  589. $finalgrade = '0';
  590. }
  591. $param['quizid'] = $quiz->id;
  592. $param['quizid2'] = $quiz->id;
  593. $param['quizid3'] = $quiz->id;
  594. $param['quizid4'] = $quiz->id;
  595. $param['statefinished'] = quiz_attempt::FINISHED;
  596. $param['statefinished2'] = quiz_attempt::FINISHED;
  597. $finalgradesubquery = "
  598. SELECT quiza.userid, $finalgrade AS newgrade
  599. FROM {quiz_attempts} quiza
  600. $join
  601. WHERE
  602. $where
  603. quiza.state = :statefinished AND
  604. quiza.preview = 0 AND
  605. quiza.quiz = :quizid3
  606. GROUP BY quiza.userid";
  607. $changedgrades = $DB->get_records_sql("
  608. SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
  609. FROM (
  610. SELECT userid
  611. FROM {quiz_grades} qg
  612. WHERE quiz = :quizid
  613. UNION
  614. SELECT DISTINCT userid
  615. FROM {quiz_attempts} quiza2
  616. WHERE
  617. quiza2.state = :statefinished2 AND
  618. quiza2.preview = 0 AND
  619. quiza2.quiz = :quizid2
  620. ) users
  621. LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
  622. LEFT JOIN (
  623. $finalgradesubquery
  624. ) newgrades ON newgrades.userid = users.userid
  625. WHERE
  626. ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
  627. ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
  628. (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
  629. // The mess on the previous line is detecting where the value is
  630. // NULL in one column, and NOT NULL in the other, but SQL does
  631. // not have an XOR operator, and MS SQL server can't cope with
  632. // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
  633. $param);
  634. $timenow = time();
  635. $todelete = array();
  636. foreach ($changedgrades as $changedgrade) {
  637. if (is_null($changedgrade->newgrade)) {
  638. $todelete[] = $changedgrade->userid;
  639. } else if (is_null($changedgrade->grade)) {
  640. $toinsert = new stdClass();
  641. $toinsert->quiz = $quiz->id;
  642. $toinsert->userid = $changedgrade->userid;
  643. $toinsert->timemodified = $timenow;
  644. $toinsert->grade = $changedgrade->newgrade;
  645. $DB->insert_record('quiz_grades', $toinsert);
  646. } else {
  647. $toupdate = new stdClass();
  648. $toupdate->id = $changedgrade->id;
  649. $toupdate->grade = $changedgrade->newgrade;
  650. $toupdate->timemodified = $timenow;
  651. $DB->update_record('quiz_grades', $toupdate);
  652. }
  653. }
  654. if (!empty($todelete)) {
  655. list($test, $params) = $DB->get_in_or_equal($todelete);
  656. $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
  657. array_merge(array($quiz->id), $params));
  658. }
  659. }
  660. /**
  661. * Return the attempt with the best grade for a quiz
  662. *
  663. * Which attempt is the best depends on $quiz->grademethod. If the grade
  664. * method is GRADEAVERAGE then this function simply returns the last attempt.
  665. * @return object The attempt with the best grade
  666. * @param object $quiz The quiz for which the best grade is to be calculated
  667. * @param array $attempts An array of all the attempts of the user at the quiz
  668. */
  669. function quiz_calculate_best_attempt($quiz, $attempts) {
  670. switch ($quiz->grademethod) {
  671. case QUIZ_ATTEMPTFIRST:
  672. foreach ($attempts as $attempt) {
  673. return $attempt;
  674. }
  675. break;
  676. case QUIZ_GRADEAVERAGE: // We need to do something with it.
  677. case QUIZ_ATTEMPTLAST:
  678. foreach ($attempts as $attempt) {
  679. $final = $attempt;
  680. }
  681. return $final;
  682. default:
  683. case QUIZ_GRADEHIGHEST:
  684. $max = -1;
  685. foreach ($attempts as $attempt) {
  686. if ($attempt->sumgrades > $max) {
  687. $max = $attempt->sumgrades;
  688. $maxattempt = $attempt;
  689. }
  690. }
  691. return $maxattempt;
  692. }
  693. }
  694. /**
  695. * @return array int => lang string the options for calculating the quiz grade
  696. * from the individual attempt grades.
  697. */
  698. function quiz_get_grading_options() {
  699. return array(
  700. QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
  701. QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
  702. QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
  703. QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
  704. );
  705. }
  706. /**
  707. * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
  708. * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
  709. * @return the lang string for that option.
  710. */
  711. function quiz_get_grading_option_name($option) {
  712. $strings = quiz_get_grading_options();
  713. return $strings[$option];
  714. }
  715. /**
  716. * @return array string => lang string the options for handling overdue quiz
  717. * attempts.
  718. */
  719. function quiz_get_overdue_handling_options() {
  720. return array(
  721. 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
  722. 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
  723. 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
  724. );
  725. }
  726. /**
  727. * @param string $state one of the state constants like IN_PROGRESS.
  728. * @return string the human-readable state name.
  729. */
  730. function quiz_attempt_state_name($state) {
  731. switch ($state) {
  732. case quiz_attempt::IN_PROGRESS:
  733. return get_string('stateinprogress', 'quiz');
  734. case quiz_attempt::OVERDUE:
  735. return get_string('stateoverdue', 'quiz');
  736. case quiz_attempt::FINISHED:
  737. return get_string('statefinished', 'quiz');
  738. case quiz_attempt::ABANDONED:
  739. return get_string('stateabandoned', 'quiz');
  740. default:
  741. throw new coding_exception('Unknown quiz attempt state.');
  742. }
  743. }
  744. // Other quiz functions ////////////////////////////////////////////////////////
  745. /**
  746. * @param object $quiz the quiz.
  747. * @param int $cmid the course_module object for this quiz.
  748. * @param object $question the question.
  749. * @param string $returnurl url to return to after action is done.
  750. * @return string html for a number of icons linked to action pages for a
  751. * question - preview and edit / view icons depending on user capabilities.
  752. */
  753. function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
  754. $html = quiz_question_preview_button($quiz, $question) . ' ' .
  755. quiz_question_edit_button($cmid, $question, $returnurl);
  756. return $html;
  757. }
  758. /**
  759. * @param int $cmid the course_module.id for this quiz.
  760. * @param object $question the question.
  761. * @param string $returnurl url to return to after action is done.
  762. * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
  763. * @return the HTML for an edit icon, view icon, or nothing for a question
  764. * (depending on permissions).
  765. */
  766. function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
  767. global $CFG, $OUTPUT;
  768. // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
  769. static $stredit = null;
  770. static $strview = null;
  771. if ($stredit === null) {
  772. $stredit = get_string('edit');
  773. $strview = get_string('view');
  774. }
  775. // What sort of icon should we show?
  776. $action = '';
  777. if (!empty($question->id) &&
  778. (question_has_capability_on($question, 'edit', $question->category) ||
  779. question_has_capability_on($question, 'move', $question->category))) {
  780. $action = $stredit;
  781. $icon = '/t/edit';
  782. } else if (!empty($question->id) &&
  783. question_has_capability_on($question, 'view', $question->category)) {
  784. $action = $strview;
  785. $icon = '/i/info';
  786. }
  787. // Build the icon.
  788. if ($action) {
  789. if ($returnurl instanceof moodle_url) {
  790. $returnurl = $returnurl->out_as_local_url(false);
  791. }
  792. $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
  793. $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
  794. return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
  795. $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
  796. '</a>';
  797. } else if ($contentaftericon) {
  798. return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
  799. } else {
  800. return '';
  801. }
  802. }
  803. /**
  804. * @param object $quiz the quiz settings
  805. * @param object $question the question
  806. * @return moodle_url to preview this question with the options from this quiz.
  807. */
  808. function quiz_question_preview_url($quiz, $question) {
  809. // Get the appropriate display options.
  810. $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
  811. mod_quiz_display_options::DURING);
  812. $maxmark = null;
  813. if (isset($question->maxmark)) {
  814. $maxmark = $question->maxmark;
  815. }
  816. // Work out the correcte preview URL.
  817. return question_preview_url($question->id, $quiz->preferredbehaviour,
  818. $maxmark, $displayoptions);
  819. }
  820. /**
  821. * @param object $quiz the quiz settings
  822. * @param object $question the question
  823. * @param bool $label if true, show the preview question label after the icon
  824. * @return the HTML for a preview question icon.
  825. */
  826. function quiz_question_preview_button($quiz, $question, $label = false) {
  827. global $CFG, $OUTPUT;
  828. if (!question_has_capability_on($question, 'use', $question->category)) {
  829. return '';
  830. }
  831. $url = quiz_question_preview_url($quiz, $question);
  832. // Do we want a label?
  833. $strpreviewlabel = '';
  834. if ($label) {
  835. $strpreviewlabel = get_string('preview', 'quiz');
  836. }
  837. // Build the icon.
  838. $strpreviewquestion = get_string('previewquestion', 'quiz');
  839. $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
  840. $action = new popup_action('click', $url, 'questionpreview',
  841. question_preview_popup_params());
  842. return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
  843. }
  844. /**
  845. * @param object $attempt the attempt.
  846. * @param object $context the quiz context.
  847. * @return int whether flags should be shown/editable to the current user for this attempt.
  848. */
  849. function quiz_get_flag_option($attempt, $context) {
  850. global $USER;
  851. if (!has_capability('moodle/question:flag', $context)) {
  852. return question_display_options::HIDDEN;
  853. } else if ($attempt->userid == $USER->id) {
  854. return question_display_options::EDITABLE;
  855. } else {
  856. return question_display_options::VISIBLE;
  857. }
  858. }
  859. /**
  860. * Work out what state this quiz attempt is in - in the sense used by
  861. * quiz_get_review_options, not in the sense of $attempt->state.
  862. * @param object $quiz the quiz settings
  863. * @param object $attempt the quiz_attempt database row.
  864. * @return int one of the mod_quiz_display_options::DURING,
  865. * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
  866. */
  867. function quiz_attempt_state($quiz, $attempt) {
  868. if ($attempt->state != quiz_attempt::FINISHED) {
  869. return mod_quiz_display_options::DURING;
  870. } else if (time() < $attempt->timefinish + 120) {
  871. return mod_quiz_display_options::IMMEDIATELY_AFTER;
  872. } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
  873. return mod_quiz_display_options::LATER_WHILE_OPEN;
  874. } else {
  875. return mod_quiz_display_options::AFTER_CLOSE;
  876. }
  877. }
  878. /**
  879. * The the appropraite mod_quiz_display_options object for this attempt at this
  880. * quiz right now.
  881. *
  882. * @param object $quiz the quiz instance.
  883. * @param object $attempt the attempt in question.
  884. * @param $context the quiz context.
  885. *
  886. * @return mod_quiz_display_options
  887. */
  888. function quiz_get_review_options($quiz, $attempt, $context) {
  889. $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
  890. $options->readonly = true;
  891. $options->flags = quiz_get_flag_option($attempt, $context);
  892. if (!empty($attempt->id)) {
  893. $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
  894. array('attempt' => $attempt->id));
  895. }
  896. // Show a link to the comment box only for closed attempts.
  897. if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
  898. !is_null($context) && has_capability('mod/quiz:grade', $context)) {
  899. $options->manualcomment = question_display_options::VISIBLE;
  900. $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
  901. array('attempt' => $attempt->id));
  902. }
  903. if (!is_null($context) && !$attempt->preview &&
  904. has_capability('mod/quiz:viewreports', $context) &&
  905. has_capability('moodle/grade:viewhidden', $context)) {
  906. // People who can see reports and hidden grades should be shown everything,
  907. // except during preview when teachers want to see what students see.
  908. $options->attempt = question_display_options::VISIBLE;
  909. $options->correctness = question_display_options::VISIBLE;
  910. $options->marks = question_display_options::MARK_AND_MAX;
  911. $options->feedback = question_display_options::VISIBLE;
  912. $options->numpartscorrect = question_display_options::VISIBLE;
  913. $options->generalfeedback = question_display_options::VISIBLE;
  914. $options->rightanswer = question_display_options::VISIBLE;
  915. $options->overallfeedback = question_display_options::VISIBLE;
  916. $options->history = question_display_options::VISIBLE;
  917. }
  918. return $options;
  919. }
  920. /**
  921. * Combines the review options from a number of different quiz attempts.
  922. * Returns an array of two ojects, so the suggested way of calling this
  923. * funciton is:
  924. * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
  925. *
  926. * @param object $quiz the quiz instance.
  927. * @param array $attempts an array of attempt objects.
  928. * @param $context the roles and permissions context,
  929. * normally the context for the quiz module instance.
  930. *
  931. * @return array of two options objects, one showing which options are true for
  932. * at least one of the attempts, the other showing which options are true
  933. * for all attempts.
  934. */
  935. function quiz_get_combined_reviewoptions($quiz, $attempts) {
  936. $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
  937. $someoptions = new stdClass();
  938. $alloptions = new stdClass();
  939. foreach ($fields as $field) {
  940. $someoptions->$field = false;
  941. $alloptions->$field = true;
  942. }
  943. $someoptions->marks = question_display_options::HIDDEN;
  944. $alloptions->marks = question_display_options::MARK_AND_MAX;
  945. foreach ($attempts as $attempt) {
  946. $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
  947. quiz_attempt_state($quiz, $attempt));
  948. foreach ($fields as $field) {
  949. $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
  950. $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
  951. }
  952. $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
  953. $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
  954. }
  955. return array($someoptions, $alloptions);
  956. }
  957. /**
  958. * Clean the question layout from various possible anomalies:
  959. * - Remove consecutive ","'s
  960. * - Remove duplicate question id's
  961. * - Remove extra "," from beginning and end
  962. * - Finally, add a ",0" in the end if there is none
  963. *
  964. * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
  965. * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
  966. * @return $string the cleaned-up layout
  967. */
  968. function quiz_clean_layout($layout, $removeemptypages = false) {
  969. // Remove repeated ','s. This can happen when a restore fails to find the right
  970. // id to relink to.
  971. $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
  972. // Remove duplicate question ids.
  973. $layout = explode(',', $layout);
  974. $cleanerlayout = array();
  975. $seen = array();
  976. foreach ($layout as $item) {
  977. if ($item == 0) {
  978. $cleanerlayout[] = '0';
  979. } else if (!in_array($item, $seen)) {
  980. $cleanerlayout[] = $item;
  981. $seen[] = $item;
  982. }
  983. }
  984. if ($removeemptypages) {
  985. // Avoid duplicate page breaks.
  986. $layout = $cleanerlayout;
  987. $cleanerlayout = array();
  988. $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
  989. foreach ($layout as $item) {
  990. if ($stripfollowingbreaks && $item == 0) {
  991. continue;
  992. }
  993. $cleanerlayout[] = $item;
  994. $stripfollowingbreaks = $item == 0;
  995. }
  996. }
  997. // Add a page break at the end if there is none.
  998. if (end($cleanerlayout) !== '0') {
  999. $cleanerlayout[] = '0';
  1000. }
  1001. return implode(',', $cleanerlayout);
  1002. }
  1003. /**
  1004. * Get the slot for a question with a particular id.
  1005. * @param object $quiz the quiz settings.
  1006. * @param int $questionid the of a question in the quiz.
  1007. * @return int the corresponding slot. Null if the question is not in the quiz.
  1008. */
  1009. function quiz_get_slot_for_question($quiz, $questionid) {
  1010. $questionids = quiz_questions_in_quiz($quiz->questions);
  1011. foreach (explode(',', $questionids) as $key => $id) {
  1012. if ($id == $questionid) {
  1013. return $key + 1;
  1014. }
  1015. }
  1016. return null;
  1017. }
  1018. // Functions for sending notification messages /////////////////////////////////
  1019. /**
  1020. * Sends a confirmation message to the student confirming that the attempt was processed.
  1021. *
  1022. * @param object $a lots of useful information that can be used in the message
  1023. * subject and body.
  1024. *
  1025. * @return int|false as for {@link message_send()}.
  1026. */
  1027. function quiz_send_confirmation($recipient, $a) {
  1028. // Add information about the recipient to $a.
  1029. // Don't do idnumber. we want idnumber to be the submitter's idnumber.
  1030. $a->username = fullname($recipient);
  1031. $a->userusername = $recipient->username;
  1032. // Prepare the message.
  1033. $eventdata = new stdClass();
  1034. $eventdata->component = 'mod_quiz';
  1035. $eventdata->name = 'confirmation';
  1036. $eventdata->notification = 1;
  1037. $eventdata->userfrom = get_admin();
  1038. $eventdata->userto = $recipient;
  1039. $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
  1040. $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
  1041. $eventdata->fullmessageformat = FORMAT_PLAIN;
  1042. $eventdata->fullmessagehtml = '';
  1043. $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
  1044. $eventdata->contexturl = $a->quizurl;
  1045. $eventdata->contexturlname = $a->quizname;
  1046. // ... and send it.
  1047. return message_send($eventdata);
  1048. }
  1049. /**
  1050. * Sends notification messages to the interested parties that assign the role capability
  1051. *
  1052. * @param object $recipient user object of the intended recipient
  1053. * @param object $a associative array of replaceable fields for the templates
  1054. *
  1055. * @return int|false as for {@link message_send()}.
  1056. */
  1057. function quiz_send_notification($recipient, $submitter, $a) {
  1058. // Recipient info for template.
  1059. $a->useridnumber = $recipient->idnumber;
  1060. $a->username = fullname($recipient);
  1061. $a->userusername = $recipient->username;
  1062. // Prepare the message.
  1063. $eventdata = new stdClass();
  1064. $eventdata->component = 'mod_quiz';
  1065. $eventdata->name = 'submission';
  1066. $eventdata->notification = 1;
  1067. $eventdata->userfrom = $submitter;
  1068. $eventdata->userto = $recipient;
  1069. $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
  1070. $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
  1071. $eventdata->fullmessageformat = FORMAT_PLAIN;
  1072. $eventdata->fullmessagehtml = '';
  1073. $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
  1074. $eventdata->contexturl = $a->quizreviewurl;
  1075. $eventdata->contexturlname = $a->quizname;
  1076. // ... and send it.
  1077. return message_send($eventdata);
  1078. }
  1079. /**
  1080. * Send all the requried messages when a quiz attempt is submitted.
  1081. *
  1082. * @param object $course the course
  1083. * @param object $quiz the quiz
  1084. * @param object $attempt this attempt just finished
  1085. * @param object $context the quiz context
  1086. * @param object $cm the coursemodule for this quiz
  1087. *
  1088. * @return bool true if all necessary messages were sent successfully, else false.
  1089. */
  1090. function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
  1091. global $CFG, $DB;
  1092. // Do nothing if required objects not present.
  1093. if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
  1094. throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
  1095. }
  1096. $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
  1097. // Check for confirmation required.
  1098. $sendconfirm = false;
  1099. $notifyexcludeusers = '';
  1100. if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
  1101. $notifyexcludeusers = $submitter->id;
  1102. $sendconfirm = true;
  1103. }
  1104. // Check for notifications required.
  1105. $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, u.emailstop, ' .
  1106. 'u.lang, u.timezone, u.mailformat, u.maildisplay';
  1107. $groups = groups_get_all_groups($course->id, $submitter->id);
  1108. if (is_array($groups) && count($groups) > 0) {
  1109. $groups = array_keys($groups);
  1110. } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
  1111. // If the user is not in a group, and the quiz is set to group mode,
  1112. // then set $groups to a non-existant id so that only users with
  1113. // 'moodle/site:accessallgroups' get notified.
  1114. $groups = -1;
  1115. } else {
  1116. $groups = '';
  1117. }
  1118. $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
  1119. $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
  1120. if (empty($userstonotify) && !$sendconfirm) {
  1121. return true; // Nothing to do.
  1122. }
  1123. $a = new stdClass();
  1124. // Course info.
  1125. $a->coursename = $course->fullname;
  1126. $a->courseshortname = $course->shortname;
  1127. // Quiz info.
  1128. $a->quizname = $quiz->name;
  1129. $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
  1130. $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
  1131. format_string($quiz->name) . ' report</a>';
  1132. $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
  1133. $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
  1134. // Attempt info.
  1135. $a->submissiontime = userdate($attempt->timefinish);
  1136. $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
  1137. $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
  1138. $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
  1139. format_string($quiz->name) . ' review</a>';
  1140. // Student who sat the quiz info.
  1141. $a->studentidnumber = $submitter->idnumber;
  1142. $a->studentname = fullname($submitter);
  1143. $a->studentusername = $submitter->username;
  1144. $allok = true;
  1145. // Send notifications if required.
  1146. if (!empty($userstonotify)) {
  1147. foreach ($userstonotify as $recipient) {
  1148. $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
  1149. }
  1150. }
  1151. // Send confirmation if required. We send the student confirmation last, so
  1152. // that if message sending is being intermittently buggy, which means we send
  1153. // some but not all messages, and then try again later, then teachers may get
  1154. // duplicate messages, but the student will always get exactly one.
  1155. if ($sendconfirm) {
  1156. $allok = $allok && quiz_send_confirmation($submitter, $a);
  1157. }
  1158. return $allok;
  1159. }
  1160. /**
  1161. * Send the notification message when a quiz attempt becomes overdue.
  1162. *
  1163. * @param object $course the course
  1164. * @param object $quiz the quiz
  1165. * @param object $attempt this attempt just finished
  1166. * @param object $context the quiz context
  1167. * @param object $cm the coursemodule for this quiz
  1168. */
  1169. function quiz_send_overdue_message($course, $quiz, $attempt, $context, $cm) {
  1170. global $CFG, $DB;
  1171. // Do nothing if required objects not present.
  1172. if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
  1173. throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
  1174. }
  1175. $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
  1176. if (!has_capability('mod/quiz:emailwarnoverdue', $context, $submitter, false)) {
  1177. return; // Message not required.
  1178. }
  1179. // Prepare lots of useful information that admins might want to include in
  1180. // the email message.
  1181. $quizname = format_string($quiz->name);
  1182. $deadlines = array();
  1183. if ($quiz->timelimit) {
  1184. $deadlines[] = $attempt->timestart + $quiz->timelimit;
  1185. }
  1186. if ($quiz->timeclose) {
  1187. $deadlines[] = $quiz->timeclose;
  1188. }
  1189. $duedate = min($deadlines);
  1190. $graceend = $duedate + $quiz->graceperiod;
  1191. $a = new stdClass();
  1192. // Course info.
  1193. $a->coursename = $course->fullname;
  1194. $a->courseshortname = $course->shortname;
  1195. // Quiz info.
  1196. $a->quizname = $quizname;
  1197. $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
  1198. $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
  1199. // Attempt info.
  1200. $a->attemptduedate = userdate($duedate);
  1201. $a->attemptgraceend = userdate($graceend);
  1202. $a->attemptsummaryurl = $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $attempt->id;
  1203. $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
  1204. // Student's info.
  1205. $a->studentidnumber = $submitter->idnumber;
  1206. $a->studentname = fullname($submitter);
  1207. $a->studentusername = $submitter->username;
  1208. // Prepare the message.
  1209. $eventdata = new stdClass();
  1210. $eventdata->component = 'mod_quiz';
  1211. $eventdata->name = 'attempt_overdue';
  1212. $eventdata->notification = 1;
  1213. $eventdata->userfrom = get_admin();
  1214. $eventdata->userto = $submitter;
  1215. $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
  1216. $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
  1217. $eventdata->fullmessageformat = FORMAT_PLAIN;
  1218. $eventdata->fullmessagehtml = '';
  1219. $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
  1220. $eventdata->contexturl = $a->quizurl;
  1221. $eventdata->contexturlname = $a->quizname;
  1222. // Send the message.
  1223. re

Large files files are truncated, but you can click here to view the full file