MDL-68784 scorm: Removed limit on allowed scorm users in report
[moodle.git] / mod / scorm / report / basic / classes / 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 namespace scormreport_basic;
26 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->libdir . '/csvlib.class.php');
29 class report extends \mod_scorm\report {
30     /**
31      * displays the full report
32      * @param \stdClass $scorm full SCORM object
33      * @param \stdClass $cm - full course_module object
34      * @param \stdClass $course - full course object
35      * @param string $download - type of download being requested
36      */
37     public function display($scorm, $cm, $course, $download) {
38         global $CFG, $DB, $OUTPUT, $PAGE;
40         $contextmodule = \context_module::instance($cm->id);
41         $action = optional_param('action', '', PARAM_ALPHA);
42         $attemptids = optional_param_array('attemptid', array(), PARAM_RAW);
43         $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_ALL_STUDENTS, PARAM_INT);
44         $PAGE->set_url(new \moodle_url($PAGE->url, array('attemptsmode' => $attemptsmode)));
46         if ($action == 'delete' && has_capability('mod/scorm:deleteresponses', $contextmodule) && confirm_sesskey()) {
47             if (scorm_delete_responses($attemptids, $scorm)) { // Delete responses.
48                 echo $OUTPUT->notification(get_string('scormresponsedeleted', 'scorm'), 'notifysuccess');
49             }
50         }
51         // Find out current groups mode.
52         $currentgroup = groups_get_activity_group($cm, true);
54         // Detailed report.
55         $mform = new \mod_scorm_report_settings($PAGE->url, compact('currentgroup'));
56         if ($fromform = $mform->get_data()) {
57             $detailedrep = $fromform->detailedrep;
58             $pagesize = $fromform->pagesize;
59             set_user_preference('scorm_report_detailed', $detailedrep);
60             set_user_preference('scorm_report_pagesize', $pagesize);
61         } else {
62             $detailedrep = get_user_preferences('scorm_report_detailed', false);
63             $pagesize = get_user_preferences('scorm_report_pagesize', 0);
64         }
65         if ($pagesize < 1) {
66             $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
67         }
69         // Select group menu.
70         $displayoptions = array();
71         $displayoptions['attemptsmode'] = $attemptsmode;
72         if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used.
73             if (!$download) {
74                 groups_print_activity_menu($cm, new \moodle_url($PAGE->url, $displayoptions));
75             }
76         }
78         // We only want to show the checkbox to delete attempts
79         // if the user has permissions and if the report mode is showing attempts.
80         $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule)
81                         && ($attemptsmode != SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO);
82         // Select the students.
83         $nostudents = false;
84         list($allowedlistsql, $params) = get_enrolled_sql($contextmodule, 'mod/scorm:savetrack', (int) $currentgroup);
85         if (empty($currentgroup)) {
86             // All users who can attempt scoes.
87             if (!$DB->record_exists_sql($allowedlistsql, $params)) {
88                 echo $OUTPUT->notification(get_string('nostudentsyet'));
89                 $nostudents = true;
90             }
91         } else {
92             // All users who can attempt scoes and who are in the currently selected group.
93             if (!$DB->record_exists_sql($allowedlistsql, $params)) {
94                 echo $OUTPUT->notification(get_string('nostudentsingroup'));
95                 $nostudents = true;
96             }
97         }
99         if ( !$nostudents ) {
100             // Now check if asked download of data.
101             $coursecontext = \context_course::instance($course->id);
102             if ($download) {
103                 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
104                 $filename = clean_filename("$shortname ".format_string($scorm->name, true));
105             }
107             // Define table columns.
108             $columns = array();
109             $headers = array();
110             if (!$download && $candelete) {
111                 $columns[] = 'checkbox';
112                 $headers[] = $this->generate_master_checkbox();
113             }
114             if (!$download && $CFG->grade_report_showuserimage) {
115                 $columns[] = 'picture';
116                 $headers[] = '';
117             }
118             $columns[] = 'fullname';
119             $headers[] = get_string('name');
120             $extrafields = get_extra_user_fields($coursecontext);
121             foreach ($extrafields as $field) {
122                 $columns[] = $field;
123                 $headers[] = get_user_field_name($field);
124             }
126             $columns[] = 'attempt';
127             $headers[] = get_string('attempt', 'scorm');
128             $columns[] = 'start';
129             $headers[] = get_string('started', 'scorm');
130             $columns[] = 'finish';
131             $headers[] = get_string('last', 'scorm');
132             $columns[] = 'score';
133             $headers[] = get_string('score', 'scorm');
134             if ($detailedrep && $scoes = $DB->get_records('scorm_scoes', array("scorm" => $scorm->id), 'sortorder, id')) {
135                 foreach ($scoes as $sco) {
136                     if ($sco->launch != '') {
137                         $columns[] = 'scograde'.$sco->id;
138                         $headers[] = format_string($sco->title);
139                     }
140                 }
141             } else {
142                 $scoes = null;
143             }
145             if (!$download) {
146                 $table = new \flexible_table('mod-scorm-report');
148                 $table->define_columns($columns);
149                 $table->define_headers($headers);
150                 $table->define_baseurl($PAGE->url);
152                 $table->sortable(true);
153                 $table->collapsible(true);
155                 // This is done to prevent redundant data, when a user has multiple attempts.
156                 $table->column_suppress('picture');
157                 $table->column_suppress('fullname');
158                 foreach ($extrafields as $field) {
159                     $table->column_suppress($field);
160                 }
162                 $table->no_sorting('start');
163                 $table->no_sorting('finish');
164                 $table->no_sorting('score');
165                 $table->no_sorting('checkbox');
166                 $table->no_sorting('picture');
168                 if ( $scoes ) {
169                     foreach ($scoes as $sco) {
170                         if ($sco->launch != '') {
171                             $table->no_sorting('scograde'.$sco->id);
172                         }
173                     }
174                 }
176                 $table->column_class('picture', 'picture');
177                 $table->column_class('fullname', 'bold');
178                 $table->column_class('score', 'bold');
180                 $table->set_attribute('cellspacing', '0');
181                 $table->set_attribute('id', 'attempts');
182                 $table->set_attribute('class', 'generaltable generalbox');
184                 // Start working -- this is necessary as soon as the niceties are over.
185                 $table->setup();
186             } else if ($download == 'ODS') {
187                 require_once("$CFG->libdir/odslib.class.php");
189                 $filename .= ".ods";
190                 // Creating a workbook.
191                 $workbook = new \MoodleODSWorkbook("-");
192                 // Sending HTTP headers.
193                 $workbook->send($filename);
194                 // Creating the first worksheet.
195                 $sheettitle = get_string('report', 'scorm');
196                 $myxls = $workbook->add_worksheet($sheettitle);
197                 // Format types.
198                 $format = $workbook->add_format();
199                 $format->set_bold(0);
200                 $formatbc = $workbook->add_format();
201                 $formatbc->set_bold(1);
202                 $formatbc->set_align('center');
203                 $formatb = $workbook->add_format();
204                 $formatb->set_bold(1);
205                 $formaty = $workbook->add_format();
206                 $formaty->set_bg_color('yellow');
207                 $formatc = $workbook->add_format();
208                 $formatc->set_align('center');
209                 $formatr = $workbook->add_format();
210                 $formatr->set_bold(1);
211                 $formatr->set_color('red');
212                 $formatr->set_align('center');
213                 $formatg = $workbook->add_format();
214                 $formatg->set_bold(1);
215                 $formatg->set_color('green');
216                 $formatg->set_align('center');
217                 // Here starts workshhet headers.
219                 $colnum = 0;
220                 foreach ($headers as $item) {
221                     $myxls->write(0, $colnum, $item, $formatbc);
222                     $colnum++;
223                 }
224                 $rownum = 1;
225             } else if ($download == 'Excel') {
226                 require_once("$CFG->libdir/excellib.class.php");
228                 $filename .= ".xls";
229                 // Creating a workbook.
230                 $workbook = new \MoodleExcelWorkbook("-");
231                 // Sending HTTP headers.
232                 $workbook->send($filename);
233                 // Creating the first worksheet.
234                 $sheettitle = get_string('report', 'scorm');
235                 $myxls = $workbook->add_worksheet($sheettitle);
236                 // Format types.
237                 $format = $workbook->add_format();
238                 $format->set_bold(0);
239                 $formatbc = $workbook->add_format();
240                 $formatbc->set_bold(1);
241                 $formatbc->set_align('center');
242                 $formatb = $workbook->add_format();
243                 $formatb->set_bold(1);
244                 $formaty = $workbook->add_format();
245                 $formaty->set_bg_color('yellow');
246                 $formatc = $workbook->add_format();
247                 $formatc->set_align('center');
248                 $formatr = $workbook->add_format();
249                 $formatr->set_bold(1);
250                 $formatr->set_color('red');
251                 $formatr->set_align('center');
252                 $formatg = $workbook->add_format();
253                 $formatg->set_bold(1);
254                 $formatg->set_color('green');
255                 $formatg->set_align('center');
257                 $colnum = 0;
258                 foreach ($headers as $item) {
259                     $myxls->write(0, $colnum, $item, $formatbc);
260                     $colnum++;
261                 }
262                 $rownum = 1;
263             } else if ($download == 'CSV') {
264                 $csvexport = new \csv_export_writer("tab");
265                 $csvexport->set_filename($filename, ".txt");
266                 $csvexport->add_data($headers);
267             }
268             // Construct the SQL.
269             $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
270             $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' .
271                     \user_picture::fields('u', array('idnumber'), 'userid') .
272                     get_extra_user_fields_sql($coursecontext, 'u', '', array('email', 'idnumber')) . ' ';
274             // This part is the same for all cases - join users and scorm_scoes_track tables.
275             $from = 'FROM {user} u ';
276             $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id;
277             switch ($attemptsmode) {
278                 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
279                     // Show only students with attempts.
280                     $where = " WHERE u.id IN ({$allowedlistsql}) AND st.userid IS NOT NULL";
281                     break;
282                 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
283                     // Show only students without attempts.
284                     $where = " WHERE u.id IN ({$allowedlistsql}) AND st.userid IS NULL";
285                     break;
286                 case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
287                     // Show all students with or without attempts.
288                     $where = " WHERE u.id IN ({$allowedlistsql}) AND (st.userid IS NOT NULL OR st.userid IS NULL)";
289                     break;
290             }
292             $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, ';
293             $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, ';
294             $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
295             $countsql .= $from.$where;
297             if (!$download) {
298                 $sort = $table->get_sql_sort();
299             } else {
300                 $sort = '';
301             }
302             // Fix some wired sorting.
303             if (empty($sort)) {
304                 $sort = ' ORDER BY uniqueid';
305             } else {
306                 $sort = ' ORDER BY '.$sort;
307             }
309             if (!$download) {
310                 // Add extra limits due to initials bar.
311                 list($twhere, $tparams) = $table->get_sql_where();
312                 if ($twhere) {
313                     $where .= ' AND '.$twhere; // Initial bar.
314                     $params = array_merge($params, $tparams);
315                 }
317                 if (!empty($countsql)) {
318                     $count = $DB->get_record_sql($countsql, $params);
319                     $totalinitials = $count->nbresults;
320                     if ($twhere) {
321                         $countsql .= ' AND '.$twhere;
322                     }
323                     $count = $DB->get_record_sql($countsql, $params);
324                     $total  = $count->nbresults;
325                 }
327                 $table->pagesize($pagesize, $total);
329                 echo \html_writer::start_div('scormattemptcounts');
330                 if ( $count->nbresults == $count->nbattempts ) {
331                     echo get_string('reportcountattempts', 'scorm', $count);
332                 } else if ( $count->nbattempts > 0 ) {
333                     echo get_string('reportcountallattempts', 'scorm', $count);
334                 } else {
335                     echo $count->nbusers.' '.get_string('users');
336                 }
337                 echo \html_writer::end_div();
338             }
340             // Fetch the attempts.
341             if (!$download) {
342                 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params,
343                 $table->get_page_start(), $table->get_page_size());
344                 echo \html_writer::start_div('', array('id' => 'scormtablecontainer'));
345                 if ($candelete) {
346                     // Start form.
347                     $strreallydel  = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
348                     echo \html_writer::start_tag('form', array('id' => 'attemptsform', 'method' => 'post',
349                                                                 'action' => $PAGE->url->out(false),
350                                                                 'onsubmit' => 'return confirm("'.$strreallydel.'");'));
351                     echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'action', 'value' => 'delete'));
352                     echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
353                     echo \html_writer::start_div('', array('style' => 'display: none;'));
354                     echo \html_writer::input_hidden_params($PAGE->url);
355                     echo \html_writer::end_div();
356                     echo \html_writer::start_div();
357                 }
358                 $table->initialbars($totalinitials > 20); // Build table rows.
359             } else {
360                 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params);
361             }
363             if ($attempts) {
364                 foreach ($attempts as $scouser) {
365                     $row = array();
366                     if (!empty($scouser->attempt)) {
367                         $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
368                     } else {
369                         $timetracks = '';
370                     }
371                     if (in_array('checkbox', $columns)) {
372                         if ($candelete && !empty($timetracks->start)) {
373                             $row[] = $this->generate_row_checkbox('attemptid[]', "{$scouser->userid}:{$scouser->attempt}");
374                         } else if ($candelete) {
375                             $row[] = '';
376                         }
377                     }
378                     if (in_array('picture', $columns)) {
379                         $user = new \stdClass();
380                         $additionalfields = explode(',', \user_picture::fields());
381                         $user = username_load_fields_from_object($user, $scouser, null, $additionalfields);
382                         $user->id = $scouser->userid;
383                         $row[] = $OUTPUT->user_picture($user, array('courseid' => $course->id));
384                     }
385                     if (!$download) {
386                         $url = new \moodle_url('/user/view.php', array('id' => $scouser->userid, 'course' => $course->id));
387                         $row[] = \html_writer::link($url, fullname($scouser));
388                     } else {
389                         $row[] = fullname($scouser);
390                     }
391                     foreach ($extrafields as $field) {
392                         $row[] = s($scouser->{$field});
393                     }
394                     if (empty($timetracks->start)) {
395                         $row[] = '-';
396                         $row[] = '-';
397                         $row[] = '-';
398                         $row[] = '-';
399                     } else {
400                         if (!$download) {
401                             $url = new \moodle_url('/mod/scorm/report/userreport.php', array('id' => $cm->id,
402                                     'user' => $scouser->userid, 'attempt' => $scouser->attempt));
403                             $row[] = \html_writer::link($url, $scouser->attempt);
404                         } else {
405                             $row[] = $scouser->attempt;
406                         }
407                         if ($download == 'ODS' || $download == 'Excel' ) {
408                             $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
409                         } else {
410                             $row[] = userdate($timetracks->start);
411                         }
412                         if ($download == 'ODS' || $download == 'Excel' ) {
413                             $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
414                         } else {
415                             $row[] = userdate($timetracks->finish);
416                         }
417                         $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
418                     }
419                     // Print out all scores of attempt.
420                     if ($scoes) {
421                         foreach ($scoes as $sco) {
422                             if ($sco->launch != '') {
423                                 if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
424                                     if ($trackdata->status == '') {
425                                         $trackdata->status = 'notattempted';
426                                     }
427                                     $strstatus = get_string($trackdata->status, 'scorm');
428                                     // If raw score exists, print it.
429                                     if ($trackdata->score_raw != '') {
430                                         $score = $trackdata->score_raw;
431                                         // Add max score if it exists.
432                                         if (scorm_version_check($scorm->version, SCORM_13)) {
433                                             $maxkey = 'cmi.score.max';
434                                         } else {
435                                             $maxkey = 'cmi.core.score.max';
436                                         }
437                                         if (isset($trackdata->$maxkey)) {
438                                             $score .= '/'.$trackdata->$maxkey;
439                                         }
440                                         // Else print out status.
441                                     } else {
442                                         $score = $strstatus;
443                                     }
444                                     if (!$download) {
445                                         $url = new \moodle_url('/mod/scorm/report/userreporttracks.php', array('id' => $cm->id,
446                                             'scoid' => $sco->id, 'user' => $scouser->userid, 'attempt' => $scouser->attempt));
447                                         $row[] = $OUTPUT->pix_icon($trackdata->status, $strstatus, 'scorm') . '<br>' .
448                                            \html_writer::link($url, $score, array('title' => get_string('details', 'scorm')));
449                                     } else {
450                                         $row[] = $score;
451                                     }
452                                 } else {
453                                     // If we don't have track data, we haven't attempted yet.
454                                     $strstatus = get_string('notattempted', 'scorm');
455                                     if (!$download) {
456                                         $row[] = $OUTPUT->pix_icon('notattempted', $strstatus, 'scorm') . '<br>' . $strstatus;
457                                     } else {
458                                         $row[] = $strstatus;
459                                     }
460                                 }
461                             }
462                         }
463                     }
465                     if (!$download) {
466                         $table->add_data($row);
467                     } else if ($download == 'Excel' or $download == 'ODS') {
468                         $colnum = 0;
469                         foreach ($row as $item) {
470                             $myxls->write($rownum, $colnum, $item, $format);
471                             $colnum++;
472                         }
473                         $rownum++;
474                     } else if ($download == 'CSV') {
475                         $csvexport->add_data($row);
476                     }
477                 }
478                 if (!$download) {
479                     $table->finish_output();
480                     if ($candelete) {
481                         echo \html_writer::start_tag('table', array('id' => 'commands'));
482                         echo \html_writer::start_tag('tr').\html_writer::start_tag('td');
483                         echo $this->generate_delete_selected_button();
484                         echo \html_writer::end_tag('td').\html_writer::end_tag('tr').\html_writer::end_tag('table');
485                         // Close form.
486                         echo \html_writer::end_tag('div');
487                         echo \html_writer::end_tag('form');
488                     }
489                     echo \html_writer::end_div();
490                     if (!empty($attempts)) {
491                         echo \html_writer::start_tag('table', array('class' => 'boxaligncenter')).\html_writer::start_tag('tr');
492                         echo \html_writer::start_tag('td');
493                         echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
494                                                                    array('download' => 'ODS') + $displayoptions),
495                                                                    get_string('downloadods'));
496                         echo \html_writer::end_tag('td');
497                         echo \html_writer::start_tag('td');
498                         echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
499                                                                    array('download' => 'Excel') + $displayoptions),
500                                                                    get_string('downloadexcel'));
501                         echo \html_writer::end_tag('td');
502                         echo \html_writer::start_tag('td');
503                         echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
504                                                                    array('download' => 'CSV') + $displayoptions),
505                                                                    get_string('downloadtext'));
506                         echo \html_writer::end_tag('td');
507                         echo \html_writer::start_tag('td');
508                         echo \html_writer::end_tag('td');
509                         echo \html_writer::end_tag('tr').\html_writer::end_tag('table');
510                     }
511                 }
512             } else {
513                 if ($candelete && !$download) {
514                     echo \html_writer::end_div();
515                     echo \html_writer::end_tag('form');
516                     $table->finish_output();
517                 }
518                 echo \html_writer::end_div();
519             }
520             // Show preferences form irrespective of attempts are there to report or not.
521             if (!$download) {
522                 $mform->set_data(compact('detailedrep', 'pagesize', 'attemptsmode'));
523                 $mform->display();
524             }
525             if ($download == 'Excel' or $download == 'ODS') {
526                 $workbook->close();
527                 exit;
528             } else if ($download == 'CSV') {
529                 $csvexport->download_file();
530                 exit;
531             }
532         } else {
533             echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
534         }
535     }// Function ends.