MDL-30528 stop recreating role_assignments on every login attempt for each user
[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         }
47         // detailed report
48         $mform = new mod_scorm_report_settings($PAGE->url, compact('currentgroup'));
49         if ($fromform = $mform->get_data()) {
50             $detailedrep = $fromform->detailedrep;
51             $pagesize = $fromform->pagesize;
52             $attemptsmode = !empty($fromform->attemptsmode) ? $fromform->attemptsmode : SCORM_REPORT_ATTEMPTS_ALL_STUDENTS;
53             set_user_preference('scorm_report_detailed', $detailedrep);
54             set_user_preference('scorm_report_pagesize', $pagesize);
55         } else {
56             $detailedrep = get_user_preferences('scorm_report_detailed', false);
57             $pagesize = get_user_preferences('scorm_report_pagesize', 0);
58             $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_STUDENTS_WITH, PARAM_INT);
59         }
60         if ($pagesize < 1) {
61             $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
62         }
64         // select group menu
65         $displayoptions = array();
66         $displayoptions['attemptsmode'] = $attemptsmode;
67         if ($groupmode = groups_get_activity_groupmode($cm)) {   // Groups are being used
68             if (!$download) {
69                 groups_print_activity_menu($cm, new moodle_url($PAGE->url, $displayoptions));
70             }
71         }
73         // We only want to show the checkbox to delete attempts
74         // if the user has permissions and if the report mode is showing attempts.
75         $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule)
76                 && ($attemptsmode!= SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO);
77         // select the students
78         $nostudents = false;
80         if (empty($currentgroup)) {
81             // all users who can attempt scoes
82             if (!$students = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', '', '', false)) {
83                 echo $OUTPUT->notification(get_string('nostudentsyet'));
84                 $nostudents = true;
85                 $allowedlist = '';
86             } else {
87                 $allowedlist = join(',', array_keys($students));
88             }
89         } else {
90             // all users who can attempt scoes and who are in the currently selected group
91             if (!$groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', $currentgroup, '', false)) {
92                 echo $OUTPUT->notification(get_string('nostudentsingroup'));
93                 $nostudents = true;
94                 $groupstudents = array();
95             }
96             $allowedlist = join(',', array_keys($groupstudents));
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[]= null;
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), 'id')) {
135                 foreach ($scoes as $sco) {
136                     if ($sco->launch!='') {
137                         $columns[]= 'scograde'.$sco->id;
138                         $headers[]= format_string($sco->title);
139                         $table->head[]= format_string($sco->title);
140                     }
141                 }
142             } else {
143                 $scoes = null;
144             }
146             if (!$download) {
147                 $table = new flexible_table('mod-scorm-report');
149                 $table->define_columns($columns);
150                 $table->define_headers($headers);
151                 $table->define_baseurl($PAGE->url);
153                 $table->sortable(true);
154                 $table->collapsible(true);
156                 $table->column_suppress('picture');
157                 $table->column_suppress('fullname');
158                 // I wonder why it is doing all this suppress malarkey?
159                 // However, if it was suppressing idnumber field before, I guess
160                 // it needs to suppress all the user identity fields now
161                 foreach ($extrafields as $field) {
162                     $table->column_suppress($field);
163                 }
165                 $table->no_sorting('start');
166                 $table->no_sorting('finish');
167                 $table->no_sorting('score');
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                 $filename .= ".txt";
265                 header("Content-Type: application/download\n");
266                 header("Content-Disposition: attachment; filename=\"$filename\"");
267                 header("Expires: 0");
268                 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
269                 header("Pragma: public");
270                 echo implode("\t", $headers)." \n";
271             }
273                             // Construct the SQL
274             $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
275             $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' .
276                     'u.id AS userid, u.idnumber, u.firstname, u.lastname, u.picture, u.imagealt, u.email' .
277                     get_extra_user_fields_sql($coursecontext, 'u', '', array('idnumber')) . ' ';
279             // This part is the same for all cases - join users and scorm_scoes_track tables
280             $from = 'FROM {user} u ';
281             $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id;
282             switch ($attemptsmode) {
283                 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
284                     // Show only students with attempts
285                     $where = ' WHERE u.id IN (' .$allowedlist. ') AND st.userid IS NOT NULL';
286                     break;
287                 case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
288                     // Show only students without attempts
289                     $where = ' WHERE u.id IN (' .$allowedlist. ') AND st.userid IS NULL';
290                     break;
291                 case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
292                     // Show all students with or without attempts
293                     $where = ' WHERE u.id IN (' .$allowedlist. ') AND (st.userid IS NOT NULL OR st.userid IS NULL)';
294                     break;
295             }
297             $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, ';
298             $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, ';
299             $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
300             $countsql .= $from.$where;
301             $params = array();
303             if (!$download) {
304                 $sort = $table->get_sql_sort();
305             } else {
306                 $sort = '';
307             }
308             // Fix some wired sorting
309             if (empty($sort)) {
310                 $sort = ' ORDER BY uniqueid';
311             } else {
312                 $sort = ' ORDER BY '.$sort;
313             }
315             if (!$download) {
316                 // Add extra limits due to initials bar
317                 list($twhere, $tparams) = $table->get_sql_where();
318                 if ($twhere) {
319                     $where .= ' AND '.$twhere; //initial bar
320                     $params = array_merge($params, $tparams);
321                 }
323                 if (!empty($countsql)) {
324                     $count = $DB->get_record_sql($countsql);
325                     $totalinitials = $count->nbresults;
326                     if ($twhere) {
327                         $countsql .= ' AND '.$twhere;
328                     }
329                     $count = $DB->get_record_sql($countsql, $params);
330                     $total  = $count->nbresults;
331                 }
333                 $table->pagesize($pagesize, $total);
335                 echo '<div class="quizattemptcounts">';
336                 if ( $count->nbresults == $count->nbattempts ) {
337                     echo get_string('reportcountattempts', 'scorm', $count);
338                 } else if ( $count->nbattempts>0 ) {
339                     echo get_string('reportcountallattempts', 'scorm', $count);
340                 } else {
341                     echo $count->nbusers.' '.get_string('users');
342                 }
343                 echo '</div>';
344             }
346             // Fetch the attempts
347             if (!$download) {
348                 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params,
349                 $table->get_page_start(), $table->get_page_size());
350                 echo '<div id="scormtablecontainer">';
351                 if ($candelete) {
352                     // Start form
353                     $strreallydel  = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
354                     echo '<form id="attemptsform" method="post" action="' . $PAGE->url->out(false) .
355                          '" onsubmit="return confirm(\''.$strreallydel.'\');">';
356                     echo '<input type="hidden" name="action" value="delete"/>';
357                     echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
358                     echo '<div style="display: none;">';
359                     echo html_writer::input_hidden_params($PAGE->url);
360                     echo '</div>';
361                     echo '<div>';
362                 }
363                 $table->initialbars($totalinitials>20); // Build table rows
364             } else {
365                 $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params);
366             }
368             if ($attempts) {
369                 foreach ($attempts as $scouser) {
370                     $row = array();
371                     if (!empty($scouser->attempt)) {
372                         $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
373                     } else {
374                         $timetracks = '';
375                     }
376                     if (in_array('checkbox', $columns)) {
377                         if ($candelete && !empty($timetracks->start)) {
378                             $row[] = '<input type="checkbox" name="attemptid[]" value="'. $scouser->userid . ':' . $scouser->attempt . '" />';
379                         } else if ($candelete) {
380                             $row[] = '';
381                         }
382                     }
383                     if (in_array('picture', $columns)) {
384                         $user = (object)array(
385                                     'id'=>$scouser->userid,
386                                     'picture'=>$scouser->picture,
387                                     'imagealt'=>$scouser->imagealt,
388                                     'email'=>$scouser->email,
389                                     'firstname'=>$scouser->firstname,
390                                     'lastname'=>$scouser->lastname);
391                         $row[] = $OUTPUT->user_picture($user, array('courseid'=>$course->id));
392                     }
393                     if (!$download) {
394                         $row[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$scouser->userid.'&amp;course='.$course->id.'">'.fullname($scouser).'</a>';
395                     } else {
396                         $row[] = fullname($scouser);
397                     }
398                     foreach ($extrafields as $field) {
399                         $row[] = s($scouser->{$field});
400                     }
401                     if (empty($timetracks->start)) {
402                         $row[] = '-';
403                         $row[] = '-';
404                         $row[] = '-';
405                         $row[] = '-';
406                     } else {
407                         if (!$download) {
408                             $row[] = '<a href="userreport.php?a='.$scorm->id.'&amp;user='.$scouser->userid.'&amp;attempt='.$scouser->attempt.'">'.$scouser->attempt.'</a>';
409                         } else {
410                             $row[] = $scouser->attempt;
411                         }
412                         if ($download =='ODS' || $download =='Excel' ) {
413                             $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
414                         } else {
415                             $row[] = userdate($timetracks->start);
416                         }
417                         if ($download =='ODS' || $download =='Excel' ) {
418                             $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
419                         } else {
420                             $row[] = userdate($timetracks->finish);
421                         }
422                         $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
423                     }
424                                     // print out all scores of attempt
425                     if ($scoes) {
426                         foreach ($scoes as $sco) {
427                             if ($sco->launch!='') {
428                                 if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
429                                     if ($trackdata->status == '') {
430                                         $trackdata->status = 'notattempted';
431                                     }
432                                     $strstatus = get_string($trackdata->status, 'scorm');
433                                     // if raw score exists, print it
434                                     if ($trackdata->score_raw != '') {
435                                         $score = $trackdata->score_raw;
436                                         // add max score if it exists
437                                         if (scorm_version_check($scorm->version, SCORM_13)) {
438                                             $maxkey = 'cmi.score.max';
439                                         } else {
440                                             $maxkey = 'cmi.core.score.max';
441                                         }
442                                         if (isset($trackdata->$maxkey)) {
443                                             $score .= '/'.$trackdata->$maxkey;
444                                         }
445                                         // else print out status
446                                     } else {
447                                         $score = $strstatus;
448                                     }
449                                     if (!$download) {
450                                         $row[] = '<img src="'.$OUTPUT->pix_url($trackdata->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>
451                                                 <a href="userreport.php?b='.$sco->id.'&amp;user='.$scouser->userid.'&amp;attempt='.$scouser->attempt.
452                                                 '" title="'.get_string('details', 'scorm').'">'.$score.'</a>';
453                                     } else {
454                                         $row[] = $score;
455                                     }
456                                 } else {
457                                     // if we don't have track data, we haven't attempted yet
458                                     $strstatus = get_string('notattempted', 'scorm');
459                                     if (!$download) {
460                                         $row[] = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>'.$strstatus;
461                                     } else {
462                                         $row[] = $strstatus;
463                                     }
464                                 }
465                             }
466                         }
467                     }
469                     if (!$download) {
470                         $table->add_data($row);
471                     } else if ($download == 'Excel' or $download == 'ODS') {
472                         $colnum = 0;
473                         foreach ($row as $item) {
474                             $myxls->write($rownum, $colnum, $item, $format);
475                             $colnum++;
476                         }
477                         $rownum++;
478                     } else if ($download=='CSV') {
479                         $text = implode("\t", $row);
480                         echo $text." \n";
481                     }
482                 }
483                 if (!$download) {
484                     $table->finish_output();
485                     if ($candelete) {
486                         echo '<table id="commands">';
487                         echo '<tr><td>';
488                         echo '<a href="javascript:select_all_in(\'DIV\', null, \'scormtablecontainer\');">'.
489                              get_string('selectall', 'scorm').'</a> / ';
490                         echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'scormtablecontainer\');">'.
491                              get_string('selectnone', 'scorm').'</a> ';
492                         echo '&nbsp;&nbsp;';
493                         echo '<input type="submit" value="'.get_string('deleteselected', 'quiz_overview').'"/>';
494                         echo '</td></tr></table>';
495                         // Close form
496                         echo '</div>';
497                         echo '</form>';
498                     }
499                     echo '</div>';
500                     if (!empty($attempts)) {
501                         echo '<table class="boxaligncenter"><tr>';
502                         echo '<td>';
503                         echo $OUTPUT->single_button(new moodle_url($PAGE->url,
504                                                                    array('download'=>'ODS') + $displayoptions),
505                                                                    get_string('downloadods'));
506                         echo "</td>\n";
507                         echo '<td>';
508                         echo $OUTPUT->single_button(new moodle_url($PAGE->url,
509                                                                    array('download'=>'Excel') + $displayoptions),
510                                                                    get_string('downloadexcel'));
511                         echo "</td>\n";
512                         echo '<td>';
513                         echo $OUTPUT->single_button(new moodle_url($PAGE->url,
514                                                                    array('download'=>'CSV') + $displayoptions),
515                                                                    get_string('downloadtext'));
516                         echo "</td>\n";
517                         echo "<td>";
518                         echo "</td>\n";
519                         echo '</tr></table>';
520                     }
521                 }
522                 if (!$download) {
523                     $mform->set_data(compact('detailedrep', 'pagesize'));
524                     $mform->display();
525                 }
526             } else {
527                 if ($candelete && !$download) {
528                     echo '</div>';
529                     echo '</form>';
530                 }
531                 echo '</div>';
532                 echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
533             }
534             if ($download == 'Excel' or $download == 'ODS') {
535                 $workbook->close();
536                 exit;
537             } else if ($download == 'CSV') {
538                 exit;
539             }
540         } else {
541             echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
542         }
543     }// function ends