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 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
22 */
23
24namespace scormreport_objectives;
25
26defined('MOODLE_INTERNAL') || die();
27
28require_once($CFG->dirroot.'/mod/scorm/report/objectives/responsessettings_form.php');
29
30/**
31 * Objectives report class
32 *
33 * @copyright  2013 Dan Marsden
34 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class report extends \mod_scorm\report {
37    /**
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
43     */
44    public function display($scorm, $cm, $course, $download) {
45        global $CFG, $DB, $OUTPUT, $PAGE;
46
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)));
52
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');
56            }
57        }
58        // Find out current groups mode.
59        $currentgroup = groups_get_activity_group($cm, true);
60
61        // Detailed report.
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);
68        } else {
69            $pagesize = get_user_preferences('scorm_report_pagesize', 0);
70            $showobjectivescore = get_user_preferences('scorm_report_objectives_score', 0);
71        }
72        if ($pagesize < 1) {
73            $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE;
74        }
75
76        // Select group menu.
77        $displayoptions = array();
78        $displayoptions['attemptsmode'] = $attemptsmode;
79        $displayoptions['objectivescore'] = $showobjectivescore;
80
81        $mform->set_data($displayoptions + array('pagesize' => $pagesize));
82        if ($groupmode = groups_get_activity_groupmode($cm)) {   // Groups are being used.
83            if (!$download) {
84                groups_print_activity_menu($cm, new \moodle_url($PAGE->url, $displayoptions));
85            }
86        }
87        $formattextoptions = array('context' => \context_course::instance($course->id));
88
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.
94        $nostudents = false;
95        list($allowedlistsql, $params) = get_enrolled_sql($contextmodule, 'mod/scorm:savetrack', (int) $currentgroup);
96        if (empty($currentgroup)) {
97            // All users who can attempt scoes.
98            if (!$DB->record_exists_sql($allowedlistsql, $params)) {
99                echo $OUTPUT->notification(get_string('nostudentsyet'));
100                $nostudents = true;
101            }
102        } else {
103            // All users who can attempt scoes and who are in the currently selected group.
104            if (!$DB->record_exists_sql($allowedlistsql, $params)) {
105                echo $OUTPUT->notification(get_string('nostudentsingroup'));
106                $nostudents = true;
107            }
108        }
109        if ( !$nostudents ) {
110            // Now check if asked download of data.
111            $coursecontext = \context_course::instance($course->id);
112            if ($download) {
113                $filename = clean_filename("$course->shortname ".format_string($scorm->name, true, $formattextoptions));
114            }
115
116            // Define table columns.
117            $columns = array();
118            $headers = array();
119            if (!$download && $candelete) {
120                $columns[] = 'checkbox';
121                $headers[] = $this->generate_master_checkbox();
122            }
123            if (!$download && $CFG->grade_report_showuserimage) {
124                $columns[] = 'picture';
125                $headers[] = '';
126            }
127            $columns[] = 'fullname';
128            $headers[] = get_string('name');
129
130            // TODO Does not support custom user profile fields (MDL-70456).
131            $extrafields = \core_user\fields::get_identity_fields($coursecontext, false);
132            foreach ($extrafields as $field) {
133                $columns[] = $field;
134                $headers[] = \core_user\fields::get_display_name($field);
135            }
136            $columns[] = 'attempt';
137            $headers[] = get_string('attempt', 'scorm');
138            $columns[] = 'start';
139            $headers[] = get_string('started', 'scorm');
140            $columns[] = 'finish';
141            $headers[] = get_string('last', 'scorm');
142            $columns[] = 'score';
143            $headers[] = get_string('score', 'scorm');
144            $scoes = $DB->get_records('scorm_scoes', array("scorm" => $scorm->id), 'sortorder, id');
145            foreach ($scoes as $sco) {
146                if ($sco->launch != '') {
147                    $columns[] = 'scograde'.$sco->id;
148                    $headers[] = format_string($sco->title, '', $formattextoptions);
149                }
150            }
151
152            // Construct the SQL.
153            $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, ';
154            // TODO Does not support custom user profile fields (MDL-70456).
155            $userfields = \core_user\fields::for_identity($coursecontext, false)->with_userpic()->including('idnumber');
156            $selectfields = $userfields->get_sql('u', false, '', 'userid')->selects;
157            $select .= 'st.scormid AS scormid, st.attempt AS attempt ' . $selectfields . ' ';
158
159            // This part is the same for all cases - join users and scorm_scoes_track tables.
160            $from = 'FROM {user} u ';
161            $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id;
162            switch ($attemptsmode) {
163                case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH:
164                    // Show only students with attempts.
165                    $where = " WHERE u.id IN ({$allowedlistsql}) AND st.userid IS NOT NULL";
166                    break;
167                case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO:
168                    // Show only students without attempts.
169                    $where = " WHERE u.id IN ({$allowedlistsql}) AND st.userid IS NULL";
170                    break;
171                case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS:
172                    // Show all students with or without attempts.
173                    $where = " WHERE u.id IN ({$allowedlistsql}) AND (st.userid IS NOT NULL OR st.userid IS NULL)";
174                    break;
175            }
176
177            $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, ';
178            $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, ';
179            $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers ';
180            $countsql .= $from.$where;
181
182            $nbmaincolumns = count($columns); // Get number of main columns used.
183
184            $objectives = get_scorm_objectives($scorm->id);
185            $nosort = array();
186            foreach ($objectives as $scoid => $sco) {
187                foreach ($sco as $id => $objectivename) {
188                    $colid = $scoid.'objectivestatus' . $id;
189                    $columns[] = $colid;
190                    $nosort[] = $colid;
191
192                    if (!$displayoptions['objectivescore']) {
193                        // Display the objective name only.
194                        $headers[] = $objectivename;
195                    } else {
196                        // Display the objective status header with a "status" suffix to avoid confusion.
197                        $headers[] = $objectivename. ' '. get_string('status', 'scormreport_objectives');
198
199                        // Now print objective score headers.
200                        $colid = $scoid.'objectivescore' . $id;
201                        $columns[] = $colid;
202                        $nosort[] = $colid;
203                        $headers[] = $objectivename. ' '. get_string('score', 'scormreport_objectives');
204                    }
205                }
206            }
207
208            $emptycell = ''; // Used when an empty cell is being printed - in html we add a space.
209            if (!$download) {
210                $emptycell = '&nbsp;';
211                $table = new \flexible_table('mod-scorm-report');
212
213                $table->define_columns($columns);
214                $table->define_headers($headers);
215                $table->define_baseurl($PAGE->url);
216
217                $table->sortable(true);
218                $table->collapsible(true);
219
220                // This is done to prevent redundant data, when a user has multiple attempts.
221                $table->column_suppress('picture');
222                $table->column_suppress('fullname');
223                foreach ($extrafields as $field) {
224                    $table->column_suppress($field);
225                }
226                foreach ($nosort as $field) {
227                    $table->no_sorting($field);
228                }
229
230                $table->no_sorting('start');
231                $table->no_sorting('finish');
232                $table->no_sorting('score');
233                $table->no_sorting('checkbox');
234                $table->no_sorting('picture');
235
236                foreach ($scoes as $sco) {
237                    if ($sco->launch != '') {
238                        $table->no_sorting('scograde'.$sco->id);
239                    }
240                }
241
242                $table->column_class('picture', 'picture');
243                $table->column_class('fullname', 'bold');
244                $table->column_class('score', 'bold');
245
246                $table->set_attribute('cellspacing', '0');
247                $table->set_attribute('id', 'attempts');
248                $table->set_attribute('class', 'generaltable generalbox');
249
250                // Start working -- this is necessary as soon as the niceties are over.
251                $table->setup();
252            } else if ($download == 'ODS') {
253                require_once("$CFG->libdir/odslib.class.php");
254
255                $filename .= ".ods";
256                // Creating a workbook.
257                $workbook = new \MoodleODSWorkbook("-");
258                // Sending HTTP headers.
259                $workbook->send($filename);
260                // Creating the first worksheet.
261                $sheettitle = get_string('report', 'scorm');
262                $myxls = $workbook->add_worksheet($sheettitle);
263                // Format types.
264                $format = $workbook->add_format();
265                $format->set_bold(0);
266                $formatbc = $workbook->add_format();
267                $formatbc->set_bold(1);
268                $formatbc->set_align('center');
269                $formatb = $workbook->add_format();
270                $formatb->set_bold(1);
271                $formaty = $workbook->add_format();
272                $formaty->set_bg_color('yellow');
273                $formatc = $workbook->add_format();
274                $formatc->set_align('center');
275                $formatr = $workbook->add_format();
276                $formatr->set_bold(1);
277                $formatr->set_color('red');
278                $formatr->set_align('center');
279                $formatg = $workbook->add_format();
280                $formatg->set_bold(1);
281                $formatg->set_color('green');
282                $formatg->set_align('center');
283                // Here starts workshhet headers.
284
285                $colnum = 0;
286                foreach ($headers as $item) {
287                    $myxls->write(0, $colnum, $item, $formatbc);
288                    $colnum++;
289                }
290                $rownum = 1;
291            } else if ($download == 'Excel') {
292                require_once("$CFG->libdir/excellib.class.php");
293
294                $filename .= ".xls";
295                // Creating a workbook.
296                $workbook = new \MoodleExcelWorkbook("-");
297                // Sending HTTP headers.
298                $workbook->send($filename);
299                // Creating the first worksheet.
300                $sheettitle = get_string('report', 'scorm');
301                $myxls = $workbook->add_worksheet($sheettitle);
302                // Format types.
303                $format = $workbook->add_format();
304                $format->set_bold(0);
305                $formatbc = $workbook->add_format();
306                $formatbc->set_bold(1);
307                $formatbc->set_align('center');
308                $formatb = $workbook->add_format();
309                $formatb->set_bold(1);
310                $formaty = $workbook->add_format();
311                $formaty->set_bg_color('yellow');
312                $formatc = $workbook->add_format();
313                $formatc->set_align('center');
314                $formatr = $workbook->add_format();
315                $formatr->set_bold(1);
316                $formatr->set_color('red');
317                $formatr->set_align('center');
318                $formatg = $workbook->add_format();
319                $formatg->set_bold(1);
320                $formatg->set_color('green');
321                $formatg->set_align('center');
322
323                $colnum = 0;
324                foreach ($headers as $item) {
325                    $myxls->write(0, $colnum, $item, $formatbc);
326                    $colnum++;
327                }
328                $rownum = 1;
329            } else if ($download == 'CSV') {
330                $csvexport = new \csv_export_writer("tab");
331                $csvexport->set_filename($filename, ".txt");
332                $csvexport->add_data($headers);
333            }
334
335            if (!$download) {
336                $sort = $table->get_sql_sort();
337            } else {
338                $sort = '';
339            }
340            // Fix some wired sorting.
341            if (empty($sort)) {
342                $sort = ' ORDER BY uniqueid';
343            } else {
344                $sort = ' ORDER BY '.$sort;
345            }
346
347            if (!$download) {
348                // Add extra limits due to initials bar.
349                list($twhere, $tparams) = $table->get_sql_where();
350                if ($twhere) {
351                    $where .= ' AND '.$twhere; // Initial bar.
352                    $params = array_merge($params, $tparams);
353                }
354
355                if (!empty($countsql)) {
356                    $count = $DB->get_record_sql($countsql, $params);
357                    $totalinitials = $count->nbresults;
358                    if ($twhere) {
359                        $countsql .= ' AND '.$twhere;
360                    }
361                    $count = $DB->get_record_sql($countsql, $params);
362                    $total  = $count->nbresults;
363                }
364
365                $table->pagesize($pagesize, $total);
366
367                echo \html_writer::start_div('scormattemptcounts');
368                if ( $count->nbresults == $count->nbattempts ) {
369                    echo get_string('reportcountattempts', 'scorm', $count);
370                } else if ( $count->nbattempts > 0 ) {
371                    echo get_string('reportcountallattempts', 'scorm', $count);
372                } else {
373                    echo $count->nbusers.' '.get_string('users');
374                }
375                echo \html_writer::end_div();
376            }
377
378            // Fetch the attempts.
379            if (!$download) {
380                $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params,
381                $table->get_page_start(), $table->get_page_size());
382                echo \html_writer::start_div('', array('id' => 'scormtablecontainer'));
383                if ($candelete) {
384                    // Start form.
385                    $strreallydel  = addslashes_js(get_string('deleteattemptcheck', 'scorm'));
386                    echo \html_writer::start_tag('form', array('id' => 'attemptsform', 'method' => 'post',
387                                                                'action' => $PAGE->url->out(false),
388                                                                'onsubmit' => 'return confirm("'.$strreallydel.'");'));
389                    echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'action', 'value' => 'delete'));
390                    echo \html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
391                    echo \html_writer::start_div('', array('style' => 'display: none;'));
392                    echo \html_writer::input_hidden_params($PAGE->url);
393                    echo \html_writer::end_div();
394                    echo \html_writer::start_div();
395                }
396                $table->initialbars($totalinitials > 20); // Build table rows.
397            } else {
398                $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params);
399            }
400            if ($attempts) {
401                foreach ($attempts as $scouser) {
402                    $row = array();
403                    if (!empty($scouser->attempt)) {
404                        $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt);
405                    } else {
406                        $timetracks = '';
407                    }
408                    if (in_array('checkbox', $columns)) {
409                        if ($candelete && !empty($timetracks->start)) {
410                            $row[] = $this->generate_row_checkbox('attemptid[]', "{$scouser->userid}:{$scouser->attempt}");
411                        } else if ($candelete) {
412                            $row[] = '';
413                        }
414                    }
415                    if (in_array('picture', $columns)) {
416                        $user = new \stdClass();
417                        $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
418                        $user = username_load_fields_from_object($user, $scouser, null, $additionalfields);
419                        $user->id = $scouser->userid;
420                        $row[] = $OUTPUT->user_picture($user, array('courseid' => $course->id));
421                    }
422                    if (!$download) {
423                        $url = new \moodle_url('/user/view.php', array('id' => $scouser->userid, 'course' => $course->id));
424                        $row[] = \html_writer::link($url, fullname($scouser));
425                    } else {
426                        $row[] = fullname($scouser);
427                    }
428                    foreach ($extrafields as $field) {
429                        $row[] = s($scouser->{$field});
430                    }
431                    if (empty($timetracks->start)) {
432                        $row[] = '-';
433                        $row[] = '-';
434                        $row[] = '-';
435                        $row[] = '-';
436                    } else {
437                        if (!$download) {
438                            $url = new \moodle_url('/mod/scorm/report/userreport.php', array('id' => $cm->id,
439                                    'user' => $scouser->userid, 'attempt' => $scouser->attempt));
440                            $row[] = \html_writer::link($url, $scouser->attempt);
441                        } else {
442                            $row[] = $scouser->attempt;
443                        }
444                        if ($download == 'ODS' || $download == 'Excel' ) {
445                            $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig"));
446                        } else {
447                            $row[] = userdate($timetracks->start);
448                        }
449                        if ($download == 'ODS' || $download == 'Excel' ) {
450                            $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig'));
451                        } else {
452                            $row[] = userdate($timetracks->finish);
453                        }
454                        $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt);
455                    }
456                    // Print out all scores of attempt.
457                    foreach ($scoes as $sco) {
458                        if ($sco->launch != '') {
459                            if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) {
460                                if ($trackdata->status == '') {
461                                    $trackdata->status = 'notattempted';
462                                }
463                                $strstatus = get_string($trackdata->status, 'scorm');
464
465                                if ($trackdata->score_raw != '') { // If raw score exists, print it.
466                                    $score = $trackdata->score_raw;
467                                    // Add max score if it exists.
468                                    if (isset($trackdata->score_max)) {
469                                        $score .= '/'.$trackdata->score_max;
470                                    }
471
472                                } else { // ...else print out status.
473                                    $score = $strstatus;
474                                }
475                                if (!$download) {
476                                    $url = new \moodle_url('/mod/scorm/report/userreporttracks.php', array('id' => $cm->id,
477                                        'scoid' => $sco->id, 'user' => $scouser->userid, 'attempt' => $scouser->attempt));
478                                    $row[] = $OUTPUT->pix_icon($trackdata->status, $strstatus, 'scorm') . '<br>' .
479                                        \html_writer::link($url, $score, array('title' => get_string('details', 'scorm')));
480                                } else {
481                                    $row[] = $score;
482                                }
483                                // Iterate over tracks and match objective id against values.
484                                $scorm2004 = false;
485                                if (scorm_version_check($scorm->version, SCORM_13)) {
486                                    $scorm2004 = true;
487                                    $objectiveprefix = "cmi.objectives.";
488                                } else {
489                                    $objectiveprefix = "cmi.objectives_";
490                                }
491
492                                $keywords = array(".id", $objectiveprefix);
493                                $objectivestatus = array();
494                                $objectivescore = array();
495                                foreach ($trackdata as $name => $value) {
496                                    if (strpos($name, $objectiveprefix) === 0 && strrpos($name, '.id') !== false) {
497                                        $num = trim(str_ireplace($keywords, '', $name));
498                                        if (is_numeric($num)) {
499                                            if ($scorm2004) {
500                                                $element = $objectiveprefix.$num.'.completion_status';
501                                            } else {
502                                                $element = $objectiveprefix.$num.'.status';
503                                            }
504                                            if (isset($trackdata->$element)) {
505                                                $objectivestatus[$value] = $trackdata->$element;
506                                            } else {
507                                                $objectivestatus[$value] = '';
508                                            }
509                                            if ($displayoptions['objectivescore']) {
510                                                $element = $objectiveprefix.$num.'.score.raw';
511                                                if (isset($trackdata->$element)) {
512                                                    $objectivescore[$value] = $trackdata->$element;
513                                                } else {
514                                                    $objectivescore[$value] = '';
515                                                }
516                                            }
517                                        }
518                                    }
519                                }
520
521                                // Interaction data.
522                                if (!empty($objectives[$trackdata->scoid])) {
523                                    foreach ($objectives[$trackdata->scoid] as $name) {
524                                        if (isset($objectivestatus[$name])) {
525                                            $row[] = s($objectivestatus[$name]);
526                                        } else {
527                                            $row[] = $emptycell;
528                                        }
529                                        if ($displayoptions['objectivescore']) {
530                                            if (isset($objectivescore[$name])) {
531                                                $row[] = s($objectivescore[$name]);
532                                            } else {
533                                                $row[] = $emptycell;
534                                            }
535
536                                        }
537                                    }
538                                }
539                                // End of interaction data.
540                            } else {
541                                // If we don't have track data, we haven't attempted yet.
542                                $strstatus = get_string('notattempted', 'scorm');
543                                if (!$download) {
544                                    $row[] = $OUTPUT->pix_icon('notattempted', $strstatus, 'scorm') . '<br>' . $strstatus;
545                                } else {
546                                    $row[] = $strstatus;
547                                }
548                                // Complete the empty cells.
549                                for ($i = 0; $i < count($columns) - $nbmaincolumns; $i++) {
550                                    $row[] = $emptycell;
551                                }
552                            }
553                        }
554                    }
555
556                    if (!$download) {
557                        $table->add_data($row);
558                    } else if ($download == 'Excel' or $download == 'ODS') {
559                        $colnum = 0;
560                        foreach ($row as $item) {
561                            $myxls->write($rownum, $colnum, $item, $format);
562                            $colnum++;
563                        }
564                        $rownum++;
565                    } else if ($download == 'CSV') {
566                        $csvexport->add_data($row);
567                    }
568                }
569                if (!$download) {
570                    $table->finish_output();
571                    if ($candelete) {
572                        echo \html_writer::start_tag('table', array('id' => 'commands'));
573                        echo \html_writer::start_tag('tr').\html_writer::start_tag('td');
574                        echo $this->generate_delete_selected_button();
575                        echo \html_writer::end_tag('td').\html_writer::end_tag('tr').\html_writer::end_tag('table');
576                        // Close form.
577                        echo \html_writer::end_tag('div');
578                        echo \html_writer::end_tag('form');
579                    }
580                    echo \html_writer::end_div();
581                    if (!empty($attempts)) {
582                        echo \html_writer::start_tag('table', array('class' => 'boxaligncenter')).\html_writer::start_tag('tr');
583                        echo \html_writer::start_tag('td');
584                        echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
585                                                                   array('download' => 'ODS') + $displayoptions),
586                                                                   get_string('downloadods'),
587                                                                   'post',
588                                                                   ['class' => 'mt-1']);
589                        echo \html_writer::end_tag('td');
590                        echo \html_writer::start_tag('td');
591                        echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
592                                                                   array('download' => 'Excel') + $displayoptions),
593                                                                   get_string('downloadexcel'),
594                                                                   'post',
595                                                                   ['class' => 'mt-1']);
596                        echo \html_writer::end_tag('td');
597                        echo \html_writer::start_tag('td');
598                        echo $OUTPUT->single_button(new \moodle_url($PAGE->url,
599                                                                   array('download' => 'CSV') + $displayoptions),
600                                                                   get_string('downloadtext'),
601                                                                   'post',
602                                                                   ['class' => 'mt-1']);
603                        echo \html_writer::end_tag('td');
604                        echo \html_writer::start_tag('td');
605                        echo \html_writer::end_tag('td');
606                        echo \html_writer::end_tag('tr').\html_writer::end_tag('table');
607                    }
608                }
609            } else {
610                if ($candelete && !$download) {
611                    echo \html_writer::end_div();
612                    echo \html_writer::end_tag('form');
613                    $table->finish_output();
614                }
615                echo \html_writer::end_div();
616            }
617            // Show preferences form irrespective of attempts are there to report or not.
618            if (!$download) {
619                $mform->set_data(compact('pagesize', 'attemptsmode'));
620                $mform->display();
621            }
622            if ($download == 'Excel' or $download == 'ODS') {
623                $workbook->close();
624                exit;
625            } else if ($download == 'CSV') {
626                $csvexport->download_file();
627                exit;
628            }
629        } else {
630            echo $OUTPUT->notification(get_string('noactivity', 'scorm'));
631        }
632    }// Function ends.
633}
634
635/**
636 * Returns The maximum numbers of Objectives associated with an Scorm Pack
637 *
638 * @param int $scormid Scorm instance id
639 * @return array an array of possible objectives.
640 */
641function get_scorm_objectives($scormid) {
642    global $DB;
643    $objectives = array();
644    $params = array();
645    $select = "scormid = ? AND ";
646    $select .= $DB->sql_like("element", "?", false);
647    $params[] = $scormid;
648    $params[] = "cmi.objectives%.id";
649    $value = $DB->sql_compare_text('value');
650    $rs = $DB->get_recordset_select("scorm_scoes_track", $select, $params, 'value', "DISTINCT $value AS value, scoid");
651    if ($rs->valid()) {
652        foreach ($rs as $record) {
653            $objectives[$record->scoid][] = $record->value;
654        }
655        // Now naturally sort the sco arrays.
656        foreach ($objectives as $scoid => $sco) {
657            natsort($objectives[$scoid]);
658        }
659    }
660    $rs->close();
661    return $objectives;
662}
663