3 * This script lists student attempts
6 * @author Martin Dougiamas, Tim Hunt and others.
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
11 require_once($CFG->libdir
.'/tablelib.php');
13 class quiz_report
extends quiz_default_report
{
18 function display($quiz, $cm, $course) {
21 // Define some strings
22 $strreallydel = addslashes(get_string('deleteattemptcheck','quiz'));
23 $strtimeformat = get_string('strftimedatetime');
24 $strreviewquestion = get_string('reviewresponse', 'quiz');
26 // Only print headers if not asked to download data
27 if (!$download = optional_param('download', NULL)) {
28 $this->print_header_and_tabs($cm, $course, $quiz, $reportmode="overview");
32 $action = optional_param('action', '', PARAM_ACTION
);
35 case 'delete': // Some attempts need to be deleted
36 $attemptids = optional_param('attemptid', array(), PARAM_INT
);
38 foreach($attemptids as $attemptid) {
39 quiz_delete_attempt($attemptid, $quiz);
40 quiz_update_grades($quiz, $USER->id
);
45 // Set of format options for teacher-created content, for example overall feedback.
46 $nocleanformatoptions = new stdClass
;
47 $nocleanformatoptions->noclean
= true;
50 $noattempts = optional_param('noattempts', 0, PARAM_INT
);
51 $detailedmarks = optional_param('detailedmarks', 0, PARAM_INT
);
52 $pagesize = optional_param('pagesize', 10, PARAM_INT
);
53 $reporturl = $CFG->wwwroot
.'/mod/quiz/report.php?mode=overview';
54 $reporturlwithoptions = $reporturl . '&id=' . $cm->id
. '&noattempts=' . $noattempts .
55 '&detailedmarks=' . $detailedmarks . '&pagesize=' . $pagesize;
57 // Print information on the number of existing attempts
58 if (!$download) { //do not print notices when downloading
59 if ($attemptnum = count_records('quiz_attempts', 'quiz', $quiz->id
, 'preview', 0)) {
61 $a->attemptnum
= $attemptnum;
62 $a->studentnum
= count_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'", 'COUNT(DISTINCT userid)');
63 $a->studentstring
= $course->students
;
65 notify(get_string('numattempts', 'quiz', $a));
69 /// find out current groups mode
70 $currentgroup = groups_get_activity_group($cm, true);
72 if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used
74 groups_print_activity_menu($cm, $reporturlwithoptions);
78 $hasfeedback = quiz_has_feedback($quiz->id
) && $quiz->grade
> 1.e
-7 && $quiz->sumgrades
> 1.e
-7;
83 // Now check if asked download of data
85 $filename = clean_filename("$course->shortname ".format_string($quiz->name
,true));
89 // Define table columns
90 $tablecolumns = array('checkbox', 'picture', 'fullname', 'timestart', 'timefinish', 'duration');
91 $tableheaders = array(NULL, '', get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted','quiz'), get_string('attemptduration', 'quiz'));
93 if ($quiz->grade
and $quiz->sumgrades
) {
94 $tablecolumns[] = 'sumgrades';
95 $tableheaders[] = get_string('grade', 'quiz').'/'.$quiz->grade
;
99 // we want to display marks for all questions
100 // Start by getting all questions
101 $questionlist = quiz_questions_in_quiz($quiz->questions
);
102 $questionids = explode(',', $questionlist);
103 $sql = "SELECT q.*, i.grade AS maxgrade, i.id AS instance".
104 " FROM {$CFG->prefix}question q,".
105 " {$CFG->prefix}quiz_question_instances i".
106 " WHERE i.quiz = '$quiz->id' AND q.id = i.question".
107 " AND q.id IN ($questionlist)";
108 if (!$questions = get_records_sql($sql)) {
109 error('No questions found');
112 foreach($questionids as $key => $id) {
113 if ($questions[$id]->length
) {
114 // Only print questions of non-zero length
115 $tablecolumns[] = '$'.$id;
116 $tableheaders[] = '#'.$number;
117 $questions[$id]->number
= $number;
118 $number +
= $questions[$id]->length
;
120 // get rid of zero length questions
121 unset($questions[$id]);
122 unset($questionids[$key]);
128 $tablecolumns[] = 'feedbacktext';
129 $tableheaders[] = get_string('feedback', 'quiz');
135 $table = new flexible_table('mod-quiz-report-overview-report');
137 $table->define_columns($tablecolumns);
138 $table->define_headers($tableheaders);
139 $table->define_baseurl($reporturlwithoptions);
141 $table->sortable(true);
142 $table->collapsible(true);
144 $table->column_suppress('picture');
145 $table->column_suppress('fullname');
147 $table->column_class('picture', 'picture');
149 $table->set_attribute('cellspacing', '0');
150 $table->set_attribute('id', 'attempts');
151 $table->set_attribute('class', 'generaltable generalbox');
153 // Start working -- this is necessary as soon as the niceties are over
155 } else if ($download =='ODS') {
156 require_once("$CFG->libdir/odslib.class.php");
159 // Creating a workbook
160 $workbook = new MoodleODSWorkbook("-");
161 // Sending HTTP headers
162 $workbook->send($filename);
163 // Creating the first worksheet
164 $sheettitle = get_string('reportoverview','quiz');
165 $myxls =& $workbook->add_worksheet($sheettitle);
167 $format =& $workbook->add_format();
168 $format->set_bold(0);
169 $formatbc =& $workbook->add_format();
170 $formatbc->set_bold(1);
171 $formatbc->set_align('center');
172 $formatb =& $workbook->add_format();
173 $formatb->set_bold(1);
174 $formaty =& $workbook->add_format();
175 $formaty->set_bg_color('yellow');
176 $formatc =& $workbook->add_format();
177 $formatc->set_align('center');
178 $formatr =& $workbook->add_format();
179 $formatr->set_bold(1);
180 $formatr->set_color('red');
181 $formatr->set_align('center');
182 $formatg =& $workbook->add_format();
183 $formatg->set_bold(1);
184 $formatg->set_color('green');
185 $formatg->set_align('center');
186 // Here starts workshhet headers
188 $headers = array(get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted', 'quiz'), get_string('attemptduration', 'quiz'));
190 if ($quiz->grade
and $quiz->sumgrades
) {
191 $headers[] = get_string('grade', 'quiz').'/'.$quiz->grade
;
194 foreach ($questionids as $id) {
195 $headers[] = '#'.$questions[$id]->number
;
199 $headers[] = get_string('feedback', 'quiz');
202 foreach ($headers as $item) {
203 $myxls->write(0,$colnum,$item,$formatbc);
207 } else if ($download =='Excel') {
208 require_once("$CFG->libdir/excellib.class.php");
211 // Creating a workbook
212 $workbook = new MoodleExcelWorkbook("-");
213 // Sending HTTP headers
214 $workbook->send($filename);
215 // Creating the first worksheet
216 $sheettitle = get_string('reportoverview','quiz');
217 $myxls =& $workbook->add_worksheet($sheettitle);
219 $format =& $workbook->add_format();
220 $format->set_bold(0);
221 $formatbc =& $workbook->add_format();
222 $formatbc->set_bold(1);
223 $formatbc->set_align('center');
224 $formatb =& $workbook->add_format();
225 $formatb->set_bold(1);
226 $formaty =& $workbook->add_format();
227 $formaty->set_bg_color('yellow');
228 $formatc =& $workbook->add_format();
229 $formatc->set_align('center');
230 $formatr =& $workbook->add_format();
231 $formatr->set_bold(1);
232 $formatr->set_color('red');
233 $formatr->set_align('center');
234 $formatg =& $workbook->add_format();
235 $formatg->set_bold(1);
236 $formatg->set_color('green');
237 $formatg->set_align('center');
238 // Here starts workshhet headers
240 $headers = array(get_string('fullname'), get_string('startedon', 'quiz'), get_string('timecompleted', 'quiz'), get_string('attemptduration', 'quiz'));
242 if ($quiz->grade
and $quiz->sumgrades
) {
243 $headers[] = get_string('grade', 'quiz').'/'.$quiz->grade
;
246 foreach ($questionids as $id) {
247 $headers[] = '#'.$questions[$id]->number
;
251 $headers[] = get_string('feedback', 'quiz');
254 foreach ($headers as $item) {
255 $myxls->write(0,$colnum,$item,$formatbc);
259 } else if ($download=='CSV') {
262 header("Content-Type: application/download\n");
263 header("Content-Disposition: attachment; filename=\"$filename\"");
264 header("Expires: 0");
265 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
266 header("Pragma: public");
268 $headers = get_string('fullname')."\t".get_string('startedon', 'quiz')."\t".get_string('timecompleted', 'quiz')."\t".get_string('attemptduration', 'quiz');
270 if ($quiz->grade
and $quiz->sumgrades
) {
271 $headers .= "\t".get_string('grade', 'quiz')."/".$quiz->grade
;
274 foreach ($questionids as $id) {
275 $headers .= "\t#".$questions[$id]->number
;
279 $headers .= "\t" . get_string('feedback', 'quiz');
284 $contextlists = get_related_contexts_string(get_context_instance(CONTEXT_COURSE
, $course->id
));
287 $select = 'SELECT '.sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')).' AS uniqueid, '.
288 'qa.uniqueid as attemptuniqueid, qa.id AS attempt, u.id AS userid, u.firstname, u.lastname, u.picture, '.
289 'qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ';
290 if ($course->id
!= SITEID
) { // this is too complicated, so just do it for each of the four cases.
291 if (!empty($currentgroup) && empty($noattempts)) {
292 // we want a particular group and we only want to see students WITH attempts.
293 // So join on groups_members and do an inner join on attempts.
294 $from = 'FROM '.$CFG->prefix
.'user u JOIN '.$CFG->prefix
.'role_assignments ra ON ra.userid = u.id '.
295 'JOIN '.$CFG->prefix
.'groups_members gm ON u.id = gm.userid '.
296 'JOIN '.$CFG->prefix
.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id
;
297 $where = ' WHERE ra.contextid ' . $contextlists . ' AND gm.groupid = '. $currentgroup .' AND qa.preview = 0';
298 } else if (!empty($currentgroup) && !empty($noattempts)) {
299 // We want a particular group and we want to do something funky with attempts
300 // So join on groups_members and left join on attempts...
301 $from = 'FROM '.$CFG->prefix
.'user u JOIN '.$CFG->prefix
.'role_assignments ra ON ra.userid = u.id '.
302 'JOIN '.$CFG->prefix
.'groups_members gm ON u.id = gm.userid '.
303 'LEFT JOIN '.$CFG->prefix
.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id
;
304 $where = ' WHERE ra.contextid ' .$contextlists . ' AND gm.groupid = '.$currentgroup;
305 if ($noattempts == 1) {
306 // noattempts = 1 means only no attempts, so make the left join ask for only records where the right is null (no attempts)
307 $where .= ' AND qa.userid IS NULL'; // show ONLY no attempts;
309 // We are including attempts, so exclude previews.
310 $where .= ' AND qa.preview = 0';
312 } else if (empty($currentgroup)) {
313 // We don't care about group, and we to do something funky with attempts
314 // So do a left join on attempts
315 $from = 'FROM '.$CFG->prefix
.'user u JOIN '.$CFG->prefix
.'role_assignments ra ON ra.userid = u.id LEFT JOIN '.$CFG->prefix
.'quiz_attempts qa ON u.id = qa.userid AND qa.quiz = '.$quiz->id
;
316 $where = " WHERE ra.contextid $contextlists";
317 if (empty($noattempts)) {
318 $where .= ' AND qa.userid IS NOT NULL AND qa.preview = 0'; // show ONLY students with attempts;
319 } else if ($noattempts == 1) {
320 // noattempts = 1 means only no attempts, so make the left join ask for only records where the right is null (no attempts)
321 $where .= ' AND qa.userid IS NULL'; // show ONLY students without attempts;
322 } else if ($noattempts == 3) {
323 // we want all attempts
324 $from = 'FROM '.$CFG->prefix
.'user u JOIN '.$CFG->prefix
.'quiz_attempts qa ON u.id = qa.userid ';
325 $where = ' WHERE qa.quiz = '.$quiz->id
.' AND qa.preview = 0';
326 } // noattempts = 2 means we want all students, with or without attempts
328 $countsql = 'SELECT COUNT(DISTINCT('.sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')).')) '.$from.$where;
330 if (empty($noattempts)) {
331 $from = 'FROM '.$CFG->prefix
.'user u JOIN '.$CFG->prefix
.'quiz_attempts qa ON u.id = qa.userid ';
332 $where = ' WHERE qa.quiz = '.$quiz->id
.' AND qa.preview = 0';
333 $countsql = 'SELECT COUNT(DISTINCT('.sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')).')) '.$from.$where;
337 // Add extra limits due to initials bar
338 if($table->get_sql_where()) {
339 $where .= ' AND '.$table->get_sql_where();
342 // Count the records NOW, before funky question grade sorting messes up $from
343 if (!empty($countsql)) {
344 $totalinitials = count_records_sql($countsql);
345 if ($table->get_sql_where()) {
346 $countsql .= ' AND '.$table->get_sql_where();
348 $total = count_records_sql($countsql);
352 // Add extra limits due to sorting by question grade
353 if($sort = $table->get_sql_sort()) {
354 $sortparts = explode(',', $sort);
356 $questionsort = false;
357 foreach($sortparts as $sortpart) {
358 $sortpart = trim($sortpart);
359 if(substr($sortpart, 0, 1) == '$') {
361 $qid = intval(substr($sortpart, 1));
362 $select .= ', grade ';
363 $from .= ' LEFT JOIN '.$CFG->prefix
.'question_sessions qns ON qns.attemptid = qa.id '.
364 'LEFT JOIN '.$CFG->prefix
.'question_states qs ON qs.id = qns.newgraded ';
365 $where .= ' AND ('.sql_isnull('qns.questionid').' OR qns.questionid = '.$qid.')';
366 $newsort[] = 'grade '.(strpos($sortpart, 'ASC')?
'ASC' : 'DESC');
367 $questionsort = true;
370 $newsort[] = $sortpart;
374 // Reconstruct the sort string
375 $sort = ' ORDER BY '.implode(', ', $newsort);
378 // Fix some wired sorting
380 $sort = ' ORDER BY uniqueid';
383 $table->pagesize($pagesize, $total);
386 // If there is feedback, include it in the query.
388 $factor = $quiz->grade
/$quiz->sumgrades
;
389 $select .= ', qf.feedbacktext ';
390 $from .= " JOIN {$CFG->prefix}quiz_feedback qf ON " .
391 "qf.quizid = $quiz->id AND qf.mingrade <= qa.sumgrades * $factor AND qa.sumgrades * $factor < qf.maxgrade";
394 // Fetch the attempts
395 if (!empty($from)) { // if we're in the site course and displaying no attempts, it makes no sense to do the query.
397 $attempts = get_records_sql($select.$from.$where.$sort,
398 $table->get_page_start(), $table->get_page_size());
400 $attempts = get_records_sql($select.$from.$where.$sort);
409 $table->initialbars($totalinitials>20);
411 if(!empty($attempts) ||
!empty($noattempts)) {
413 foreach ($attempts as $attempt) {
415 $picture = print_user_picture($attempt->userid
, $course->id
, $attempt->picture
, false, true);
417 // uncomment the commented lines below if you are choosing to show unenrolled users and
418 // have uncommented the corresponding lines earlier in this script
419 //if (in_array($attempt->userid, $unenrolledusers)) {
420 // $userlink = '<a class="dimmed" href="'.$CFG->wwwroot.'/user/view.php?id='.$attempt->userid.'&course='.$course->id.'">'.fullname($attempt).'</a>';
423 $userlink = '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$attempt->userid
.'&course='.$course->id
.'">'.fullname($attempt).'</a>';
427 '<input type="checkbox" name="attemptid[]" value="'.$attempt->attempt
.'" />',
430 empty($attempt->attempt
) ?
'-' : '<a href="review.php?q='.$quiz->id
.'&attempt='.$attempt->attempt
.'">'.userdate($attempt->timestart
, $strtimeformat).'</a>',
431 empty($attempt->timefinish
) ?
'-' : '<a href="review.php?q='.$quiz->id
.'&attempt='.$attempt->attempt
.'">'.userdate($attempt->timefinish
, $strtimeformat).'</a>',
432 empty($attempt->attempt
) ?
'-' : (empty($attempt->timefinish
) ?
get_string('unfinished', 'quiz') : format_time($attempt->duration
))
435 $row = array(fullname($attempt),
436 empty($attempt->attempt
) ?
'-' : userdate($attempt->timestart
, $strtimeformat),
437 empty($attempt->timefinish
) ?
'-' : userdate($attempt->timefinish
, $strtimeformat),
438 empty($attempt->attempt
) ?
'-' : (empty($attempt->timefinish
) ?
get_string('unfinished', 'quiz') : format_time($attempt->duration
))
442 if ($quiz->grade
and $quiz->sumgrades
) {
444 $row[] = $attempt->sumgrades
=== NULL ?
'-' : '<a href="review.php?q='.$quiz->id
.'&attempt='.$attempt->attempt
.'">'.round($attempt->sumgrades
/ $quiz->sumgrades
* $quiz->grade
,$quiz->decimalpoints
).'</a>';
446 $row[] = $attempt->sumgrades
=== NULL ?
'-' : round($attempt->sumgrades
/ $quiz->sumgrades
* $quiz->grade
,$quiz->decimalpoints
);
450 if(empty($attempt->attempt
)) {
451 foreach($questionids as $questionid) {
455 foreach($questionids as $questionid) {
456 if ($gradedstateid = get_field('question_sessions', 'newgraded', 'attemptid', $attempt->attemptuniqueid
, 'questionid', $questionid)) {
457 $grade = round(get_field('question_states', 'grade', 'id', $gradedstateid), $quiz->decimalpoints
);
462 $row[] = link_to_popup_window ('/mod/quiz/reviewquestion.php?state='.$gradedstateid.'&number='.$questions[$questionid]->number
, 'reviewquestion', $grade, 450, 650, $strreviewquestion, 'none', true);
470 if ($attempt->timefinish
) {
471 $row[] = format_text($attempt->feedbacktext
, FORMAT_MOODLE
, $nocleanformatoptions);
477 $table->add_data($row);
478 } else if ($download == 'Excel' or $download == 'ODS') {
480 foreach($row as $item){
481 $myxls->write($rownum,$colnum,$item,$format);
485 } else if ($download=='CSV') {
486 $text = implode("\t", $row);
493 echo '<div id="tablecontainer">';
494 echo '<form id="attemptsform" method="post" action="' . $reporturlwithoptions . '" onsubmit="var menu = document.getElementById(\'menuaction\'); return (menu.options[menu.selectedIndex].value == \'delete\' ? confirm(\''.$strreallydel.'\') : true);">';
498 $table->print_html();
500 // Print "Select all" etc.
501 if (!empty($attempts)) {
502 echo '<table id="commands">';
504 echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectall', 'quiz').'</a> / ';
505 echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectnone', 'quiz').'</a> ';
507 $options = array('delete' => get_string('delete'));
508 echo choose_from_menu($options, 'action', '', get_string('withselected', 'quiz'), 'if(this.selectedIndex > 0) submitFormById(\'attemptsform\');', '', true);
509 echo '<noscript id="noscriptmenuaction" style="display: inline;"><div>';
510 echo '<input type="submit" value="'.get_string('go').'" /></div></noscript>';
511 echo '<script type="text/javascript">'."\n<!--\n".'document.getElementById("noscriptmenuaction").style.display = "none";'."\n-->\n".'</script>';
512 echo '</td></tr></table>';
516 echo '</form></div>';
518 if (!empty($attempts)) {
519 echo '<table class="boxaligncenter"><tr>';
521 $options["id"] = $cm->id
;
522 $options["q"] = $quiz->id
;
523 $options['sesskey'] = sesskey();
524 $options["noheader"] = "yes";
525 $options['noattempts'] = $noattempts;
526 $options['detailedmarks'] = $detailedmarks;
528 $options["download"] = "ODS";
529 print_single_button($reporturl, $options, get_string("downloadods"));
532 $options["download"] = "Excel";
533 print_single_button($reporturl, $options, get_string("downloadexcel"));
536 $options["download"] = "CSV";
537 print_single_button($reporturl, $options, get_string("downloadtext"));
540 helpbutton('overviewdownload', get_string('overviewdownload', 'quiz_overview'), 'quiz');
542 echo '</tr></table>';
544 } else if ($download == 'Excel' or $download == 'ODS') {
547 } else if ($download == 'CSV') {
553 $table->print_html();
556 // Print display options
557 echo '<div class="controls">';
558 echo '<form id="options" action="' . $reporturl . '" method="get">';
560 echo '<p>'.get_string('displayoptions', 'quiz').': </p>';
561 echo '<input type="hidden" name="id" value="'.$cm->id
.'" />';
562 echo '<input type="hidden" name="q" value="'.$quiz->id
.'" />';
563 echo '<input type="hidden" name="noattempts" value="0" />';
564 echo '<input type="hidden" name="detailedmarks" value="0" />';
565 echo '<table id="overview-options" class="boxaligncenter">';
566 echo '<tr align="left">';
567 echo '<td><label for="pagesize">'.get_string('pagesize', 'quiz').'</label></td>';
568 echo '<td><input type="text" id="pagesize" name="pagesize" size="3" value="'.$pagesize.'" /></td>';
570 echo '<tr align="left">';
571 echo '<td colspan="2">';
572 $options = array(0 => get_string('attemptsonly','quiz_overview', $course->students
));
573 if ($course->id
!= SITEID
) {
574 $options[1] = get_string('noattemptsonly', 'quiz_overview', $course->students
);
575 $options[2] = get_string('allstudents','quiz_overview', $course->students
);
576 $options[3] = get_string('allattempts','quiz_overview');
578 choose_from_menu($options,'noattempts',$noattempts,'');
580 echo '<tr align="left">';
581 echo '<td colspan="2"><input type="checkbox" id="checkdetailedmarks" name="detailedmarks" '.($detailedmarks?
'checked="checked" ':'').'value="1" /> <label for="checkdetailedmarks">'.get_string('showdetailedmarks', 'quiz').'</label> ';
583 echo '<tr><td colspan="2" align="center">';
584 echo '<input type="submit" value="'.get_string('go').'" />';
585 echo '</td></tr></table>';