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