MDL-59523 course_reset: Added date update message when resetting.
[moodle.git] / mod / scorm / lib.php
blob620d71e35f029aba49a814c0f1c7fe76d492b33e
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
23 /** SCORM_TYPE_LOCAL = local */
24 define('SCORM_TYPE_LOCAL', 'local');
25 /** SCORM_TYPE_LOCALSYNC = localsync */
26 define('SCORM_TYPE_LOCALSYNC', 'localsync');
27 /** SCORM_TYPE_EXTERNAL = external */
28 define('SCORM_TYPE_EXTERNAL', 'external');
29 /** SCORM_TYPE_AICCURL = external AICC url */
30 define('SCORM_TYPE_AICCURL', 'aiccurl');
32 define('SCORM_TOC_SIDE', 0);
33 define('SCORM_TOC_HIDDEN', 1);
34 define('SCORM_TOC_POPUP', 2);
35 define('SCORM_TOC_DISABLED', 3);
37 // Used to show/hide navigation buttons and set their position.
38 define('SCORM_NAV_DISABLED', 0);
39 define('SCORM_NAV_UNDER_CONTENT', 1);
40 define('SCORM_NAV_FLOATING', 2);
42 // Used to check what SCORM version is being used.
43 define('SCORM_12', 1);
44 define('SCORM_13', 2);
45 define('SCORM_AICC', 3);
47 // List of possible attemptstatusdisplay options.
48 define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
49 define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
50 define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
51 define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
53 /**
54 * Return an array of status options
56 * Optionally with translated strings
58 * @param bool $with_strings (optional)
59 * @return array
61 function scorm_status_options($withstrings = false) {
62 // Id's are important as they are bits.
63 $options = array(
64 2 => 'passed',
65 4 => 'completed'
68 if ($withstrings) {
69 foreach ($options as $key => $value) {
70 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
74 return $options;
78 /**
79 * Given an object containing all the necessary data,
80 * (defined by the form in mod_form.php) this function
81 * will create a new instance and return the id number
82 * of the new instance.
84 * @global stdClass
85 * @global object
86 * @uses CONTEXT_MODULE
87 * @uses SCORM_TYPE_LOCAL
88 * @uses SCORM_TYPE_LOCALSYNC
89 * @uses SCORM_TYPE_EXTERNAL
90 * @param object $scorm Form data
91 * @param object $mform
92 * @return int new instance id
94 function scorm_add_instance($scorm, $mform=null) {
95 global $CFG, $DB;
97 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
99 if (empty($scorm->timeopen)) {
100 $scorm->timeopen = 0;
102 if (empty($scorm->timeclose)) {
103 $scorm->timeclose = 0;
105 if (empty($scorm->completionstatusallscos)) {
106 $scorm->completionstatusallscos = 0;
108 $cmid = $scorm->coursemodule;
109 $cmidnumber = $scorm->cmidnumber;
110 $courseid = $scorm->course;
112 $context = context_module::instance($cmid);
114 $scorm = scorm_option2text($scorm);
115 $scorm->width = (int)str_replace('%', '', $scorm->width);
116 $scorm->height = (int)str_replace('%', '', $scorm->height);
118 if (!isset($scorm->whatgrade)) {
119 $scorm->whatgrade = 0;
122 $id = $DB->insert_record('scorm', $scorm);
124 // Update course module record - from now on this instance properly exists and all function may be used.
125 $DB->set_field('course_modules', 'instance', $id, array('id' => $cmid));
127 // Reload scorm instance.
128 $record = $DB->get_record('scorm', array('id' => $id));
130 // Store the package and verify.
131 if ($record->scormtype === SCORM_TYPE_LOCAL) {
132 if (!empty($scorm->packagefile)) {
133 $fs = get_file_storage();
134 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
135 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
136 0, array('subdirs' => 0, 'maxfiles' => 1));
137 // Get filename of zip that was uploaded.
138 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
139 $file = reset($files);
140 $filename = $file->get_filename();
141 if ($filename !== false) {
142 $record->reference = $filename;
146 } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
147 $record->reference = $scorm->packageurl;
148 } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
149 $record->reference = $scorm->packageurl;
150 } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
151 $record->reference = $scorm->packageurl;
152 $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
153 } else {
154 return false;
157 // Save reference.
158 $DB->update_record('scorm', $record);
160 // Extra fields required in grade related functions.
161 $record->course = $courseid;
162 $record->cmidnumber = $cmidnumber;
163 $record->cmid = $cmid;
165 scorm_parse($record, true);
167 scorm_grade_item_update($record);
168 scorm_update_calendar($record, $cmid);
169 if (!empty($scorm->completionexpected)) {
170 \core_completion\api::update_completion_date_event($cmid, 'scorm', $record, $scorm->completionexpected);
173 return $record->id;
177 * Given an object containing all the necessary data,
178 * (defined by the form in mod_form.php) this function
179 * will update an existing instance with new data.
181 * @global stdClass
182 * @global object
183 * @uses CONTEXT_MODULE
184 * @uses SCORM_TYPE_LOCAL
185 * @uses SCORM_TYPE_LOCALSYNC
186 * @uses SCORM_TYPE_EXTERNAL
187 * @param object $scorm Form data
188 * @param object $mform
189 * @return bool
191 function scorm_update_instance($scorm, $mform=null) {
192 global $CFG, $DB;
194 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
196 if (empty($scorm->timeopen)) {
197 $scorm->timeopen = 0;
199 if (empty($scorm->timeclose)) {
200 $scorm->timeclose = 0;
202 if (empty($scorm->completionstatusallscos)) {
203 $scorm->completionstatusallscos = 0;
206 $cmid = $scorm->coursemodule;
207 $cmidnumber = $scorm->cmidnumber;
208 $courseid = $scorm->course;
210 $scorm->id = $scorm->instance;
212 $context = context_module::instance($cmid);
214 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
215 if (!empty($scorm->packagefile)) {
216 $fs = get_file_storage();
217 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
218 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
219 0, array('subdirs' => 0, 'maxfiles' => 1));
220 // Get filename of zip that was uploaded.
221 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
222 $file = reset($files);
223 $filename = $file->get_filename();
224 if ($filename !== false) {
225 $scorm->reference = $filename;
229 } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
230 $scorm->reference = $scorm->packageurl;
231 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
232 $scorm->reference = $scorm->packageurl;
233 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
234 $scorm->reference = $scorm->packageurl;
235 $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
236 } else {
237 return false;
240 $scorm = scorm_option2text($scorm);
241 $scorm->width = (int)str_replace('%', '', $scorm->width);
242 $scorm->height = (int)str_replace('%', '', $scorm->height);
243 $scorm->timemodified = time();
245 if (!isset($scorm->whatgrade)) {
246 $scorm->whatgrade = 0;
249 $DB->update_record('scorm', $scorm);
250 // We need to find this out before we blow away the form data.
251 $completionexpected = (!empty($scorm->completionexpected)) ? $scorm->completionexpected : null;
253 $scorm = $DB->get_record('scorm', array('id' => $scorm->id));
255 // Extra fields required in grade related functions.
256 $scorm->course = $courseid;
257 $scorm->idnumber = $cmidnumber;
258 $scorm->cmid = $cmid;
260 scorm_parse($scorm, (bool)$scorm->updatefreq);
262 scorm_grade_item_update($scorm);
263 scorm_update_grades($scorm);
264 scorm_update_calendar($scorm, $cmid);
265 \core_completion\api::update_completion_date_event($cmid, 'scorm', $scorm, $completionexpected);
267 return true;
271 * Given an ID of an instance of this module,
272 * this function will permanently delete the instance
273 * and any data that depends on it.
275 * @global stdClass
276 * @global object
277 * @param int $id Scorm instance id
278 * @return boolean
280 function scorm_delete_instance($id) {
281 global $CFG, $DB;
283 if (! $scorm = $DB->get_record('scorm', array('id' => $id))) {
284 return false;
287 $result = true;
289 // Delete any dependent records.
290 if (! $DB->delete_records('scorm_scoes_track', array('scormid' => $scorm->id))) {
291 $result = false;
293 if ($scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id))) {
294 foreach ($scoes as $sco) {
295 if (! $DB->delete_records('scorm_scoes_data', array('scoid' => $sco->id))) {
296 $result = false;
299 $DB->delete_records('scorm_scoes', array('scorm' => $scorm->id));
301 if (! $DB->delete_records('scorm', array('id' => $scorm->id))) {
302 $result = false;
305 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
306 $result = false;
308 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
309 $result = false;
311 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
312 $result = false;
314 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
315 $result = false;
317 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
318 $result = false;
320 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
321 $result = false;
323 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
324 $result = false;
327 scorm_grade_item_delete($scorm);
329 return $result;
333 * Return a small object with summary information about what a
334 * user has done with a given particular instance of this module
335 * Used for user activity reports.
337 * @global stdClass
338 * @param int $course Course id
339 * @param int $user User id
340 * @param int $mod
341 * @param int $scorm The scorm id
342 * @return mixed
344 function scorm_user_outline($course, $user, $mod, $scorm) {
345 global $CFG;
346 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
348 require_once("$CFG->libdir/gradelib.php");
349 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
350 if (!empty($grades->items[0]->grades)) {
351 $grade = reset($grades->items[0]->grades);
352 $result = new stdClass();
353 $result->info = get_string('grade') . ': '. $grade->str_long_grade;
355 // Datesubmitted == time created. dategraded == time modified or time overridden
356 // if grade was last modified by the user themselves use date graded. Otherwise use date submitted.
357 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
358 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
359 $result->time = $grade->dategraded;
360 } else {
361 $result->time = $grade->datesubmitted;
364 return $result;
366 return null;
370 * Print a detailed representation of what a user has done with
371 * a given particular instance of this module, for user activity reports.
373 * @global stdClass
374 * @global object
375 * @param object $course
376 * @param object $user
377 * @param object $mod
378 * @param object $scorm
379 * @return boolean
381 function scorm_user_complete($course, $user, $mod, $scorm) {
382 global $CFG, $DB, $OUTPUT;
383 require_once("$CFG->libdir/gradelib.php");
385 $liststyle = 'structlist';
386 $now = time();
387 $firstmodify = $now;
388 $lastmodify = 0;
389 $sometoreport = false;
390 $report = '';
392 // First Access and Last Access dates for SCOs.
393 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
394 $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
395 $firstmodify = $timetracks->start;
396 $lastmodify = $timetracks->finish;
398 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
399 if (!empty($grades->items[0]->grades)) {
400 $grade = reset($grades->items[0]->grades);
401 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
402 if ($grade->str_feedback) {
403 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
407 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
408 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
409 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
410 array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
411 if (count($orgs) <= 1) {
412 unset($orgs);
413 $orgs = array();
414 $org = new stdClass();
415 $org->identifier = '';
416 $orgs[] = $org;
418 $report .= html_writer::start_div('mod-scorm');
419 foreach ($orgs as $org) {
420 $conditions = array();
421 $currentorg = '';
422 if (!empty($org->identifier)) {
423 $report .= html_writer::div($org->title, 'orgtitle');
424 $currentorg = $org->identifier;
425 $conditions['organization'] = $currentorg;
427 $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
428 $conditions['scorm'] = $scorm->id;
429 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
430 // Drop keys so that we can access array sequentially.
431 $scoes = array_values($scoes);
432 $level = 0;
433 $sublist = 1;
434 $parents[$level] = '/';
435 foreach ($scoes as $pos => $sco) {
436 if ($parents[$level] != $sco->parent) {
437 if ($level > 0 && $parents[$level - 1] == $sco->parent) {
438 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
439 $level--;
440 } else {
441 $i = $level;
442 $closelist = '';
443 while (($i > 0) && ($parents[$level] != $sco->parent)) {
444 $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
445 $i--;
447 if (($i == 0) && ($sco->parent != $currentorg)) {
448 $report .= html_writer::start_tag('li');
449 $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
450 $level++;
451 } else {
452 $report .= $closelist;
453 $level = $i;
455 $parents[$level] = $sco->parent;
458 $report .= html_writer::start_tag('li');
459 if (isset($scoes[$pos + 1])) {
460 $nextsco = $scoes[$pos + 1];
461 } else {
462 $nextsco = false;
464 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
465 (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
466 $sublist++;
467 } else {
468 $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
471 if ($sco->launch) {
472 $score = '';
473 $totaltime = '';
474 if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
475 if ($usertrack->status == '') {
476 $usertrack->status = 'notattempted';
478 $strstatus = get_string($usertrack->status, 'scorm');
479 $report .= $OUTPUT->pix_icon($usertrack->status, $strstatus, 'scorm');
480 } else {
481 if ($sco->scormtype == 'sco') {
482 $report .= $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
483 } else {
484 $report .= $OUTPUT->pix_icon('asset', get_string('asset', 'scorm'), 'scorm');
487 $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
488 if ($usertrack !== false) {
489 $sometoreport = true;
490 $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
491 foreach ($usertrack as $element => $value) {
492 if (substr($element, 0, 3) == 'cmi') {
493 $report .= html_writer::tag('li', $element.' => '.s($value));
496 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
498 } else {
499 $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
502 for ($i = 0; $i < $level; $i++) {
503 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
506 $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
508 $report .= html_writer::end_div();
510 if ($sometoreport) {
511 if ($firstmodify < $now) {
512 $timeago = format_time($now - $firstmodify);
513 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
515 if ($lastmodify > 0) {
516 $timeago = format_time($now - $lastmodify);
517 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
519 echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
520 echo $report;
521 } else {
522 print_string('noactivity', 'scorm');
525 return true;
529 * Function to be run periodically according to the moodle Tasks API
530 * This function searches for things that need to be done, such
531 * as sending out mail, toggling flags etc ...
533 * @global stdClass
534 * @global object
535 * @return boolean
537 function scorm_cron_scheduled_task () {
538 global $CFG, $DB;
540 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
542 $sitetimezone = core_date::get_server_timezone();
543 // Now see if there are any scorm updates to be done.
545 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time.
546 set_config('scorm_updatetimelast', 0);
549 $timenow = time();
550 $updatetime = usergetmidnight($timenow, $sitetimezone);
552 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
554 set_config('scorm_updatetimelast', $timenow);
556 mtrace('Updating scorm packages which require daily update');// We are updating.
558 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
559 foreach ($scormsupdate as $scormupdate) {
560 scorm_parse($scormupdate, true);
563 // Now clear out AICC session table with old session data.
564 $cfgscorm = get_config('scorm');
565 if (!empty($cfgscorm->allowaicchacp)) {
566 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata * 24 * 60 * 60);
567 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
571 return true;
575 * Return grade for given user or all users.
577 * @global stdClass
578 * @global object
579 * @param int $scormid id of scorm
580 * @param int $userid optional user id, 0 means all users
581 * @return array array of grades, false if none
583 function scorm_get_user_grades($scorm, $userid=0) {
584 global $CFG, $DB;
585 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
587 $grades = array();
588 if (empty($userid)) {
589 $scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid",
590 array($scorm->id), "", "userid,null");
591 if ($scousers) {
592 foreach ($scousers as $scouser) {
593 $grades[$scouser->userid] = new stdClass();
594 $grades[$scouser->userid]->id = $scouser->userid;
595 $grades[$scouser->userid]->userid = $scouser->userid;
596 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
598 } else {
599 return false;
602 } else {
603 $preattempt = $DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid",
604 array($scorm->id, $userid), "", "userid,null");
605 if (!$preattempt) {
606 return false; // No attempt yet.
608 $grades[$userid] = new stdClass();
609 $grades[$userid]->id = $userid;
610 $grades[$userid]->userid = $userid;
611 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
614 return $grades;
618 * Update grades in central gradebook
620 * @category grade
621 * @param object $scorm
622 * @param int $userid specific user only, 0 mean all
623 * @param bool $nullifnone
625 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
626 global $CFG;
627 require_once($CFG->libdir.'/gradelib.php');
628 require_once($CFG->libdir.'/completionlib.php');
630 if ($grades = scorm_get_user_grades($scorm, $userid)) {
631 scorm_grade_item_update($scorm, $grades);
632 // Set complete.
633 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
634 } else if ($userid and $nullifnone) {
635 $grade = new stdClass();
636 $grade->userid = $userid;
637 $grade->rawgrade = null;
638 scorm_grade_item_update($scorm, $grade);
639 // Set incomplete.
640 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
641 } else {
642 scorm_grade_item_update($scorm);
647 * Update/create grade item for given scorm
649 * @category grade
650 * @uses GRADE_TYPE_VALUE
651 * @uses GRADE_TYPE_NONE
652 * @param object $scorm object with extra cmidnumber
653 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
654 * @return object grade_item
656 function scorm_grade_item_update($scorm, $grades=null) {
657 global $CFG, $DB;
658 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
659 if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
660 require_once($CFG->libdir.'/gradelib.php');
663 $params = array('itemname' => $scorm->name);
664 if (isset($scorm->cmidnumber)) {
665 $params['idnumber'] = $scorm->cmidnumber;
668 if ($scorm->grademethod == GRADESCOES) {
669 $maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.
670 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id));
671 if ($maxgrade) {
672 $params['gradetype'] = GRADE_TYPE_VALUE;
673 $params['grademax'] = $maxgrade;
674 $params['grademin'] = 0;
675 } else {
676 $params['gradetype'] = GRADE_TYPE_NONE;
678 } else {
679 $params['gradetype'] = GRADE_TYPE_VALUE;
680 $params['grademax'] = $scorm->maxgrade;
681 $params['grademin'] = 0;
684 if ($grades === 'reset') {
685 $params['reset'] = true;
686 $grades = null;
689 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
693 * Delete grade item for given scorm
695 * @category grade
696 * @param object $scorm object
697 * @return object grade_item
699 function scorm_grade_item_delete($scorm) {
700 global $CFG;
701 require_once($CFG->libdir.'/gradelib.php');
703 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted' => 1));
707 * List the actions that correspond to a view of this module.
708 * This is used by the participation report.
710 * Note: This is not used by new logging system. Event with
711 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
712 * be considered as view action.
714 * @return array
716 function scorm_get_view_actions() {
717 return array('pre-view', 'view', 'view all', 'report');
721 * List the actions that correspond to a post of this module.
722 * This is used by the participation report.
724 * Note: This is not used by new logging system. Event with
725 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
726 * will be considered as post action.
728 * @return array
730 function scorm_get_post_actions() {
731 return array();
735 * @param object $scorm
736 * @return object $scorm
738 function scorm_option2text($scorm) {
739 $scormpopoupoptions = scorm_get_popup_options_array();
741 if (isset($scorm->popup)) {
742 if ($scorm->popup == 1) {
743 $optionlist = array();
744 foreach ($scormpopoupoptions as $name => $option) {
745 if (isset($scorm->$name)) {
746 $optionlist[] = $name.'='.$scorm->$name;
747 } else {
748 $optionlist[] = $name.'=0';
751 $scorm->options = implode(',', $optionlist);
752 } else {
753 $scorm->options = '';
755 } else {
756 $scorm->popup = 0;
757 $scorm->options = '';
759 return $scorm;
763 * Implementation of the function for printing the form elements that control
764 * whether the course reset functionality affects the scorm.
766 * @param object $mform form passed by reference
768 function scorm_reset_course_form_definition(&$mform) {
769 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
770 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
774 * Course reset form defaults.
776 * @return array
778 function scorm_reset_course_form_defaults($course) {
779 return array('reset_scorm' => 1);
783 * Removes all grades from gradebook
785 * @global stdClass
786 * @global object
787 * @param int $courseid
788 * @param string optional type
790 function scorm_reset_gradebook($courseid, $type='') {
791 global $CFG, $DB;
793 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
794 FROM {scorm} s, {course_modules} cm, {modules} m
795 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
797 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
798 foreach ($scorms as $scorm) {
799 scorm_grade_item_update($scorm, 'reset');
805 * Actual implementation of the reset course functionality, delete all the
806 * scorm attempts for course $data->courseid.
808 * @global stdClass
809 * @global object
810 * @param object $data the data submitted from the reset course.
811 * @return array status array
813 function scorm_reset_userdata($data) {
814 global $CFG, $DB;
816 $componentstr = get_string('modulenameplural', 'scorm');
817 $status = array();
819 if (!empty($data->reset_scorm)) {
820 $scormssql = "SELECT s.id
821 FROM {scorm} s
822 WHERE s.course=?";
824 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
826 // Remove all grades from gradebook.
827 if (empty($data->reset_gradebook_grades)) {
828 scorm_reset_gradebook($data->courseid);
831 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallattempts', 'scorm'), 'error' => false);
834 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
835 // See MDL-9367.
836 shift_course_mod_dates('scorm', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
837 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
839 return $status;
843 * Returns all other caps used in module
845 * @return array
847 function scorm_get_extra_capabilities() {
848 return array('moodle/site:accessallgroups');
852 * Lists all file areas current user may browse
854 * @param object $course
855 * @param object $cm
856 * @param object $context
857 * @return array
859 function scorm_get_file_areas($course, $cm, $context) {
860 $areas = array();
861 $areas['content'] = get_string('areacontent', 'scorm');
862 $areas['package'] = get_string('areapackage', 'scorm');
863 return $areas;
867 * File browsing support for SCORM file areas
869 * @package mod_scorm
870 * @category files
871 * @param file_browser $browser file browser instance
872 * @param array $areas file areas
873 * @param stdClass $course course object
874 * @param stdClass $cm course module object
875 * @param stdClass $context context object
876 * @param string $filearea file area
877 * @param int $itemid item ID
878 * @param string $filepath file path
879 * @param string $filename file name
880 * @return file_info instance or null if not found
882 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
883 global $CFG;
885 if (!has_capability('moodle/course:managefiles', $context)) {
886 return null;
889 // No writing for now!
891 $fs = get_file_storage();
893 if ($filearea === 'content') {
895 $filepath = is_null($filepath) ? '/' : $filepath;
896 $filename = is_null($filename) ? '.' : $filename;
898 $urlbase = $CFG->wwwroot.'/pluginfile.php';
899 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
900 if ($filepath === '/' and $filename === '.') {
901 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
902 } else {
903 // Not found.
904 return null;
907 require_once("$CFG->dirroot/mod/scorm/locallib.php");
908 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
910 } else if ($filearea === 'package') {
911 $filepath = is_null($filepath) ? '/' : $filepath;
912 $filename = is_null($filename) ? '.' : $filename;
914 $urlbase = $CFG->wwwroot.'/pluginfile.php';
915 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
916 if ($filepath === '/' and $filename === '.') {
917 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
918 } else {
919 // Not found.
920 return null;
923 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
926 // Scorm_intro handled in file_browser.
928 return false;
932 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
934 * @package mod_scorm
935 * @category files
936 * @param stdClass $course course object
937 * @param stdClass $cm course module object
938 * @param stdClass $context context object
939 * @param string $filearea file area
940 * @param array $args extra arguments
941 * @param bool $forcedownload whether or not force download
942 * @param array $options additional options affecting the file serving
943 * @return bool false if file not found, does not return if found - just send the file
945 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
946 global $CFG, $DB;
948 if ($context->contextlevel != CONTEXT_MODULE) {
949 return false;
952 require_login($course, true, $cm);
954 $canmanageactivity = has_capability('moodle/course:manageactivities', $context);
955 $lifetime = null;
957 // Check SCORM availability.
958 if (!$canmanageactivity) {
959 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
961 $scorm = $DB->get_record('scorm', array('id' => $cm->instance), 'id, timeopen, timeclose', MUST_EXIST);
962 list($available, $warnings) = scorm_get_availability_status($scorm);
963 if (!$available) {
964 return false;
968 if ($filearea === 'content') {
969 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
970 $relativepath = implode('/', $args);
971 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
972 // TODO: add any other access restrictions here if needed!
974 } else if ($filearea === 'package') {
975 // Check if the global setting for disabling package downloads is enabled.
976 $protectpackagedownloads = get_config('scorm', 'protectpackagedownloads');
977 if ($protectpackagedownloads and !$canmanageactivity) {
978 return false;
980 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
981 $relativepath = implode('/', $args);
982 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
983 $lifetime = 0; // No caching here.
985 } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
986 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
987 $relativepath = implode('/', $args);
989 // Get imsmanifest file.
990 $fs = get_file_storage();
991 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
992 $file = reset($files);
994 // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
995 $packagefilename = $file->get_filename();
996 if (strtolower($packagefilename) !== 'imsmanifest.xml') {
997 return false;
1000 $file->send_relative_file($relativepath);
1001 } else {
1002 return false;
1005 $fs = get_file_storage();
1006 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1007 if ($filearea === 'content') { // Return file not found straight away to improve performance.
1008 send_header_404();
1009 die;
1011 return false;
1014 // Finally send the file.
1015 send_stored_file($file, $lifetime, 0, false, $options);
1019 * @uses FEATURE_GROUPS
1020 * @uses FEATURE_GROUPINGS
1021 * @uses FEATURE_MOD_INTRO
1022 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1023 * @uses FEATURE_COMPLETION_HAS_RULES
1024 * @uses FEATURE_GRADE_HAS_GRADE
1025 * @uses FEATURE_GRADE_OUTCOMES
1026 * @param string $feature FEATURE_xx constant for requested feature
1027 * @return mixed True if module supports feature, false if not, null if doesn't know
1029 function scorm_supports($feature) {
1030 switch($feature) {
1031 case FEATURE_GROUPS: return true;
1032 case FEATURE_GROUPINGS: return true;
1033 case FEATURE_MOD_INTRO: return true;
1034 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1035 case FEATURE_COMPLETION_HAS_RULES: return true;
1036 case FEATURE_GRADE_HAS_GRADE: return true;
1037 case FEATURE_GRADE_OUTCOMES: return true;
1038 case FEATURE_BACKUP_MOODLE2: return true;
1039 case FEATURE_SHOW_DESCRIPTION: return true;
1041 default: return null;
1046 * Get the filename for a temp log file
1048 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1049 * @param integer $scoid - scoid of object this log entry is for
1050 * @return string The filename as an absolute path
1052 function scorm_debug_log_filename($type, $scoid) {
1053 global $CFG, $USER;
1055 $logpath = $CFG->tempdir.'/scormlogs';
1056 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1057 return $logfile;
1061 * writes log output to a temp log file
1063 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1064 * @param string $text - text to be written to file.
1065 * @param integer $scoid - scoid of object this log entry is for.
1067 function scorm_debug_log_write($type, $text, $scoid) {
1068 global $CFG;
1070 $debugenablelog = get_config('scorm', 'allowapidebug');
1071 if (!$debugenablelog || empty($text)) {
1072 return;
1074 if (make_temp_directory('scormlogs/')) {
1075 $logfile = scorm_debug_log_filename($type, $scoid);
1076 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1077 @chmod($logfile, $CFG->filepermissions);
1082 * Remove debug log file
1084 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1085 * @param integer $scoid - scoid of object this log entry is for
1086 * @return boolean True if the file is successfully deleted, false otherwise
1088 function scorm_debug_log_remove($type, $scoid) {
1090 $debugenablelog = get_config('scorm', 'allowapidebug');
1091 $logfile = scorm_debug_log_filename($type, $scoid);
1092 if (!$debugenablelog || !file_exists($logfile)) {
1093 return false;
1096 return @unlink($logfile);
1100 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1102 * @deprecated since 3.3
1103 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1104 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1105 * @param array $htmlarray
1106 * @return mixed
1108 function scorm_print_overview($courses, &$htmlarray) {
1109 global $USER, $CFG;
1111 debugging('The function scorm_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1113 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1114 return array();
1117 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
1118 return;
1121 $strscorm = get_string('modulename', 'scorm');
1122 $strduedate = get_string('duedate', 'scorm');
1124 foreach ($scorms as $scorm) {
1125 $time = time();
1126 $showattemptstatus = false;
1127 if ($scorm->timeopen) {
1128 $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
1130 if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1131 $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) {
1132 $showattemptstatus = true;
1134 if ($showattemptstatus || !empty($isopen) || !empty($scorm->timeclose)) {
1135 $str = html_writer::start_div('scorm overview').html_writer::div($strscorm. ': '.
1136 html_writer::link($CFG->wwwroot.'/mod/scorm/view.php?id='.$scorm->coursemodule, $scorm->name,
1137 array('title' => $strscorm, 'class' => $scorm->visible ? '' : 'dimmed')), 'name');
1138 if ($scorm->timeclose) {
1139 $str .= html_writer::div($strduedate.': '.userdate($scorm->timeclose), 'info');
1141 if ($showattemptstatus) {
1142 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1143 $str .= html_writer::div(scorm_get_attempt_status($USER, $scorm), 'details');
1145 $str .= html_writer::end_div();
1146 if (empty($htmlarray[$scorm->course]['scorm'])) {
1147 $htmlarray[$scorm->course]['scorm'] = $str;
1148 } else {
1149 $htmlarray[$scorm->course]['scorm'] .= $str;
1156 * Return a list of page types
1157 * @param string $pagetype current page type
1158 * @param stdClass $parentcontext Block's parent context
1159 * @param stdClass $currentcontext Current context of block
1161 function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1162 $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1163 return $modulepagetype;
1167 * Returns the SCORM version used.
1168 * @param string $scormversion comes from $scorm->version
1169 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1170 * @return Scorm version.
1172 function scorm_version_check($scormversion, $version='') {
1173 $scormversion = trim(strtolower($scormversion));
1174 if (empty($version) || $version == SCORM_12) {
1175 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1176 return SCORM_12;
1178 if (!empty($version)) {
1179 return false;
1182 if (empty($version) || $version == SCORM_13) {
1183 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1184 return SCORM_13;
1186 if (!empty($version)) {
1187 return false;
1190 if (empty($version) || $version == SCORM_AICC) {
1191 if (strpos($scormversion, 'aicc')) {
1192 return SCORM_AICC;
1194 if (!empty($version)) {
1195 return false;
1198 return false;
1202 * Obtains the automatic completion state for this scorm based on any conditions
1203 * in scorm settings.
1205 * @param object $course Course
1206 * @param object $cm Course-module
1207 * @param int $userid User ID
1208 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1209 * @return bool True if completed, false if not. (If no conditions, then return
1210 * value depends on comparison type)
1212 function scorm_get_completion_state($course, $cm, $userid, $type) {
1213 global $DB;
1215 $result = $type;
1217 // Get scorm.
1218 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1219 print_error('cannotfindscorm');
1221 // Only check for existence of tracks and return false if completionstatusrequired or completionscorerequired
1222 // this means that if only view is required we don't end up with a false state.
1223 if ($scorm->completionstatusrequired !== null ||
1224 $scorm->completionscorerequired !== null) {
1225 // Get user's tracks data.
1226 $tracks = $DB->get_records_sql(
1228 SELECT
1230 scoid,
1231 element,
1232 value
1233 FROM
1234 {scorm_scoes_track}
1235 WHERE
1236 scormid = ?
1237 AND userid = ?
1238 AND element IN
1240 'cmi.core.lesson_status',
1241 'cmi.completion_status',
1242 'cmi.success_status',
1243 'cmi.core.score.raw',
1244 'cmi.score.raw'
1247 array($scorm->id, $userid)
1250 if (!$tracks) {
1251 return completion_info::aggregate_completion_states($type, $result, false);
1255 // Check for status.
1256 if ($scorm->completionstatusrequired !== null) {
1258 // Get status.
1259 $statuses = array_flip(scorm_status_options());
1260 $nstatus = 0;
1261 // Check any track for these values.
1262 $scostatus = array();
1263 foreach ($tracks as $track) {
1264 if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1265 continue;
1267 if (array_key_exists($track->value, $statuses)) {
1268 $scostatus[$track->scoid] = true;
1269 $nstatus |= $statuses[$track->value];
1273 if (!empty($scorm->completionstatusallscos)) {
1274 // Iterate over all scos and make sure each has a lesson_status.
1275 $scos = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id, 'scormtype' => 'sco'));
1276 foreach ($scos as $sco) {
1277 if (empty($scostatus[$sco->id])) {
1278 return completion_info::aggregate_completion_states($type, $result, false);
1281 return completion_info::aggregate_completion_states($type, $result, true);
1282 } else if ($scorm->completionstatusrequired & $nstatus) {
1283 return completion_info::aggregate_completion_states($type, $result, true);
1284 } else {
1285 return completion_info::aggregate_completion_states($type, $result, false);
1289 // Check for score.
1290 if ($scorm->completionscorerequired !== null) {
1291 $maxscore = -1;
1293 foreach ($tracks as $track) {
1294 if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1295 continue;
1298 if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1299 $maxscore = floatval($track->value);
1303 if ($scorm->completionscorerequired <= $maxscore) {
1304 return completion_info::aggregate_completion_states($type, $result, true);
1305 } else {
1306 return completion_info::aggregate_completion_states($type, $result, false);
1310 return $result;
1314 * Register the ability to handle drag and drop file uploads
1315 * @return array containing details of the files / types the mod can handle
1317 function scorm_dndupload_register() {
1318 return array('files' => array(
1319 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1324 * Handle a file that has been uploaded
1325 * @param object $uploadinfo details of the file / content that has been uploaded
1326 * @return int instance id of the newly created mod
1328 function scorm_dndupload_handle($uploadinfo) {
1330 $context = context_module::instance($uploadinfo->coursemodule);
1331 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1332 $fs = get_file_storage();
1333 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1334 $file = reset($files);
1336 // Validate the file, make sure it's a valid SCORM package!
1337 $errors = scorm_validate_package($file);
1338 if (!empty($errors)) {
1339 return false;
1341 // Create a default scorm object to pass to scorm_add_instance()!
1342 $scorm = get_config('scorm');
1343 $scorm->course = $uploadinfo->course->id;
1344 $scorm->coursemodule = $uploadinfo->coursemodule;
1345 $scorm->cmidnumber = '';
1346 $scorm->name = $uploadinfo->displayname;
1347 $scorm->scormtype = SCORM_TYPE_LOCAL;
1348 $scorm->reference = $file->get_filename();
1349 $scorm->intro = '';
1350 $scorm->width = $scorm->framewidth;
1351 $scorm->height = $scorm->frameheight;
1353 return scorm_add_instance($scorm, null);
1357 * Sets activity completion state
1359 * @param object $scorm object
1360 * @param int $userid User ID
1361 * @param int $completionstate Completion state
1362 * @param array $grades grades array of users with grades - used when $userid = 0
1364 function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1365 $course = new stdClass();
1366 $course->id = $scorm->course;
1367 $completion = new completion_info($course);
1369 // Check if completion is enabled site-wide, or for the course.
1370 if (!$completion->is_enabled()) {
1371 return;
1374 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1375 if (empty($cm) || !$completion->is_enabled($cm)) {
1376 return;
1379 if (empty($userid)) { // We need to get all the relevant users from $grades param.
1380 foreach ($grades as $grade) {
1381 $completion->update_state($cm, $completionstate, $grade->userid);
1383 } else {
1384 $completion->update_state($cm, $completionstate, $userid);
1389 * Check that a Zip file contains a valid SCORM package
1391 * @param $file stored_file a Zip file.
1392 * @return array empty if no issue is found. Array of error message otherwise
1394 function scorm_validate_package($file) {
1395 $packer = get_file_packer('application/zip');
1396 $errors = array();
1397 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1398 $file->import_external_file_contents();
1400 $filelist = $file->list_files($packer);
1402 if (!is_array($filelist)) {
1403 $errors['packagefile'] = get_string('badarchive', 'scorm');
1404 } else {
1405 $aiccfound = false;
1406 $badmanifestpresent = false;
1407 foreach ($filelist as $info) {
1408 if ($info->pathname == 'imsmanifest.xml') {
1409 return array();
1410 } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1411 // This package has an imsmanifest file inside a folder of the package.
1412 $badmanifestpresent = true;
1414 if (preg_match('/\.cst$/', $info->pathname)) {
1415 return array();
1418 if (!$aiccfound) {
1419 if ($badmanifestpresent) {
1420 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1421 } else {
1422 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1426 return $errors;
1430 * Check and set the correct mode and attempt when entering a SCORM package.
1432 * @param object $scorm object
1433 * @param string $newattempt should a new attempt be generated here.
1434 * @param int $attempt the attempt number this is for.
1435 * @param int $userid the userid of the user.
1436 * @param string $mode the current mode that has been selected.
1438 function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1439 global $DB;
1441 if (($mode == 'browse')) {
1442 if ($scorm->hidebrowse == 1) {
1443 // Prevent Browse mode if hidebrowse is set.
1444 $mode = 'normal';
1445 } else {
1446 // We don't need to check attempts as browse mode is set.
1447 return;
1450 // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1451 $incomplete = true;
1452 $sql = "SELECT sc.id, t.value
1453 FROM {scorm_scoes} sc
1454 LEFT JOIN {scorm_scoes_track} t ON sc.scorm = t.scormid AND sc.id = t.scoid
1455 AND t.element = 'cmi.core.lesson_status' AND t.userid = ? AND t.attempt = ?
1456 WHERE sc.scormtype = 'sco' AND sc.scorm = ?";
1457 $tracks = $DB->get_recordset_sql($sql, array($userid, $attempt, $scorm->id));
1459 foreach ($tracks as $track) {
1460 if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1461 $incomplete = false;
1462 } else {
1463 $incomplete = true;
1464 break; // Found an incomplete sco, so the result as a whole is incomplete.
1467 $tracks->close();
1469 // Validate user request to start a new attempt.
1470 if ($incomplete === true) {
1471 // The option to start a new attempt should never have been presented. Force false.
1472 $newattempt = 'off';
1473 } else if (!empty($scorm->forcenewattempt)) {
1474 // A new attempt should be forced for already completed attempts.
1475 $newattempt = 'on';
1478 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1479 $attempt++;
1480 $mode = 'normal';
1481 } else { // Check if review mode should be set.
1482 if ($incomplete === true) {
1483 $mode = 'normal';
1484 } else {
1485 $mode = 'review';
1491 * Trigger the course_module_viewed event.
1493 * @param stdClass $scorm scorm object
1494 * @param stdClass $course course object
1495 * @param stdClass $cm course module object
1496 * @param stdClass $context context object
1497 * @since Moodle 3.0
1499 function scorm_view($scorm, $course, $cm, $context) {
1501 // Trigger course_module_viewed event.
1502 $params = array(
1503 'context' => $context,
1504 'objectid' => $scorm->id
1507 $event = \mod_scorm\event\course_module_viewed::create($params);
1508 $event->add_record_snapshot('course_modules', $cm);
1509 $event->add_record_snapshot('course', $course);
1510 $event->add_record_snapshot('scorm', $scorm);
1511 $event->trigger();
1515 * Check if the module has any update that affects the current user since a given time.
1517 * @param cm_info $cm course module data
1518 * @param int $from the time to check updates from
1519 * @param array $filter if we need to check only specific updates
1520 * @return stdClass an object with the different type of areas indicating if they were updated or not
1521 * @since Moodle 3.2
1523 function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1524 global $DB, $USER, $CFG;
1525 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1527 $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1528 $updates = new stdClass();
1529 list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1530 if (!$available) {
1531 return $updates;
1533 $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1535 $updates->tracks = (object) array('updated' => false);
1536 $select = 'scormid = ? AND userid = ? AND timemodified > ?';
1537 $params = array($scorm->id, $USER->id, $from);
1538 $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1539 if (!empty($tracks)) {
1540 $updates->tracks->updated = true;
1541 $updates->tracks->itemids = array_keys($tracks);
1544 // Now, teachers should see other students updates.
1545 if (has_capability('mod/scorm:viewreport', $cm->context)) {
1546 $select = 'scormid = ? AND timemodified > ?';
1547 $params = array($scorm->id, $from);
1549 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1550 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1551 if (empty($groupusers)) {
1552 return $updates;
1554 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1555 $select .= ' AND userid ' . $insql;
1556 $params = array_merge($params, $inparams);
1559 $updates->usertracks = (object) array('updated' => false);
1560 $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1561 if (!empty($tracks)) {
1562 $updates->usertracks->updated = true;
1563 $updates->usertracks->itemids = array_keys($tracks);
1566 return $updates;
1570 * Get icon mapping for font-awesome.
1572 function mod_scorm_get_fontawesome_icon_map() {
1573 return [
1574 'mod_scorm:assetc' => 'fa-file-archive-o',
1575 'mod_scorm:asset' => 'fa-file-archive-o',
1576 'mod_scorm:browsed' => 'fa-book',
1577 'mod_scorm:completed' => 'fa-check-square-o',
1578 'mod_scorm:failed' => 'fa-times',
1579 'mod_scorm:incomplete' => 'fa-pencil-square-o',
1580 'mod_scorm:minus' => 'fa-minus',
1581 'mod_scorm:notattempted' => 'fa-square-o',
1582 'mod_scorm:passed' => 'fa-check',
1583 'mod_scorm:plus' => 'fa-plus',
1584 'mod_scorm:popdown' => 'fa-window-close-o',
1585 'mod_scorm:popup' => 'fa-window-restore',
1586 'mod_scorm:suspend' => 'fa-pause',
1587 'mod_scorm:wait' => 'fa-clock-o',
1592 * This standard function will check all instances of this module
1593 * and make sure there are up-to-date events created for each of them.
1594 * If courseid = 0, then every scorm event in the site is checked, else
1595 * only scorm events belonging to the course specified are checked.
1597 * @param int $courseid
1598 * @param int|stdClass $instance scorm module instance or ID.
1599 * @param int|stdClass $cm Course module object or ID.
1600 * @return bool
1602 function scorm_refresh_events($courseid = 0, $instance = null, $cm = null) {
1603 global $CFG, $DB;
1605 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1607 // If we have instance information then we can just update the one event instead of updating all events.
1608 if (isset($instance)) {
1609 if (!is_object($instance)) {
1610 $instance = $DB->get_record('scorm', array('id' => $instance), '*', MUST_EXIST);
1612 if (isset($cm)) {
1613 if (!is_object($cm)) {
1614 $cm = (object)array('id' => $cm);
1616 } else {
1617 $cm = get_coursemodule_from_instance('scorm', $instance->id);
1619 scorm_update_calendar($instance, $cm->id);
1620 return true;
1623 if ($courseid) {
1624 // Make sure that the course id is numeric.
1625 if (!is_numeric($courseid)) {
1626 return false;
1628 if (!$scorms = $DB->get_records('scorm', array('course' => $courseid))) {
1629 return false;
1631 } else {
1632 if (!$scorms = $DB->get_records('scorm')) {
1633 return false;
1637 foreach ($scorms as $scorm) {
1638 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1639 scorm_update_calendar($scorm, $cm->id);
1642 return true;
1646 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1648 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1649 * is not displayed on the block.
1651 * @param calendar_event $event
1652 * @param \core_calendar\action_factory $factory
1653 * @return \core_calendar\local\event\entities\action_interface|null
1655 function mod_scorm_core_calendar_provide_event_action(calendar_event $event,
1656 \core_calendar\action_factory $factory) {
1657 global $CFG;
1659 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1661 $cm = get_fast_modinfo($event->courseid)->instances['scorm'][$event->instance];
1663 if (has_capability('mod/scorm:viewreport', $cm->context)) {
1664 // Teachers do not need to be reminded to complete a scorm.
1665 return null;
1668 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
1669 // The scorm has closed so the user can no longer submit anything.
1670 return null;
1673 // Restore scorm object from cached values in $cm, we only need id, timeclose and timeopen.
1674 $customdata = $cm->customdata ?: [];
1675 $customdata['id'] = $cm->instance;
1676 $scorm = (object)($customdata + ['timeclose' => 0, 'timeopen' => 0]);
1678 // Check that the SCORM activity is open.
1679 list($actionable, $warnings) = scorm_get_availability_status($scorm);
1681 return $factory->create_instance(
1682 get_string('enter', 'scorm'),
1683 new \moodle_url('/mod/scorm/view.php', array('id' => $cm->id)),
1685 $actionable
1690 * Add a get_coursemodule_info function in case any SCORM type wants to add 'extra' information
1691 * for the course (see resource).
1693 * Given a course_module object, this function returns any "extra" information that may be needed
1694 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1696 * @param stdClass $coursemodule The coursemodule object (record).
1697 * @return cached_cm_info An object on information that the courses
1698 * will know about (most noticeably, an icon).
1700 function scorm_get_coursemodule_info($coursemodule) {
1701 global $DB;
1703 $dbparams = ['id' => $coursemodule->instance];
1704 $fields = 'id, name, intro, introformat, completionstatusrequired, completionscorerequired, completionstatusallscos, '.
1705 'timeopen, timeclose';
1706 if (!$scorm = $DB->get_record('scorm', $dbparams, $fields)) {
1707 return false;
1710 $result = new cached_cm_info();
1711 $result->name = $scorm->name;
1713 if ($coursemodule->showdescription) {
1714 // Convert intro to html. Do not filter cached version, filters run at display time.
1715 $result->content = format_module_intro('scorm', $scorm, $coursemodule->id, false);
1718 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1719 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1720 $result->customdata['customcompletionrules']['completionstatusrequired'] = $scorm->completionstatusrequired;
1721 $result->customdata['customcompletionrules']['completionscorerequired'] = $scorm->completionscorerequired;
1722 $result->customdata['customcompletionrules']['completionstatusallscos'] = $scorm->completionstatusallscos;
1724 // Populate some other values that can be used in calendar or on dashboard.
1725 if ($scorm->timeopen) {
1726 $result->customdata['timeopen'] = $scorm->timeopen;
1728 if ($scorm->timeclose) {
1729 $result->customdata['timeclose'] = $scorm->timeclose;
1732 return $result;
1736 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1738 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1739 * @return array $descriptions the array of descriptions for the custom rules.
1741 function mod_scorm_get_completion_active_rule_descriptions($cm) {
1742 // Values will be present in cm_info, and we assume these are up to date.
1743 if (empty($cm->customdata['customcompletionrules'])
1744 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1745 return [];
1748 $descriptions = [];
1749 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1750 switch ($key) {
1751 case 'completionstatusrequired':
1752 if (is_null($val)) {
1753 continue;
1755 // Determine the selected statuses using a bitwise operation.
1756 $cvalues = array();
1757 foreach (scorm_status_options(true) as $bit => $string) {
1758 if (($val & $bit) == $bit) {
1759 $cvalues[] = $string;
1762 $statusstring = implode(', ', $cvalues);
1763 $descriptions[] = get_string('completionstatusrequireddesc', 'scorm', $statusstring);
1764 break;
1765 case 'completionscorerequired':
1766 if (is_null($val)) {
1767 continue;
1769 $descriptions[] = get_string('completionscorerequireddesc', 'scorm', $val);
1770 break;
1771 case 'completionstatusallscos':
1772 if (empty($val)) {
1773 continue;
1775 $descriptions[] = get_string('completionstatusallscos', 'scorm');
1776 break;
1777 default:
1778 break;
1781 return $descriptions;