MDL-35163 quiz Make quiz report options available to attempts form
[moodle.git] / mod / quiz / report / attemptsreport_table.php
CommitLineData
f5e42695
TH
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/**
ac4d9157 18 * Base class for the table used by a {@link quiz_attempts_report}.
f5e42695
TH
19 *
20 * @package mod_quiz
21 * @copyright 2010 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25
26defined('MOODLE_INTERNAL') || die();
27
28require_once($CFG->libdir.'/tablelib.php');
29
30
31/**
ac4d9157 32 * Base class for the table used by a {@link quiz_attempts_report}.
f5e42695
TH
33 *
34 * @copyright 2010 The Open University
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
ac4d9157 37abstract class quiz_attempts_report_table extends table_sql {
f5e42695
TH
38 public $useridfield = 'userid';
39
40 /** @var moodle_url the URL of this report. */
41 protected $reporturl;
42
43 /** @var array the display options. */
44 protected $displayoptions;
45
46 /**
47 * @var array information about the latest step of each question.
48 * Loaded by {@link load_question_latest_steps()}, if applicable.
49 */
50 protected $lateststeps = null;
51
9d58dae3 52 /** @var object the quiz settings for the quiz we are reporting on. */
f5e42695 53 protected $quiz;
9d58dae3
TH
54
55 /** @var context the quiz context. */
f5e42695 56 protected $context;
9d58dae3
TH
57
58 /** @var string HTML fragment to select the first/best/last attempt, if appropriate. */
f5e42695 59 protected $qmsubselect;
9d58dae3
TH
60
61 /** @var object mod_quiz_attempts_report_options the options affecting this report. */
e97d60ad 62 protected $options;
9d58dae3 63
9d58dae3 64 /** @var object the ids of the students in the currently selected group, if applicable. */
f5e42695 65 protected $groupstudents;
9d58dae3
TH
66
67 /** @var object the ids of the students in the course. */
f5e42695 68 protected $students;
9d58dae3
TH
69
70 /** @var object the questions that comprise this quiz.. */
f5e42695 71 protected $questions;
9d58dae3
TH
72
73 /** @var bool whether to include the column with checkboxes to select each attempt. */
f5e42695
TH
74 protected $includecheckboxes;
75
9d58dae3
TH
76 /**
77 * Constructor
78 * @param string $uniqueid
79 * @param object $quiz
80 * @param context $context
81 * @param string $qmsubselect
82 * @param mod_quiz_attempts_report_options $options
83 * @param array $groupstudents
84 * @param array $students
85 * @param array $questions
86 * @param moodle_url $reporturl
87 */
e97d60ad
TH
88 public function __construct($uniqueid, $quiz, $context, $qmsubselect,
89 mod_quiz_attempts_report_options $options, $groupstudents, $students,
90 $questions, $reporturl) {
f5e42695
TH
91 parent::__construct($uniqueid);
92 $this->quiz = $quiz;
93 $this->context = $context;
94 $this->qmsubselect = $qmsubselect;
f5e42695
TH
95 $this->groupstudents = $groupstudents;
96 $this->students = $students;
97 $this->questions = $questions;
e97d60ad 98 $this->includecheckboxes = $options->checkboxcolumn;
f5e42695 99 $this->reporturl = $reporturl;
e97d60ad 100 $this->options = $options;
f5e42695
TH
101 }
102
9d58dae3
TH
103 /**
104 * Generate the display of the checkbox column.
105 * @param object $attempt the table row being output.
106 * @return string HTML content to go inside the td.
107 */
f5e42695
TH
108 public function col_checkbox($attempt) {
109 if ($attempt->attempt) {
110 return '<input type="checkbox" name="attemptid[]" value="'.$attempt->attempt.'" />';
111 } else {
112 return '';
113 }
114 }
115
9d58dae3
TH
116 /**
117 * Generate the display of the user's picture column.
118 * @param object $attempt the table row being output.
119 * @return string HTML content to go inside the td.
120 */
f5e42695
TH
121 public function col_picture($attempt) {
122 global $OUTPUT;
123 $user = new stdClass();
124 $user->id = $attempt->userid;
125 $user->lastname = $attempt->lastname;
126 $user->firstname = $attempt->firstname;
127 $user->imagealt = $attempt->imagealt;
128 $user->picture = $attempt->picture;
129 $user->email = $attempt->email;
130 return $OUTPUT->user_picture($user);
131 }
132
9d58dae3
TH
133 /**
134 * Generate the display of the user's full name column.
135 * @param object $attempt the table row being output.
136 * @return string HTML content to go inside the td.
137 */
f5e42695
TH
138 public function col_fullname($attempt) {
139 $html = parent::col_fullname($attempt);
140 if ($this->is_downloading()) {
141 return $html;
142 }
143
144 return $html . html_writer::empty_tag('br') . html_writer::link(
145 new moodle_url('/mod/quiz/review.php', array('attempt' => $attempt->attempt)),
146 get_string('reviewattempt', 'quiz'), array('class' => 'reviewlink'));
147 }
148
c547514a
TH
149 /**
150 * Generate the display of the attempt state column.
151 * @param object $attempt the table row being output.
152 * @return string HTML content to go inside the td.
153 */
154 public function col_state($attempt) {
f8b66522
TH
155 if (!is_null($attempt->attempt)) {
156 return quiz_attempt::state_name($attempt->state);
157 } else {
158 return '-';
159 }
c547514a
TH
160 }
161
9d58dae3
TH
162 /**
163 * Generate the display of the start time column.
164 * @param object $attempt the table row being output.
165 * @return string HTML content to go inside the td.
166 */
f5e42695
TH
167 public function col_timestart($attempt) {
168 if ($attempt->attempt) {
169 return userdate($attempt->timestart, $this->strtimeformat);
170 } else {
171 return '-';
172 }
173 }
174
9d58dae3
TH
175 /**
176 * Generate the display of the finish time column.
177 * @param object $attempt the table row being output.
178 * @return string HTML content to go inside the td.
179 */
f5e42695
TH
180 public function col_timefinish($attempt) {
181 if ($attempt->attempt && $attempt->timefinish) {
182 return userdate($attempt->timefinish, $this->strtimeformat);
183 } else {
184 return '-';
185 }
186 }
187
9d58dae3
TH
188 /**
189 * Generate the display of the time taken column.
190 * @param object $attempt the table row being output.
191 * @return string HTML content to go inside the td.
192 */
f5e42695
TH
193 public function col_duration($attempt) {
194 if ($attempt->timefinish) {
195 return format_time($attempt->timefinish - $attempt->timestart);
f5e42695
TH
196 } else {
197 return '-';
198 }
199 }
200
9d58dae3
TH
201 /**
202 * Generate the display of the feedback column.
203 * @param object $attempt the table row being output.
204 * @return string HTML content to go inside the td.
205 */
f5e42695 206 public function col_feedbacktext($attempt) {
be18f589 207 if ($attempt->state != quiz_attempt::FINISHED) {
f5e42695
TH
208 return '-';
209 }
210
211 $feedback = quiz_report_feedback_for_grade(
212 quiz_rescale_grade($attempt->sumgrades, $this->quiz, false),
213 $this->quiz->id, $this->context);
214
215 if ($this->is_downloading()) {
216 $feedback = strip_tags($feedback);
217 }
218
219 return $feedback;
220 }
221
222 public function get_row_class($attempt) {
223 if ($this->qmsubselect && $attempt->gradedattempt) {
224 return 'gradedattempt';
225 } else {
226 return '';
227 }
228 }
229
230 /**
231 * Make a link to review an individual question in a popup window.
232 *
233 * @param string $data HTML fragment. The text to make into the link.
234 * @param object $attempt data for the row of the table being output.
235 * @param int $slot the number used to identify this question within this usage.
236 */
237 public function make_review_link($data, $attempt, $slot) {
238 global $OUTPUT;
239
240 $stepdata = $this->lateststeps[$attempt->usageid][$slot];
241 $state = question_state::get($stepdata->state);
242
243 $flag = '';
244 if ($stepdata->flagged) {
245 $flag = ' ' . $OUTPUT->pix_icon('i/flagged', get_string('flagged', 'question'),
246 'moodle', array('class' => 'questionflag'));
247 }
248
249 $feedbackimg = '';
250 if ($state->is_finished() && $state != question_state::$needsgrading) {
251 $feedbackimg = ' ' . $this->icon_for_fraction($stepdata->fraction);
252 }
253
254 $output = html_writer::tag('span', html_writer::tag('span',
255 $data . $feedbackimg . $flag,
256 array('class' => $state->get_state_class(true))), array('class' => 'que'));
257
258 $url = new moodle_url('/mod/quiz/reviewquestion.php',
259 array('attempt' => $attempt->attempt, 'slot' => $slot));
260 $output = $OUTPUT->action_link($url, $output,
261 new popup_action('click', $url, 'reviewquestion',
262 array('height' => 450, 'width' => 650)),
263 array('title' => get_string('reviewresponse', 'quiz')));
264
265 return $output;
266 }
267
268 /**
269 * Return an appropriate icon (green tick, red cross, etc.) for a grade.
270 * @param float $fraction grade on a scale 0..1.
271 * @return string html fragment.
272 */
273 protected function icon_for_fraction($fraction) {
274 global $OUTPUT;
275
276 $state = question_state::graded_state_for_fraction($fraction);
277 if ($state == question_state::$gradedright) {
278 $icon = 'i/tick_green_big';
279 } else if ($state == question_state::$gradedpartial) {
280 $icon = 'i/tick_amber_big';
281 } else {
282 $icon = 'i/cross_red_big';
283 }
284
285 return $OUTPUT->pix_icon($icon, get_string($state->get_feedback_class(), 'question'),
286 'moodle', array('class' => 'icon'));
287 }
288
289 /**
290 * Load information about the latest state of selected questions in selected attempts.
291 *
292 * The results are returned as an two dimensional array $qubaid => $slot => $dataobject
293 *
294 * @param qubaid_condition $qubaids used to restrict which usages are included
295 * in the query. See {@link qubaid_condition}.
f5e42695
TH
296 * @return array of records. See the SQL in this function to see the fields available.
297 */
298 protected function load_question_latest_steps(qubaid_condition $qubaids) {
299 $dm = new question_engine_data_mapper();
300 $latesstepdata = $dm->load_questions_usages_latest_steps(
301 $qubaids, array_keys($this->questions));
302
303 $lateststeps = array();
304 foreach ($latesstepdata as $step) {
305 $lateststeps[$step->questionusageid][$step->slot] = $step;
306 }
307
308 return $lateststeps;
309 }
310
311 /**
9d58dae3
TH
312 * Does this report require the detailed information for each question from the
313 * question_attempts_steps table?
f5e42695
TH
314 * @return bool should {@link query_db()} call {@link load_question_latest_steps}?
315 */
316 protected function requires_latest_steps_loaded() {
317 return false;
318 }
319
320 /**
321 * Is this a column that depends on joining to the latest state information?
322 * If so, return the corresponding slot. If not, return false.
323 * @param string $column a column name
324 * @return int false if no, else a slot.
325 */
326 protected function is_latest_step_column($column) {
327 return false;
328 }
329
330 /**
331 * Get any fields that might be needed when sorting on date for a particular slot.
332 * @param int $slot the slot for the column we want.
333 * @param string $alias the table alias for latest state information relating to that slot.
334 */
335 protected function get_required_latest_state_fields($slot, $alias) {
336 return '';
337 }
338
339 /**
340 * Contruct all the parts of the main database query.
341 * @param array $reportstudents list if userids of users to include in the report.
342 * @return array with 4 elements ($fields, $from, $where, $params) that can be used to
343 * build the actual database query.
344 */
345 public function base_sql($reportstudents) {
346 global $DB;
347
348 $fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid,';
349
350 if ($this->qmsubselect) {
351 $fields .= "\n(CASE WHEN $this->qmsubselect THEN 1 ELSE 0 END) AS gradedattempt,";
352 }
353
354 $extrafields = get_extra_user_fields_sql($this->context, 'u', '',
355 array('id', 'idnumber', 'firstname', 'lastname', 'picture',
356 'imagealt', 'institution', 'department', 'email'));
357 $fields .= '
358 quiza.uniqueid AS usageid,
359 quiza.id AS attempt,
360 u.id AS userid,
361 u.idnumber,
362 u.firstname,
363 u.lastname,
364 u.picture,
365 u.imagealt,
366 u.institution,
367 u.department,
368 u.email' . $extrafields . ',
c547514a 369 quiza.state,
f5e42695
TH
370 quiza.sumgrades,
371 quiza.timefinish,
372 quiza.timestart,
373 CASE WHEN quiza.timefinish = 0 THEN null
374 WHEN quiza.timefinish > quiza.timestart THEN quiza.timefinish - quiza.timestart
375 ELSE 0 END AS duration';
be18f589 376 // To explain that last bit, timefinish can be non-zero and less
f5e42695 377 // than timestart when you have two load-balanced servers with very
768a7588 378 // badly synchronised clocks, and a student does a really quick attempt.
f5e42695 379
768a7588 380 // This part is the same for all cases. Join the users and quiz_attempts tables.
f5e42695
TH
381 $from = "\n{user} u";
382 $from .= "\nLEFT JOIN {quiz_attempts} quiza ON
383 quiza.userid = u.id AND quiza.quiz = :quizid";
384 $params = array('quizid' => $this->quiz->id);
385
863872e3 386 if ($this->qmsubselect && $this->options->onlygraded) {
f5e42695
TH
387 $from .= " AND $this->qmsubselect";
388 }
863872e3
TH
389
390 switch ($this->options->attempts) {
391 case quiz_attempts_report::ALL_WITH:
768a7588 392 // Show all attempts, including students who are no longer in the course.
f5e42695
TH
393 $where = 'quiza.id IS NOT NULL AND quiza.preview = 0';
394 break;
863872e3 395 case quiz_attempts_report::ENROLLED_WITH:
768a7588 396 // Show only students with attempts.
f5e42695
TH
397 list($usql, $uparams) = $DB->get_in_or_equal(
398 $reportstudents, SQL_PARAMS_NAMED, 'u');
399 $params += $uparams;
400 $where = "u.id $usql AND quiza.preview = 0 AND quiza.id IS NOT NULL";
401 break;
863872e3 402 case quiz_attempts_report::ENROLLED_WITHOUT:
768a7588 403 // Show only students without attempts.
f5e42695
TH
404 list($usql, $uparams) = $DB->get_in_or_equal(
405 $reportstudents, SQL_PARAMS_NAMED, 'u');
406 $params += $uparams;
407 $where = "u.id $usql AND quiza.id IS NULL";
408 break;
863872e3 409 case quiz_attempts_report::ENROLLED_ALL:
768a7588 410 // Show all students with or without attempts.
f5e42695
TH
411 list($usql, $uparams) = $DB->get_in_or_equal(
412 $reportstudents, SQL_PARAMS_NAMED, 'u');
413 $params += $uparams;
414 $where = "u.id $usql AND (quiza.preview = 0 OR quiza.preview IS NULL)";
415 break;
416 }
417
863872e3
TH
418 if ($this->options->states) {
419 list($statesql, $stateparams) = $DB->get_in_or_equal($this->options->states,
420 SQL_PARAMS_NAMED, 'state');
421 $params += $stateparams;
422 $where .= " AND (quiza.state $statesql OR quiza.state IS NULL)";
423 }
424
f5e42695
TH
425 return array($fields, $from, $where, $params);
426 }
427
428 /**
429 * Add the information about the latest state of the question with slot
430 * $slot to the query.
431 *
432 * The extra information is added as a join to a
433 * 'table' with alias qa$slot, with columns that are a union of
434 * the columns of the question_attempts and question_attempts_states tables.
435 *
436 * @param int $slot the question to add information for.
437 */
438 protected function add_latest_state_join($slot) {
439 $alias = 'qa' . $slot;
440
441 $fields = $this->get_required_latest_state_fields($slot, $alias);
442 if (!$fields) {
443 return;
444 }
445
446 // This condition roughly filters the list of attempts to be considered.
447 // It is only used in a subselect to help crappy databases (see MDL-30122)
448 // therefore, it is better to use a very simple join, which may include
449 // too many records, than to do a super-accurate join.
450 $qubaids = new qubaid_join("{quiz_attempts} {$alias}quiza", "{$alias}quiza.uniqueid",
451 "{$alias}quiza.quiz = :{$alias}quizid", array("{$alias}quizid" => $this->sql->params['quizid']));
452
453 $dm = new question_engine_data_mapper();
454 list($inlineview, $viewparams) = $dm->question_attempt_latest_state_view($alias, $qubaids);
455
456 $this->sql->fields .= ",\n$fields";
457 $this->sql->from .= "\nLEFT JOIN $inlineview ON " .
458 "$alias.questionusageid = quiza.uniqueid AND $alias.slot = :{$alias}slot";
459 $this->sql->params[$alias . 'slot'] = $slot;
460 $this->sql->params = array_merge($this->sql->params, $viewparams);
461 }
462
463 /**
464 * Get an appropriate qubaid_condition for loading more data about the
465 * attempts we are displaying.
466 * @return qubaid_condition
467 */
468 protected function get_qubaids_condition() {
469 if (is_null($this->rawdata)) {
470 throw new coding_exception(
471 'Cannot call get_qubaids_condition until the main data has been loaded.');
472 }
473
474 if ($this->is_downloading()) {
475 // We want usages for all attempts.
476 return new qubaid_join($this->sql->from, 'quiza.uniqueid',
477 $this->sql->where, $this->sql->params);
478 }
479
480 $qubaids = array();
481 foreach ($this->rawdata as $attempt) {
482 if ($attempt->usageid > 0) {
483 $qubaids[] = $attempt->usageid;
484 }
485 }
486
487 return new qubaid_list($qubaids);
488 }
489
490 public function query_db($pagesize, $useinitialsbar = true) {
491 $doneslots = array();
492 foreach ($this->get_sort_columns() as $column => $notused) {
493 $slot = $this->is_latest_step_column($column);
494 if ($slot && !in_array($slot, $doneslots)) {
495 $this->add_latest_state_join($slot);
496 $doneslots[] = $slot;
497 }
498 }
499
500 parent::query_db($pagesize, $useinitialsbar);
501
502 if ($this->requires_latest_steps_loaded()) {
503 $qubaids = $this->get_qubaids_condition();
504 $this->lateststeps = $this->load_question_latest_steps($qubaids);
505 }
506 }
507
508 public function get_sort_columns() {
509 // Add attemptid as a final tie-break to the sort. This ensures that
510 // Attempts by the same student appear in order when just sorting by name.
511 $sortcolumns = parent::get_sort_columns();
512 $sortcolumns['quiza.id'] = SORT_ASC;
513 return $sortcolumns;
514 }
515
516 public function wrap_html_start() {
517 if ($this->is_downloading() || !$this->includecheckboxes) {
518 return;
519 }
520
8d9abcf0 521 $url = $this->options->get_url();
f5e42695
TH
522 $url->param('sesskey', sesskey());
523
524 echo '<div id="tablecontainer">';
525 echo '<form id="attemptsform" method="post" action="' . $url->out_omit_querystring() . '">';
526
527 echo html_writer::input_hidden_params($url);
528 echo '<div>';
529 }
530
531 public function wrap_html_finish() {
532 if ($this->is_downloading() || !$this->includecheckboxes) {
533 return;
534 }
535
536 echo '<div id="commands">';
537 echo '<a href="javascript:select_all_in(\'DIV\', null, \'tablecontainer\');">' .
538 get_string('selectall', 'quiz') . '</a> / ';
539 echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'tablecontainer\');">' .
540 get_string('selectnone', 'quiz') . '</a> ';
541 echo '&nbsp;&nbsp;';
542 $this->submit_buttons();
543 echo '</div>';
768a7588
TH
544
545 // Close the form.
f5e42695
TH
546 echo '</div>';
547 echo '</form></div>';
548 }
549
550 /**
551 * Output any submit buttons required by the $this->includecheckboxes form.
552 */
553 protected function submit_buttons() {
554 global $PAGE;
555 if (has_capability('mod/quiz:deleteattempts', $this->context)) {
556 echo '<input type="submit" id="deleteattemptsbutton" name="delete" value="' .
557 get_string('deleteselected', 'quiz_overview') . '"/>';
558 $PAGE->requires->event_handler('#deleteattemptsbutton', 'click', 'M.util.show_confirm_dialog',
559 array('message' => get_string('deleteattemptcheck', 'quiz')));
560 }
561 }
562}