PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/mod/quiz/lib.php

https://bitbucket.org/andrewdavidson/sl-clone
PHP | 1802 lines | 1098 code | 224 blank | 480 comment | 203 complexity | 74b5e42a9ccb790e46cc3bdd19d8361c MD5 | raw file
Possible License(s): AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, Apache-2.0, GPL-3.0, BSD-3-Clause, LGPL-2.1

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 for the quiz module.
  18. *
  19. * This contains functions that are called also from outside the quiz module
  20. * Functions that are only called by the quiz module itself are in {@link locallib.php}
  21. *
  22. * @package mod
  23. * @subpackage quiz
  24. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  25. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26. */
  27. defined('MOODLE_INTERNAL') || die();
  28. require_once($CFG->libdir . '/eventslib.php');
  29. require_once($CFG->dirroot . '/calendar/lib.php');
  30. /**#@+
  31. * Option controlling what options are offered on the quiz settings form.
  32. */
  33. define('QUIZ_MAX_ATTEMPT_OPTION', 10);
  34. define('QUIZ_MAX_QPP_OPTION', 50);
  35. define('QUIZ_MAX_DECIMAL_OPTION', 5);
  36. define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
  37. /**#@-*/
  38. /**#@+
  39. * Options determining how the grades from individual attempts are combined to give
  40. * the overall grade for a user
  41. */
  42. define('QUIZ_GRADEHIGHEST', '1');
  43. define('QUIZ_GRADEAVERAGE', '2');
  44. define('QUIZ_ATTEMPTFIRST', '3');
  45. define('QUIZ_ATTEMPTLAST', '4');
  46. /**#@-*/
  47. /**
  48. * @var int If start and end date for the quiz are more than this many seconds apart
  49. * they will be represented by two separate events in the calendar
  50. */
  51. define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
  52. /**#@+
  53. * Options for navigation method within quizzes.
  54. */
  55. define('QUIZ_NAVMETHOD_FREE', 'free');
  56. define('QUIZ_NAVMETHOD_SEQ', 'sequential');
  57. /**#@-*/
  58. /**
  59. * Given an object containing all the necessary data,
  60. * (defined by the form in mod_form.php) this function
  61. * will create a new instance and return the id number
  62. * of the new instance.
  63. *
  64. * @param object $quiz the data that came from the form.
  65. * @return mixed the id of the new instance on success,
  66. * false or a string error message on failure.
  67. */
  68. function quiz_add_instance($quiz) {
  69. global $DB;
  70. $cmid = $quiz->coursemodule;
  71. // Process the options from the form.
  72. $quiz->created = time();
  73. $quiz->questions = '';
  74. $result = quiz_process_options($quiz);
  75. if ($result && is_string($result)) {
  76. return $result;
  77. }
  78. // Try to store it in the database.
  79. $quiz->id = $DB->insert_record('quiz', $quiz);
  80. // Do the processing required after an add or an update.
  81. quiz_after_add_or_update($quiz);
  82. return $quiz->id;
  83. }
  84. /**
  85. * Given an object containing all the necessary data,
  86. * (defined by the form in mod_form.php) this function
  87. * will update an existing instance with new data.
  88. *
  89. * @param object $quiz the data that came from the form.
  90. * @return mixed true on success, false or a string error message on failure.
  91. */
  92. function quiz_update_instance($quiz, $mform) {
  93. global $CFG, $DB;
  94. // Process the options from the form.
  95. $result = quiz_process_options($quiz);
  96. if ($result && is_string($result)) {
  97. return $result;
  98. }
  99. $oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
  100. // Repaginate, if asked to.
  101. if (!$quiz->shufflequestions && !empty($quiz->repaginatenow)) {
  102. require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  103. $quiz->questions = quiz_repaginate(quiz_clean_layout($oldquiz->questions, true),
  104. $quiz->questionsperpage);
  105. }
  106. unset($quiz->repaginatenow);
  107. // Update the database.
  108. $quiz->id = $quiz->instance;
  109. $DB->update_record('quiz', $quiz);
  110. // Do the processing required after an add or an update.
  111. quiz_after_add_or_update($quiz);
  112. if ($oldquiz->grademethod != $quiz->grademethod) {
  113. require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  114. $quiz->sumgrades = $oldquiz->sumgrades;
  115. $quiz->grade = $oldquiz->grade;
  116. quiz_update_all_final_grades($quiz);
  117. quiz_update_grades($quiz);
  118. }
  119. // Delete any previous preview attempts.
  120. quiz_delete_previews($quiz);
  121. return true;
  122. }
  123. /**
  124. * Given an ID of an instance of this module,
  125. * this function will permanently delete the instance
  126. * and any data that depends on it.
  127. *
  128. * @param int $id the id of the quiz to delete.
  129. * @return bool success or failure.
  130. */
  131. function quiz_delete_instance($id) {
  132. global $DB;
  133. $quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
  134. quiz_delete_all_attempts($quiz);
  135. quiz_delete_all_overrides($quiz);
  136. $DB->delete_records('quiz_question_instances', array('quiz' => $quiz->id));
  137. $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
  138. $events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
  139. foreach ($events as $event) {
  140. $event = calendar_event::load($event);
  141. $event->delete();
  142. }
  143. quiz_grade_item_delete($quiz);
  144. $DB->delete_records('quiz', array('id' => $quiz->id));
  145. return true;
  146. }
  147. /**
  148. * Deletes a quiz override from the database and clears any corresponding calendar events
  149. *
  150. * @param object $quiz The quiz object.
  151. * @param int $overrideid The id of the override being deleted
  152. * @return bool true on success
  153. */
  154. function quiz_delete_override($quiz, $overrideid) {
  155. global $DB;
  156. $override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
  157. // Delete the events.
  158. $events = $DB->get_records('event', array('modulename' => 'quiz',
  159. 'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
  160. 'userid' => (int)$override->userid));
  161. foreach ($events as $event) {
  162. $eventold = calendar_event::load($event);
  163. $eventold->delete();
  164. }
  165. $DB->delete_records('quiz_overrides', array('id' => $overrideid));
  166. return true;
  167. }
  168. /**
  169. * Deletes all quiz overrides from the database and clears any corresponding calendar events
  170. *
  171. * @param object $quiz The quiz object.
  172. */
  173. function quiz_delete_all_overrides($quiz) {
  174. global $DB;
  175. $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
  176. foreach ($overrides as $override) {
  177. quiz_delete_override($quiz, $override->id);
  178. }
  179. }
  180. /**
  181. * Updates a quiz object with override information for a user.
  182. *
  183. * Algorithm: For each quiz setting, if there is a matching user-specific override,
  184. * then use that otherwise, if there are group-specific overrides, return the most
  185. * lenient combination of them. If neither applies, leave the quiz setting unchanged.
  186. *
  187. * Special case: if there is more than one password that applies to the user, then
  188. * quiz->extrapasswords will contain an array of strings giving the remaining
  189. * passwords.
  190. *
  191. * @param object $quiz The quiz object.
  192. * @param int $userid The userid.
  193. * @return object $quiz The updated quiz object.
  194. */
  195. function quiz_update_effective_access($quiz, $userid) {
  196. global $DB;
  197. // Check for user override.
  198. $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
  199. if (!$override) {
  200. $override = new stdClass();
  201. $override->timeopen = null;
  202. $override->timeclose = null;
  203. $override->timelimit = null;
  204. $override->attempts = null;
  205. $override->password = null;
  206. }
  207. // Check for group overrides.
  208. $groupings = groups_get_user_groups($quiz->course, $userid);
  209. if (!empty($groupings[0])) {
  210. // Select all overrides that apply to the User's groups.
  211. list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
  212. $sql = "SELECT * FROM {quiz_overrides}
  213. WHERE groupid $extra AND quiz = ?";
  214. $params[] = $quiz->id;
  215. $records = $DB->get_records_sql($sql, $params);
  216. // Combine the overrides.
  217. $opens = array();
  218. $closes = array();
  219. $limits = array();
  220. $attempts = array();
  221. $passwords = array();
  222. foreach ($records as $gpoverride) {
  223. if (isset($gpoverride->timeopen)) {
  224. $opens[] = $gpoverride->timeopen;
  225. }
  226. if (isset($gpoverride->timeclose)) {
  227. $closes[] = $gpoverride->timeclose;
  228. }
  229. if (isset($gpoverride->timelimit)) {
  230. $limits[] = $gpoverride->timelimit;
  231. }
  232. if (isset($gpoverride->attempts)) {
  233. $attempts[] = $gpoverride->attempts;
  234. }
  235. if (isset($gpoverride->password)) {
  236. $passwords[] = $gpoverride->password;
  237. }
  238. }
  239. // If there is a user override for a setting, ignore the group override.
  240. if (is_null($override->timeopen) && count($opens)) {
  241. $override->timeopen = min($opens);
  242. }
  243. if (is_null($override->timeclose) && count($closes)) {
  244. $override->timeclose = max($closes);
  245. }
  246. if (is_null($override->timelimit) && count($limits)) {
  247. $override->timelimit = max($limits);
  248. }
  249. if (is_null($override->attempts) && count($attempts)) {
  250. $override->attempts = max($attempts);
  251. }
  252. if (is_null($override->password) && count($passwords)) {
  253. $override->password = array_shift($passwords);
  254. if (count($passwords)) {
  255. $override->extrapasswords = $passwords;
  256. }
  257. }
  258. }
  259. // Merge with quiz defaults.
  260. $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
  261. foreach ($keys as $key) {
  262. if (isset($override->{$key})) {
  263. $quiz->{$key} = $override->{$key};
  264. }
  265. }
  266. return $quiz;
  267. }
  268. /**
  269. * Delete all the attempts belonging to a quiz.
  270. *
  271. * @param object $quiz The quiz object.
  272. */
  273. function quiz_delete_all_attempts($quiz) {
  274. global $CFG, $DB;
  275. require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  276. question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
  277. $DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
  278. $DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
  279. }
  280. /**
  281. * Get the best current grade for a particular user in a quiz.
  282. *
  283. * @param object $quiz the quiz settings.
  284. * @param int $userid the id of the user.
  285. * @return float the user's current grade for this quiz, or null if this user does
  286. * not have a grade on this quiz.
  287. */
  288. function quiz_get_best_grade($quiz, $userid) {
  289. global $DB;
  290. $grade = $DB->get_field('quiz_grades', 'grade',
  291. array('quiz' => $quiz->id, 'userid' => $userid));
  292. // Need to detect errors/no result, without catching 0 grades.
  293. if ($grade === false) {
  294. return null;
  295. }
  296. return $grade + 0; // Convert to number.
  297. }
  298. /**
  299. * Is this a graded quiz? If this method returns true, you can assume that
  300. * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
  301. * divide by them).
  302. *
  303. * @param object $quiz a row from the quiz table.
  304. * @return bool whether this is a graded quiz.
  305. */
  306. function quiz_has_grades($quiz) {
  307. return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
  308. }
  309. /**
  310. * Return a small object with summary information about what a
  311. * user has done with a given particular instance of this module
  312. * Used for user activity reports.
  313. * $return->time = the time they did it
  314. * $return->info = a short text description
  315. *
  316. * @param object $course
  317. * @param object $user
  318. * @param object $mod
  319. * @param object $quiz
  320. * @return object|null
  321. */
  322. function quiz_user_outline($course, $user, $mod, $quiz) {
  323. global $DB, $CFG;
  324. require_once("$CFG->libdir/gradelib.php");
  325. $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
  326. if (empty($grades->items[0]->grades)) {
  327. return null;
  328. } else {
  329. $grade = reset($grades->items[0]->grades);
  330. }
  331. $result = new stdClass();
  332. $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
  333. // Datesubmitted == time created. dategraded == time modified or time overridden
  334. // if grade was last modified by the user themselves use date graded. Otherwise use
  335. // date submitted.
  336. // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
  337. if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
  338. $result->time = $grade->dategraded;
  339. } else {
  340. $result->time = $grade->datesubmitted;
  341. }
  342. return $result;
  343. }
  344. /**
  345. * Print a detailed representation of what a user has done with
  346. * a given particular instance of this module, for user activity reports.
  347. *
  348. * @param object $course
  349. * @param object $user
  350. * @param object $mod
  351. * @param object $quiz
  352. * @return bool
  353. */
  354. function quiz_user_complete($course, $user, $mod, $quiz) {
  355. global $DB, $CFG, $OUTPUT;
  356. require_once($CFG->libdir . '/gradelib.php');
  357. require_once($CFG->libdir . '/mod/quiz/locallib.php');
  358. $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
  359. if (!empty($grades->items[0]->grades)) {
  360. $grade = reset($grades->items[0]->grades);
  361. echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
  362. if ($grade->str_feedback) {
  363. echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
  364. }
  365. }
  366. if ($attempts = $DB->get_records('quiz_attempts',
  367. array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
  368. foreach ($attempts as $attempt) {
  369. echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
  370. if ($attempt->state != quiz_attempt::FINISHED) {
  371. echo quiz_attempt_state_name($attempt->state);
  372. } else {
  373. echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
  374. quiz_format_grade($quiz, $quiz->sumgrades);
  375. }
  376. echo ' - '.userdate($attempt->timemodified).'<br />';
  377. }
  378. } else {
  379. print_string('noattempts', 'quiz');
  380. }
  381. return true;
  382. }
  383. /**
  384. * Quiz periodic clean-up tasks.
  385. */
  386. function quiz_cron() {
  387. global $CFG;
  388. mtrace('');
  389. // Since the quiz specifies $module->cron = 60, so that the subplugins can
  390. // have frequent cron if they need it, we now need to do our own scheduling.
  391. $quizconfig = get_config('quiz');
  392. if (!isset($quizconfig->overduelastrun)) {
  393. $quizconfig->overduelastrun = 0;
  394. $quizconfig->overduedoneto = 0;
  395. }
  396. $timenow = time();
  397. if ($timenow > $quizconfig->overduelastrun + 3600) {
  398. require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
  399. $overduehander = new mod_quiz_overdue_attempt_updater();
  400. $processto = $timenow - $quizconfig->graceperiodmin;
  401. mtrace(' Looking for quiz overdue quiz attempts between ' .
  402. userdate($quizconfig->overduedoneto) . ' and ' . userdate($processto) . '...');
  403. list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $quizconfig->overduedoneto, $processto);
  404. set_config('overduelastrun', $timenow, 'quiz');
  405. set_config('overduedoneto', $processto, 'quiz');
  406. mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
  407. }
  408. // Run cron for our sub-plugin types.
  409. cron_execute_plugin_type('quiz', 'quiz reports');
  410. cron_execute_plugin_type('quizaccess', 'quiz access rules');
  411. return true;
  412. }
  413. /**
  414. * @param int $quizid the quiz id.
  415. * @param int $userid the userid.
  416. * @param string $status 'all', 'finished' or 'unfinished' to control
  417. * @param bool $includepreviews
  418. * @return an array of all the user's attempts at this quiz. Returns an empty
  419. * array if there are none.
  420. */
  421. function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
  422. global $DB, $CFG;
  423. // TODO MDL-33071 it is very annoying to have to included all of locallib.php
  424. // just to get the quiz_attempt::FINISHED constants, but I will try to sort
  425. // that out properly for Moodle 2.4. For now, I will just do a quick fix for
  426. // MDL-33048.
  427. require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  428. $params = array();
  429. switch ($status) {
  430. case 'all':
  431. $statuscondition = '';
  432. break;
  433. case 'finished':
  434. $statuscondition = ' AND state IN (:state1, :state2)';
  435. $params['state1'] = quiz_attempt::FINISHED;
  436. $params['state2'] = quiz_attempt::ABANDONED;
  437. break;
  438. case 'unfinished':
  439. $statuscondition = ' AND state IN (:state1, :state2)';
  440. $params['state1'] = quiz_attempt::IN_PROGRESS;
  441. $params['state2'] = quiz_attempt::OVERDUE;
  442. break;
  443. }
  444. $previewclause = '';
  445. if (!$includepreviews) {
  446. $previewclause = ' AND preview = 0';
  447. }
  448. $params['quizid'] = $quizid;
  449. $params['userid'] = $userid;
  450. return $DB->get_records_select('quiz_attempts',
  451. 'quiz = :quizid AND userid = :userid' . $previewclause . $statuscondition,
  452. $params, 'attempt ASC');
  453. }
  454. /**
  455. * Return grade for given user or all users.
  456. *
  457. * @param int $quizid id of quiz
  458. * @param int $userid optional user id, 0 means all users
  459. * @return array array of grades, false if none. These are raw grades. They should
  460. * be processed with quiz_format_grade for display.
  461. */
  462. function quiz_get_user_grades($quiz, $userid = 0) {
  463. global $CFG, $DB;
  464. $params = array($quiz->id);
  465. $usertest = '';
  466. if ($userid) {
  467. $params[] = $userid;
  468. $usertest = 'AND u.id = ?';
  469. }
  470. return $DB->get_records_sql("
  471. SELECT
  472. u.id,
  473. u.id AS userid,
  474. qg.grade AS rawgrade,
  475. qg.timemodified AS dategraded,
  476. MAX(qa.timefinish) AS datesubmitted
  477. FROM {user} u
  478. JOIN {quiz_grades} qg ON u.id = qg.userid
  479. JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
  480. WHERE qg.quiz = ?
  481. $usertest
  482. GROUP BY u.id, qg.grade, qg.timemodified", $params);
  483. }
  484. /**
  485. * Round a grade to to the correct number of decimal places, and format it for display.
  486. *
  487. * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
  488. * @param float $grade The grade to round.
  489. * @return float
  490. */
  491. function quiz_format_grade($quiz, $grade) {
  492. if (is_null($grade)) {
  493. return get_string('notyetgraded', 'quiz');
  494. }
  495. return format_float($grade, $quiz->decimalpoints);
  496. }
  497. /**
  498. * Round a grade to to the correct number of decimal places, and format it for display.
  499. *
  500. * @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
  501. * @param float $grade The grade to round.
  502. * @return float
  503. */
  504. function quiz_format_question_grade($quiz, $grade) {
  505. if (empty($quiz->questiondecimalpoints)) {
  506. $quiz->questiondecimalpoints = -1;
  507. }
  508. if ($quiz->questiondecimalpoints == -1) {
  509. return format_float($grade, $quiz->decimalpoints);
  510. } else {
  511. return format_float($grade, $quiz->questiondecimalpoints);
  512. }
  513. }
  514. /**
  515. * Update grades in central gradebook
  516. *
  517. * @category grade
  518. * @param object $quiz the quiz settings.
  519. * @param int $userid specific user only, 0 means all users.
  520. * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
  521. */
  522. function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
  523. global $CFG, $DB;
  524. require_once($CFG->libdir.'/gradelib.php');
  525. if ($quiz->grade == 0) {
  526. quiz_grade_item_update($quiz);
  527. } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
  528. quiz_grade_item_update($quiz, $grades);
  529. } else if ($userid && $nullifnone) {
  530. $grade = new stdClass();
  531. $grade->userid = $userid;
  532. $grade->rawgrade = null;
  533. quiz_grade_item_update($quiz, $grade);
  534. } else {
  535. quiz_grade_item_update($quiz);
  536. }
  537. }
  538. /**
  539. * Update all grades in gradebook.
  540. */
  541. function quiz_upgrade_grades() {
  542. global $DB;
  543. $sql = "SELECT COUNT('x')
  544. FROM {quiz} a, {course_modules} cm, {modules} m
  545. WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
  546. $count = $DB->count_records_sql($sql);
  547. $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
  548. FROM {quiz} a, {course_modules} cm, {modules} m
  549. WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
  550. $rs = $DB->get_recordset_sql($sql);
  551. if ($rs->valid()) {
  552. $pbar = new progress_bar('quizupgradegrades', 500, true);
  553. $i=0;
  554. foreach ($rs as $quiz) {
  555. $i++;
  556. upgrade_set_timeout(60*5); // Set up timeout, may also abort execution.
  557. quiz_update_grades($quiz, 0, false);
  558. $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
  559. }
  560. }
  561. $rs->close();
  562. }
  563. /**
  564. * Create or update the grade item for given quiz
  565. *
  566. * @category grade
  567. * @param object $quiz object with extra cmidnumber
  568. * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
  569. * @return int 0 if ok, error code otherwise
  570. */
  571. function quiz_grade_item_update($quiz, $grades = null) {
  572. global $CFG, $OUTPUT;
  573. require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  574. require_once($CFG->libdir.'/gradelib.php');
  575. if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
  576. $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
  577. } else {
  578. $params = array('itemname' => $quiz->name);
  579. }
  580. if ($quiz->grade > 0) {
  581. $params['gradetype'] = GRADE_TYPE_VALUE;
  582. $params['grademax'] = $quiz->grade;
  583. $params['grademin'] = 0;
  584. } else {
  585. $params['gradetype'] = GRADE_TYPE_NONE;
  586. }
  587. // What this is trying to do:
  588. // 1. If the quiz is set to not show grades while the quiz is still open,
  589. // and is set to show grades after the quiz is closed, then create the
  590. // grade_item with a show-after date that is the quiz close date.
  591. // 2. If the quiz is set to not show grades at either of those times,
  592. // create the grade_item as hidden.
  593. // 3. If the quiz is set to show grades, create the grade_item visible.
  594. $openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
  595. mod_quiz_display_options::LATER_WHILE_OPEN);
  596. $closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
  597. mod_quiz_display_options::AFTER_CLOSE);
  598. if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
  599. $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
  600. $params['hidden'] = 1;
  601. } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
  602. $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
  603. if ($quiz->timeclose) {
  604. $params['hidden'] = $quiz->timeclose;
  605. } else {
  606. $params['hidden'] = 1;
  607. }
  608. } else {
  609. // Either
  610. // a) both open and closed enabled
  611. // b) open enabled, closed disabled - we can not "hide after",
  612. // grades are kept visible even after closing.
  613. $params['hidden'] = 0;
  614. }
  615. if ($grades === 'reset') {
  616. $params['reset'] = true;
  617. $grades = null;
  618. }
  619. $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
  620. if (!empty($gradebook_grades->items)) {
  621. $grade_item = $gradebook_grades->items[0];
  622. if ($grade_item->locked) {
  623. // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
  624. $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
  625. if (!$confirm_regrade) {
  626. $message = get_string('gradeitemislocked', 'grades');
  627. $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
  628. '&amp;mode=overview';
  629. $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
  630. echo $OUTPUT->box_start('generalbox', 'notice');
  631. echo '<p>'. $message .'</p>';
  632. echo $OUTPUT->container_start('buttons');
  633. echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
  634. echo $OUTPUT->single_button($back_link, get_string('cancel'));
  635. echo $OUTPUT->container_end();
  636. echo $OUTPUT->box_end();
  637. return GRADE_UPDATE_ITEM_LOCKED;
  638. }
  639. }
  640. }
  641. return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
  642. }
  643. /**
  644. * Delete grade item for given quiz
  645. *
  646. * @category grade
  647. * @param object $quiz object
  648. * @return object quiz
  649. */
  650. function quiz_grade_item_delete($quiz) {
  651. global $CFG;
  652. require_once($CFG->libdir . '/gradelib.php');
  653. return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
  654. null, array('deleted' => 1));
  655. }
  656. /**
  657. * This standard function will check all instances of this module
  658. * and make sure there are up-to-date events created for each of them.
  659. * If courseid = 0, then every quiz event in the site is checked, else
  660. * only quiz events belonging to the course specified are checked.
  661. * This function is used, in its new format, by restore_refresh_events()
  662. *
  663. * @param int $courseid
  664. * @return bool
  665. */
  666. function quiz_refresh_events($courseid = 0) {
  667. global $DB;
  668. if ($courseid == 0) {
  669. if (!$quizzes = $DB->get_records('quiz')) {
  670. return true;
  671. }
  672. } else {
  673. if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) {
  674. return true;
  675. }
  676. }
  677. foreach ($quizzes as $quiz) {
  678. quiz_update_events($quiz);
  679. }
  680. return true;
  681. }
  682. /**
  683. * Returns all quiz graded users since a given time for specified quiz
  684. */
  685. function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
  686. $courseid, $cmid, $userid = 0, $groupid = 0) {
  687. global $CFG, $COURSE, $USER, $DB;
  688. require_once('locallib.php');
  689. if ($COURSE->id == $courseid) {
  690. $course = $COURSE;
  691. } else {
  692. $course = $DB->get_record('course', array('id' => $courseid));
  693. }
  694. $modinfo = get_fast_modinfo($course);
  695. $cm = $modinfo->cms[$cmid];
  696. $quiz = $DB->get_record('quiz', array('id' => $cm->instance));
  697. if ($userid) {
  698. $userselect = "AND u.id = :userid";
  699. $params['userid'] = $userid;
  700. } else {
  701. $userselect = '';
  702. }
  703. if ($groupid) {
  704. $groupselect = 'AND gm.groupid = :groupid';
  705. $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
  706. $params['groupid'] = $groupid;
  707. } else {
  708. $groupselect = '';
  709. $groupjoin = '';
  710. }
  711. $params['timestart'] = $timestart;
  712. $params['quizid'] = $quiz->id;
  713. if (!$attempts = $DB->get_records_sql("
  714. SELECT qa.*,
  715. u.firstname, u.lastname, u.email, u.picture, u.imagealt
  716. FROM {quiz_attempts} qa
  717. JOIN {user} u ON u.id = qa.userid
  718. $groupjoin
  719. WHERE qa.timefinish > :timestart
  720. AND qa.quiz = :quizid
  721. AND qa.preview = 0
  722. $userselect
  723. $groupselect
  724. ORDER BY qa.timefinish ASC", $params)) {
  725. return;
  726. }
  727. $context = get_context_instance(CONTEXT_MODULE, $cm->id);
  728. $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
  729. $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
  730. $grader = has_capability('mod/quiz:viewreports', $context);
  731. $groupmode = groups_get_activity_groupmode($cm, $course);
  732. if (is_null($modinfo->groups)) {
  733. // Load all my groups and cache it in modinfo.
  734. $modinfo->groups = groups_get_user_groups($course->id);
  735. }
  736. $usersgroups = null;
  737. $aname = format_string($cm->name, true);
  738. foreach ($attempts as $attempt) {
  739. if ($attempt->userid != $USER->id) {
  740. if (!$grader) {
  741. // Grade permission required.
  742. continue;
  743. }
  744. if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
  745. if (is_null($usersgroups)) {
  746. $usersgroups = groups_get_all_groups($course->id,
  747. $attempt->userid, $cm->groupingid);
  748. if (is_array($usersgroups)) {
  749. $usersgroups = array_keys($usersgroups);
  750. } else {
  751. $usersgroups = array();
  752. }
  753. }
  754. if (!array_intersect($usersgroups, $modinfo->groups[$cm->id])) {
  755. continue;
  756. }
  757. }
  758. }
  759. $options = quiz_get_review_options($quiz, $attempt, $context);
  760. $tmpactivity = new stdClass();
  761. $tmpactivity->type = 'quiz';
  762. $tmpactivity->cmid = $cm->id;
  763. $tmpactivity->name = $aname;
  764. $tmpactivity->sectionnum = $cm->sectionnum;
  765. $tmpactivity->timestamp = $attempt->timefinish;
  766. $tmpactivity->content->attemptid = $attempt->id;
  767. $tmpactivity->content->attempt = $attempt->attempt;
  768. if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
  769. $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
  770. $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
  771. } else {
  772. $tmpactivity->content->sumgrades = null;
  773. $tmpactivity->content->maxgrade = null;
  774. }
  775. $tmpactivity->user->id = $attempt->userid;
  776. $tmpactivity->user->firstname = $attempt->firstname;
  777. $tmpactivity->user->lastname = $attempt->lastname;
  778. $tmpactivity->user->fullname = fullname($attempt, $viewfullnames);
  779. $tmpactivity->user->picture = $attempt->picture;
  780. $tmpactivity->user->imagealt = $attempt->imagealt;
  781. $tmpactivity->user->email = $attempt->email;
  782. $activities[$index++] = $tmpactivity;
  783. }
  784. }
  785. function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
  786. global $CFG, $OUTPUT;
  787. echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
  788. echo '<tr><td class="userpicture" valign="top">';
  789. echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid));
  790. echo '</td><td>';
  791. if ($detail) {
  792. $modname = $modnames[$activity->type];
  793. echo '<div class="title">';
  794. echo '<img src="' . $OUTPUT->pix_url('icon', $activity->type) . '" ' .
  795. 'class="icon" alt="' . $modname . '" />';
  796. echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
  797. $activity->cmid . '">' . $activity->name . '</a>';
  798. echo '</div>';
  799. }
  800. echo '<div class="grade">';
  801. echo get_string('attempt', 'quiz', $activity->content->attempt);
  802. if (isset($activity->content->maxgrade)) {
  803. $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
  804. echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
  805. $activity->content->attemptid . '">' . $grades . '</a>)';
  806. }
  807. echo '</div>';
  808. echo '<div class="user">';
  809. echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
  810. '&amp;course=' . $courseid . '">' . $activity->user->fullname .
  811. '</a> - ' . userdate($activity->timestamp);
  812. echo '</div>';
  813. echo '</td></tr></table>';
  814. return;
  815. }
  816. /**
  817. * Pre-process the quiz options form data, making any necessary adjustments.
  818. * Called by add/update instance in this file.
  819. *
  820. * @param object $quiz The variables set on the form.
  821. */
  822. function quiz_process_options($quiz) {
  823. global $CFG;
  824. require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  825. require_once($CFG->libdir . '/questionlib.php');
  826. $quiz->timemodified = time();
  827. // Quiz name.
  828. if (!empty($quiz->name)) {
  829. $quiz->name = trim($quiz->name);
  830. }
  831. // Password field - different in form to stop browsers that remember passwords
  832. // getting confused.
  833. $quiz->password = $quiz->quizpassword;
  834. unset($quiz->quizpassword);
  835. // Quiz feedback.
  836. if (isset($quiz->feedbacktext)) {
  837. // Clean up the boundary text.
  838. for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
  839. if (empty($quiz->feedbacktext[$i]['text'])) {
  840. $quiz->feedbacktext[$i]['text'] = '';
  841. } else {
  842. $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
  843. }
  844. }
  845. // Check the boundary value is a number or a percentage, and in range.
  846. $i = 0;
  847. while (!empty($quiz->feedbackboundaries[$i])) {
  848. $boundary = trim($quiz->feedbackboundaries[$i]);
  849. if (!is_numeric($boundary)) {
  850. if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
  851. $boundary = trim(substr($boundary, 0, -1));
  852. if (is_numeric($boundary)) {
  853. $boundary = $boundary * $quiz->grade / 100.0;
  854. } else {
  855. return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
  856. }
  857. }
  858. }
  859. if ($boundary <= 0 || $boundary >= $quiz->grade) {
  860. return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
  861. }
  862. if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
  863. return get_string('feedbackerrororder', 'quiz', $i + 1);
  864. }
  865. $quiz->feedbackboundaries[$i] = $boundary;
  866. $i += 1;
  867. }
  868. $numboundaries = $i;
  869. // Check there is nothing in the remaining unused fields.
  870. if (!empty($quiz->feedbackboundaries)) {
  871. for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
  872. if (!empty($quiz->feedbackboundaries[$i]) &&
  873. trim($quiz->feedbackboundaries[$i]) != '') {
  874. return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
  875. }
  876. }
  877. }
  878. for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
  879. if (!empty($quiz->feedbacktext[$i]['text']) &&
  880. trim($quiz->feedbacktext[$i]['text']) != '') {
  881. return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
  882. }
  883. }
  884. // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
  885. $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
  886. $quiz->feedbackboundaries[$numboundaries] = 0;
  887. $quiz->feedbackboundarycount = $numboundaries;
  888. }
  889. // Combing the individual settings into the review columns.
  890. $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
  891. $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
  892. $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
  893. $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
  894. $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
  895. $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
  896. $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
  897. $quiz->reviewattempt |= mod_quiz_display_options::DURING;
  898. $quiz->reviewoverallfeedback &= ~mod_quiz_display_options::DURING;
  899. }
  900. /**
  901. * Helper function for {@link quiz_process_options()}.
  902. * @param object $fromform the sumbitted form date.
  903. * @param string $field one of the review option field names.
  904. */
  905. function quiz_review_option_form_to_db($fromform, $field) {
  906. static $times = array(
  907. 'during' => mod_quiz_display_options::DURING,
  908. 'immediately' => mod_quiz_display_options::IMMEDIATELY_AFTER,
  909. 'open' => mod_quiz_display_options::LATER_WHILE_OPEN,
  910. 'closed' => mod_quiz_display_options::AFTER_CLOSE,
  911. );
  912. $review = 0;
  913. foreach ($times as $whenname => $when) {
  914. $fieldname = $field . $whenname;
  915. if (isset($fromform->$fieldname)) {
  916. $review |= $when;
  917. unset($fromform->$fieldname);
  918. }
  919. }
  920. return $review;
  921. }
  922. /**
  923. * This function is called at the end of quiz_add_instance
  924. * and quiz_update_instance, to do the common processing.
  925. *
  926. * @param object $quiz the quiz object.
  927. */
  928. function quiz_after_add_or_update($quiz) {
  929. global $DB;
  930. $cmid = $quiz->coursemodule;
  931. // We need to use context now, so we need to make sure all needed info is already in db.
  932. $DB->set_field('course_modules', 'instance', $quiz->id, array('id'=>$cmid));
  933. $context = get_context_instance(CONTEXT_MODULE, $cmid);
  934. // Save the feedback.
  935. $DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
  936. for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
  937. $feedback = new stdClass();
  938. $feedback->quizid = $quiz->id;
  939. $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
  940. $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
  941. $feedback->mingrade = $quiz->feedbackboundaries[$i];
  942. $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
  943. $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
  944. $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
  945. $context->id, 'mod_quiz', 'feedback', $feedback->id,
  946. array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0),
  947. $quiz->feedbacktext[$i]['text']);
  948. $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
  949. array('id' => $feedback->id));
  950. }
  951. // Store any settings belonging to the access rules.
  952. quiz_access_manager::save_settings($quiz);
  953. // Update the events relating to this quiz.
  954. quiz_update_events($quiz);
  955. // Update related grade item.
  956. quiz_grade_item_update($quiz);
  957. }
  958. /**
  959. * This function updates the events associated to the quiz.
  960. * If $override is non-zero, then it updates only the events
  961. * associated with the specified override.
  962. *
  963. * @uses QUIZ_MAX_EVENT_LENGTH
  964. * @param object $quiz the quiz object.
  965. * @param object optional $override limit to a specific override
  966. */
  967. function quiz_update_events($quiz, $override = null) {
  968. global $DB;
  969. // Load the old events relating to this quiz.
  970. $conds = array('modulename'=>'quiz',
  971. 'instance'=>$quiz->id);
  972. if (!empty($override)) {
  973. // Only load events for this override.
  974. $conds['groupid'] = isset($override->groupid)? $override->groupid : 0;
  975. $conds['userid'] = isset($override->userid)? $override->userid : 0;
  976. }
  977. $oldevents = $DB->get_records('event', $conds);
  978. // Now make a todo list of all that needs to be updated.
  979. if (empty($override)) {
  980. // We are updating the primary settings for the quiz, so we
  981. // need to add all the overrides.
  982. $overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id));
  983. // As well as the original quiz (empty override).
  984. $overrides[] = new stdClass();
  985. } else {
  986. // Just do the one override.
  987. $overrides = array($override);
  988. }
  989. foreach ($overrides as $current) {
  990. $groupid = isset($current->groupid)? $current->groupid : 0;
  991. $userid = isset($current->userid)? $current->userid : 0;
  992. $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
  993. $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
  994. // Only add open/close events for an override if they differ from the quiz default.
  995. $addopen = empty($current->id) || !empty($current->timeopen);
  996. $addclose = empty($current->id) || !empty($current->timeclose);
  997. $event = new stdClass();
  998. $event->description = format_module_intro('quiz', $quiz, $quiz->coursemodule);
  999. // Events module won't show user events when the courseid is nonzero.
  1000. $event->courseid = ($userid) ? 0 : $quiz->course;
  1001. $event->groupid = $groupid;
  1002. $event->userid = $userid;
  1003. $event->modulename = 'quiz';
  1004. $event->instance = $quiz->id;
  1005. $event->timestart = $timeopen;
  1006. $event->timeduration = max($timeclose - $timeopen, 0);
  1007. $event->visible = instance_is_visible('quiz', $quiz);
  1008. $event->eventtype = 'open';
  1009. // Determine the event name.
  1010. if ($groupid) {
  1011. $params = new stdClass();
  1012. $params->quiz = $quiz->name;
  1013. $params->group = groups_get_group_name($groupid);
  1014. if ($params->group === false) {
  1015. // Group doesn't exist, just skip it.
  1016. continue;
  1017. }
  1018. $eventname = get_string('overridegroupeventname', 'quiz', $params);
  1019. } else if ($userid) {
  1020. $params = new stdClass();
  1021. $params->quiz = $quiz->name;
  1022. $eventname = get_string('overrideusereventname', 'quiz', $params);
  1023. } else {
  1024. $eventname = $quiz->name;
  1025. }
  1026. if ($addopen or $addclose) {
  1027. if ($timeclose and $timeopen and $event->timeduration <= QUIZ_MAX_EVENT_LENGTH) {
  1028. // Single event for the whole quiz.
  1029. if ($oldevent = array_shift($oldevents)) {
  1030. $event->id = $oldevent->id;
  1031. } else {
  1032. unset($event->id);
  1033. }
  1034. $event->name = $eventname;
  1035. // The method calendar_event::create will reuse a db record if the id field is set.
  1036. calendar_event::create($event);
  1037. } else {
  1038. // Separate start and end events.
  1039. $event->timeduration = 0;
  1040. if ($timeopen && $addopen) {
  1041. if ($oldevent = array_shift($oldevents)) {
  1042. $event->id = $oldevent->id;
  1043. } else {
  1044. unset($event->id);
  1045. }
  1046. $event->name = $eventname.' ('.get_string('quizopens', 'quiz').')';
  1047. // The method calendar_event::create will reuse a db record if the id field is set.
  1048. calendar_event::create($event);
  1049. }
  1050. if ($timeclose && $addclose) {
  1051. if ($oldevent = array_shift($oldevents)) {
  1052. $event->id = $oldevent->id;
  1053. } else {
  1054. unset($event->id);
  1055. }
  1056. $event->name = $eventname.' ('.get_string('quizcloses', 'quiz').')';
  1057. $event->timestart = $timeclose;
  1058. $event->eventtype = 'close';
  1059. calendar_event::create($event);
  1060. }
  1061. }
  1062. }
  1063. }
  1064. // Delete any leftover events.
  1065. foreach ($oldevents as $badevent) {
  1066. $badevent = calendar_event::load($badevent);
  1067. $badevent->delete();
  1068. }
  1069. }
  1070. /**
  1071. * @return array
  1072. */
  1073. function quiz_get_view_actions() {
  1074. return array('view', 'view all', 'report', 'review');
  1075. }
  1076. /**
  1077. * @return array
  1078. */
  1079. function quiz_get_post_actions() {
  1080. return array('attempt', 'close attempt', 'preview', 'editquestions',
  1081. 'delete attempt', 'manualgrade');
  1082. }
  1083. /**
  1084. * @param array $questionids of question ids.
  1085. * @return bool whether any of these questions are used by any instance of this module.
  1086. */
  1087. function quiz_questions_in_use($questionids) {
  1088. global $DB, $CFG;
  1089. require_once($CFG->libdir . '/questionlib.php');
  1090. list($test, $params) = $DB->get_in_or_equal($questionids);
  1091. return $DB->record_exists_select('quiz_question_instances',
  1092. 'question ' . $test, $params) || question_engine::questions_in_use(
  1093. $questionids, new qubaid_join('{quiz_attempts} quiza',
  1094. 'quiza.uniqueid', 'quiza.preview = 0'));
  1095. }
  1096. /**
  1097. * Implementation of the function for printing the form elements that control
  1098. * whether the course reset functionality affects the quiz.
  1099. *
  1100. * @param $mform the course reset form that is being built.
  1101. */
  1102. function quiz_reset_course_form_definition($mform) {
  1103. $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
  1104. $mform->addElement('advcheckbox', 'reset_quiz_attempts',
  1105. get_string('removeallquizattempts', 'quiz'));
  1106. }
  1107. /**
  1108. * Course reset form defaults.
  1109. * @return array the defaults.
  1110. */
  1111. function quiz_reset_course_form_defaults($course) {
  1112. return array('reset_quiz_attempts' => 1);
  1113. }
  1114. /**
  1115. * Removes all grades from gradebook
  1116. *
  1117. * @param int $courseid
  1118. * @param string optional type
  1119. */
  1120. function quiz_reset_gradebook($courseid, $type='') {
  1121. global $CFG, $DB;
  1122. $quizzes = $DB->get_records_sql("
  1123. SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
  1124. FROM {modules} m
  1125. JOIN {course_modules} cm ON m.id = cm.module
  1126. JOIN {quiz} q ON cm.instance = q.id
  1127. WHERE m.name = 'quiz' AND cm.course = ?", array($courseid));
  1128. foreach ($quizzes as $quiz) {
  1129. quiz_grade_item_update($quiz, 'reset');
  1130. }
  1131. }
  1132. /**
  1133. * Actual implementation of the reset course functionality, delete all the
  1134. * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
  1135. * set and true.
  1136. *
  1137. * Also, move the quiz open and close dates, if the course start date is changing.
  1138. *
  1139. * @param object $data the data submitted from the reset course.
  1140. * @return array status array
  1141. */
  1142. function quiz_reset_userdata($data) {
  1143. global $CFG, $DB;
  1144. require_once($CFG->libdir.'/questionlib.php');
  1145. $componentstr = get_string('modulenameplural', 'quiz');
  1146. $status = array();
  1147. // Delete attempts.
  1148. if (!empty($data->reset_quiz_attempts)) {
  1149. require_once($CFG->libdir . '/questionlib.php');
  1150. question_engine::delete_questions_usage_by_activities(new qubaid_join(
  1151. '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
  1152. 'quiza.uniqueid', 'quiz.course = :quizcourseid',
  1153. array('quizcourseid' => $data->courseid)));
  1154. $DB->delete_records_select('quiz_attempts',
  1155. 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
  1156. $status[] = array(
  1157. 'component' => $componentstr,
  1158. 'item' => get_string('attemptsdeleted', 'quiz'),
  1159. 'error' => false);
  1160. // Remove all grades from gradebook.
  1161. $DB->delete_records_select('quiz_grades',
  1162. 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', array($data->courseid));
  1163. if (empty($data->reset_gradebook_grades)) {
  1164. quiz_reset_gradebook($data->courseid);
  1165. }
  1166. $status[] = array(
  1167. 'component' => $componentstr,
  1168. 'item' => get_string('gradesdeleted', 'quiz'),
  1169. 'error' => false);
  1170. }
  1171. // Updating dates - shift may be negative too.
  1172. if ($data->timeshift) {
  1173. shift_course_mod_dates('quiz', array('timeopen', 'timeclose'),
  1174. $data->timeshift, $data->courseid);
  1175. $status[] = array(
  1176. 'component' => $componentstr,
  1177. 'item' => get_string('openclosedatesupdated', 'quiz'),
  1178. 'error' => false);
  1179. }
  1180. return $status;
  1181. }
  1182. /**
  1183. * Checks whether the current user is allowed to view a file uploaded in a quiz.
  1184. * Teachers can view any from their courses, students can only view their own.
  1185. *
  1186. * @param int $attemptuniqueid int attempt id
  1187. * @param int $questionid int question id
  1188. * @return bool to indicate access granted or denied
  1189. */
  1190. function quiz_check_file_access($attemptuniqueid, $questionid, $context = null) {
  1191. global $USER, $DB, $CFG;
  1192. require_once(dirname(__FILE__).'/attemptlib.php');
  1193. require_once(dirname(__FILE__).'/locallib.php');
  1194. $attempt = $DB->get_record('quiz_attempts', array('uniqueid' => $attemptuniqueid));
  1195. $attemptobj = quiz_attempt::create($attempt->id);
  1196. // Does the question exist?
  1197. if (!$question = $DB->get_record('question', array('id' => $questionid))) {
  1198. return false;
  1199. }
  1200. if ($context === null) {
  1201. $quiz = $DB->get_record('quiz', array('id' => $attempt->quiz));
  1202. $cm = get_coursemodule_from_id('quiz', $quiz->id);
  1203. $context = get_context_instance(CONTEXT_MODULE, $cm->id);
  1204. }
  1205. // Load those questions and the associated states.
  1206. $attemptobj->load_questions(array($questionid));
  1207. $attemptobj->load_question_states(array($questionid));
  1208. // Obtain the state.
  1209. $state = $attemptobj->get_question_state($questionid);
  1210. // Obtain the question.
  1211. $question = $attemptobj->get_question($questionid);
  1212. // Access granted if the current user submitted this file.
  1213. if ($attempt->userid != $USER->id) {
  1214. return false;
  1215. }
  1216. // Access granted if the current user has permission to grade quizzes in this course.
  1217. if (!(has_capability('mod/quiz:viewreports', $context) ||
  1218. has_capability('mod/quiz:grade', $context))) {
  1219. return false;

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