2 // This file is part of Moodle - http://moodle.org/
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.
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.
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 * Core Report class of objectives SCORM report plugin
18 * @package scormreport_objectives
19 * @author Dan Marsden <dan@danmarsden.com>
20 * @copyright 2013 Dan Marsden
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 namespace scormreport_objectives;
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->dirroot.'/mod/scorm/report/objectives/responsessettings_form.php');
31 * Objectives report class
33 * @copyright 2013 Dan Marsden
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class report extends \mod_scorm\report {
38 * displays the full report
39 * @param \stdClass $scorm full SCORM object
40 * @param \stdClass $cm - full course_module object
41 * @param \stdClass $course - full course object
42 * @param string $download - type of download being requested
44 public function display($scorm, $cm, $course, $download) {
45 global $CFG, $DB, $OUTPUT, $PAGE;
47 $contextmodule = \context_module::instance($cm->id);
48 $action = optional_param('action', '', PARAM_ALPHA);
49 $attemptids = optional_param_array('attemptid', array(), PARAM_RAW);
50 $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_ALL_STUDENTS, PARAM_INT);
51 $PAGE->set_url(new \moodle_url($PAGE->url, array('attemptsmode' => $attemptsmode)));
53 if ($action == 'delete' && has_capability('mod/scorm:deleteresponses', $contextmodule) && confirm_sesskey()) {
54 if (scorm_delete_responses($attemptids, $scorm)) { // Delete responses.
55 echo $OUTPUT->notification(get_string('scormresponsedeleted', 'scorm'), 'notifysuccess');
58 // Find out current groups mode.
59 $currentgroup = groups_get_activity_group($cm, true);
62 $mform = new \mod_scorm_report_objectives_settings($PAGE->url, compact('currentgroup'));
63 if ($fromform = $mform->get_data()) {
64 $pagesize = $fromform->pagesize;
65 $showobjectivescore = $fromform->objectivescore;
66 set_user_preference('scorm_report_pagesize', $pagesize);
67 set_user_preference('scorm_report_objectives_score', $showobjectivescore);
69 $pagesize = get_user_preferences('scorm_report_pagesize', 0);
70 $showobjectivescore = get_user_preferences('scorm_report_objectives_score', 0);
73 $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
77 $displayoptions = array();
78 $displayoptions['attemptsmode'] = $attemptsmode;
79 $displayoptions['objectivescore'] = $showobjectivescore;
81 $mform->set_data($displayoptions + array('pagesize' => $pagesize));
82 if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used.
84 groups_print_activity_menu($cm, new \moodle_url($PAGE->url, $displayoptions));
87 $formattextoptions = array('context' => \context_course::instance($course->id));
89 // We only want to show the checkbox to delete attempts
90 // if the user has permissions and if the report mode is showing attempts.
91 $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule)
92 && ($attemptsmode != SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO);
93 // Select the students.
96 if (empty($currentgroup)) {
97 // All users who can attempt scoes.
98 if (!$students = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', 'u.id', '', '', '', '', '', false)) {
99 echo $OUTPUT->notification(get_string('nostudentsyet'));
103 $allowedlist = array_keys($students);
107 // All users who can attempt scoes and who are in the currently selected group.
108 $groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack',
109 'u.id', '', '', '', $currentgroup, '', false);
110 if (!$groupstudents) {
111 echo $OUTPUT->notification(get_string('nostudentsingroup'));
113 $groupstudents = array();
115 $allowedlist = array_keys($groupstudents);
116 unset($groupstudents);
118 if ( !$nostudents ) {
119 // Now check if asked download of data.
120 $coursecontext = \context_course::instance($course->id);
122 $filename = clean_filename("$course->shortname ".format_string($scorm->name, true, $formattextoptions));
125 // Define table columns.
128 if (!$download && $candelete) {
129 $columns[] = 'checkbox';
132 if (!$download && $CFG->grade_report_showuserimage) {
133 $columns[] = 'picture';
136 $columns[] = 'fullname';
137 $headers[] = get_string('name');
139 $extrafields = get_extra_user_fields($coursecontext);
140 foreach ($extrafields as $field) {
142 $headers[] = get_user_field_name($field);
144 $columns[] = 'attempt';
145 $headers[] = get_string('attempt', 'scorm');
146 $columns[] = 'start';
147 $headers[] = get_string('started', 'scorm');
148 $columns[] = 'finish';
149 $headers[] = get_string('last', 'scorm');
150 $columns[] = 'score';
151 $headers[] = get_string('score', 'scorm');
152 $scoes = $DB->get_records('scorm_scoes', array("scorm" => $scorm->id), 'sortorder, id');
153 foreach ($scoes as $sco) {
154 if ($sco->launch != '') {
155 $columns[] = 'scograde'.$sco->id;
156 $headers[] = format_string($sco->title, '', $formattextoptions);
161 list($usql, $params) = $DB->get_in_or_equal($allowedlist, SQL_PARAMS_NAMED);
162 // Construct the SQL.
163 $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
164 $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' .
165 \user_picture::fields('u', array('idnumber'), 'userid') .
166 get_extra_user_fields_sql($coursecontext, 'u', '', array('email', 'idnumber')) . ' ';
168 // This part is the same for all cases - join users and scorm_scoes_track tables.
169 $from = 'FROM {user} u ';
170 $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id;
171 switch ($attemptsmode) {
172 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
173 // Show only students with attempts.
174 $where = ' WHERE u.id ' .$usql. ' AND st.userid IS NOT NULL';
176 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
177 // Show only students without attempts.
178 $where = ' WHERE u.id ' .$usql. ' AND st.userid IS NULL';
180 case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
181 // Show all students with or without attempts.
182 $where = ' WHERE u.id ' .$usql. ' AND (st.userid IS NOT NULL OR st.userid IS NULL)';
186 $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, ';
187 $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, ';
188 $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
189 $countsql .= $from.$where;
191 $nbmaincolumns = count($columns); // Get number of main columns used.
193 $objectives = get_scorm_objectives($scorm->id);
195 foreach ($objectives as $scoid => $sco) {
196 foreach ($sco as $id => $objectivename) {
197 $colid = $scoid.'objectivestatus' . $id;
201 if (!$displayoptions['objectivescore']) {
202 // Display the objective name only.
203 $headers[] = $objectivename;
205 // Display the objective status header with a "status" suffix to avoid confusion.
206 $headers[] = $objectivename. ' '. get_string('status', 'scormreport_objectives');
208 // Now print objective score headers.
209 $colid = $scoid.'objectivescore' . $id;
212 $headers[] = $objectivename. ' '. get_string('score', 'scormreport_objectives');
217 $emptycell = ''; // Used when an empty cell is being printed - in html we add a space.
219 $emptycell = ' ';
220 $table = new \flexible_table('mod-scorm-report');
222 $table->define_columns($columns);
223 $table->define_headers($headers);
224 $table->define_baseurl($PAGE->url);
226 $table->sortable(true);
227 $table->collapsible(true);
229 // This is done to prevent redundant data, when a user has multiple attempts.
230 $table->column_suppress('picture');
231 $table->column_suppress('fullname');
232 foreach ($extrafields as $field) {
233 $table->column_suppress($field);
235 foreach ($nosort as $field) {
236 $table->no_sorting($field);
239 $table->no_sorting('start');
240 $table->no_sorting('finish');
241 $table->no_sorting('score');
242 $table->no_sorting('checkbox');
243 $table->no_sorting('picture');
245 foreach ($scoes as $sco) {
246 if ($sco->launch != '') {
247 $table->no_sorting('scograde'.$sco->id);
251 $table->column_class('picture', 'picture');
252 $table->column_class('fullname', 'bold');
253 $table->column_class('score', 'bold');
255 $table->set_attribute('cellspacing', '0');
256 $table->set_attribute('id', 'attempts');
257 $table->set_attribute('class', 'generaltable generalbox');
259 // Start working -- this is necessary as soon as the niceties are over.
261 } else if ($download == 'ODS') {
262 require_once("$CFG->libdir/odslib.class.php");
265 // Creating a workbook.
266 $workbook = new \MoodleODSWorkbook("-");
267 // Sending HTTP headers.
268 $workbook->send($filename);
269 // Creating the first worksheet.
270 $sheettitle = get_string('report', 'scorm');
271 $myxls = $workbook->add_worksheet($sheettitle);
273 $format = $workbook->add_format();
274 $format->set_bold(0);
275 $formatbc = $workbook->add_format();
276 $formatbc->set_bold(1);
277 $formatbc->set_align('center');
278 $formatb = $workbook->add_format();
279 $formatb->set_bold(1);
280 $formaty = $workbook->add_format();
281 $formaty->set_bg_color('yellow');
282 $formatc = $workbook->add_format();
283 $formatc->set_align('center');
284 $formatr = $workbook->add_format();
285 $formatr->set_bold(1);
286 $formatr->set_color('red');
287 $formatr->set_align('center');
288 $formatg = $workbook->add_format();
289 $formatg->set_bold(1);
290 $formatg->set_color('green');
291 $formatg->set_align('center');
292 // Here starts workshhet headers.
295 foreach ($headers as $item) {
296 $myxls->write(0, $colnum, $item, $formatbc);
300 } else if ($download == 'Excel') {
301 require_once("$CFG->libdir/excellib.class.php");
304 // Creating a workbook.
305 $workbook = new \MoodleExcelWorkbook("-");
306 // Sending HTTP headers.
307 $workbook->send($filename);
308 // Creating the first worksheet.
309 $sheettitle = get_string('report', 'scorm');
310 $myxls = $workbook->add_worksheet($sheettitle);
312 $format = $workbook->add_format();
313 $format->set_bold(0);
314 $formatbc = $workbook->add_format();
315 $formatbc->set_bold(1);
316 $formatbc->set_align('center');
317 $formatb = $workbook->add_format();
318 $formatb->set_bold(1);
319 $formaty = $workbook->add_format();
320 $formaty->set_bg_color('yellow');
321 $formatc = $workbook->add_format();
322 $formatc->set_align('center');
323 $formatr = $workbook->add_format();
324 $formatr->set_bold(1);
325 $formatr->set_color('red');
326 $formatr->set_align('center');
327 $formatg = $workbook->add_format();
328 $formatg->set_bold(1);
329 $formatg->set_color('green');
330 $formatg->set_align('center');
333 foreach ($headers as $item) {
334 $myxls->write(0, $colnum, $item, $formatbc);
338 } else if ($download == 'CSV') {
339 $csvexport = new \csv_export_writer("tab");
340 $csvexport->set_filename($filename, ".txt");
341 $csvexport->add_data($headers);
345 $sort = $table->get_sql_sort();
349 // Fix some wired sorting.
351 $sort = ' ORDER BY uniqueid';
353 $sort = ' ORDER BY '.$sort;
357 // Add extra limits due to initials bar.
358 list($twhere, $tparams) = $table->get_sql_where();
360 $where .= ' AND '.$twhere; // Initial bar.
361 $params = array_merge($params, $tparams);
364 if (!empty($countsql)) {
365 $count = $DB->get_record_sql($countsql, $params);
366 $totalinitials = $count->nbresults;
368 $countsql .= ' AND '.$twhere;
370 $count = $DB->get_record_sql($countsql, $params);
371 $total = $count->nbresults;
374 $table->pagesize($pagesize, $total);
376 echo \html_writer::start_div('scormattemptcounts');
377 if ( $count->nbresults == $count->nbattempts ) {
378 echo get_string('reportcountattempts', 'scorm', $count);
379 } else if ( $count->nbattempts > 0 ) {
380 echo get_string('reportcountallattempts', 'scorm', $count);
382 echo $count->nbusers.' '.get_string('users');
384 echo \html_writer::end_div();
387 // Fetch the attempts.
389 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params,
390 $table->get_page_start(), $table->get_page_size());
391 echo \html_writer::start_div('', array('id' => 'scormtablecontainer'));
394 $strreallydel = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
395 echo \html_writer::start_tag('form', array('id' => 'attemptsform', 'method' => 'post',
396 'action' => $PAGE->url->out(false),
397 'onsubmit' => 'return confirm("'.$strreallydel.'");'));
398 echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'action', 'value' => 'delete'));
399 echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
400 echo \html_writer::start_div('', array('style' => 'display: none;'));
401 echo \html_writer::input_hidden_params($PAGE->url);
402 echo \html_writer::end_div();
403 echo \html_writer::start_div();
405 $table->initialbars($totalinitials > 20); // Build table rows.
407 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params);
410 foreach ($attempts as $scouser) {
412 if (!empty($scouser->attempt)) {
413 $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
417 if (in_array('checkbox', $columns)) {
418 if ($candelete && !empty($timetracks->start)) {
419 $row[] = \html_writer::checkbox('attemptid[]', $scouser->userid . ':' . $scouser->attempt, false);
420 } else if ($candelete) {
424 if (in_array('picture', $columns)) {
425 $user = new \stdClass();
426 $additionalfields = explode(',', \user_picture::fields());
427 $user = username_load_fields_from_object($user, $scouser, null, $additionalfields);
428 $user->id = $scouser->userid;
429 $row[] = $OUTPUT->user_picture($user, array('courseid' => $course->id));
432 $url = new \moodle_url('/user/view.php', array('id' => $scouser->userid, 'course' => $course->id));
433 $row[] = \html_writer::link($url, fullname($scouser));
435 $row[] = fullname($scouser);
437 foreach ($extrafields as $field) {
438 $row[] = s($scouser->{$field});
440 if (empty($timetracks->start)) {
447 $url = new \moodle_url('/mod/scorm/report/userreport.php', array('id' => $cm->id,
448 'user' => $scouser->userid, 'attempt' => $scouser->attempt));
449 $row[] = \html_writer::link($url, $scouser->attempt);
451 $row[] = $scouser->attempt;
453 if ($download == 'ODS' || $download == 'Excel' ) {
454 $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
456 $row[] = userdate($timetracks->start);
458 if ($download == 'ODS' || $download == 'Excel' ) {
459 $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
461 $row[] = userdate($timetracks->finish);
463 $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
465 // Print out all scores of attempt.
466 foreach ($scoes as $sco) {
467 if ($sco->launch != '') {
468 if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
469 if ($trackdata->status == '') {
470 $trackdata->status = 'notattempted';
472 $strstatus = get_string($trackdata->status, 'scorm');
474 if ($trackdata->score_raw != '') { // If raw score exists, print it.
475 $score = $trackdata->score_raw;
476 // Add max score if it exists.
477 if (isset($trackdata->score_max)) {
478 $score .= '/'.$trackdata->score_max;
481 } else { // ...else print out status.
485 $url = new \moodle_url('/mod/scorm/report/userreporttracks.php', array('id' => $cm->id,
486 'scoid' => $sco->id, 'user' => $scouser->userid, 'attempt' => $scouser->attempt));
487 $row[] = $OUTPUT->pix_icon($trackdata->status, $strstatus, 'scorm') . '<br>' .
488 \html_writer::link($url, $score, array('title' => get_string('details', 'scorm')));
492 // Iterate over tracks and match objective id against values.
494 if (scorm_version_check($scorm->version, SCORM_13)) {
496 $objectiveprefix = "cmi.objectives.";
498 $objectiveprefix = "cmi.objectives_";
501 $keywords = array(".id", $objectiveprefix);
502 $objectivestatus = array();
503 $objectivescore = array();
504 foreach ($trackdata as $name => $value) {
505 if (strpos($name, $objectiveprefix) === 0 && strrpos($name, '.id') !== false) {
506 $num = trim(str_ireplace($keywords, '', $name));
507 if (is_numeric($num)) {
509 $element = $objectiveprefix.$num.'.completion_status';
511 $element = $objectiveprefix.$num.'.status';
513 if (isset($trackdata->$element)) {
514 $objectivestatus[$value] = $trackdata->$element;
516 $objectivestatus[$value] = '';
518 if ($displayoptions['objectivescore']) {
519 $element = $objectiveprefix.$num.'.score.raw';
520 if (isset($trackdata->$element)) {
521 $objectivescore[$value] = $trackdata->$element;
523 $objectivescore[$value] = '';
531 if (!empty($objectives[$trackdata->scoid])) {
532 foreach ($objectives[$trackdata->scoid] as $name) {
533 if (isset($objectivestatus[$name])) {
534 $row[] = s($objectivestatus[$name]);
538 if ($displayoptions['objectivescore']) {
539 if (isset($objectivescore[$name])) {
540 $row[] = s($objectivescore[$name]);
548 // End of interaction data.
550 // If we don't have track data, we haven't attempted yet.
551 $strstatus = get_string('notattempted', 'scorm');
553 $row[] = $OUTPUT->pix_icon('notattempted', $strstatus, 'scorm') . '<br>' . $strstatus;
557 // Complete the empty cells.
558 for ($i = 0; $i < count($columns) - $nbmaincolumns; $i++) {
566 $table->add_data($row);
567 } else if ($download == 'Excel' or $download == 'ODS') {
569 foreach ($row as $item) {
570 $myxls->write($rownum, $colnum, $item, $format);
574 } else if ($download == 'CSV') {
575 $csvexport->add_data($row);
579 $table->finish_output();
581 echo \html_writer::start_tag('table', array('id' => 'commands'));
582 echo \html_writer::start_tag('tr').\html_writer::start_tag('td');
583 echo \html_writer::link('#', get_string('selectall', 'scorm'), array('id' => 'checkattempts'));
585 echo \html_writer::link('#', get_string('selectnone', 'scorm'), array('id' => 'uncheckattempts'));
586 $PAGE->requires->js_amd_inline("
587 require(['jquery'], function($) {
588 $('#checkattempts').click(function(e) {
589 $('#attemptsform').find('input:checkbox').prop('checked', true);
592 $('#uncheckattempts').click(function(e) {
593 $('#attemptsform').find('input:checkbox').prop('checked', false);
598 echo \html_writer::empty_tag('input', array('type' => 'submit',
599 'value' => get_string('deleteselected', 'scorm'),
600 'class' => 'btn btn-secondary'));
601 echo \html_writer::end_tag('td').\html_writer::end_tag('tr').\html_writer::end_tag('table');
603 echo \html_writer::end_tag('div');
604 echo \html_writer::end_tag('form');
606 echo \html_writer::end_div();
607 if (!empty($attempts)) {
608 echo \html_writer::start_tag('table', array('class' => 'boxaligncenter')).\html_writer::start_tag('tr');
609 echo \html_writer::start_tag('td');
610 echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
611 array('download' => 'ODS') + $displayoptions),
612 get_string('downloadods'),
614 ['class' => 'mt-1']);
615 echo \html_writer::end_tag('td');
616 echo \html_writer::start_tag('td');
617 echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
618 array('download' => 'Excel') + $displayoptions),
619 get_string('downloadexcel'),
621 ['class' => 'mt-1']);
622 echo \html_writer::end_tag('td');
623 echo \html_writer::start_tag('td');
624 echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
625 array('download' => 'CSV') + $displayoptions),
626 get_string('downloadtext'),
628 ['class' => 'mt-1']);
629 echo \html_writer::end_tag('td');
630 echo \html_writer::start_tag('td');
631 echo \html_writer::end_tag('td');
632 echo \html_writer::end_tag('tr').\html_writer::end_tag('table');
636 if ($candelete && !$download) {
637 echo \html_writer::end_div();
638 echo \html_writer::end_tag('form');
639 $table->finish_output();
641 echo \html_writer::end_div();
643 // Show preferences form irrespective of attempts are there to report or not.
645 $mform->set_data(compact('pagesize', 'attemptsmode'));
648 if ($download == 'Excel' or $download == 'ODS') {
651 } else if ($download == 'CSV') {
652 $csvexport->download_file();
656 echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
662 * Returns The maximum numbers of Objectives associated with an Scorm Pack
664 * @param int $scormid Scorm instance id
665 * @return array an array of possible objectives.
667 function get_scorm_objectives($scormid) {
669 $objectives = array();
671 $select = "scormid = ? AND ";
672 $select .= $DB->sql_like("element", "?", false);
673 $params[] = $scormid;
674 $params[] = "cmi.objectives%.id";
675 $value = $DB->sql_compare_text('value');
676 $rs = $DB->get_recordset_select("scorm_scoes_track", $select, $params, 'value', "DISTINCT $value AS value, scoid");
678 foreach ($rs as $record) {
679 $objectives[$record->scoid][] = $record->value;
681 // Now naturally sort the sco arrays.
682 foreach ($objectives as $scoid => $sco) {
683 natsort($objectives[$scoid]);