MDL-28282 Scorm Restorting Groups support in Scomr reports
[moodle.git] / mod / scorm / report / basic / report.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/>.
16 /**
17  * Core Report class of basic reporting plugin
18  * @package    scormreport
19  * @subpackage basic
20  * @author     Dan Marsden and Ankit Kumar Agarwal
21  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22  */
24 defined('MOODLE_INTERNAL') || die();
26 class scorm_basic_report extends scorm_default_report {
27     /**
28      * displays the full report
29      * @param stdClass $scorm full SCORM object
30      * @param stdClass $cm - full course_module object
31      * @param stdClass $course - full course object
32      * @param string $download - type of download being requested
33      */
34     function display($scorm, $cm, $course, $download) {
35         global $CFG, $DB, $OUTPUT, $PAGE;
36         $contextmodule= get_context_instance(CONTEXT_MODULE, $cm->id);
37         $action = optional_param('action', '', PARAM_ALPHA);
38         $attemptids = optional_param_array('attemptid', array(), PARAM_RAW);
40         if ($action == 'delete' && has_capability('mod/scorm:deleteresponses', $contextmodule) && confirm_sesskey()) {
41             if (scorm_delete_responses($attemptids, $scorm)) { //delete responses.
42                 add_to_log($course->id, 'scorm', 'delete attempts', 'report.php?id=' . $cm->id, implode(",", $attemptids), $cm->id);
43                 echo $OUTPUT->notification(get_string('scormresponsedeleted', 'scorm'), 'notifysuccess');
44             }
45         }
46         // find out current groups mode
47         $currentgroup = groups_get_activity_group($cm, true);
49         // detailed report
50         $mform = new mod_scorm_report_settings($PAGE->url, compact('currentgroup'));
51         if ($fromform = $mform->get_data()) {
52             $detailedrep = $fromform->detailedrep;
53             $pagesize = $fromform->pagesize;
54             $attemptsmode = !empty($fromform->attemptsmode) ? $fromform->attemptsmode : SCORM_REPORT_ATTEMPTS_ALL_STUDENTS;
55             set_user_preference('scorm_report_detailed', $detailedrep);
56             set_user_preference('scorm_report_pagesize', $pagesize);
57         } else {
58             $detailedrep = get_user_preferences('scorm_report_detailed', false);
59             $pagesize = get_user_preferences('scorm_report_pagesize', 0);
60             $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_STUDENTS_WITH, PARAM_INT);
61         }
62         if ($pagesize < 1) {
63             $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
64         }
66         // select group menu
67         $displayoptions = array();
68         $displayoptions['attemptsmode'] = $attemptsmode;
69         if ($groupmode = groups_get_activity_groupmode($cm)) {   // Groups are being used
70             if (!$download) {
71                 groups_print_activity_menu($cm, new moodle_url($PAGE->url, $displayoptions));
72             }
73         }
75         // We only want to show the checkbox to delete attempts
76         // if the user has permissions and if the report mode is showing attempts.
77         $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule)
78                 && ($attemptsmode!= SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO);
79         // select the students
80         $nostudents = false;
82         if (empty($currentgroup)) {
83             // all users who can attempt scoes
84             if (!$students = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', '', '', false)) {
85                 echo $OUTPUT->notification(get_string('nostudentsyet'));
86                 $nostudents = true;
87                 $allowedlist = '';
88             } else {
89                 $allowedlist = join(',', array_keys($students));
90             }
91         } else {
92             // all users who can attempt scoes and who are in the currently selected group
93             if (!$groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', $currentgroup, '', false)) {
94                 echo $OUTPUT->notification(get_string('nostudentsingroup'));
95                 $nostudents = true;
96                 $groupstudents = array();
97             }
98             $allowedlist = join(',', array_keys($groupstudents));
99         }
101         if ( !$nostudents ) {
102             // Now check if asked download of data
103             $coursecontext = context_course::instance($course->id);
104             if ($download) {
105                 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
106                 $filename = clean_filename("$shortname ".format_string($scorm->name, true));
107             }
109             // Define table columns
110             $columns = array();
111             $headers = array();
112             if (!$download && $candelete) {
113                 $columns[]= 'checkbox';
114                 $headers[]= null;
115             }
116             if (!$download && $CFG->grade_report_showuserimage) {
117                 $columns[]= 'picture';
118                 $headers[]= '';
119             }
120             $columns[]= 'fullname';
121             $headers[]= get_string('name');
122             $extrafields = get_extra_user_fields($coursecontext);
123             foreach ($extrafields as $field) {
124                 $columns[] = $field;
125                 $headers[] = get_user_field_name($field);
126             }
128             $columns[]= 'attempt';
129             $headers[]= get_string('attempt', 'scorm');
130             $columns[]= 'start';
131             $headers[]= get_string('started', 'scorm');
132             $columns[]= 'finish';
133             $headers[]= get_string('last', 'scorm');
134             $columns[]= 'score';
135             $headers[]= get_string('score', 'scorm');
136             if ($detailedrep && $scoes = $DB->get_records('scorm_scoes', array("scorm"=>$scorm->id), 'id')) {
137                 foreach ($scoes as $sco) {
138                     if ($sco->launch!='') {
139                         $columns[]= 'scograde'.$sco->id;
140                         $headers[]= format_string($sco->title);
141                         $table->head[]= format_string($sco->title);
142                     }
143                 }
144             } else {
145                 $scoes = null;
146             }
148             if (!$download) {
149                 $table = new flexible_table('mod-scorm-report');
151                 $table->define_columns($columns);
152                 $table->define_headers($headers);
153                 $table->define_baseurl($PAGE->url);
155                 $table->sortable(true);
156                 $table->collapsible(true);
158                 $table->column_suppress('picture');
159                 $table->column_suppress('fullname');
160                 // I wonder why it is doing all this suppress malarkey?
161                 // However, if it was suppressing idnumber field before, I guess
162                 // it needs to suppress all the user identity fields now
163                 foreach ($extrafields as $field) {
164                     $table->column_suppress($field);
165                 }
167                 $table->no_sorting('start');
168                 $table->no_sorting('finish');
169                 $table->no_sorting('score');
170                 if ( $scoes ) {
171                     foreach ($scoes as $sco) {
172                         if ($sco->launch!='') {
173                             $table->no_sorting('scograde'.$sco->id);
174                         }
175                     }
176                 }
178                 $table->column_class('picture', 'picture');
179                 $table->column_class('fullname', 'bold');
180                 $table->column_class('score', 'bold');
182                 $table->set_attribute('cellspacing', '0');
183                 $table->set_attribute('id', 'attempts');
184                 $table->set_attribute('class', 'generaltable generalbox');
186                 // Start working -- this is necessary as soon as the niceties are over
187                 $table->setup();
188             } else if ($download =='ODS') {
189                 require_once("$CFG->libdir/odslib.class.php");
191                 $filename .= ".ods";
192                 // Creating a workbook
193                 $workbook = new MoodleODSWorkbook("-");
194                 // Sending HTTP headers
195                 $workbook->send($filename);
196                 // Creating the first worksheet
197                 $sheettitle = get_string('report', 'scorm');
198                 $myxls =& $workbook->add_worksheet($sheettitle);
199                 // format types
200                 $format =& $workbook->add_format();
201                 $format->set_bold(0);
202                 $formatbc =& $workbook->add_format();
203                 $formatbc->set_bold(1);
204                 $formatbc->set_align('center');
205                 $formatb =& $workbook->add_format();
206                 $formatb->set_bold(1);
207                 $formaty =& $workbook->add_format();
208                 $formaty->set_bg_color('yellow');
209                 $formatc =& $workbook->add_format();
210                 $formatc->set_align('center');
211                 $formatr =& $workbook->add_format();
212                 $formatr->set_bold(1);
213                 $formatr->set_color('red');
214                 $formatr->set_align('center');
215                 $formatg =& $workbook->add_format();
216                 $formatg->set_bold(1);
217                 $formatg->set_color('green');
218                 $formatg->set_align('center');
219                 // Here starts workshhet headers
221                 $colnum = 0;
222                 foreach ($headers as $item) {
223                     $myxls->write(0, $colnum, $item, $formatbc);
224                     $colnum++;
225                 }
226                 $rownum=1;
227             } else if ($download =='Excel') {
228                 require_once("$CFG->libdir/excellib.class.php");
230                 $filename .= ".xls";
231                 // Creating a workbook
232                 $workbook = new MoodleExcelWorkbook("-");
233                 // Sending HTTP headers
234                 $workbook->send($filename);
235                 // Creating the first worksheet
236                 $sheettitle = get_string('report', 'scorm');
237                 $myxls =& $workbook->add_worksheet($sheettitle);
238                 // format types
239                 $format =& $workbook->add_format();
240                 $format->set_bold(0);
241                 $formatbc =& $workbook->add_format();
242                 $formatbc->set_bold(1);
243                 $formatbc->set_align('center');
244                 $formatb =& $workbook->add_format();
245                 $formatb->set_bold(1);
246                 $formaty =& $workbook->add_format();
247                 $formaty->set_bg_color('yellow');
248                 $formatc =& $workbook->add_format();
249                 $formatc->set_align('center');
250                 $formatr =& $workbook->add_format();
251                 $formatr->set_bold(1);
252                 $formatr->set_color('red');
253                 $formatr->set_align('center');
254                 $formatg =& $workbook->add_format();
255                 $formatg->set_bold(1);
256                 $formatg->set_color('green');
257                 $formatg->set_align('center');
259                 $colnum = 0;
260                 foreach ($headers as $item) {
261                     $myxls->write(0, $colnum, $item, $formatbc);
262                     $colnum++;
263                 }
264                 $rownum=1;
265             } else if ($download=='CSV') {
266                 $filename .= ".txt";
267                 header("Content-Type: application/download\n");
268                 header("Content-Disposition: attachment; filename=\"$filename\"");
269                 header("Expires: 0");
270                 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
271                 header("Pragma: public");
272                 echo implode("\t", $headers)." \n";
273             }
275                             // Construct the SQL
276             $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
277             $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' .
278                     'u.id AS userid, u.idnumber, u.firstname, u.lastname, u.picture, u.imagealt, u.email' .
279                     get_extra_user_fields_sql($coursecontext, 'u', '', array('idnumber')) . ' ';
281             // This part is the same for all cases - join users and scorm_scoes_track tables
282             $from = 'FROM {user} u ';
283             $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id;
284             switch ($attemptsmode) {
285                 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
286                     // Show only students with attempts
287                     $where = ' WHERE u.id IN (' .$allowedlist. ') AND st.userid IS NOT NULL';
288                     break;
289                 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
290                     // Show only students without attempts
291                     $where = ' WHERE u.id IN (' .$allowedlist. ') AND st.userid IS NULL';
292                     break;
293                 case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
294                     // Show all students with or without attempts
295                     $where = ' WHERE u.id IN (' .$allowedlist. ') AND (st.userid IS NOT NULL OR st.userid IS NULL)';
296                     break;
297             }
299             $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, ';
300             $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, ';
301             $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
302             $countsql .= $from.$where;
303             $params = array();
305             if (!$download) {
306                 $sort = $table->get_sql_sort();
307             } else {
308                 $sort = '';
309             }
310             // Fix some wired sorting
311             if (empty($sort)) {
312                 $sort = ' ORDER BY uniqueid';
313             } else {
314                 $sort = ' ORDER BY '.$sort;
315             }
317             if (!$download) {
318                 // Add extra limits due to initials bar
319                 list($twhere, $tparams) = $table->get_sql_where();
320                 if ($twhere) {
321                     $where .= ' AND '.$twhere; //initial bar
322                     $params = array_merge($params, $tparams);
323                 }
325                 if (!empty($countsql)) {
326                     $count = $DB->get_record_sql($countsql);
327                     $totalinitials = $count->nbresults;
328                     if ($twhere) {
329                         $countsql .= ' AND '.$twhere;
330                     }
331                     $count = $DB->get_record_sql($countsql, $params);
332                     $total  = $count->nbresults;
333                 }
335                 $table->pagesize($pagesize, $total);
337                 echo '<div class="quizattemptcounts">';
338                 if ( $count->nbresults == $count->nbattempts ) {
339                     echo get_string('reportcountattempts', 'scorm', $count);
340                 } else if ( $count->nbattempts>0 ) {
341                     echo get_string('reportcountallattempts', 'scorm', $count);
342                 } else {
343                     echo $count->nbusers.' '.get_string('users');
344                 }
345                 echo '</div>';
346             }
348             // Fetch the attempts
349             if (!$download) {
350                 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params,
351                 $table->get_page_start(), $table->get_page_size());
352                 echo '<div id="scormtablecontainer">';
353                 if ($candelete) {
354                     // Start form
355                     $strreallydel  = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
356                     echo '<form id="attemptsform" method="post" action="' . $PAGE->url->out(false) .
357                          '" onsubmit="return confirm(\''.$strreallydel.'\');">';
358                     echo '<input type="hidden" name="action" value="delete"/>';
359                     echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
360                     echo '<div style="display: none;">';
361                     echo html_writer::input_hidden_params($PAGE->url);
362                     echo '</div>';
363                     echo '<div>';
364                 }
365                 $table->initialbars($totalinitials>20); // Build table rows
366             } else {
367                 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params);
368             }
370             if ($attempts) {
371                 foreach ($attempts as $scouser) {
372                     $row = array();
373                     if (!empty($scouser->attempt)) {
374                         $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
375                     } else {
376                         $timetracks = '';
377                     }
378                     if (in_array('checkbox', $columns)) {
379                         if ($candelete && !empty($timetracks->start)) {
380                             $row[] = '<input type="checkbox" name="attemptid[]" value="'. $scouser->userid . ':' . $scouser->attempt . '" />';
381                         } else if ($candelete) {
382                             $row[] = '';
383                         }
384                     }
385                     if (in_array('picture', $columns)) {
386                         $user = (object)array(
387                                     'id'=>$scouser->userid,
388                                     'picture'=>$scouser->picture,
389                                     'imagealt'=>$scouser->imagealt,
390                                     'email'=>$scouser->email,
391                                     'firstname'=>$scouser->firstname,
392                                     'lastname'=>$scouser->lastname);
393                         $row[] = $OUTPUT->user_picture($user, array('courseid'=>$course->id));
394                     }
395                     if (!$download) {
396                         $row[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$scouser->userid.'&amp;course='.$course->id.'">'.fullname($scouser).'</a>';
397                     } else {
398                         $row[] = fullname($scouser);
399                     }
400                     foreach ($extrafields as $field) {
401                         $row[] = s($scouser->{$field});
402                     }
403                     if (empty($timetracks->start)) {
404                         $row[] = '-';
405                         $row[] = '-';
406                         $row[] = '-';
407                         $row[] = '-';
408                     } else {
409                         if (!$download) {
410                             $row[] = '<a href="userreport.php?a='.$scorm->id.'&amp;user='.$scouser->userid.'&amp;attempt='.$scouser->attempt.'">'.$scouser->attempt.'</a>';
411                         } else {
412                             $row[] = $scouser->attempt;
413                         }
414                         if ($download =='ODS' || $download =='Excel' ) {
415                             $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
416                         } else {
417                             $row[] = userdate($timetracks->start);
418                         }
419                         if ($download =='ODS' || $download =='Excel' ) {
420                             $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
421                         } else {
422                             $row[] = userdate($timetracks->finish);
423                         }
424                         $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
425                     }
426                                     // print out all scores of attempt
427                     if ($scoes) {
428                         foreach ($scoes as $sco) {
429                             if ($sco->launch!='') {
430                                 if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
431                                     if ($trackdata->status == '') {
432                                         $trackdata->status = 'notattempted';
433                                     }
434                                     $strstatus = get_string($trackdata->status, 'scorm');
435                                     // if raw score exists, print it
436                                     if ($trackdata->score_raw != '') {
437                                         $score = $trackdata->score_raw;
438                                         // add max score if it exists
439                                         if (scorm_version_check($scorm->version, SCORM_13)) {
440                                             $maxkey = 'cmi.score.max';
441                                         } else {
442                                             $maxkey = 'cmi.core.score.max';
443                                         }
444                                         if (isset($trackdata->$maxkey)) {
445                                             $score .= '/'.$trackdata->$maxkey;
446                                         }
447                                         // else print out status
448                                     } else {
449                                         $score = $strstatus;
450                                     }
451                                     if (!$download) {
452                                         $row[] = '<img src="'.$OUTPUT->pix_url($trackdata->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>
453                                                 <a href="userreport.php?b='.$sco->id.'&amp;user='.$scouser->userid.'&amp;attempt='.$scouser->attempt.
454                                                 '" title="'.get_string('details', 'scorm').'">'.$score.'</a>';
455                                     } else {
456                                         $row[] = $score;
457                                     }
458                                 } else {
459                                     // if we don't have track data, we haven't attempted yet
460                                     $strstatus = get_string('notattempted', 'scorm');
461                                     if (!$download) {
462                                         $row[] = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>'.$strstatus;
463                                     } else {
464                                         $row[] = $strstatus;
465                                     }
466                                 }
467                             }
468                         }
469                     }
471                     if (!$download) {
472                         $table->add_data($row);
473                     } else if ($download == 'Excel' or $download == 'ODS') {
474                         $colnum = 0;
475                         foreach ($row as $item) {
476                             $myxls->write($rownum, $colnum, $item, $format);
477                             $colnum++;
478                         }
479                         $rownum++;
480                     } else if ($download=='CSV') {
481                         $text = implode("\t", $row);
482                         echo $text." \n";
483                     }
484                 }
485                 if (!$download) {
486                     $table->finish_output();
487                     if ($candelete) {
488                         echo '<table id="commands">';
489                         echo '<tr><td>';
490                         echo '<a href="javascript:select_all_in(\'DIV\', null, \'scormtablecontainer\');">'.
491                              get_string('selectall', 'scorm').'</a> / ';
492                         echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'scormtablecontainer\');">'.
493                              get_string('selectnone', 'scorm').'</a> ';
494                         echo '&nbsp;&nbsp;';
495                         echo '<input type="submit" value="'.get_string('deleteselected', 'quiz_overview').'"/>';
496                         echo '</td></tr></table>';
497                         // Close form
498                         echo '</div>';
499                         echo '</form>';
500                     }
501                     echo '</div>';
502                     if (!empty($attempts)) {
503                         echo '<table class="boxaligncenter"><tr>';
504                         echo '<td>';
505                         echo $OUTPUT->single_button(new moodle_url($PAGE->url,
506                                                                    array('download'=>'ODS') + $displayoptions),
507                                                                    get_string('downloadods'));
508                         echo "</td>\n";
509                         echo '<td>';
510                         echo $OUTPUT->single_button(new moodle_url($PAGE->url,
511                                                                    array('download'=>'Excel') + $displayoptions),
512                                                                    get_string('downloadexcel'));
513                         echo "</td>\n";
514                         echo '<td>';
515                         echo $OUTPUT->single_button(new moodle_url($PAGE->url,
516                                                                    array('download'=>'CSV') + $displayoptions),
517                                                                    get_string('downloadtext'));
518                         echo "</td>\n";
519                         echo "<td>";
520                         echo "</td>\n";
521                         echo '</tr></table>';
522                     }
523                 }
524                 if (!$download) {
525                     $mform->set_data(compact('detailedrep', 'pagesize'));
526                     $mform->display();
527                 }
528             } else {
529                 if ($candelete && !$download) {
530                     echo '</div>';
531                     echo '</form>';
532                 }
533                 echo '</div>';
534                 echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
535             }
536             if ($download == 'Excel' or $download == 'ODS') {
537                 $workbook->close();
538                 exit;
539             } else if ($download == 'CSV') {
540                 exit;
541             }
542         } else {
543             echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
544         }
545     }// function ends