Merge branch 'mdl41996-master' of https://github.com/tlock/moodle
[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;
f5e42695
TH
125 $user->imagealt = $attempt->imagealt;
126 $user->picture = $attempt->picture;
127 $user->email = $attempt->email;
a327f25e
AG
128 foreach (get_all_user_name_fields() as $addname) {
129 $user->$addname = $attempt->$addname;
130 }
f5e42695
TH
131 return $OUTPUT->user_picture($user);
132 }
133
9d58dae3
TH
134 /**
135 * Generate the display of the user's full name column.
136 * @param object $attempt the table row being output.
137 * @return string HTML content to go inside the td.
138 */
f5e42695
TH
139 public function col_fullname($attempt) {
140 $html = parent::col_fullname($attempt);
7d0f566b 141 if ($this->is_downloading() || empty($attempt->attempt)) {
f5e42695
TH
142 return $html;
143 }
144
145 return $html . html_writer::empty_tag('br') . html_writer::link(
146 new moodle_url('/mod/quiz/review.php', array('attempt' => $attempt->attempt)),
147 get_string('reviewattempt', 'quiz'), array('class' => 'reviewlink'));
148 }
149
c547514a
TH
150 /**
151 * Generate the display of the attempt state column.
152 * @param object $attempt the table row being output.
153 * @return string HTML content to go inside the td.
154 */
155 public function col_state($attempt) {
f8b66522
TH
156 if (!is_null($attempt->attempt)) {
157 return quiz_attempt::state_name($attempt->state);
158 } else {
159 return '-';
160 }
c547514a
TH
161 }
162
9d58dae3
TH
163 /**
164 * Generate the display of the start time column.
165 * @param object $attempt the table row being output.
166 * @return string HTML content to go inside the td.
167 */
f5e42695
TH
168 public function col_timestart($attempt) {
169 if ($attempt->attempt) {
170 return userdate($attempt->timestart, $this->strtimeformat);
171 } else {
172 return '-';
173 }
174 }
175
9d58dae3
TH
176 /**
177 * Generate the display of the finish time column.
178 * @param object $attempt the table row being output.
179 * @return string HTML content to go inside the td.
180 */
f5e42695
TH
181 public function col_timefinish($attempt) {
182 if ($attempt->attempt && $attempt->timefinish) {
183 return userdate($attempt->timefinish, $this->strtimeformat);
184 } else {
185 return '-';
186 }
187 }
188
9d58dae3
TH
189 /**
190 * Generate the display of the time taken column.
191 * @param object $attempt the table row being output.
192 * @return string HTML content to go inside the td.
193 */
f5e42695
TH
194 public function col_duration($attempt) {
195 if ($attempt->timefinish) {
196 return format_time($attempt->timefinish - $attempt->timestart);
f5e42695
TH
197 } else {
198 return '-';
199 }
200 }
201
9d58dae3
TH
202 /**
203 * Generate the display of the feedback column.
204 * @param object $attempt the table row being output.
205 * @return string HTML content to go inside the td.
206 */
f5e42695 207 public function col_feedbacktext($attempt) {
be18f589 208 if ($attempt->state != quiz_attempt::FINISHED) {
f5e42695
TH
209 return '-';
210 }
211
212 $feedback = quiz_report_feedback_for_grade(
213 quiz_rescale_grade($attempt->sumgrades, $this->quiz, false),
214 $this->quiz->id, $this->context);
215
216 if ($this->is_downloading()) {
217 $feedback = strip_tags($feedback);
218 }
219
220 return $feedback;
221 }
222
223 public function get_row_class($attempt) {
224 if ($this->qmsubselect && $attempt->gradedattempt) {
225 return 'gradedattempt';
226 } else {
227 return '';
228 }
229 }
230
231 /**
232 * Make a link to review an individual question in a popup window.
233 *
234 * @param string $data HTML fragment. The text to make into the link.
235 * @param object $attempt data for the row of the table being output.
236 * @param int $slot the number used to identify this question within this usage.
237 */
238 public function make_review_link($data, $attempt, $slot) {
239 global $OUTPUT;
240
241 $stepdata = $this->lateststeps[$attempt->usageid][$slot];
242 $state = question_state::get($stepdata->state);
243
244 $flag = '';
245 if ($stepdata->flagged) {
c3847443 246 $flag = $OUTPUT->pix_icon('i/flagged', get_string('flagged', 'question'),
f5e42695
TH
247 'moodle', array('class' => 'questionflag'));
248 }
249
250 $feedbackimg = '';
251 if ($state->is_finished() && $state != question_state::$needsgrading) {
c3847443 252 $feedbackimg = $this->icon_for_fraction($stepdata->fraction);
f5e42695
TH
253 }
254
c3847443
FM
255 $output = html_writer::tag('span', $feedbackimg . html_writer::tag('span',
256 $data, array('class' => $state->get_state_class(true))) . $flag, array('class' => 'que'));
f5e42695
TH
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
6e4a2acf
TH
276 $feedbackclass = question_state::graded_state_for_fraction($fraction)->get_feedback_class();
277 return $OUTPUT->pix_icon('i/grade_' . $feedbackclass, get_string($feedbackclass, 'question'),
f5e42695
TH
278 'moodle', array('class' => 'icon'));
279 }
280
281 /**
282 * Load information about the latest state of selected questions in selected attempts.
283 *
284 * The results are returned as an two dimensional array $qubaid => $slot => $dataobject
285 *
286 * @param qubaid_condition $qubaids used to restrict which usages are included
287 * in the query. See {@link qubaid_condition}.
f5e42695
TH
288 * @return array of records. See the SQL in this function to see the fields available.
289 */
290 protected function load_question_latest_steps(qubaid_condition $qubaids) {
291 $dm = new question_engine_data_mapper();
292 $latesstepdata = $dm->load_questions_usages_latest_steps(
293 $qubaids, array_keys($this->questions));
294
295 $lateststeps = array();
296 foreach ($latesstepdata as $step) {
297 $lateststeps[$step->questionusageid][$step->slot] = $step;
298 }
299
300 return $lateststeps;
301 }
302
303 /**
9d58dae3
TH
304 * Does this report require the detailed information for each question from the
305 * question_attempts_steps table?
f5e42695
TH
306 * @return bool should {@link query_db()} call {@link load_question_latest_steps}?
307 */
308 protected function requires_latest_steps_loaded() {
309 return false;
310 }
311
312 /**
313 * Is this a column that depends on joining to the latest state information?
314 * If so, return the corresponding slot. If not, return false.
315 * @param string $column a column name
316 * @return int false if no, else a slot.
317 */
318 protected function is_latest_step_column($column) {
319 return false;
320 }
321
322 /**
323 * Get any fields that might be needed when sorting on date for a particular slot.
324 * @param int $slot the slot for the column we want.
325 * @param string $alias the table alias for latest state information relating to that slot.
326 */
327 protected function get_required_latest_state_fields($slot, $alias) {
328 return '';
329 }
330
331 /**
332 * Contruct all the parts of the main database query.
333 * @param array $reportstudents list if userids of users to include in the report.
334 * @return array with 4 elements ($fields, $from, $where, $params) that can be used to
335 * build the actual database query.
336 */
337 public function base_sql($reportstudents) {
338 global $DB;
339
340 $fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid,';
341
342 if ($this->qmsubselect) {
343 $fields .= "\n(CASE WHEN $this->qmsubselect THEN 1 ELSE 0 END) AS gradedattempt,";
344 }
345
346 $extrafields = get_extra_user_fields_sql($this->context, 'u', '',
347 array('id', 'idnumber', 'firstname', 'lastname', 'picture',
348 'imagealt', 'institution', 'department', 'email'));
a327f25e 349 $allnames = get_all_user_name_fields(true, 'u');
f5e42695
TH
350 $fields .= '
351 quiza.uniqueid AS usageid,
352 quiza.id AS attempt,
353 u.id AS userid,
a327f25e 354 u.idnumber, ' . $allnames . ',
f5e42695
TH
355 u.picture,
356 u.imagealt,
357 u.institution,
358 u.department,
359 u.email' . $extrafields . ',
c547514a 360 quiza.state,
f5e42695
TH
361 quiza.sumgrades,
362 quiza.timefinish,
363 quiza.timestart,
364 CASE WHEN quiza.timefinish = 0 THEN null
365 WHEN quiza.timefinish > quiza.timestart THEN quiza.timefinish - quiza.timestart
366 ELSE 0 END AS duration';
be18f589 367 // To explain that last bit, timefinish can be non-zero and less
f5e42695 368 // than timestart when you have two load-balanced servers with very
768a7588 369 // badly synchronised clocks, and a student does a really quick attempt.
f5e42695 370
768a7588 371 // This part is the same for all cases. Join the users and quiz_attempts tables.
f5e42695
TH
372 $from = "\n{user} u";
373 $from .= "\nLEFT JOIN {quiz_attempts} quiza ON
374 quiza.userid = u.id AND quiza.quiz = :quizid";
375 $params = array('quizid' => $this->quiz->id);
376
863872e3 377 if ($this->qmsubselect && $this->options->onlygraded) {
f5e42695
TH
378 $from .= " AND $this->qmsubselect";
379 }
863872e3
TH
380
381 switch ($this->options->attempts) {
382 case quiz_attempts_report::ALL_WITH:
768a7588 383 // Show all attempts, including students who are no longer in the course.
f5e42695
TH
384 $where = 'quiza.id IS NOT NULL AND quiza.preview = 0';
385 break;
863872e3 386 case quiz_attempts_report::ENROLLED_WITH:
768a7588 387 // Show only students with attempts.
f5e42695
TH
388 list($usql, $uparams) = $DB->get_in_or_equal(
389 $reportstudents, SQL_PARAMS_NAMED, 'u');
390 $params += $uparams;
391 $where = "u.id $usql AND quiza.preview = 0 AND quiza.id IS NOT NULL";
392 break;
863872e3 393 case quiz_attempts_report::ENROLLED_WITHOUT:
768a7588 394 // Show only students without attempts.
f5e42695
TH
395 list($usql, $uparams) = $DB->get_in_or_equal(
396 $reportstudents, SQL_PARAMS_NAMED, 'u');
397 $params += $uparams;
398 $where = "u.id $usql AND quiza.id IS NULL";
399 break;
863872e3 400 case quiz_attempts_report::ENROLLED_ALL:
768a7588 401 // Show all students with or without attempts.
f5e42695
TH
402 list($usql, $uparams) = $DB->get_in_or_equal(
403 $reportstudents, SQL_PARAMS_NAMED, 'u');
404 $params += $uparams;
405 $where = "u.id $usql AND (quiza.preview = 0 OR quiza.preview IS NULL)";
406 break;
407 }
408
863872e3
TH
409 if ($this->options->states) {
410 list($statesql, $stateparams) = $DB->get_in_or_equal($this->options->states,
411 SQL_PARAMS_NAMED, 'state');
412 $params += $stateparams;
413 $where .= " AND (quiza.state $statesql OR quiza.state IS NULL)";
414 }
415
f5e42695
TH
416 return array($fields, $from, $where, $params);
417 }
418
419 /**
420 * Add the information about the latest state of the question with slot
421 * $slot to the query.
422 *
423 * The extra information is added as a join to a
424 * 'table' with alias qa$slot, with columns that are a union of
425 * the columns of the question_attempts and question_attempts_states tables.
426 *
427 * @param int $slot the question to add information for.
428 */
429 protected function add_latest_state_join($slot) {
430 $alias = 'qa' . $slot;
431
432 $fields = $this->get_required_latest_state_fields($slot, $alias);
433 if (!$fields) {
434 return;
435 }
436
437 // This condition roughly filters the list of attempts to be considered.
438 // It is only used in a subselect to help crappy databases (see MDL-30122)
439 // therefore, it is better to use a very simple join, which may include
440 // too many records, than to do a super-accurate join.
441 $qubaids = new qubaid_join("{quiz_attempts} {$alias}quiza", "{$alias}quiza.uniqueid",
442 "{$alias}quiza.quiz = :{$alias}quizid", array("{$alias}quizid" => $this->sql->params['quizid']));
443
444 $dm = new question_engine_data_mapper();
445 list($inlineview, $viewparams) = $dm->question_attempt_latest_state_view($alias, $qubaids);
446
447 $this->sql->fields .= ",\n$fields";
448 $this->sql->from .= "\nLEFT JOIN $inlineview ON " .
449 "$alias.questionusageid = quiza.uniqueid AND $alias.slot = :{$alias}slot";
450 $this->sql->params[$alias . 'slot'] = $slot;
451 $this->sql->params = array_merge($this->sql->params, $viewparams);
452 }
453
454 /**
455 * Get an appropriate qubaid_condition for loading more data about the
456 * attempts we are displaying.
457 * @return qubaid_condition
458 */
459 protected function get_qubaids_condition() {
460 if (is_null($this->rawdata)) {
461 throw new coding_exception(
462 'Cannot call get_qubaids_condition until the main data has been loaded.');
463 }
464
465 if ($this->is_downloading()) {
466 // We want usages for all attempts.
467 return new qubaid_join($this->sql->from, 'quiza.uniqueid',
468 $this->sql->where, $this->sql->params);
469 }
470
471 $qubaids = array();
472 foreach ($this->rawdata as $attempt) {
473 if ($attempt->usageid > 0) {
474 $qubaids[] = $attempt->usageid;
475 }
476 }
477
478 return new qubaid_list($qubaids);
479 }
480
481 public function query_db($pagesize, $useinitialsbar = true) {
482 $doneslots = array();
483 foreach ($this->get_sort_columns() as $column => $notused) {
484 $slot = $this->is_latest_step_column($column);
485 if ($slot && !in_array($slot, $doneslots)) {
486 $this->add_latest_state_join($slot);
487 $doneslots[] = $slot;
488 }
489 }
490
491 parent::query_db($pagesize, $useinitialsbar);
492
493 if ($this->requires_latest_steps_loaded()) {
494 $qubaids = $this->get_qubaids_condition();
495 $this->lateststeps = $this->load_question_latest_steps($qubaids);
496 }
497 }
498
499 public function get_sort_columns() {
500 // Add attemptid as a final tie-break to the sort. This ensures that
501 // Attempts by the same student appear in order when just sorting by name.
502 $sortcolumns = parent::get_sort_columns();
503 $sortcolumns['quiza.id'] = SORT_ASC;
504 return $sortcolumns;
505 }
506
507 public function wrap_html_start() {
508 if ($this->is_downloading() || !$this->includecheckboxes) {
509 return;
510 }
511
8d9abcf0 512 $url = $this->options->get_url();
f5e42695
TH
513 $url->param('sesskey', sesskey());
514
515 echo '<div id="tablecontainer">';
516 echo '<form id="attemptsform" method="post" action="' . $url->out_omit_querystring() . '">';
517
518 echo html_writer::input_hidden_params($url);
519 echo '<div>';
520 }
521
522 public function wrap_html_finish() {
523 if ($this->is_downloading() || !$this->includecheckboxes) {
524 return;
525 }
526
527 echo '<div id="commands">';
528 echo '<a href="javascript:select_all_in(\'DIV\', null, \'tablecontainer\');">' .
529 get_string('selectall', 'quiz') . '</a> / ';
530 echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'tablecontainer\');">' .
531 get_string('selectnone', 'quiz') . '</a> ';
532 echo '&nbsp;&nbsp;';
533 $this->submit_buttons();
534 echo '</div>';
768a7588
TH
535
536 // Close the form.
f5e42695
TH
537 echo '</div>';
538 echo '</form></div>';
539 }
540
541 /**
542 * Output any submit buttons required by the $this->includecheckboxes form.
543 */
544 protected function submit_buttons() {
545 global $PAGE;
546 if (has_capability('mod/quiz:deleteattempts', $this->context)) {
547 echo '<input type="submit" id="deleteattemptsbutton" name="delete" value="' .
548 get_string('deleteselected', 'quiz_overview') . '"/>';
549 $PAGE->requires->event_handler('#deleteattemptsbutton', 'click', 'M.util.show_confirm_dialog',
550 array('message' => get_string('deleteattemptcheck', 'quiz')));
551 }
552 }
553}