MDL-74610 quiz: fix grade items query for MySQL
[moodle.git] / mod / quiz / classes / local / reports / attempts_report_table.php
blobcff272963121b636799c0a74e097be66eb3b8def
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 namespace mod_quiz\local\reports;
19 defined('MOODLE_INTERNAL') || die();
21 require_once($CFG->libdir.'/tablelib.php');
23 use coding_exception;
24 use context_module;
25 use html_writer;
26 use mod_quiz\quiz_attempt;
27 use mod_quiz\quiz_settings;
28 use moodle_url;
29 use popup_action;
30 use question_state;
31 use qubaid_condition;
32 use qubaid_join;
33 use qubaid_list;
34 use question_engine_data_mapper;
35 use stdClass;
37 /**
38 * Base class for the table used by a {@see attempts_report}.
40 * @package mod_quiz
41 * @copyright 2010 The Open University
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 abstract class attempts_report_table extends \table_sql {
45 public $useridfield = 'userid';
47 /** @var moodle_url the URL of this report. */
48 protected $reporturl;
50 /** @var array the display options. */
51 protected $displayoptions;
53 /**
54 * @var array information about the latest step of each question.
55 * Loaded by {@see load_question_latest_steps()}, if applicable.
57 protected $lateststeps = null;
59 /**
60 * @var float[][]|null total mark for each grade item. Array question_usage.id => quiz_grade_item.id => mark.
61 * Loaded by {@see load_grade_item_marks()}, if applicable.
63 protected ?array $gradeitemtotals = null;
65 /** @var stdClass the quiz settings for the quiz we are reporting on. */
66 protected $quiz;
68 /** @var quiz_settings quiz settings object for this quiz. Gets set in {@see attempts_report::et_up_table_columns()}. */
69 protected quiz_settings $quizobj;
71 /** @var context_module the quiz context. */
72 protected $context;
74 /** @var string HTML fragment to select the first/best/last attempt, if appropriate. */
75 protected $qmsubselect;
77 /** @var stdClass attempts_report_options the options affecting this report. */
78 protected $options;
80 /** @var \core\dml\sql_join Contains joins, wheres, params to find students
81 * in the currently selected group, if applicable.
83 protected $groupstudentsjoins;
85 /** @var \core\dml\sql_join Contains joins, wheres, params to find the students in the course. */
86 protected $studentsjoins;
88 /** @var array the questions that comprise this quiz. */
89 protected $questions;
91 /** @var bool whether to include the column with checkboxes to select each attempt. */
92 protected $includecheckboxes;
94 /** @var string The toggle group name for the checkboxes in the checkbox column. */
95 protected $togglegroup = 'quiz-attempts';
97 /** @var string strftime format. */
98 protected $strtimeformat;
100 /** @var bool|null used by {@see col_state()} to cache the has_capability result. */
101 protected $canreopen = null;
104 * Constructor.
106 * @param string $uniqueid
107 * @param stdClass $quiz
108 * @param context_module $context
109 * @param string $qmsubselect
110 * @param attempts_report_options $options
111 * @param \core\dml\sql_join $groupstudentsjoins Contains joins, wheres, params
112 * @param \core\dml\sql_join $studentsjoins Contains joins, wheres, params
113 * @param array $questions
114 * @param moodle_url $reporturl
116 public function __construct($uniqueid, $quiz, $context, $qmsubselect,
117 attempts_report_options $options, \core\dml\sql_join $groupstudentsjoins, \core\dml\sql_join $studentsjoins,
118 $questions, $reporturl) {
119 parent::__construct($uniqueid);
120 $this->quiz = $quiz;
121 $this->context = $context;
122 $this->qmsubselect = $qmsubselect;
123 $this->groupstudentsjoins = $groupstudentsjoins;
124 $this->studentsjoins = $studentsjoins;
125 $this->questions = $questions;
126 $this->includecheckboxes = $options->checkboxcolumn;
127 $this->reporturl = $reporturl;
128 $this->options = $options;
132 * A way for the report to pass in the quiz settings object. Currently done in {@see attempts_report::set_up_table_columns()}.
134 * @param quiz_settings $quizobj
136 public function set_quiz_setting(quiz_settings $quizobj): void {
137 $this->quizobj = $quizobj;
141 * Generate the display of the checkbox column.
143 * @param stdClass $attempt the table row being output.
144 * @return string HTML content to go inside the td.
146 public function col_checkbox($attempt) {
147 global $OUTPUT;
149 if ($attempt->attempt) {
150 $checkbox = new \core\output\checkbox_toggleall($this->togglegroup, false, [
151 'id' => "attemptid_{$attempt->attempt}",
152 'name' => 'attemptid[]',
153 'value' => $attempt->attempt,
154 'label' => get_string('selectattempt', 'quiz'),
155 'labelclasses' => 'accesshide',
157 return $OUTPUT->render($checkbox);
158 } else {
159 return '';
164 * Generate the display of the user's picture column.
166 * @param stdClass $attempt the table row being output.
167 * @return string HTML content to go inside the td.
169 public function col_picture($attempt) {
170 global $OUTPUT;
171 $user = new stdClass();
172 $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
173 $user = username_load_fields_from_object($user, $attempt, null, $additionalfields);
174 $user->id = $attempt->userid;
175 return $OUTPUT->user_picture($user);
179 * Generate the display of the user's full name column.
181 * @param stdClass $attempt the table row being output.
182 * @return string HTML content to go inside the td.
184 public function col_fullname($attempt) {
185 $html = parent::col_fullname($attempt);
186 if ($this->is_downloading() || empty($attempt->attempt)) {
187 return $html;
190 return $html . html_writer::empty_tag('br') . html_writer::link(
191 new moodle_url('/mod/quiz/review.php', ['attempt' => $attempt->attempt]),
192 get_string('reviewattempt', 'quiz'), ['class' => 'reviewlink']);
196 * Generate the display of the attempt state column.
198 * @param stdClass $attempt the table row being output.
199 * @return string HTML content to go inside the td.
201 public function col_state($attempt) {
202 if (is_null($attempt->attempt)) {
203 return '-';
206 $display = quiz_attempt::state_name($attempt->state);
207 if ($this->is_downloading()) {
208 return $display;
211 $this->canreopen ??= has_capability('mod/quiz:reopenattempts', $this->context);
212 if ($attempt->state == quiz_attempt::ABANDONED && $this->canreopen) {
213 $display .= ' ' . html_writer::tag('button', get_string('reopenattempt', 'quiz'), [
214 'type' => 'button',
215 'class' => 'btn btn-secondary',
216 'data-action' => 'reopen-attempt',
217 'data-attempt-id' => $attempt->attempt,
218 'data-after-action-url' => $this->reporturl->out_as_local_url(false),
222 return $display;
226 * Generate the display of the start time column.
228 * @param stdClass $attempt the table row being output.
229 * @return string HTML content to go inside the td.
231 public function col_timestart($attempt) {
232 if ($attempt->attempt) {
233 return userdate($attempt->timestart, $this->strtimeformat);
234 } else {
235 return '-';
240 * Generate the display of the finish time column.
242 * @param stdClass $attempt the table row being output.
243 * @return string HTML content to go inside the td.
245 public function col_timefinish($attempt) {
246 if ($attempt->attempt && $attempt->timefinish) {
247 return userdate($attempt->timefinish, $this->strtimeformat);
248 } else {
249 return '-';
254 * Generate the display of the duration column.
256 * @param stdClass $attempt the table row being output.
257 * @return string HTML content to go inside the td.
259 public function col_duration($attempt) {
260 if ($attempt->timefinish) {
261 return format_time($attempt->timefinish - $attempt->timestart);
262 } else {
263 return '-';
268 * Generate the display of the feedback column.
270 * @param stdClass $attempt the table row being output.
271 * @return string HTML content to go inside the td.
273 public function col_feedbacktext($attempt) {
274 if ($attempt->state != quiz_attempt::FINISHED) {
275 return '-';
278 $feedback = quiz_report_feedback_for_grade(
279 quiz_rescale_grade($attempt->sumgrades, $this->quiz, false),
280 $this->quiz->id, $this->context);
282 if ($this->is_downloading()) {
283 $feedback = strip_tags($feedback);
286 return $feedback;
289 public function other_cols($colname, $attempt) {
290 $gradeitemid = $this->is_grade_item_column($colname);
292 if (!$gradeitemid) {
293 return parent::other_cols($colname, $attempt);
295 if (isset($this->gradeitemtotals[$attempt->usageid][$gradeitemid])) {
296 $grade = quiz_format_grade($this->quiz, $this->gradeitemtotals[$attempt->usageid][$gradeitemid]);
297 return $grade;
298 } else {
299 return '-';
304 * Is this the column key for an extra grade item column?
306 * @param string $columnname e.g. 'marks123' or 'duration'.
307 * @return int grade item id if this is a column for showing that grade item grade, else, 0.
309 protected function is_grade_item_column(string $columnname): int {
310 if (preg_match('/^marks(\d+)$/', $columnname, $matches)) {
311 return $matches[1];
313 return 0;
316 public function get_row_class($attempt) {
317 if ($this->qmsubselect && $attempt->gradedattempt) {
318 return 'gradedattempt';
319 } else {
320 return '';
325 * Make a link to review an individual question in a popup window.
327 * @param string $data HTML fragment. The text to make into the link.
328 * @param stdClass $attempt data for the row of the table being output.
329 * @param int $slot the number used to identify this question within this usage.
331 public function make_review_link($data, $attempt, $slot) {
332 global $OUTPUT, $CFG;
334 $flag = '';
335 if ($this->is_flagged($attempt->usageid, $slot)) {
336 $flag = $OUTPUT->pix_icon('i/flagged', get_string('flagged', 'question'),
337 'moodle', ['class' => 'questionflag']);
340 $feedbackimg = '';
341 $state = $this->slot_state($attempt, $slot);
342 if ($state && $state->is_finished() && $state != question_state::$needsgrading) {
343 $feedbackimg = $this->icon_for_fraction($this->slot_fraction($attempt, $slot));
346 $output = html_writer::tag('span', $feedbackimg . html_writer::tag('span',
347 $data, ['class' => $state->get_state_class(true)]) . $flag, ['class' => 'que']);
349 $reviewparams = ['attempt' => $attempt->attempt, 'slot' => $slot];
350 if (isset($attempt->try)) {
351 $reviewparams['step'] = $this->step_no_for_try($attempt->usageid, $slot, $attempt->try);
353 $url = new moodle_url('/mod/quiz/reviewquestion.php', $reviewparams);
354 $output = $OUTPUT->action_link($url, $output,
355 new popup_action('click', $url, 'reviewquestion',
356 ['height' => 450, 'width' => 650]),
357 ['title' => get_string('reviewresponse', 'quiz')]);
359 if (!empty($CFG->enableplagiarism)) {
360 require_once($CFG->libdir . '/plagiarismlib.php');
361 $output .= plagiarism_get_links([
362 'context' => $this->context->id,
363 'component' => 'qtype_'.$this->questions[$slot]->qtype,
364 'cmid' => $this->context->instanceid,
365 'area' => $attempt->usageid,
366 'itemid' => $slot,
367 'userid' => $attempt->userid]);
369 return $output;
373 * Get the question attempt state for a particular question in a particular quiz attempt.
375 * @param stdClass $attempt the row data.
376 * @param int $slot indicates which question.
377 * @return question_state the state of that question.
379 protected function slot_state($attempt, $slot) {
380 $stepdata = $this->lateststeps[$attempt->usageid][$slot];
381 return question_state::get($stepdata->state);
385 * Work out if a particular question in a particular attempt has been flagged.
387 * @param int $questionusageid used to identify the attempt of interest.
388 * @param int $slot identifies which question in the attempt to check.
389 * @return bool true if the question is flagged in the attempt.
391 protected function is_flagged($questionusageid, $slot) {
392 $stepdata = $this->lateststeps[$questionusageid][$slot];
393 return $stepdata->flagged;
397 * Get the mark (out of 1) for the question in a particular slot.
399 * @param stdClass $attempt the row data
400 * @param int $slot which slot to check.
401 * @return float the score for this question on a scale of 0 - 1.
403 protected function slot_fraction($attempt, $slot) {
404 $stepdata = $this->lateststeps[$attempt->usageid][$slot];
405 return $stepdata->fraction;
409 * Return an appropriate icon (green tick, red cross, etc.) for a grade.
411 * @param float $fraction grade on a scale 0..1.
412 * @return string html fragment.
414 protected function icon_for_fraction($fraction) {
415 global $OUTPUT;
417 $feedbackclass = question_state::graded_state_for_fraction($fraction)->get_feedback_class();
418 return $OUTPUT->pix_icon('i/grade_' . $feedbackclass, get_string($feedbackclass, 'question'),
419 'moodle', ['class' => 'icon']);
423 * Load any extra data after main query.
425 * At this point you can call {@see get_qubaids_condition} to get the condition
426 * that limits the query to just the question usages shown in this report page or
427 * alternatively for all attempts if downloading a full report.
429 protected function load_extra_data() {
430 $this->lateststeps = $this->load_question_latest_steps();
434 * Load the total mark for each grade item for each attempt.
436 protected function load_grade_item_marks(): void {
437 if (count($this->rawdata) === 0) {
438 $this->gradeitemtotals = [];
439 return;
442 $this->gradeitemtotals = $this->quizobj->get_grade_calculator()->load_grade_item_totals(
443 $this->get_qubaids_condition());
447 * Load information about the latest state of selected questions in selected attempts.
449 * The results are returned as a two-dimensional array $qubaid => $slot => $dataobject.
451 * @param qubaid_condition|null $qubaids used to restrict which usages are included
452 * in the query. See {@see qubaid_condition}.
453 * @return array of records. See the SQL in this function to see the fields available.
455 protected function load_question_latest_steps(qubaid_condition $qubaids = null) {
456 if ($qubaids === null) {
457 $qubaids = $this->get_qubaids_condition();
459 $dm = new question_engine_data_mapper();
460 $latesstepdata = $dm->load_questions_usages_latest_steps(
461 $qubaids, array_keys($this->questions));
463 $lateststeps = [];
464 foreach ($latesstepdata as $step) {
465 $lateststeps[$step->questionusageid][$step->slot] = $step;
468 return $lateststeps;
472 * Does this report require loading any more data after the main query.
474 * @return bool should {@see query_db()} call {@see load_extra_data}?
476 protected function requires_extra_data() {
477 return $this->requires_latest_steps_loaded();
481 * Does this report require the detailed information for each question from the question_attempts_steps table?
483 * @return bool should {@see load_extra_data} call {@see load_question_latest_steps}?
485 protected function requires_latest_steps_loaded() {
486 return false;
490 * Is this a column that depends on joining to the latest state information?
492 * If so, return the corresponding slot. If not, return false.
494 * @param string $column a column name
495 * @return int|false false if no, else a slot.
497 protected function is_latest_step_column($column) {
498 return false;
502 * Get any fields that might be needed when sorting on date for a particular slot.
504 * Note: these values are only used for sorting. The values displayed are taken
505 * from $this->lateststeps loaded in load_extra_data().
507 * @param int $slot the slot for the column we want.
508 * @param string $alias the table alias for latest state information relating to that slot.
509 * @return string definitions of extra fields to add to the SELECT list of the query.
511 protected function get_required_latest_state_fields($slot, $alias) {
512 return '';
516 * Contruct all the parts of the main database query.
518 * @param \core\dml\sql_join $allowedstudentsjoins (joins, wheres, params) defines allowed users for the report.
519 * @return array with 4 elements [$fields, $from, $where, $params] that can be used to
520 * build the actual database query.
522 public function base_sql(\core\dml\sql_join $allowedstudentsjoins) {
523 global $DB;
525 // Please note this uniqueid column is not the same as quiza.uniqueid.
526 $fields = 'DISTINCT ' . $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid,';
528 if ($this->qmsubselect) {
529 $fields .= "\n(CASE WHEN $this->qmsubselect THEN 1 ELSE 0 END) AS gradedattempt,";
532 $userfieldsapi = \core_user\fields::for_identity($this->context)->with_name()
533 ->excluding('id', 'idnumber', 'picture', 'imagealt', 'institution', 'department', 'email');
534 $userfields = $userfieldsapi->get_sql('u', true, '', '', false);
536 $fields .= '
537 quiza.uniqueid AS usageid,
538 quiza.id AS attempt,
539 u.id AS userid,
540 u.idnumber,
541 u.picture,
542 u.imagealt,
543 u.institution,
544 u.department,
545 u.email,' . $userfields->selects . ',
546 quiza.state,
547 quiza.sumgrades,
548 quiza.timefinish,
549 quiza.timestart,
550 CASE WHEN quiza.timefinish = 0 THEN null
551 WHEN quiza.timefinish > quiza.timestart THEN quiza.timefinish - quiza.timestart
552 ELSE 0 END AS duration';
553 // To explain that last bit, timefinish can be non-zero and less
554 // than timestart when you have two load-balanced servers with very
555 // badly synchronised clocks, and a student does a really quick attempt.
557 // This part is the same for all cases. Join the users and quiz_attempts tables.
558 $from = " {user} u";
559 $from .= "\n{$userfields->joins}";
560 $from .= "\nLEFT JOIN {quiz_attempts} quiza ON
561 quiza.userid = u.id AND quiza.quiz = :quizid";
562 $params = array_merge($userfields->params, ['quizid' => $this->quiz->id]);
564 if ($this->qmsubselect && $this->options->onlygraded) {
565 $from .= " AND (quiza.state <> :finishedstate OR $this->qmsubselect)";
566 $params['finishedstate'] = quiz_attempt::FINISHED;
569 switch ($this->options->attempts) {
570 case attempts_report::ALL_WITH:
571 // Show all attempts, including students who are no longer in the course.
572 $where = 'quiza.id IS NOT NULL AND quiza.preview = 0';
573 break;
574 case attempts_report::ENROLLED_WITH:
575 // Show only students with attempts.
576 $from .= "\n" . $allowedstudentsjoins->joins;
577 $where = "quiza.preview = 0 AND quiza.id IS NOT NULL AND " . $allowedstudentsjoins->wheres;
578 $params = array_merge($params, $allowedstudentsjoins->params);
579 break;
580 case attempts_report::ENROLLED_WITHOUT:
581 // Show only students without attempts.
582 $from .= "\n" . $allowedstudentsjoins->joins;
583 $where = "quiza.id IS NULL AND " . $allowedstudentsjoins->wheres;
584 $params = array_merge($params, $allowedstudentsjoins->params);
585 break;
586 case attempts_report::ENROLLED_ALL:
587 // Show all students with or without attempts.
588 $from .= "\n" . $allowedstudentsjoins->joins;
589 $where = "(quiza.preview = 0 OR quiza.preview IS NULL) AND " . $allowedstudentsjoins->wheres;
590 $params = array_merge($params, $allowedstudentsjoins->params);
591 break;
594 if ($this->options->states) {
595 [$statesql, $stateparams] = $DB->get_in_or_equal($this->options->states,
596 SQL_PARAMS_NAMED, 'state');
597 $params += $stateparams;
598 $where .= " AND (quiza.state $statesql OR quiza.state IS NULL)";
601 return [$fields, $from, $where, $params];
605 * Lets subclasses modify the SQL after the count query has been created and before the full query is.
607 * @param string $fields SELECT list.
608 * @param string $from JOINs part of the SQL.
609 * @param string $where WHERE clauses.
610 * @param array $params Query params.
611 * @return array with 4 elements ($fields, $from, $where, $params) as from base_sql.
613 protected function update_sql_after_count($fields, $from, $where, $params) {
614 return [$fields, $from, $where, $params];
618 * Set up the SQL queries (count rows, and get data).
620 * @param \core\dml\sql_join $allowedjoins (joins, wheres, params) defines allowed users for the report.
622 public function setup_sql_queries($allowedjoins) {
623 [$fields, $from, $where, $params] = $this->base_sql($allowedjoins);
625 // The WHERE clause is vital here, because some parts of tablelib.php will expect to
626 // add bits like ' AND x = 1' on the end, and that needs to leave to valid SQL.
627 $this->set_count_sql("SELECT COUNT(1) FROM (SELECT $fields FROM $from WHERE $where) temp WHERE 1 = 1", $params);
629 [$fields, $from, $where, $params] = $this->update_sql_after_count($fields, $from, $where, $params);
630 $this->set_sql($fields, $from, $where, $params);
634 * Add the information about the latest state of the question with slot
635 * $slot to the query.
637 * The extra information is added as a join to a
638 * 'table' with alias qa$slot, with columns that are a union of
639 * the columns of the question_attempts and question_attempts_states tables.
641 * @param int $slot the question to add information for.
643 protected function add_latest_state_join($slot) {
644 $alias = 'qa' . $slot;
646 $fields = $this->get_required_latest_state_fields($slot, $alias);
647 if (!$fields) {
648 return;
651 // This condition roughly filters the list of attempts to be considered.
652 // It is only used in a sub-select to help database query optimisers (see MDL-30122).
653 // Therefore, it is better to use a very simple which may include
654 // too many records, than to do a super-accurate join.
655 $qubaids = new qubaid_join("{quiz_attempts} {$alias}quiza", "{$alias}quiza.uniqueid",
656 "{$alias}quiza.quiz = :{$alias}quizid", ["{$alias}quizid" => $this->sql->params['quizid']]);
658 $dm = new question_engine_data_mapper();
659 [$inlineview, $viewparams] = $dm->question_attempt_latest_state_view($alias, $qubaids);
661 $this->sql->fields .= ",\n$fields";
662 $this->sql->from .= "\nLEFT JOIN $inlineview ON " .
663 "$alias.questionusageid = quiza.uniqueid AND $alias.slot = :{$alias}slot";
664 $this->sql->params[$alias . 'slot'] = $slot;
665 $this->sql->params = array_merge($this->sql->params, $viewparams);
669 * Add a field marks$gradeitemid to the query, with the total score for that grade item.
671 * @param int $gradeitemid the grade item to add information for.
673 protected function add_grade_item_mark(int $gradeitemid): void {
674 $dm = new question_engine_data_mapper();
676 $alias = 'gimarks' . $gradeitemid;
678 $this->sql->fields .= ",\n(
679 SELECT SUM({$alias}qas.fraction * {$alias}qa.maxmark) AS summarks
681 FROM {quiz_slots} {$alias}slot
682 JOIN {question_attempts} {$alias}qa ON {$alias}qa.slot = {$alias}slot.slot
683 JOIN {question_attempt_steps} {$alias}qas ON {$alias}qas.questionattemptid = {$alias}qa.id
684 AND {$alias}qas.sequencenumber = {$dm->latest_step_for_qa_subquery("{$alias}qa.id")}
685 WHERE {$alias}qa.questionusageid = quiza.uniqueid
686 AND {$alias}slot.quizgradeitemid = :{$alias}gradeitemid
687 ) AS marks$gradeitemid";
688 $this->sql->params[$alias . 'gradeitemid'] = $gradeitemid;
692 * Get an appropriate qubaid_condition for loading more data about the attempts we are displaying.
694 * @return qubaid_condition
696 protected function get_qubaids_condition() {
697 if (is_null($this->rawdata)) {
698 throw new coding_exception(
699 'Cannot call get_qubaids_condition until the main data has been loaded.');
702 if ($this->is_downloading()) {
703 // We want usages for all attempts.
704 return new qubaid_join("(
705 SELECT DISTINCT quiza.uniqueid
706 FROM " . $this->sql->from . "
707 WHERE " . $this->sql->where . "
708 ) quizasubquery", 'quizasubquery.uniqueid',
709 "1 = 1", $this->sql->params);
712 $qubaids = [];
713 foreach ($this->rawdata as $attempt) {
714 if ($attempt->usageid > 0) {
715 $qubaids[] = $attempt->usageid;
719 return new qubaid_list($qubaids);
722 public function query_db($pagesize, $useinitialsbar = true) {
723 $doneslots = [];
724 $donegradeitems = [];
725 foreach ($this->get_sort_columns() as $column => $notused) {
726 $slot = $this->is_latest_step_column($column);
727 if ($slot && !in_array($slot, $doneslots)) {
728 $this->add_latest_state_join($slot);
729 $doneslots[] = $slot;
732 $gradeitemid = $this->is_grade_item_column($column);
733 if ($gradeitemid && !in_array($gradeitemid, $donegradeitems)) {
734 $this->add_grade_item_mark($gradeitemid);
735 $donegradeitems[] = $gradeitemid;
739 parent::query_db($pagesize, $useinitialsbar);
741 // Load grade-item totals if required.
742 foreach ($this->columns as $columnname => $notused) {
743 if ($this->is_grade_item_column($columnname)) {
744 $this->load_grade_item_marks();
745 break;
749 if ($this->requires_extra_data()) {
750 $this->load_extra_data();
754 public function get_sort_columns() {
755 // Add attemptid as a final tie-break to the sort. This ensures that
756 // Attempts by the same student appear in order when just sorting by name.
757 $sortcolumns = parent::get_sort_columns();
758 $sortcolumns['quiza.id'] = SORT_ASC;
759 return $sortcolumns;
762 public function wrap_html_start() {
763 if ($this->is_downloading() || !$this->includecheckboxes) {
764 return;
767 $url = $this->options->get_url();
768 $url->param('sesskey', sesskey());
770 echo '<div id="tablecontainer">';
771 echo '<form id="attemptsform" method="post" action="' . $url->out_omit_querystring() . '">';
773 echo html_writer::input_hidden_params($url);
774 echo '<div>';
777 public function wrap_html_finish() {
778 global $PAGE;
779 if ($this->is_downloading() || !$this->includecheckboxes) {
780 return;
783 echo '<div id="commands">';
784 $this->submit_buttons();
785 echo '</div>';
787 // Close the form.
788 echo '</div>';
789 echo '</form></div>';
793 * Output any submit buttons required by the $this->includecheckboxes form.
795 protected function submit_buttons() {
796 global $PAGE;
797 if (has_capability('mod/quiz:deleteattempts', $this->context)) {
798 $deletebuttonparams = [
799 'type' => 'submit',
800 'class' => 'btn btn-secondary mr-1',
801 'id' => 'deleteattemptsbutton',
802 'name' => 'delete',
803 'value' => get_string('deleteselected', 'quiz_overview'),
804 'data-action' => 'toggle',
805 'data-togglegroup' => $this->togglegroup,
806 'data-toggle' => 'action',
807 'disabled' => true,
808 'data-modal' => 'confirmation',
809 'data-modal-type' => 'delete',
810 'data-modal-content-str' => json_encode(['deleteattemptcheck', 'quiz']),
812 echo html_writer::empty_tag('input', $deletebuttonparams);
817 * Generates the contents for the checkbox column header.
819 * It returns the HTML for a master \core\output\checkbox_toggleall component that selects/deselects all quiz attempts.
821 * @param string $columnname The name of the checkbox column.
822 * @return string
824 public function checkbox_col_header(string $columnname) {
825 global $OUTPUT;
827 // Make sure to disable sorting on this column.
828 $this->no_sorting($columnname);
830 // Build the select/deselect all control.
831 $selectallid = $this->uniqueid . '-selectall-attempts';
832 $selectalltext = get_string('selectall', 'quiz');
833 $deselectalltext = get_string('selectnone', 'quiz');
834 $mastercheckbox = new \core\output\checkbox_toggleall($this->togglegroup, true, [
835 'id' => $selectallid,
836 'name' => $selectallid,
837 'value' => 1,
838 'label' => $selectalltext,
839 'labelclasses' => 'accesshide',
840 'selectall' => $selectalltext,
841 'deselectall' => $deselectalltext,
844 return $OUTPUT->render($mastercheckbox);