Merge branch 'mdl41996-master' of https://github.com/tlock/moodle
[moodle.git] / mod / quiz / report / attemptsreport_table.php
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/>.
17 /**
18  * Base class for the table used by a {@link quiz_attempts_report}.
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  */
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->libdir.'/tablelib.php');
31 /**
32  * Base class for the table used by a {@link quiz_attempts_report}.
33  *
34  * @copyright 2010 The Open University
35  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 abstract class quiz_attempts_report_table extends table_sql {
38     public $useridfield = 'userid';
40     /** @var moodle_url the URL of this report. */
41     protected $reporturl;
43     /** @var array the display options. */
44     protected $displayoptions;
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;
52     /** @var object the quiz settings for the quiz we are reporting on. */
53     protected $quiz;
55     /** @var context the quiz context. */
56     protected $context;
58     /** @var string HTML fragment to select the first/best/last attempt, if appropriate. */
59     protected $qmsubselect;
61     /** @var object mod_quiz_attempts_report_options the options affecting this report. */
62     protected $options;
64     /** @var object the ids of the students in the currently selected group, if applicable. */
65     protected $groupstudents;
67     /** @var object the ids of the students in the course. */
68     protected $students;
70     /** @var object the questions that comprise this quiz.. */
71     protected $questions;
73     /** @var bool whether to include the column with checkboxes to select each attempt. */
74     protected $includecheckboxes;
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      */
88     public function __construct($uniqueid, $quiz, $context, $qmsubselect,
89             mod_quiz_attempts_report_options $options, $groupstudents, $students,
90             $questions, $reporturl) {
91         parent::__construct($uniqueid);
92         $this->quiz = $quiz;
93         $this->context = $context;
94         $this->qmsubselect = $qmsubselect;
95         $this->groupstudents = $groupstudents;
96         $this->students = $students;
97         $this->questions = $questions;
98         $this->includecheckboxes = $options->checkboxcolumn;
99         $this->reporturl = $reporturl;
100         $this->options = $options;
101     }
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      */
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     }
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      */
121     public function col_picture($attempt) {
122         global $OUTPUT;
123         $user = new stdClass();
124         $user->id = $attempt->userid;
125         $user->imagealt = $attempt->imagealt;
126         $user->picture = $attempt->picture;
127         $user->email = $attempt->email;
128         foreach (get_all_user_name_fields() as $addname) {
129             $user->$addname = $attempt->$addname;
130         }
131         return $OUTPUT->user_picture($user);
132     }
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      */
139     public function col_fullname($attempt) {
140         $html = parent::col_fullname($attempt);
141         if ($this->is_downloading() || empty($attempt->attempt)) {
142             return $html;
143         }
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     }
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) {
156         if (!is_null($attempt->attempt)) {
157             return quiz_attempt::state_name($attempt->state);
158         } else {
159             return  '-';
160         }
161     }
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      */
168     public function col_timestart($attempt) {
169         if ($attempt->attempt) {
170             return userdate($attempt->timestart, $this->strtimeformat);
171         } else {
172             return  '-';
173         }
174     }
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      */
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     }
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      */
194     public function col_duration($attempt) {
195         if ($attempt->timefinish) {
196             return format_time($attempt->timefinish - $attempt->timestart);
197         } else {
198             return '-';
199         }
200     }
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      */
207     public function col_feedbacktext($attempt) {
208         if ($attempt->state != quiz_attempt::FINISHED) {
209             return '-';
210         }
212         $feedback = quiz_report_feedback_for_grade(
213                 quiz_rescale_grade($attempt->sumgrades, $this->quiz, false),
214                 $this->quiz->id, $this->context);
216         if ($this->is_downloading()) {
217             $feedback = strip_tags($feedback);
218         }
220         return $feedback;
221     }
223     public function get_row_class($attempt) {
224         if ($this->qmsubselect && $attempt->gradedattempt) {
225             return 'gradedattempt';
226         } else {
227             return '';
228         }
229     }
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;
241         $stepdata = $this->lateststeps[$attempt->usageid][$slot];
242         $state = question_state::get($stepdata->state);
244         $flag = '';
245         if ($stepdata->flagged) {
246             $flag = $OUTPUT->pix_icon('i/flagged', get_string('flagged', 'question'),
247                     'moodle', array('class' => 'questionflag'));
248         }
250         $feedbackimg = '';
251         if ($state->is_finished() && $state != question_state::$needsgrading) {
252             $feedbackimg = $this->icon_for_fraction($stepdata->fraction);
253         }
255         $output = html_writer::tag('span', $feedbackimg . html_writer::tag('span',
256                 $data, array('class' => $state->get_state_class(true))) . $flag, array('class' => 'que'));
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')));
265         return $output;
266     }
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;
276         $feedbackclass = question_state::graded_state_for_fraction($fraction)->get_feedback_class();
277         return $OUTPUT->pix_icon('i/grade_' . $feedbackclass, get_string($feedbackclass, 'question'),
278                 'moodle', array('class' => 'icon'));
279     }
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}.
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));
295         $lateststeps = array();
296         foreach ($latesstepdata as $step) {
297             $lateststeps[$step->questionusageid][$step->slot] = $step;
298         }
300         return $lateststeps;
301     }
303     /**
304      * Does this report require the detailed information for each question from the
305      * question_attempts_steps table?
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     }
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     }
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     }
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;
340         $fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid,';
342         if ($this->qmsubselect) {
343             $fields .= "\n(CASE WHEN $this->qmsubselect THEN 1 ELSE 0 END) AS gradedattempt,";
344         }
346         $extrafields = get_extra_user_fields_sql($this->context, 'u', '',
347                 array('id', 'idnumber', 'firstname', 'lastname', 'picture',
348                 'imagealt', 'institution', 'department', 'email'));
349         $allnames = get_all_user_name_fields(true, 'u');
350         $fields .= '
351                 quiza.uniqueid AS usageid,
352                 quiza.id AS attempt,
353                 u.id AS userid,
354                 u.idnumber, ' . $allnames . ',
355                 u.picture,
356                 u.imagealt,
357                 u.institution,
358                 u.department,
359                 u.email' . $extrafields . ',
360                 quiza.state,
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';
367             // To explain that last bit, timefinish can be non-zero and less
368             // than timestart when you have two load-balanced servers with very
369             // badly synchronised clocks, and a student does a really quick attempt.
371         // This part is the same for all cases. Join the users and quiz_attempts tables.
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);
377         if ($this->qmsubselect && $this->options->onlygraded) {
378             $from .= " AND $this->qmsubselect";
379         }
381         switch ($this->options->attempts) {
382             case quiz_attempts_report::ALL_WITH:
383                 // Show all attempts, including students who are no longer in the course.
384                 $where = 'quiza.id IS NOT NULL AND quiza.preview = 0';
385                 break;
386             case quiz_attempts_report::ENROLLED_WITH:
387                 // Show only students with attempts.
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;
393             case quiz_attempts_report::ENROLLED_WITHOUT:
394                 // Show only students without attempts.
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;
400             case quiz_attempts_report::ENROLLED_ALL:
401                 // Show all students with or without attempts.
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         }
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         }
416         return array($fields, $from, $where, $params);
417     }
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;
432         $fields = $this->get_required_latest_state_fields($slot, $alias);
433         if (!$fields) {
434             return;
435         }
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']));
444         $dm = new question_engine_data_mapper();
445         list($inlineview, $viewparams) = $dm->question_attempt_latest_state_view($alias, $qubaids);
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     }
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         }
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         }
471         $qubaids = array();
472         foreach ($this->rawdata as $attempt) {
473             if ($attempt->usageid > 0) {
474                 $qubaids[] = $attempt->usageid;
475             }
476         }
478         return new qubaid_list($qubaids);
479     }
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         }
491         parent::query_db($pagesize, $useinitialsbar);
493         if ($this->requires_latest_steps_loaded()) {
494             $qubaids = $this->get_qubaids_condition();
495             $this->lateststeps = $this->load_question_latest_steps($qubaids);
496         }
497     }
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     }
507     public function wrap_html_start() {
508         if ($this->is_downloading() || !$this->includecheckboxes) {
509             return;
510         }
512         $url = $this->options->get_url();
513         $url->param('sesskey', sesskey());
515         echo '<div id="tablecontainer">';
516         echo '<form id="attemptsform" method="post" action="' . $url->out_omit_querystring() . '">';
518         echo html_writer::input_hidden_params($url);
519         echo '<div>';
520     }
522     public function wrap_html_finish() {
523         if ($this->is_downloading() || !$this->includecheckboxes) {
524             return;
525         }
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>';
536         // Close the form.
537         echo '</div>';
538         echo '</form></div>';
539     }
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     }