PageRenderTime 61ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/moodle/mod/quiz/lib.php

#
PHP | 1770 lines | 1089 code | 214 blank | 467 comment | 205 complexity | 0b34aea77664a861d93f823bcf0434ad MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, Apache-2.0

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

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