weekly release 5.0dev
[moodle.git] / mod / scorm / lib.php
blob8f7f08e7f1a5d65737976fad539a187260884390
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.
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 /**
18 * @package mod_scorm
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 defined('MOODLE_INTERNAL') || die();
24 /** SCORM_TYPE_LOCAL = local */
25 define('SCORM_TYPE_LOCAL', 'local');
26 /** SCORM_TYPE_LOCALSYNC = localsync */
27 define('SCORM_TYPE_LOCALSYNC', 'localsync');
28 /** SCORM_TYPE_EXTERNAL = external */
29 define('SCORM_TYPE_EXTERNAL', 'external');
30 /** SCORM_TYPE_AICCURL = external AICC url */
31 define('SCORM_TYPE_AICCURL', 'aiccurl');
33 define('SCORM_TOC_SIDE', 0);
34 define('SCORM_TOC_HIDDEN', 1);
35 define('SCORM_TOC_POPUP', 2);
36 define('SCORM_TOC_DISABLED', 3);
38 // Used to show/hide navigation buttons and set their position.
39 define('SCORM_NAV_DISABLED', 0);
40 define('SCORM_NAV_UNDER_CONTENT', 1);
41 define('SCORM_NAV_FLOATING', 2);
43 // Used to check what SCORM version is being used.
44 define('SCORM_12', 1);
45 define('SCORM_13', 2);
46 define('SCORM_AICC', 3);
48 // List of possible attemptstatusdisplay options.
49 define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
50 define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
51 define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
52 define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
54 define('SCORM_EVENT_TYPE_OPEN', 'open');
55 define('SCORM_EVENT_TYPE_CLOSE', 'close');
57 require_once(__DIR__ . '/deprecatedlib.php');
59 /**
60 * Return an array of status options
62 * Optionally with translated strings
64 * @param bool $with_strings (optional)
65 * @return array
67 function scorm_status_options($withstrings = false) {
68 // Id's are important as they are bits.
69 $options = array(
70 2 => 'passed',
71 4 => 'completed'
74 if ($withstrings) {
75 foreach ($options as $key => $value) {
76 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
80 return $options;
84 /**
85 * Given an object containing all the necessary data,
86 * (defined by the form in mod_form.php) this function
87 * will create a new instance and return the id number
88 * of the new instance.
90 * @global stdClass
91 * @global object
92 * @uses CONTEXT_MODULE
93 * @uses SCORM_TYPE_LOCAL
94 * @uses SCORM_TYPE_LOCALSYNC
95 * @uses SCORM_TYPE_EXTERNAL
96 * @param object $scorm Form data
97 * @param object $mform
98 * @return int new instance id
100 function scorm_add_instance($scorm, $mform=null) {
101 global $CFG, $DB;
103 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
105 if (empty($scorm->timeopen)) {
106 $scorm->timeopen = 0;
108 if (empty($scorm->timeclose)) {
109 $scorm->timeclose = 0;
111 if (empty($scorm->completionstatusallscos)) {
112 $scorm->completionstatusallscos = 0;
114 $cmid = $scorm->coursemodule;
115 $cmidnumber = $scorm->cmidnumber;
116 $courseid = $scorm->course;
118 $context = context_module::instance($cmid);
120 $scorm = scorm_option2text($scorm);
121 $scorm->width = (int)str_replace('%', '', $scorm->width);
122 $scorm->height = (int)str_replace('%', '', $scorm->height);
124 if (!isset($scorm->whatgrade)) {
125 $scorm->whatgrade = 0;
128 $id = $DB->insert_record('scorm', $scorm);
130 // Update course module record - from now on this instance properly exists and all function may be used.
131 $DB->set_field('course_modules', 'instance', $id, array('id' => $cmid));
133 // Reload scorm instance.
134 $record = $DB->get_record('scorm', array('id' => $id));
136 // Store the package and verify.
137 if ($record->scormtype === SCORM_TYPE_LOCAL) {
138 if (!empty($scorm->packagefile)) {
139 $fs = get_file_storage();
140 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
141 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
142 0, array('subdirs' => 0, 'maxfiles' => 1));
143 // Get filename of zip that was uploaded.
144 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
145 $file = reset($files);
146 $filename = $file->get_filename();
147 if ($filename !== false) {
148 $record->reference = $filename;
152 } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
153 $record->reference = $scorm->packageurl;
154 } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
155 $record->reference = $scorm->packageurl;
156 } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
157 $record->reference = $scorm->packageurl;
158 $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
159 } else {
160 return false;
163 // Save reference.
164 $DB->update_record('scorm', $record);
166 // Extra fields required in grade related functions.
167 $record->course = $courseid;
168 $record->cmidnumber = $cmidnumber;
169 $record->cmid = $cmid;
171 scorm_parse($record, true);
173 scorm_grade_item_update($record);
174 scorm_update_calendar($record, $cmid);
175 if (!empty($scorm->completionexpected)) {
176 \core_completion\api::update_completion_date_event($cmid, 'scorm', $record, $scorm->completionexpected);
179 return $record->id;
183 * Given an object containing all the necessary data,
184 * (defined by the form in mod_form.php) this function
185 * will update an existing instance with new data.
187 * @global stdClass
188 * @global object
189 * @uses CONTEXT_MODULE
190 * @uses SCORM_TYPE_LOCAL
191 * @uses SCORM_TYPE_LOCALSYNC
192 * @uses SCORM_TYPE_EXTERNAL
193 * @param object $scorm Form data
194 * @param object $mform
195 * @return bool
197 function scorm_update_instance($scorm, $mform=null) {
198 global $CFG, $DB;
200 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
202 if (empty($scorm->timeopen)) {
203 $scorm->timeopen = 0;
205 if (empty($scorm->timeclose)) {
206 $scorm->timeclose = 0;
208 if (empty($scorm->completionstatusallscos)) {
209 $scorm->completionstatusallscos = 0;
212 $cmid = $scorm->coursemodule;
213 $cmidnumber = $scorm->cmidnumber;
214 $courseid = $scorm->course;
216 $scorm->id = $scorm->instance;
218 $context = context_module::instance($cmid);
220 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
221 if (!empty($scorm->packagefile)) {
222 $fs = get_file_storage();
223 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
224 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
225 0, array('subdirs' => 0, 'maxfiles' => 1));
226 // Get filename of zip that was uploaded.
227 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
228 $file = reset($files);
229 $filename = $file->get_filename();
230 if ($filename !== false) {
231 $scorm->reference = $filename;
235 } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
236 $scorm->reference = $scorm->packageurl;
237 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
238 $scorm->reference = $scorm->packageurl;
239 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
240 $scorm->reference = $scorm->packageurl;
241 $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
242 } else {
243 return false;
246 $scorm = scorm_option2text($scorm);
247 $scorm->width = (int)str_replace('%', '', $scorm->width);
248 $scorm->height = (int)str_replace('%', '', $scorm->height);
249 $scorm->timemodified = time();
251 if (!isset($scorm->whatgrade)) {
252 $scorm->whatgrade = 0;
255 $DB->update_record('scorm', $scorm);
256 // We need to find this out before we blow away the form data.
257 $completionexpected = (!empty($scorm->completionexpected)) ? $scorm->completionexpected : null;
259 $scorm = $DB->get_record('scorm', array('id' => $scorm->id));
261 // Extra fields required in grade related functions.
262 $scorm->course = $courseid;
263 $scorm->idnumber = $cmidnumber;
264 $scorm->cmid = $cmid;
266 scorm_parse($scorm, (bool)$scorm->updatefreq);
268 scorm_grade_item_update($scorm);
269 scorm_update_grades($scorm);
270 scorm_update_calendar($scorm, $cmid);
271 \core_completion\api::update_completion_date_event($cmid, 'scorm', $scorm, $completionexpected);
273 return true;
277 * Given an ID of an instance of this module,
278 * this function will permanently delete the instance
279 * and any data that depends on it.
281 * @global stdClass
282 * @global object
283 * @param int $id Scorm instance id
284 * @return boolean
286 function scorm_delete_instance($id) {
287 global $CFG, $DB;
289 if (! $scorm = $DB->get_record('scorm', array('id' => $id))) {
290 return false;
293 $result = true;
295 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
296 // Delete any dependent records.
297 scorm_delete_tracks($scorm->id);
298 if ($scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id))) {
299 foreach ($scoes as $sco) {
300 if (! $DB->delete_records('scorm_scoes_data', array('scoid' => $sco->id))) {
301 $result = false;
304 $DB->delete_records('scorm_scoes', array('scorm' => $scorm->id));
307 scorm_grade_item_delete($scorm);
309 // We must delete the module record after we delete the grade item.
310 if (! $DB->delete_records('scorm', array('id' => $scorm->id))) {
311 $result = false;
314 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
315 $result = false;
317 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
318 $result = false;
320 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
321 $result = false;
323 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
324 $result = false;
326 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
327 $result = false;
329 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
330 $result = false;
332 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
333 $result = false;
336 return $result;
340 * Return a small object with summary information about what a
341 * user has done with a given particular instance of this module
342 * Used for user activity reports.
344 * @param stdClass $course Course object
345 * @param stdClass $user User
346 * @param stdClass $mod
347 * @param stdClass $scorm The scorm
348 * @return mixed
350 function scorm_user_outline($course, $user, $mod, $scorm) {
351 global $CFG;
352 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
354 require_once("$CFG->libdir/gradelib.php");
355 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
356 if (!empty($grades->items[0]->grades)) {
357 $grade = reset($grades->items[0]->grades);
358 $result = (object) [
359 'time' => grade_get_date_for_user_grade($grade, $user),
361 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
362 $result->info = get_string('gradenoun') . ': '. $grade->str_long_grade;
363 } else {
364 $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
367 return $result;
369 return null;
373 * Print a detailed representation of what a user has done with
374 * a given particular instance of this module, for user activity reports.
376 * @global stdClass
377 * @global object
378 * @param object $course
379 * @param object $user
380 * @param object $mod
381 * @param object $scorm
382 * @return boolean
384 function scorm_user_complete($course, $user, $mod, $scorm) {
385 global $CFG, $DB, $OUTPUT;
386 require_once("$CFG->libdir/gradelib.php");
388 $liststyle = 'structlist';
389 $now = time();
390 $firstmodify = $now;
391 $lastmodify = 0;
392 $sometoreport = false;
393 $report = '';
395 // First Access and Last Access dates for SCOs.
396 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
397 $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
398 $firstmodify = $timetracks->start;
399 $lastmodify = $timetracks->finish;
401 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
402 if (!empty($grades->items[0]->grades)) {
403 $grade = reset($grades->items[0]->grades);
404 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
405 echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade);
406 if ($grade->str_feedback) {
407 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
409 } else {
410 echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
414 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
415 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
416 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
417 array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
418 if (count($orgs) <= 1) {
419 unset($orgs);
420 $orgs = array();
421 $org = new stdClass();
422 $org->identifier = '';
423 $orgs[] = $org;
425 $report .= html_writer::start_div('mod-scorm');
426 foreach ($orgs as $org) {
427 $conditions = array();
428 $currentorg = '';
429 if (!empty($org->identifier)) {
430 $report .= html_writer::div($org->title, 'orgtitle');
431 $currentorg = $org->identifier;
432 $conditions['organization'] = $currentorg;
434 $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
435 $conditions['scorm'] = $scorm->id;
436 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
437 // Drop keys so that we can access array sequentially.
438 $scoes = array_values($scoes);
439 $level = 0;
440 $sublist = 1;
441 $parents[$level] = '/';
442 foreach ($scoes as $pos => $sco) {
443 if ($parents[$level] != $sco->parent) {
444 if ($level > 0 && $parents[$level - 1] == $sco->parent) {
445 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
446 $level--;
447 } else {
448 $i = $level;
449 $closelist = '';
450 while (($i > 0) && ($parents[$level] != $sco->parent)) {
451 $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
452 $i--;
454 if (($i == 0) && ($sco->parent != $currentorg)) {
455 $report .= html_writer::start_tag('li');
456 $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
457 $level++;
458 } else {
459 $report .= $closelist;
460 $level = $i;
462 $parents[$level] = $sco->parent;
465 $report .= html_writer::start_tag('li');
466 if (isset($scoes[$pos + 1])) {
467 $nextsco = $scoes[$pos + 1];
468 } else {
469 $nextsco = false;
471 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
472 (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
473 $sublist++;
474 } else {
475 $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
478 if ($sco->launch) {
479 $score = '';
480 $totaltime = '';
481 if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
482 if ($usertrack->status == '') {
483 $usertrack->status = 'notattempted';
485 $strstatus = get_string($usertrack->status, 'scorm');
486 $report .= $OUTPUT->pix_icon($usertrack->status, $strstatus, 'scorm');
487 } else {
488 if ($sco->scormtype == 'sco') {
489 $report .= $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
490 } else {
491 $report .= $OUTPUT->pix_icon('asset', get_string('asset', 'scorm'), 'scorm');
494 $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
495 if ($usertrack !== false) {
496 $sometoreport = true;
497 $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
498 foreach ($usertrack as $element => $value) {
499 if (substr($element, 0, 3) == 'cmi') {
500 $report .= html_writer::tag('li', s($element) . ' => ' . s($value));
503 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
505 } else {
506 $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
509 for ($i = 0; $i < $level; $i++) {
510 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
513 $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
515 $report .= html_writer::end_div();
517 if ($sometoreport) {
518 if ($firstmodify < $now) {
519 $timeago = format_time($now - $firstmodify);
520 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
522 if ($lastmodify > 0) {
523 $timeago = format_time($now - $lastmodify);
524 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
526 echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
527 echo $report;
528 } else {
529 print_string('noactivity', 'scorm');
532 return true;
536 * Function to be run periodically according to the moodle Tasks API
537 * This function searches for things that need to be done, such
538 * as sending out mail, toggling flags etc ...
540 * @global stdClass
541 * @global object
542 * @return boolean
544 function scorm_cron_scheduled_task () {
545 global $CFG, $DB;
547 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
549 $sitetimezone = core_date::get_server_timezone();
550 // Now see if there are any scorm updates to be done.
552 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time.
553 set_config('scorm_updatetimelast', 0);
556 $timenow = time();
557 $updatetime = usergetmidnight($timenow, $sitetimezone);
559 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
561 set_config('scorm_updatetimelast', $timenow);
563 mtrace('Updating scorm packages which require daily update');// We are updating.
565 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
566 foreach ($scormsupdate as $scormupdate) {
567 scorm_parse($scormupdate, true);
570 // Now clear out AICC session table with old session data.
571 $cfgscorm = get_config('scorm');
572 if (!empty($cfgscorm->allowaicchacp)) {
573 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata * 24 * 60 * 60);
574 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
578 return true;
582 * Return grade for given user or all users.
584 * @global stdClass
585 * @global object
586 * @param int $scormid id of scorm
587 * @param int $userid optional user id, 0 means all users
588 * @return array array of grades, false if none
590 function scorm_get_user_grades($scorm, $userid=0) {
591 global $CFG, $DB;
592 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
594 $grades = array();
595 if (empty($userid)) {
596 $sql = "SELECT DISTINCT userid
597 FROM {scorm_attempt}
598 WHERE scormid = ?";
599 $scousers = $DB->get_recordset_sql($sql, [$scorm->id]);
601 foreach ($scousers as $scouser) {
602 $grades[$scouser->userid] = new stdClass();
603 $grades[$scouser->userid]->id = $scouser->userid;
604 $grades[$scouser->userid]->userid = $scouser->userid;
605 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
607 $scousers->close();
608 } else {
609 $preattempt = $DB->record_exists('scorm_attempt', ['scormid' => $scorm->id, 'userid' => $userid]);
610 if (!$preattempt) {
611 return false; // No attempt yet.
613 $grades[$userid] = new stdClass();
614 $grades[$userid]->id = $userid;
615 $grades[$userid]->userid = $userid;
616 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
619 if (empty($grades)) {
620 return false;
623 return $grades;
627 * Update grades in central gradebook
629 * @category grade
630 * @param object $scorm
631 * @param int $userid specific user only, 0 mean all
632 * @param bool $nullifnone
634 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
635 global $CFG;
636 require_once($CFG->libdir.'/gradelib.php');
637 require_once($CFG->libdir.'/completionlib.php');
639 if ($grades = scorm_get_user_grades($scorm, $userid)) {
640 scorm_grade_item_update($scorm, $grades);
641 // Set complete.
642 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
643 } else if ($userid and $nullifnone) {
644 $grade = new stdClass();
645 $grade->userid = $userid;
646 $grade->rawgrade = null;
647 scorm_grade_item_update($scorm, $grade);
648 // Set incomplete.
649 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
650 } else {
651 scorm_grade_item_update($scorm);
656 * Update/create grade item for given scorm
658 * @category grade
659 * @uses GRADE_TYPE_VALUE
660 * @uses GRADE_TYPE_NONE
661 * @param object $scorm object with extra cmidnumber
662 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
663 * @return object grade_item
665 function scorm_grade_item_update($scorm, $grades=null) {
666 global $CFG, $DB;
667 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
668 if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
669 require_once($CFG->libdir.'/gradelib.php');
672 $params = array('itemname' => $scorm->name);
673 if (isset($scorm->cmidnumber)) {
674 $params['idnumber'] = $scorm->cmidnumber;
677 if ($scorm->grademethod == GRADESCOES) {
678 $maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.
679 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id));
680 if ($maxgrade) {
681 $params['gradetype'] = GRADE_TYPE_VALUE;
682 $params['grademax'] = $maxgrade;
683 $params['grademin'] = 0;
684 } else {
685 $params['gradetype'] = GRADE_TYPE_NONE;
687 } else {
688 $params['gradetype'] = GRADE_TYPE_VALUE;
689 $params['grademax'] = $scorm->maxgrade;
690 $params['grademin'] = 0;
693 if ($grades === 'reset') {
694 $params['reset'] = true;
695 $grades = null;
698 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
702 * Delete grade item for given scorm
704 * @category grade
705 * @param object $scorm object
706 * @return object grade_item
708 function scorm_grade_item_delete($scorm) {
709 global $CFG;
710 require_once($CFG->libdir.'/gradelib.php');
712 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted' => 1));
716 * List the actions that correspond to a view of this module.
717 * This is used by the participation report.
719 * Note: This is not used by new logging system. Event with
720 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
721 * be considered as view action.
723 * @return array
725 function scorm_get_view_actions() {
726 return array('pre-view', 'view', 'view all', 'report');
730 * List the actions that correspond to a post of this module.
731 * This is used by the participation report.
733 * Note: This is not used by new logging system. Event with
734 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
735 * will be considered as post action.
737 * @return array
739 function scorm_get_post_actions() {
740 return array();
744 * @param object $scorm
745 * @return object $scorm
747 function scorm_option2text($scorm) {
748 $scormpopoupoptions = scorm_get_popup_options_array();
750 if (isset($scorm->popup)) {
751 if ($scorm->popup == 1) {
752 $optionlist = array();
753 foreach ($scormpopoupoptions as $name => $option) {
754 if (isset($scorm->$name)) {
755 $optionlist[] = $name.'='.$scorm->$name;
756 } else {
757 $optionlist[] = $name.'=0';
760 $scorm->options = implode(',', $optionlist);
761 } else {
762 $scorm->options = '';
764 } else {
765 $scorm->popup = 0;
766 $scorm->options = '';
768 return $scorm;
772 * Implementation of the function for printing the form elements that control
773 * whether the course reset functionality affects the scorm.
775 * @param MoodleQuickForm $mform form passed by reference
777 function scorm_reset_course_form_definition(&$mform) {
778 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
779 $mform->addElement('static', 'scormdelete', get_string('delete'));
780 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
784 * Course reset form defaults.
786 * @return array
788 function scorm_reset_course_form_defaults($course) {
789 return array('reset_scorm' => 1);
793 * Removes all grades from gradebook
795 * @global stdClass
796 * @global object
797 * @param int $courseid
798 * @param string optional type
800 function scorm_reset_gradebook($courseid, $type='') {
801 global $CFG, $DB;
803 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
804 FROM {scorm} s, {course_modules} cm, {modules} m
805 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
807 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
808 foreach ($scorms as $scorm) {
809 scorm_grade_item_update($scorm, 'reset');
815 * Actual implementation of the reset course functionality, delete all the
816 * scorm attempts for course $data->courseid.
818 * @global stdClass
819 * @global object
820 * @param object $data the data submitted from the reset course.
821 * @return array status array
823 function scorm_reset_userdata($data) {
824 global $DB, $CFG;
825 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
827 $componentstr = get_string('modulenameplural', 'scorm');
828 $status = [];
830 if (!empty($data->reset_scorm)) {
832 $scorms = $DB->get_recordset('scorm', ['course' => $data->courseid]);
833 foreach ($scorms as $scorm) {
834 scorm_delete_tracks($scorm->id);
836 $scorms->close();
838 // Remove all grades from gradebook.
839 if (empty($data->reset_gradebook_grades)) {
840 scorm_reset_gradebook($data->courseid);
843 $status[] = ['component' => $componentstr, 'item' => get_string('deleteallattempts', 'scorm'), 'error' => false];
846 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
847 // See MDL-9367.
848 shift_course_mod_dates('scorm', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
849 $status[] = ['component' => $componentstr, 'item' => get_string('date'), 'error' => false];
851 return $status;
855 * Lists all file areas current user may browse
857 * @param object $course
858 * @param object $cm
859 * @param object $context
860 * @return array
862 function scorm_get_file_areas($course, $cm, $context) {
863 $areas = array();
864 $areas['content'] = get_string('areacontent', 'scorm');
865 $areas['package'] = get_string('areapackage', 'scorm');
866 return $areas;
870 * File browsing support for SCORM file areas
872 * @package mod_scorm
873 * @category files
874 * @param file_browser $browser file browser instance
875 * @param array $areas file areas
876 * @param stdClass $course course object
877 * @param stdClass $cm course module object
878 * @param stdClass $context context object
879 * @param string $filearea file area
880 * @param int $itemid item ID
881 * @param string $filepath file path
882 * @param string $filename file name
883 * @return file_info instance or null if not found
885 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
886 global $CFG;
888 if (!has_capability('moodle/course:managefiles', $context)) {
889 return null;
892 // No writing for now!
894 $fs = get_file_storage();
896 if ($filearea === 'content') {
898 $filepath = is_null($filepath) ? '/' : $filepath;
899 $filename = is_null($filename) ? '.' : $filename;
901 $urlbase = $CFG->wwwroot.'/pluginfile.php';
902 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
903 if ($filepath === '/' and $filename === '.') {
904 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
905 } else {
906 // Not found.
907 return null;
910 require_once("$CFG->dirroot/mod/scorm/locallib.php");
911 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
913 } else if ($filearea === 'package') {
914 $filepath = is_null($filepath) ? '/' : $filepath;
915 $filename = is_null($filename) ? '.' : $filename;
917 $urlbase = $CFG->wwwroot.'/pluginfile.php';
918 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
919 if ($filepath === '/' and $filename === '.') {
920 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
921 } else {
922 // Not found.
923 return null;
926 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
929 // Scorm_intro handled in file_browser.
931 return false;
935 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
937 * @package mod_scorm
938 * @category files
939 * @param stdClass $course course object
940 * @param stdClass $cm course module object
941 * @param stdClass $context context object
942 * @param string $filearea file area
943 * @param array $args extra arguments
944 * @param bool $forcedownload whether or not force download
945 * @param array $options additional options affecting the file serving
946 * @return bool false if file not found, does not return if found - just send the file
948 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
949 global $CFG, $DB;
951 if ($context->contextlevel != CONTEXT_MODULE) {
952 return false;
955 require_login($course, true, $cm);
957 $canmanageactivity = has_capability('moodle/course:manageactivities', $context);
958 $lifetime = null;
960 // Check SCORM availability.
961 if (!$canmanageactivity) {
962 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
964 $scorm = $DB->get_record('scorm', array('id' => $cm->instance), 'id, timeopen, timeclose', MUST_EXIST);
965 list($available, $warnings) = scorm_get_availability_status($scorm);
966 if (!$available) {
967 return false;
971 if ($filearea === 'content') {
972 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
973 $relativepath = implode('/', $args);
974 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
975 $options['immutable'] = true; // Add immutable option, $relativepath changes on file update.
977 } else if ($filearea === 'package') {
978 // Check if the global setting for disabling package downloads is enabled.
979 $protectpackagedownloads = get_config('scorm', 'protectpackagedownloads');
980 if ($protectpackagedownloads and !$canmanageactivity) {
981 return false;
983 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
984 $relativepath = implode('/', $args);
985 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
986 $lifetime = 0; // No caching here.
988 } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
989 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
990 $relativepath = implode('/', $args);
992 // Get imsmanifest file.
993 $fs = get_file_storage();
994 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
995 $file = reset($files);
997 // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
998 $packagefilename = $file->get_filename();
999 if (strtolower($packagefilename) !== 'imsmanifest.xml') {
1000 return false;
1003 $file->send_relative_file($relativepath);
1004 } else {
1005 return false;
1008 $fs = get_file_storage();
1009 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1010 if ($filearea === 'content') { // Return file not found straight away to improve performance.
1011 send_header_404();
1012 die;
1014 return false;
1017 // Allow SVG files to be loaded within SCORM content, instead of forcing download.
1018 $options['dontforcesvgdownload'] = true;
1020 // Finally send the file.
1021 send_stored_file($file, $lifetime, 0, false, $options);
1025 * @uses FEATURE_GROUPS
1026 * @uses FEATURE_GROUPINGS
1027 * @uses FEATURE_MOD_INTRO
1028 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1029 * @uses FEATURE_COMPLETION_HAS_RULES
1030 * @uses FEATURE_GRADE_HAS_GRADE
1031 * @uses FEATURE_GRADE_OUTCOMES
1032 * @param string $feature FEATURE_xx constant for requested feature
1033 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1035 function scorm_supports($feature) {
1036 switch($feature) {
1037 case FEATURE_GROUPS: return true;
1038 case FEATURE_GROUPINGS: return true;
1039 case FEATURE_MOD_INTRO: return true;
1040 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1041 case FEATURE_COMPLETION_HAS_RULES: return true;
1042 case FEATURE_GRADE_HAS_GRADE: return true;
1043 case FEATURE_GRADE_OUTCOMES: return true;
1044 case FEATURE_BACKUP_MOODLE2: return true;
1045 case FEATURE_SHOW_DESCRIPTION: return true;
1046 case FEATURE_MOD_PURPOSE:
1047 return MOD_PURPOSE_INTERACTIVECONTENT;
1049 default: return null;
1054 * Get the filename for a temp log file
1056 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1057 * @param integer $scoid - scoid of object this log entry is for
1058 * @return string The filename as an absolute path
1060 function scorm_debug_log_filename($type, $scoid) {
1061 global $CFG, $USER;
1063 $logpath = $CFG->tempdir.'/scormlogs';
1064 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1065 return $logfile;
1069 * writes log output to a temp log file
1071 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1072 * @param string $text - text to be written to file.
1073 * @param integer $scoid - scoid of object this log entry is for.
1075 function scorm_debug_log_write($type, $text, $scoid) {
1076 global $CFG;
1078 $debugenablelog = get_config('scorm', 'allowapidebug');
1079 if (!$debugenablelog || empty($text)) {
1080 return;
1082 if (make_temp_directory('scormlogs/')) {
1083 $logfile = scorm_debug_log_filename($type, $scoid);
1084 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1085 @chmod($logfile, $CFG->filepermissions);
1090 * Remove debug log file
1092 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1093 * @param integer $scoid - scoid of object this log entry is for
1094 * @return boolean True if the file is successfully deleted, false otherwise
1096 function scorm_debug_log_remove($type, $scoid) {
1098 $debugenablelog = get_config('scorm', 'allowapidebug');
1099 $logfile = scorm_debug_log_filename($type, $scoid);
1100 if (!$debugenablelog || !file_exists($logfile)) {
1101 return false;
1104 return @unlink($logfile);
1108 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
1110 function scorm_print_overview() {
1111 throw new coding_exception('scorm_print_overview() can not be used any more and is obsolete.');
1115 * Return a list of page types
1116 * @param string $pagetype current page type
1117 * @param stdClass $parentcontext Block's parent context
1118 * @param stdClass $currentcontext Current context of block
1120 function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1121 $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1122 return $modulepagetype;
1126 * Returns the SCORM version used.
1127 * @param string $scormversion comes from $scorm->version
1128 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1129 * @return Scorm version.
1131 function scorm_version_check($scormversion, $version='') {
1132 $scormversion = trim(strtolower($scormversion));
1133 if (empty($version) || $version == SCORM_12) {
1134 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1135 return SCORM_12;
1137 if (!empty($version)) {
1138 return false;
1141 if (empty($version) || $version == SCORM_13) {
1142 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1143 return SCORM_13;
1145 if (!empty($version)) {
1146 return false;
1149 if (empty($version) || $version == SCORM_AICC) {
1150 if (strpos($scormversion, 'aicc')) {
1151 return SCORM_AICC;
1153 if (!empty($version)) {
1154 return false;
1157 return false;
1161 * Register the ability to handle drag and drop file uploads
1162 * @return array containing details of the files / types the mod can handle
1164 function scorm_dndupload_register() {
1165 return array('files' => array(
1166 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1171 * Handle a file that has been uploaded
1172 * @param object $uploadinfo details of the file / content that has been uploaded
1173 * @return int instance id of the newly created mod
1175 function scorm_dndupload_handle($uploadinfo) {
1177 $context = context_module::instance($uploadinfo->coursemodule);
1178 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1179 $fs = get_file_storage();
1180 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1181 $file = reset($files);
1183 // Validate the file, make sure it's a valid SCORM package!
1184 $errors = scorm_validate_package($file);
1185 if (!empty($errors)) {
1186 return false;
1188 // Create a default scorm object to pass to scorm_add_instance()!
1189 $scorm = get_config('scorm');
1190 $scorm->course = $uploadinfo->course->id;
1191 $scorm->coursemodule = $uploadinfo->coursemodule;
1192 $scorm->cmidnumber = '';
1193 $scorm->name = $uploadinfo->displayname;
1194 $scorm->scormtype = SCORM_TYPE_LOCAL;
1195 $scorm->reference = $file->get_filename();
1196 $scorm->intro = '';
1197 $scorm->width = $scorm->framewidth;
1198 $scorm->height = $scorm->frameheight;
1200 return scorm_add_instance($scorm, null);
1204 * Sets activity completion state
1206 * @param object $scorm object
1207 * @param int $userid User ID
1208 * @param int $completionstate Completion state
1209 * @param array $grades grades array of users with grades - used when $userid = 0
1211 function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1212 $course = new stdClass();
1213 $course->id = $scorm->course;
1214 $completion = new completion_info($course);
1216 // Check if completion is enabled site-wide, or for the course.
1217 if (!$completion->is_enabled()) {
1218 return;
1221 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1222 if (empty($cm) || !$completion->is_enabled($cm)) {
1223 return;
1226 if (empty($userid)) { // We need to get all the relevant users from $grades param.
1227 foreach ($grades as $grade) {
1228 $completion->update_state($cm, $completionstate, $grade->userid);
1230 } else {
1231 $completion->update_state($cm, $completionstate, $userid);
1236 * Check that a Zip file contains a valid SCORM package
1238 * @param $file stored_file a Zip file.
1239 * @return array empty if no issue is found. Array of error message otherwise
1241 function scorm_validate_package($file) {
1242 $packer = get_file_packer('application/zip');
1243 $errors = array();
1244 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1245 $file->import_external_file_contents();
1247 $filelist = $file->list_files($packer);
1249 if (!is_array($filelist)) {
1250 $errors['packagefile'] = get_string('badarchive', 'scorm');
1251 } else {
1252 $aiccfound = false;
1253 $badmanifestpresent = false;
1254 foreach ($filelist as $info) {
1255 if ($info->pathname == 'imsmanifest.xml') {
1256 return array();
1257 } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1258 // This package has an imsmanifest file inside a folder of the package.
1259 $badmanifestpresent = true;
1261 if (preg_match('/\.cst$/', $info->pathname)) {
1262 return array();
1265 if (!$aiccfound) {
1266 if ($badmanifestpresent) {
1267 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1268 } else {
1269 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1273 return $errors;
1277 * Check and set the correct mode and attempt when entering a SCORM package.
1279 * @param object $scorm object
1280 * @param string $newattempt should a new attempt be generated here.
1281 * @param int $attempt the attempt number this is for.
1282 * @param int $userid the userid of the user.
1283 * @param string $mode the current mode that has been selected.
1285 function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1286 global $DB;
1288 if (($mode == 'browse')) {
1289 if ($scorm->hidebrowse == 1) {
1290 // Prevent Browse mode if hidebrowse is set.
1291 $mode = 'normal';
1292 } else {
1293 // We don't need to check attempts as browse mode is set.
1294 return;
1298 if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS) {
1299 // This SCORM is configured to force a new attempt on every re-entry.
1300 $newattempt = 'on';
1301 $mode = 'normal';
1302 if ($attempt == 1) {
1303 // Check if the user has any existing data or if this is really the first attempt.
1304 $exists = $DB->record_exists('scorm_attempt', ['userid' => $userid, 'scormid' => $scorm->id]);
1305 if (!$exists) {
1306 // No records yet - Attempt should == 1.
1307 return;
1310 $attempt++;
1312 return;
1314 // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1315 $incomplete = true;
1317 // Note - in SCORM_13 the cmi-core.lesson_status field was split into
1318 // 'cmi.completion_status' and 'cmi.success_status'.
1319 // 'cmi.completion_status' can only contain values 'completed', 'incomplete', 'not attempted' or 'unknown'.
1320 // This means the values 'passed' or 'failed' will never be reported for a track in SCORM_13 and
1321 // the only status that will be treated as complete is 'completed'.
1323 $completionelements = array(
1324 SCORM_12 => 'cmi.core.lesson_status',
1325 SCORM_13 => 'cmi.completion_status',
1326 SCORM_AICC => 'cmi.core.lesson_status'
1328 $scormversion = scorm_version_check($scorm->version);
1329 if($scormversion===false) {
1330 $scormversion = SCORM_12;
1332 $completionelement = $completionelements[$scormversion];
1334 $sql = "SELECT sc.id, sub.value
1335 FROM {scorm_scoes} sc
1336 LEFT JOIN (SELECT v.scoid, v.value
1337 FROM {scorm_attempt} a
1338 JOIN {scorm_scoes_value} v ON a.id = v.attemptid
1339 JOIN {scorm_element} e on e.id = v.elementid AND e.element = :element
1340 WHERE a.userid = :userid AND a.attempt = :attempt AND a.scormid = :scormid) sub ON sub.scoid = sc.id
1341 WHERE sc.scormtype = 'sco' AND sc.scorm = :scormid2";
1342 $tracks = $DB->get_recordset_sql($sql, ['userid' => $userid, 'attempt' => $attempt,
1343 'element' => $completionelement, 'scormid' => $scorm->id,
1344 'scormid2' => $scorm->id]);
1346 foreach ($tracks as $track) {
1347 if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1348 $incomplete = false;
1349 } else {
1350 $incomplete = true;
1351 break; // Found an incomplete sco, so the result as a whole is incomplete.
1354 $tracks->close();
1356 // Validate user request to start a new attempt.
1357 if ($incomplete === true) {
1358 // The option to start a new attempt should never have been presented. Force false.
1359 $newattempt = 'off';
1360 } else if (!empty($scorm->forcenewattempt)) {
1361 // A new attempt should be forced for already completed attempts.
1362 $newattempt = 'on';
1365 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1366 $attempt++;
1367 $mode = 'normal';
1368 } else { // Check if review mode should be set.
1369 if ($incomplete === true) {
1370 $mode = 'normal';
1371 } else {
1372 $mode = 'review';
1378 * Trigger the course_module_viewed event.
1380 * @param stdClass $scorm scorm object
1381 * @param stdClass $course course object
1382 * @param stdClass $cm course module object
1383 * @param stdClass $context context object
1384 * @since Moodle 3.0
1386 function scorm_view($scorm, $course, $cm, $context) {
1388 // Trigger course_module_viewed event.
1389 $params = array(
1390 'context' => $context,
1391 'objectid' => $scorm->id
1394 $event = \mod_scorm\event\course_module_viewed::create($params);
1395 $event->add_record_snapshot('course_modules', $cm);
1396 $event->add_record_snapshot('course', $course);
1397 $event->add_record_snapshot('scorm', $scorm);
1398 $event->trigger();
1402 * Check if the module has any update that affects the current user since a given time.
1404 * @param cm_info $cm course module data
1405 * @param int $from the time to check updates from
1406 * @param array $filter if we need to check only specific updates
1407 * @return stdClass an object with the different type of areas indicating if they were updated or not
1408 * @since Moodle 3.2
1410 function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1411 global $DB, $USER, $CFG;
1412 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1414 $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1415 $updates = new stdClass();
1416 list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1417 if (!$available) {
1418 return $updates;
1420 $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1422 $updates->tracks = (object) array('updated' => false);
1423 $sql = "SELECT v.id
1424 FROM {scorm_scoes_value} v
1425 JOIN {scorm_attempt} a ON a.id = v.attemptid
1426 WHERE a.scormid = :scormid AND v.timemodified > :timemodified";
1427 $params = ['scormid' => $scorm->id, 'timemodified' => $from, 'userid' => $USER->id];
1428 $tracks = $DB->get_records_sql($sql ." AND a.userid = :userid", $params);
1429 if (!empty($tracks)) {
1430 $updates->tracks->updated = true;
1431 $updates->tracks->itemids = array_keys($tracks);
1434 // Now, teachers should see other students updates.
1435 if (has_capability('mod/scorm:viewreport', $cm->context)) {
1436 $params = ['scormid' => $scorm->id, 'timemodified' => $from];
1438 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1439 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1440 if (empty($groupusers)) {
1441 return $updates;
1443 list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1444 $sql .= ' AND userid ' . $insql;
1445 $params = array_merge($params, $inparams);
1448 $updates->usertracks = (object) array('updated' => false);
1450 $tracks = $DB->get_records_sql($sql, $params);
1451 if (!empty($tracks)) {
1452 $updates->usertracks->updated = true;
1453 $updates->usertracks->itemids = array_keys($tracks);
1456 return $updates;
1460 * Get icon mapping for font-awesome.
1462 function mod_scorm_get_fontawesome_icon_map() {
1463 return [
1464 'mod_scorm:asset' => 'fa-regular fa-file-zipper',
1465 'mod_scorm:assetc' => 'fa-regular fa-file-zipper',
1466 'mod_scorm:browsed' => 'fa-book',
1467 'mod_scorm:completed' => 'fa-check',
1468 'mod_scorm:failed' => 'fa-xmark',
1469 'mod_scorm:incomplete' => 'fa-pen-to-square',
1470 'mod_scorm:minus' => 'fa-minus',
1471 'mod_scorm:notattempted' => 'fa-regular fa-square',
1472 'mod_scorm:passed' => 'fa-check-double',
1473 'mod_scorm:plus' => 'fa-plus',
1474 'mod_scorm:popdown' => 'fa-regular fa-rectangle-xmark',
1475 'mod_scorm:popup' => 'fa-regular fa-window-restore',
1476 'mod_scorm:suspend' => 'fa-pause',
1477 'mod_scorm:wait' => 'fa-spinner fa-spin',
1482 * This standard function will check all instances of this module
1483 * and make sure there are up-to-date events created for each of them.
1484 * If courseid = 0, then every scorm event in the site is checked, else
1485 * only scorm events belonging to the course specified are checked.
1487 * @param int $courseid
1488 * @param int|stdClass $instance scorm module instance or ID.
1489 * @param int|stdClass $cm Course module object or ID.
1490 * @return bool
1492 function scorm_refresh_events($courseid = 0, $instance = null, $cm = null) {
1493 global $CFG, $DB;
1495 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1497 // If we have instance information then we can just update the one event instead of updating all events.
1498 if (isset($instance)) {
1499 if (!is_object($instance)) {
1500 $instance = $DB->get_record('scorm', array('id' => $instance), '*', MUST_EXIST);
1502 if (isset($cm)) {
1503 if (!is_object($cm)) {
1504 $cm = (object)array('id' => $cm);
1506 } else {
1507 $cm = get_coursemodule_from_instance('scorm', $instance->id);
1509 scorm_update_calendar($instance, $cm->id);
1510 return true;
1513 if ($courseid) {
1514 // Make sure that the course id is numeric.
1515 if (!is_numeric($courseid)) {
1516 return false;
1518 if (!$scorms = $DB->get_records('scorm', array('course' => $courseid))) {
1519 return false;
1521 } else {
1522 if (!$scorms = $DB->get_records('scorm')) {
1523 return false;
1527 foreach ($scorms as $scorm) {
1528 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1529 scorm_update_calendar($scorm, $cm->id);
1532 return true;
1536 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1538 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1539 * is not displayed on the block.
1541 * @param calendar_event $event
1542 * @param \core_calendar\action_factory $factory
1543 * @param int $userid User id override
1544 * @return \core_calendar\local\event\entities\action_interface|null
1546 function mod_scorm_core_calendar_provide_event_action(calendar_event $event,
1547 \core_calendar\action_factory $factory, $userid = null) {
1548 global $CFG, $USER;
1550 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1552 if (empty($userid)) {
1553 $userid = $USER->id;
1556 $cm = get_fast_modinfo($event->courseid, $userid)->instances['scorm'][$event->instance];
1558 if (has_capability('mod/scorm:viewreport', $cm->context, $userid)) {
1559 // Teachers do not need to be reminded to complete a scorm.
1560 return null;
1563 $completion = new \completion_info($cm->get_course());
1565 $completiondata = $completion->get_data($cm, false, $userid);
1567 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1568 return null;
1571 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
1572 // The scorm has closed so the user can no longer submit anything.
1573 return null;
1576 // Restore scorm object from cached values in $cm, we only need id, timeclose and timeopen.
1577 $customdata = $cm->customdata ?: [];
1578 $customdata['id'] = $cm->instance;
1579 $scorm = (object)($customdata + ['timeclose' => 0, 'timeopen' => 0]);
1581 // Check that the SCORM activity is open.
1582 list($actionable, $warnings) = scorm_get_availability_status($scorm, false, null, $userid);
1584 return $factory->create_instance(
1585 get_string('enter', 'scorm'),
1586 new \moodle_url('/mod/scorm/view.php', array('id' => $cm->id)),
1588 $actionable
1593 * Add a get_coursemodule_info function in case any SCORM type wants to add 'extra' information
1594 * for the course (see resource).
1596 * Given a course_module object, this function returns any "extra" information that may be needed
1597 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1599 * @param stdClass $coursemodule The coursemodule object (record).
1600 * @return cached_cm_info An object on information that the courses
1601 * will know about (most noticeably, an icon).
1603 function scorm_get_coursemodule_info($coursemodule) {
1604 global $DB;
1606 $dbparams = ['id' => $coursemodule->instance];
1607 $fields = 'id, name, intro, introformat, completionstatusrequired, completionscorerequired, completionstatusallscos, '.
1608 'timeopen, timeclose';
1609 if (!$scorm = $DB->get_record('scorm', $dbparams, $fields)) {
1610 return false;
1613 $result = new cached_cm_info();
1614 $result->name = $scorm->name;
1616 if ($coursemodule->showdescription) {
1617 // Convert intro to html. Do not filter cached version, filters run at display time.
1618 $result->content = format_module_intro('scorm', $scorm, $coursemodule->id, false);
1621 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1622 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1623 $result->customdata['customcompletionrules']['completionstatusrequired'] = $scorm->completionstatusrequired;
1624 $result->customdata['customcompletionrules']['completionscorerequired'] = $scorm->completionscorerequired;
1625 $result->customdata['customcompletionrules']['completionstatusallscos'] = $scorm->completionstatusallscos;
1627 // Populate some other values that can be used in calendar or on dashboard.
1628 if ($scorm->timeopen) {
1629 $result->customdata['timeopen'] = $scorm->timeopen;
1631 if ($scorm->timeclose) {
1632 $result->customdata['timeclose'] = $scorm->timeclose;
1635 return $result;
1639 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1641 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1642 * @return array $descriptions the array of descriptions for the custom rules.
1644 function mod_scorm_get_completion_active_rule_descriptions($cm) {
1645 // Values will be present in cm_info, and we assume these are up to date.
1646 if (empty($cm->customdata['customcompletionrules'])
1647 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1648 return [];
1651 $descriptions = [];
1652 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1653 switch ($key) {
1654 case 'completionstatusrequired':
1655 if (!is_null($val)) {
1656 // Determine the selected statuses using a bitwise operation.
1657 $cvalues = array();
1658 foreach (scorm_status_options(true) as $bit => $string) {
1659 if (($val & $bit) == $bit) {
1660 $cvalues[] = $string;
1663 $statusstring = implode(', ', $cvalues);
1664 $descriptions[] = get_string('completionstatusrequireddesc', 'scorm', $statusstring);
1666 break;
1667 case 'completionscorerequired':
1668 if (!is_null($val)) {
1669 $descriptions[] = get_string('completionscorerequireddesc', 'scorm', $val);
1671 break;
1672 case 'completionstatusallscos':
1673 if (!empty($val)) {
1674 $descriptions[] = get_string('completionstatusallscos', 'scorm');
1676 break;
1677 default:
1678 break;
1681 return $descriptions;
1685 * This function will update the scorm module according to the
1686 * event that has been modified.
1688 * It will set the timeopen or timeclose value of the scorm instance
1689 * according to the type of event provided.
1691 * @throws \moodle_exception
1692 * @param \calendar_event $event
1693 * @param stdClass $scorm The module instance to get the range from
1695 function mod_scorm_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $scorm) {
1696 global $DB;
1698 if (empty($event->instance) || $event->modulename != 'scorm') {
1699 return;
1702 if ($event->instance != $scorm->id) {
1703 return;
1706 if (!in_array($event->eventtype, [SCORM_EVENT_TYPE_OPEN, SCORM_EVENT_TYPE_CLOSE])) {
1707 return;
1710 $courseid = $event->courseid;
1711 $modulename = $event->modulename;
1712 $instanceid = $event->instance;
1713 $modified = false;
1715 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1716 $context = context_module::instance($coursemodule->id);
1718 // The user does not have the capability to modify this activity.
1719 if (!has_capability('moodle/course:manageactivities', $context)) {
1720 return;
1723 if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1724 // If the event is for the scorm activity opening then we should
1725 // set the start time of the scorm activity to be the new start
1726 // time of the event.
1727 if ($scorm->timeopen != $event->timestart) {
1728 $scorm->timeopen = $event->timestart;
1729 $scorm->timemodified = time();
1730 $modified = true;
1732 } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1733 // If the event is for the scorm activity closing then we should
1734 // set the end time of the scorm activity to be the new start
1735 // time of the event.
1736 if ($scorm->timeclose != $event->timestart) {
1737 $scorm->timeclose = $event->timestart;
1738 $modified = true;
1742 if ($modified) {
1743 $scorm->timemodified = time();
1744 $DB->update_record('scorm', $scorm);
1745 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1746 $event->trigger();
1751 * This function calculates the minimum and maximum cutoff values for the timestart of
1752 * the given event.
1754 * It will return an array with two values, the first being the minimum cutoff value and
1755 * the second being the maximum cutoff value. Either or both values can be null, which
1756 * indicates there is no minimum or maximum, respectively.
1758 * If a cutoff is required then the function must return an array containing the cutoff
1759 * timestamp and error string to display to the user if the cutoff value is violated.
1761 * A minimum and maximum cutoff return value will look like:
1763 * [1505704373, 'The date must be after this date'],
1764 * [1506741172, 'The date must be before this date']
1767 * @param \calendar_event $event The calendar event to get the time range for
1768 * @param \stdClass $instance The module instance to get the range from
1769 * @return array Returns an array with min and max date.
1771 function mod_scorm_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1772 $mindate = null;
1773 $maxdate = null;
1775 if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1776 // The start time of the open event can't be equal to or after the
1777 // close time of the scorm activity.
1778 if (!empty($instance->timeclose)) {
1779 $maxdate = [
1780 $instance->timeclose,
1781 get_string('openafterclose', 'scorm')
1784 } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1785 // The start time of the close event can't be equal to or earlier than the
1786 // open time of the scorm activity.
1787 if (!empty($instance->timeopen)) {
1788 $mindate = [
1789 $instance->timeopen,
1790 get_string('closebeforeopen', 'scorm')
1795 return [$mindate, $maxdate];
1799 * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
1801 * @param string $filearea The filearea.
1802 * @param array $args The path (the part after the filearea and before the filename).
1803 * @return array The itemid and the filepath inside the $args path, for the defined filearea.
1805 function mod_scorm_get_path_from_pluginfile(string $filearea, array $args): array {
1806 // SCORM never has an itemid (the number represents the revision but it's not stored in database).
1807 array_shift($args);
1809 // Get the filepath.
1810 if (empty($args)) {
1811 $filepath = '/';
1812 } else {
1813 $filepath = '/' . implode('/', $args) . '/';
1816 return [
1817 'itemid' => 0,
1818 'filepath' => $filepath,
1823 * Callback to fetch the activity event type lang string.
1825 * @param string $eventtype The event type.
1826 * @return lang_string The event type lang string.
1828 function mod_scorm_core_calendar_get_event_action_string(string $eventtype): string {
1829 $modulename = get_string('modulename', 'scorm');
1831 switch ($eventtype) {
1832 case SCORM_EVENT_TYPE_OPEN:
1833 $identifier = 'calendarstart';
1834 break;
1835 case SCORM_EVENT_TYPE_CLOSE:
1836 $identifier = 'calendarend';
1837 break;
1838 default:
1839 return get_string('requiresaction', 'calendar', $modulename);
1842 return get_string($identifier, 'scorm', $modulename);
1846 * This function extends the settings navigation block for the site.
1848 * It is safe to rely on PAGE here as we will only ever be within the module
1849 * context when this is called
1851 * @param settings_navigation $settings navigation_node object.
1852 * @param navigation_node $scormnode navigation_node object.
1853 * @return void
1855 function scorm_extend_settings_navigation(settings_navigation $settings, navigation_node $scormnode): void {
1856 if (has_capability('mod/scorm:viewreport', $settings->get_page()->cm->context)) {
1857 $url = new moodle_url('/mod/scorm/report.php', ['id' => $settings->get_page()->cm->id]);
1858 $scormnode->add(get_string("reports", "scorm"), $url, navigation_node::TYPE_CUSTOM, null, 'scormreport');