MDL-76897 quiz: quiz_update_all_final_grades -> grade_calculator
[moodle.git] / mod / quiz / report / overview / report.php
blobfabca54c49bafb601b3770ccc4395579ddbd7193
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.
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/>.
17 /**
18 * This file defines the quiz overview report class.
20 * @package quiz_overview
21 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 use mod_quiz\local\reports\attempts_report;
26 use mod_quiz\question\bank\qbank_helper;
27 use mod_quiz\quiz_attempt;
28 use mod_quiz\quiz_settings;
30 defined('MOODLE_INTERNAL') || die();
32 require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_options.php');
33 require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_form.php');
34 require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_table.php');
37 /**
38 * Quiz report subclass for the overview (grades) report.
40 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class quiz_overview_report extends attempts_report {
45 /**
46 * @var bool whether there are actually students to show, given the options.
48 protected $hasgroupstudents;
50 /**
51 * @var array|null cached copy of qbank_helper::get_question_structure for use during regrades.
53 protected $structureforregrade = null;
55 /**
56 * @var array|null used during regrades, to cache which new questionid to use for each old on.
57 * for random questions, stores oldquestionid => newquestionid.
58 * See get_new_question_for_regrade.
60 protected $newquestionidsforold = null;
62 public function display($quiz, $cm, $course) {
63 global $DB, $PAGE;
65 list($currentgroup, $studentsjoins, $groupstudentsjoins, $allowedjoins) = $this->init(
66 'overview', 'quiz_overview_settings_form', $quiz, $cm, $course);
68 $options = new quiz_overview_options('overview', $quiz, $cm, $course);
70 if ($fromform = $this->form->get_data()) {
71 $options->process_settings_from_form($fromform);
73 } else {
74 $options->process_settings_from_params();
77 $this->form->set_data($options->get_initial_form_data());
79 // Load the required questions.
80 $questions = quiz_report_get_significant_questions($quiz);
81 // Prepare for downloading, if applicable.
82 $courseshortname = format_string($course->shortname, true,
83 ['context' => context_course::instance($course->id)]);
84 $table = new quiz_overview_table($quiz, $this->context, $this->qmsubselect,
85 $options, $groupstudentsjoins, $studentsjoins, $questions, $options->get_url());
86 $filename = quiz_report_download_filename(get_string('overviewfilename', 'quiz_overview'),
87 $courseshortname, $quiz->name);
88 $table->is_downloading($options->download, $filename,
89 $courseshortname . ' ' . format_string($quiz->name, true));
90 if ($table->is_downloading()) {
91 raise_memory_limit(MEMORY_EXTRA);
94 $this->hasgroupstudents = false;
95 if (!empty($groupstudentsjoins->joins)) {
96 $sql = "SELECT DISTINCT u.id
97 FROM {user} u
98 $groupstudentsjoins->joins
99 WHERE $groupstudentsjoins->wheres";
100 $this->hasgroupstudents = $DB->record_exists_sql($sql, $groupstudentsjoins->params);
102 $hasstudents = false;
103 if (!empty($studentsjoins->joins)) {
104 $sql = "SELECT DISTINCT u.id
105 FROM {user} u
106 $studentsjoins->joins
107 WHERE $studentsjoins->wheres";
108 $hasstudents = $DB->record_exists_sql($sql, $studentsjoins->params);
110 if ($options->attempts == self::ALL_WITH) {
111 // This option is only available to users who can access all groups in
112 // groups mode, so setting allowed to empty (which means all quiz attempts
113 // are accessible, is not a security porblem.
114 $allowedjoins = new \core\dml\sql_join();
117 $this->course = $course; // Hack to make this available in process_actions.
118 $this->process_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $allowedjoins, $options->get_url());
120 $hasquestions = quiz_has_questions($quiz->id);
122 // Start output.
123 if (!$table->is_downloading()) {
124 // Only print headers if not asked to download data.
125 $this->print_standard_header_and_messages($cm, $course, $quiz,
126 $options, $currentgroup, $hasquestions, $hasstudents);
128 // Print the display options.
129 $this->form->display();
132 $hasstudents = $hasstudents && (!$currentgroup || $this->hasgroupstudents);
133 if ($hasquestions && ($hasstudents || $options->attempts == self::ALL_WITH)) {
134 // Construct the SQL.
135 $table->setup_sql_queries($allowedjoins);
137 if (!$table->is_downloading()) {
138 // Output the regrade buttons.
139 if (has_capability('mod/quiz:regrade', $this->context)) {
140 $regradesneeded = $this->count_question_attempts_needing_regrade(
141 $quiz, $groupstudentsjoins);
142 if ($currentgroup) {
143 $a= new stdClass();
144 $a->groupname = groups_get_group_name($currentgroup);
145 $a->coursestudents = get_string('participants');
146 $a->countregradeneeded = $regradesneeded;
147 $regradealldrydolabel =
148 get_string('regradealldrydogroup', 'quiz_overview', $a);
149 $regradealldrylabel =
150 get_string('regradealldrygroup', 'quiz_overview', $a);
151 $regradealllabel =
152 get_string('regradeallgroup', 'quiz_overview', $a);
153 } else {
154 $regradealldrydolabel =
155 get_string('regradealldrydo', 'quiz_overview', $regradesneeded);
156 $regradealldrylabel =
157 get_string('regradealldry', 'quiz_overview');
158 $regradealllabel =
159 get_string('regradeall', 'quiz_overview');
161 $displayurl = new moodle_url($options->get_url(), ['sesskey' => sesskey()]);
162 echo '<div class="regradebuttons">';
163 echo '<form action="'.$displayurl->out_omit_querystring().'">';
164 echo '<div>';
165 echo html_writer::input_hidden_params($displayurl);
166 echo '<input type="submit" class="btn btn-secondary" name="regradeall" value="'.$regradealllabel.'"/>';
167 echo '<input type="submit" class="btn btn-secondary ml-1" name="regradealldry" value="' .
168 $regradealldrylabel . '"/>';
169 if ($regradesneeded) {
170 echo '<input type="submit" class="btn btn-secondary ml-1" name="regradealldrydo" value="' .
171 $regradealldrydolabel . '"/>';
173 echo '</div>';
174 echo '</form>';
175 echo '</div>';
177 // Print information on the grading method.
178 if ($strattempthighlight = quiz_report_highlighting_grading_method(
179 $quiz, $this->qmsubselect, $options->onlygraded)) {
180 echo '<div class="quizattemptcounts mt-3">' . $strattempthighlight . '</div>';
184 // Define table columns.
185 $columns = [];
186 $headers = [];
188 if (!$table->is_downloading() && $options->checkboxcolumn) {
189 $columnname = 'checkbox';
190 $columns[] = $columnname;
191 $headers[] = $table->checkbox_col_header($columnname);
194 $this->add_user_columns($table, $columns, $headers);
195 $this->add_state_column($columns, $headers);
196 $this->add_time_columns($columns, $headers);
198 $this->add_grade_columns($quiz, $options->usercanseegrades, $columns, $headers, false);
200 if (!$table->is_downloading() && has_capability('mod/quiz:regrade', $this->context) &&
201 $this->has_regraded_questions($table->sql->from, $table->sql->where, $table->sql->params)) {
202 $columns[] = 'regraded';
203 $headers[] = get_string('regrade', 'quiz_overview');
206 if ($options->slotmarks) {
207 foreach ($questions as $slot => $question) {
208 $columns[] = 'qsgrade' . $slot;
209 $header = get_string('qbrief', 'quiz', $question->number);
210 if (!$table->is_downloading()) {
211 $header .= '<br />';
212 } else {
213 $header .= ' ';
215 $header .= '/' . quiz_rescale_grade($question->maxmark, $quiz, 'question');
216 $headers[] = $header;
220 $this->set_up_table_columns($table, $columns, $headers, $this->get_base_url(), $options, false);
221 $table->set_attribute('class', 'generaltable generalbox grades');
223 $table->out($options->pagesize, true);
226 if (!$table->is_downloading() && $options->usercanseegrades) {
227 $output = $PAGE->get_renderer('mod_quiz');
228 list($bands, $bandwidth) = self::get_bands_count_and_width($quiz);
229 $labels = self::get_bands_labels($bands, $bandwidth, $quiz);
231 if ($currentgroup && $this->hasgroupstudents) {
232 $sql = "SELECT qg.id
233 FROM {quiz_grades} qg
234 JOIN {user} u on u.id = qg.userid
235 {$groupstudentsjoins->joins}
236 WHERE qg.quiz = $quiz->id AND {$groupstudentsjoins->wheres}";
237 if ($DB->record_exists_sql($sql, $groupstudentsjoins->params)) {
238 $data = quiz_report_grade_bands($bandwidth, $bands, $quiz->id, $groupstudentsjoins);
239 $chart = self::get_chart($labels, $data);
240 $graphname = get_string('overviewreportgraphgroup', 'quiz_overview', groups_get_group_name($currentgroup));
241 // Numerical range data should display in LTR even for RTL languages.
242 echo $output->chart($chart, $graphname, ['dir' => 'ltr']);
246 if ($DB->record_exists('quiz_grades', ['quiz' => $quiz->id])) {
247 $data = quiz_report_grade_bands($bandwidth, $bands, $quiz->id, new \core\dml\sql_join());
248 $chart = self::get_chart($labels, $data);
249 $graphname = get_string('overviewreportgraph', 'quiz_overview');
250 // Numerical range data should display in LTR even for RTL languages.
251 echo $output->chart($chart, $graphname, ['dir' => 'ltr']);
254 return true;
258 * Extends parent function processing any submitted actions.
260 * @param stdClass $quiz
261 * @param stdClass $cm
262 * @param int $currentgroup
263 * @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params)
264 * @param \core\dml\sql_join $allowedjoins (joins, wheres, params)
265 * @param moodle_url $redirecturl
267 protected function process_actions($quiz, $cm, $currentgroup, \core\dml\sql_join $groupstudentsjoins,
268 \core\dml\sql_join $allowedjoins, $redirecturl) {
269 parent::process_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $allowedjoins, $redirecturl);
271 if (empty($currentgroup) || $this->hasgroupstudents) {
272 if (optional_param('regrade', 0, PARAM_BOOL) && confirm_sesskey()) {
273 if ($attemptids = optional_param_array('attemptid', [], PARAM_INT)) {
274 $this->start_regrade($quiz, $cm);
275 $this->regrade_attempts($quiz, false, $groupstudentsjoins, $attemptids);
276 $this->finish_regrade($redirecturl);
281 if (optional_param('regradeall', 0, PARAM_BOOL) && confirm_sesskey()) {
282 $this->start_regrade($quiz, $cm);
283 $this->regrade_attempts($quiz, false, $groupstudentsjoins);
284 $this->finish_regrade($redirecturl);
286 } else if (optional_param('regradealldry', 0, PARAM_BOOL) && confirm_sesskey()) {
287 $this->start_regrade($quiz, $cm);
288 $this->regrade_attempts($quiz, true, $groupstudentsjoins);
289 $this->finish_regrade($redirecturl);
291 } else if (optional_param('regradealldrydo', 0, PARAM_BOOL) && confirm_sesskey()) {
292 $this->start_regrade($quiz, $cm);
293 $this->regrade_attempts_needing_it($quiz, $groupstudentsjoins);
294 $this->finish_regrade($redirecturl);
299 * Check necessary capabilities, and start the display of the regrade progress page.
300 * @param stdClass $quiz the quiz settings.
301 * @param stdClass $cm the cm object for the quiz.
303 protected function start_regrade($quiz, $cm) {
304 require_capability('mod/quiz:regrade', $this->context);
305 $this->print_header_and_tabs($cm, $this->course, $quiz, $this->mode);
309 * Finish displaying the regrade progress page.
310 * @param moodle_url $nexturl where to send the user after the regrade.
311 * @uses exit. This method never returns.
313 protected function finish_regrade($nexturl) {
314 global $OUTPUT;
315 \core\notification::success(get_string('regradecomplete', 'quiz_overview'));
316 echo $OUTPUT->continue_button($nexturl);
317 echo $OUTPUT->footer();
318 die();
322 * Unlock the session and allow the regrading process to run in the background.
324 protected function unlock_session() {
325 \core\session\manager::write_close();
326 ignore_user_abort(true);
330 * Regrade a particular quiz attempt. Either for real ($dryrun = false), or
331 * as a pretend regrade to see which fractions would change. The outcome is
332 * stored in the quiz_overview_regrades table.
334 * Note, $attempt is not upgraded in the database. The caller needs to do that.
335 * However, $attempt->sumgrades is updated, if this is not a dry run.
337 * @param stdClass $attempt the quiz attempt to regrade.
338 * @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
339 * @param array $slots if null, regrade all questions, otherwise, just regrade
340 * the questions with those slots.
341 * @return array messages array with keys slot number, and values reasons why that slot cannot be regraded.
343 public function regrade_attempt($attempt, $dryrun = false, $slots = null): array {
344 global $DB;
345 // Need more time for a quiz with many questions.
346 core_php_time_limit::raise(300);
348 $transaction = $DB->start_delegated_transaction();
350 $quba = question_engine::load_questions_usage_by_activity($attempt->uniqueid);
352 if (is_null($slots)) {
353 $slots = $quba->get_slots();
356 $messages = [];
357 $finished = $attempt->state == quiz_attempt::FINISHED;
358 foreach ($slots as $slot) {
359 $qqr = new stdClass();
360 $qqr->oldfraction = $quba->get_question_fraction($slot);
361 $otherquestionversion = $this->get_new_question_for_regrade($attempt, $quba, $slot);
363 $message = $quba->validate_can_regrade_with_other_version($slot, $otherquestionversion);
364 if ($message) {
365 $messages[$slot] = $message;
366 continue;
369 $quba->regrade_question($slot, $finished, null, $otherquestionversion);
371 $qqr->newfraction = $quba->get_question_fraction($slot);
373 if (abs($qqr->oldfraction - $qqr->newfraction) > 1e-7) {
374 $qqr->questionusageid = $quba->get_id();
375 $qqr->slot = $slot;
376 $qqr->regraded = empty($dryrun);
377 $qqr->timemodified = time();
378 $DB->insert_record('quiz_overview_regrades', $qqr, false);
382 if (!$dryrun) {
383 question_engine::save_questions_usage_by_activity($quba);
385 $params = [
386 'objectid' => $attempt->id,
387 'relateduserid' => $attempt->userid,
388 'context' => $this->context,
389 'other' => [
390 'quizid' => $attempt->quiz
393 $event = \mod_quiz\event\attempt_regraded::create($params);
394 $event->trigger();
397 $transaction->allow_commit();
399 // Really, PHP should not need this hint, but without this, we just run out of memory.
400 $quba = null;
401 $transaction = null;
402 gc_collect_cycles();
403 return $messages;
407 * For use in tests only. Clear the cached regrade data.
409 public function clear_regrade_date_cache(): void {
410 $this->structureforregrade = null;
411 $this->newquestionidsforold = null;
415 * Work out of we should be using a new question version for a particular slot in a regrade.
417 * @param stdClass $attempt the attempt being regraded.
418 * @param question_usage_by_activity $quba the question_usage corresponding to that.
419 * @param int $slot which slot is currently being regraded.
420 * @return question_definition other question version to use for this slot.
422 protected function get_new_question_for_regrade(stdClass $attempt,
423 question_usage_by_activity $quba, int $slot): question_definition {
425 // If the cache is empty, get information about all the slots.
426 if ($this->structureforregrade === null) {
427 $this->newquestionidsforold = [];
428 // Load the data about all the non-random slots now.
429 $this->structureforregrade = qbank_helper::get_question_structure(
430 $attempt->quiz, $this->context);
433 // Because of 'Redo question in attempt' feature, we need to find the original slot number.
434 $originalslot = $quba->get_question_attempt_metadata($slot, 'originalslot') ?? $slot;
436 // If this is a non-random slot, we will have the right info cached.
437 if ($this->structureforregrade[$originalslot]->qtype != 'random') {
438 // This is a non-random slot.
439 return question_bank::load_question($this->structureforregrade[$originalslot]->questionid);
442 // We must be dealing with a random question. Check that cache.
443 $currentquestion = $quba->get_question_attempt($originalslot)->get_question(false);
444 if (isset($this->newquestionidsforold[$currentquestion->id])) {
445 return question_bank::load_question($this->newquestionidsforold[$currentquestion->id]);
448 // This is a random question we have not seen yet. Find the latest version.
449 $versionsoptions = qbank_helper::get_version_options($currentquestion->id);
450 $latestversion = reset($versionsoptions);
451 $this->newquestionidsforold[$currentquestion->id] = $latestversion->questionid;
452 return question_bank::load_question($latestversion->questionid);
456 * Regrade attempts for this quiz, exactly which attempts are regraded is
457 * controlled by the parameters.
459 * @param stdClass $quiz the quiz settings.
460 * @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
461 * @param \core\dml\sql_join|null $groupstudentsjoins empty for all attempts, otherwise regrade attempts
462 * for these users.
463 * @param array $attemptids blank for all attempts, otherwise only regrade
464 * attempts whose id is in this list.
466 protected function regrade_attempts($quiz, $dryrun = false,
467 core\dml\sql_join $groupstudentsjoins = null, $attemptids = []) {
468 global $DB;
469 $this->unlock_session();
471 $userfieldsapi = \core_user\fields::for_name();
472 $sql = "SELECT quiza.*, " . $userfieldsapi->get_sql('u', false, '', '', false)->selects . "
473 FROM {quiz_attempts} quiza
474 JOIN {user} u ON u.id = quiza.userid";
475 $where = "quiz = :qid AND preview = 0";
476 $params = ['qid' => $quiz->id];
478 if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
479 $sql .= "\n{$groupstudentsjoins->joins}";
480 $where .= " AND {$groupstudentsjoins->wheres}";
481 $params += $groupstudentsjoins->params;
484 if ($attemptids) {
485 list($attemptidcondition, $attemptidparams) = $DB->get_in_or_equal($attemptids, SQL_PARAMS_NAMED);
486 $where .= " AND quiza.id $attemptidcondition";
487 $params += $attemptidparams;
490 $sql .= "\nWHERE {$where}";
491 $attempts = $DB->get_records_sql($sql, $params);
492 if (!$attempts) {
493 return;
496 $this->regrade_batch_of_attempts($quiz, $attempts, $dryrun, $groupstudentsjoins);
500 * Regrade those questions in those attempts that are marked as needing regrading
501 * in the quiz_overview_regrades table.
502 * @param stdClass $quiz the quiz settings.
503 * @param \core\dml\sql_join $groupstudentsjoins empty for all attempts, otherwise regrade attempts
504 * for these users.
506 protected function regrade_attempts_needing_it($quiz, \core\dml\sql_join $groupstudentsjoins) {
507 global $DB;
508 $this->unlock_session();
510 $join = '{quiz_overview_regrades} qqr ON qqr.questionusageid = quiza.uniqueid';
511 $where = "quiza.quiz = :qid AND quiza.preview = 0 AND qqr.regraded = 0";
512 $params = ['qid' => $quiz->id];
514 // Fetch all attempts that need regrading.
515 if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
516 $join .= "\nJOIN {user} u ON u.id = quiza.userid
517 {$groupstudentsjoins->joins}";
518 $where .= " AND {$groupstudentsjoins->wheres}";
519 $params += $groupstudentsjoins->params;
522 $toregrade = $DB->get_recordset_sql("
523 SELECT quiza.uniqueid, qqr.slot
524 FROM {quiz_attempts} quiza
525 JOIN $join
526 WHERE $where", $params);
528 $attemptquestions = [];
529 foreach ($toregrade as $row) {
530 $attemptquestions[$row->uniqueid][] = $row->slot;
532 $toregrade->close();
534 if (!$attemptquestions) {
535 return;
538 list($uniqueidcondition, $params) = $DB->get_in_or_equal(array_keys($attemptquestions));
539 $userfieldsapi = \core_user\fields::for_name();
540 $attempts = $DB->get_records_sql("
541 SELECT quiza.*, " . $userfieldsapi->get_sql('u', false, '', '', false)->selects . "
542 FROM {quiz_attempts} quiza
543 JOIN {user} u ON u.id = quiza.userid
544 WHERE quiza.uniqueid $uniqueidcondition
545 ", $params);
547 foreach ($attempts as $attempt) {
548 $attempt->regradeonlyslots = $attemptquestions[$attempt->uniqueid];
551 $this->regrade_batch_of_attempts($quiz, $attempts, false, $groupstudentsjoins);
555 * This is a helper used by {@link regrade_attempts()} and
556 * {@link regrade_attempts_needing_it()}.
558 * Given an array of attempts, it regrades them all, or does a dry run.
559 * Each object in the attempts array must be a row from the quiz_attempts
560 * table, with the \core_user\fields::for_name() fields from the user table joined in.
561 * In addition, if $attempt->regradeonlyslots is set, then only those slots
562 * are regraded, otherwise all slots are regraded.
564 * @param stdClass $quiz the quiz settings.
565 * @param array $attempts of data from the quiz_attempts table, with extra data as above.
566 * @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
567 * @param \core\dml\sql_join $groupstudentsjoins empty for all attempts, otherwise regrade attempts
569 protected function regrade_batch_of_attempts($quiz, array $attempts,
570 bool $dryrun, \core\dml\sql_join $groupstudentsjoins) {
571 global $OUTPUT;
572 $this->clear_regrade_table($quiz, $groupstudentsjoins);
574 $progressbar = new progress_bar('quiz_overview_regrade', 500, true);
575 $a = [
576 'count' => count($attempts),
577 'done' => 0,
579 foreach ($attempts as $attempt) {
580 $a['done']++;
581 $a['attemptnum'] = $attempt->attempt;
582 $a['name'] = fullname($attempt);
583 $a['attemptid'] = $attempt->id;
584 if (!isset($attempt->regradeonlyslots)) {
585 $attempt->regradeonlyslots = null;
587 $progressbar->update($a['done'], $a['count'],
588 get_string('regradingattemptxofywithdetails', 'quiz_overview', $a));
589 $messages = $this->regrade_attempt($attempt, $dryrun, $attempt->regradeonlyslots);
590 if ($messages) {
591 $items = [];
592 foreach ($messages as $slot => $message) {
593 $items[] = get_string('regradingattemptissue', 'quiz_overview',
594 ['slot' => $slot, 'reason' => $message]);
596 echo $OUTPUT->notification(
597 html_writer::tag('p', get_string('regradingattemptxofyproblem', 'quiz_overview', $a)) .
598 html_writer::alist($items), \core\output\notification::NOTIFY_WARNING);
601 $progressbar->update($a['done'], $a['count'],
602 get_string('regradedsuccessfullyxofy', 'quiz_overview', $a));
604 if (!$dryrun) {
605 $this->update_overall_grades($quiz);
610 * Count the number of attempts in need of a regrade.
612 * @param stdClass $quiz the quiz settings.
613 * @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params) If this is given, only data relating
614 * to these users is cleared.
615 * @return int the number of attempts.
617 protected function count_question_attempts_needing_regrade($quiz, \core\dml\sql_join $groupstudentsjoins) {
618 global $DB;
620 $userjoin = '';
621 $usertest = '';
622 $params = [];
623 if ($this->hasgroupstudents) {
624 $userjoin = "JOIN {user} u ON u.id = quiza.userid
625 {$groupstudentsjoins->joins}";
626 $usertest = "{$groupstudentsjoins->wheres} AND u.id = quiza.userid AND ";
627 $params = $groupstudentsjoins->params;
630 $params['cquiz'] = $quiz->id;
631 $sql = "SELECT COUNT(DISTINCT quiza.id)
632 FROM {quiz_attempts} quiza
633 JOIN {quiz_overview_regrades} qqr ON quiza.uniqueid = qqr.questionusageid
634 $userjoin
635 WHERE
636 $usertest
637 quiza.quiz = :cquiz AND
638 quiza.preview = 0 AND
639 qqr.regraded = 0";
640 return $DB->count_records_sql($sql, $params);
644 * Are there any pending regrades in the table we are going to show?
645 * @param string $from tables used by the main query.
646 * @param string $where where clause used by the main query.
647 * @param array $params required by the SQL.
648 * @return bool whether there are pending regrades.
650 protected function has_regraded_questions($from, $where, $params) {
651 global $DB;
652 return $DB->record_exists_sql("
653 SELECT 1
654 FROM {$from}
655 JOIN {quiz_overview_regrades} qor ON qor.questionusageid = quiza.uniqueid
656 WHERE {$where}", $params);
660 * Remove all information about pending/complete regrades from the database.
661 * @param stdClass $quiz the quiz settings.
662 * @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params). If this is given, only data relating
663 * to these users is cleared.
665 protected function clear_regrade_table($quiz, \core\dml\sql_join $groupstudentsjoins) {
666 global $DB;
668 // Fetch all attempts that need regrading.
669 $select = "questionusageid IN (
670 SELECT uniqueid
671 FROM {quiz_attempts} quiza";
672 $where = "WHERE quiza.quiz = :qid";
673 $params = ['qid' => $quiz->id];
674 if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
675 $select .= "\nJOIN {user} u ON u.id = quiza.userid
676 {$groupstudentsjoins->joins}";
677 $where .= " AND {$groupstudentsjoins->wheres}";
678 $params += $groupstudentsjoins->params;
680 $select .= "\n$where)";
682 $DB->delete_records_select('quiz_overview_regrades', $select, $params);
686 * Update the final grades for all attempts. This method is used following a regrade.
688 * @param stdClass $quiz the quiz settings.
690 protected function update_overall_grades($quiz) {
691 $gradecalculator = $this->quizobj->get_grade_calculator();
692 $gradecalculator->recompute_all_attempt_sumgrades();
693 $gradecalculator->recompute_all_final_grades();
694 quiz_update_grades($quiz);
698 * Get the bands configuration for the quiz.
700 * This returns the configuration for having between 11 and 20 bars in
701 * a chart based on the maximum grade to be given on a quiz. The width of
702 * a band is the number of grade points it encapsulates.
704 * @param stdClass $quiz The quiz object.
705 * @return array Contains the number of bands, and their width.
707 public static function get_bands_count_and_width($quiz) {
708 $bands = $quiz->grade;
709 while ($bands > 20 || $bands <= 10) {
710 if ($bands > 50) {
711 $bands /= 5;
712 } else if ($bands > 20) {
713 $bands /= 2;
715 if ($bands < 4) {
716 $bands *= 5;
717 } else if ($bands <= 10) {
718 $bands *= 2;
721 // See MDL-34589. Using doubles as array keys causes problems in PHP 5.4, hence the explicit cast to int.
722 $bands = (int) ceil($bands);
723 return [$bands, $quiz->grade / $bands];
727 * Get the bands labels.
729 * @param int $bands The number of bands.
730 * @param int $bandwidth The band width.
731 * @param stdClass $quiz The quiz object.
732 * @return string[] The labels.
734 public static function get_bands_labels($bands, $bandwidth, $quiz) {
735 $bandlabels = [];
736 for ($i = 1; $i <= $bands; $i++) {
737 $bandlabels[] = quiz_format_grade($quiz, ($i - 1) * $bandwidth) . ' - ' . quiz_format_grade($quiz, $i * $bandwidth);
739 return $bandlabels;
743 * Get a chart.
745 * @param string[] $labels Chart labels.
746 * @param int[] $data The data.
747 * @return \core\chart_base
749 protected static function get_chart($labels, $data) {
750 $chart = new \core\chart_bar();
751 $chart->set_labels($labels);
752 $chart->get_xaxis(0, true)->set_label(get_string('gradenoun'));
754 $yaxis = $chart->get_yaxis(0, true);
755 $yaxis->set_label(get_string('participants'));
756 $yaxis->set_stepsize(max(1, round(max($data) / 10)));
758 $series = new \core\chart_series(get_string('participants'), $data);
759 $chart->add_series($series);
760 return $chart;