2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Library of internal classes and functions for module SCORM
21 * @copyright 1999 onwards Roberto Pinna
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once("$CFG->dirroot/mod/scorm/lib.php");
26 require_once("$CFG->libdir/filelib.php");
28 // Constants and settings for module scorm.
29 define('SCORM_UPDATE_NEVER', '0');
30 define('SCORM_UPDATE_EVERYDAY', '2');
31 define('SCORM_UPDATE_EVERYTIME', '3');
33 define('SCORM_SKIPVIEW_NEVER', '0');
34 define('SCORM_SKIPVIEW_FIRST', '1');
35 define('SCORM_SKIPVIEW_ALWAYS', '2');
38 define('SCO_DATA', 1);
39 define('SCO_ONLY', 2);
41 define('GRADESCOES', '0');
42 define('GRADEHIGHEST', '1');
43 define('GRADEAVERAGE', '2');
44 define('GRADESUM', '3');
46 define('HIGHESTATTEMPT', '0');
47 define('AVERAGEATTEMPT', '1');
48 define('FIRSTATTEMPT', '2');
49 define('LASTATTEMPT', '3');
51 define('TOCJSLINK', 1);
52 define('TOCFULLURL', 2);
54 // Local Library of functions for module scorm.
58 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 class scorm_package_file_info
extends file_info_stored
{
62 public function get_parent() {
63 if ($this->lf
->get_filepath() === '/' and $this->lf
->get_filename() === '.') {
64 return $this->browser
->get_file_info($this->context
);
66 return parent
::get_parent();
68 public function get_visible_name() {
69 if ($this->lf
->get_filepath() === '/' and $this->lf
->get_filename() === '.') {
70 return $this->topvisiblename
;
72 return parent
::get_visible_name();
77 * Returns an array of the popup options for SCORM and each options default value
79 * @return array an array of popup options as the key and their defaults as the value
81 function scorm_get_popup_options_array() {
82 $cfgscorm = get_config('scorm');
84 return array('scrollbars' => isset($cfgscorm->scrollbars
) ?
$cfgscorm->scrollbars
: 0,
85 'directories' => isset($cfgscorm->directories
) ?
$cfgscorm->directories
: 0,
86 'location' => isset($cfgscorm->location
) ?
$cfgscorm->location
: 0,
87 'menubar' => isset($cfgscorm->menubar
) ?
$cfgscorm->menubar
: 0,
88 'toolbar' => isset($cfgscorm->toolbar
) ?
$cfgscorm->toolbar
: 0,
89 'status' => isset($cfgscorm->status
) ?
$cfgscorm->status
: 0);
93 * Returns an array of the array of what grade options
95 * @return array an array of what grade options
97 function scorm_get_grade_method_array() {
98 return array (GRADESCOES
=> get_string('gradescoes', 'scorm'),
99 GRADEHIGHEST
=> get_string('gradehighest', 'scorm'),
100 GRADEAVERAGE
=> get_string('gradeaverage', 'scorm'),
101 GRADESUM
=> get_string('gradesum', 'scorm'));
105 * Returns an array of the array of what grade options
107 * @return array an array of what grade options
109 function scorm_get_what_grade_array() {
110 return array (HIGHESTATTEMPT
=> get_string('highestattempt', 'scorm'),
111 AVERAGEATTEMPT
=> get_string('averageattempt', 'scorm'),
112 FIRSTATTEMPT
=> get_string('firstattempt', 'scorm'),
113 LASTATTEMPT
=> get_string('lastattempt', 'scorm'));
117 * Returns an array of the array of skip view options
119 * @return array an array of skip view options
121 function scorm_get_skip_view_array() {
122 return array(SCORM_SKIPVIEW_NEVER
=> get_string('never'),
123 SCORM_SKIPVIEW_FIRST
=> get_string('firstaccess', 'scorm'),
124 SCORM_SKIPVIEW_ALWAYS
=> get_string('always'));
128 * Returns an array of the array of hide table of contents options
130 * @return array an array of hide table of contents options
132 function scorm_get_hidetoc_array() {
133 return array(SCORM_TOC_SIDE
=> get_string('sided', 'scorm'),
134 SCORM_TOC_HIDDEN
=> get_string('hidden', 'scorm'),
135 SCORM_TOC_POPUP
=> get_string('popupmenu', 'scorm'),
136 SCORM_TOC_DISABLED
=> get_string('disabled', 'scorm'));
140 * Returns an array of the array of update frequency options
142 * @return array an array of update frequency options
144 function scorm_get_updatefreq_array() {
145 return array(SCORM_UPDATE_NEVER
=> get_string('never'),
146 SCORM_UPDATE_EVERYDAY
=> get_string('everyday', 'scorm'),
147 SCORM_UPDATE_EVERYTIME
=> get_string('everytime', 'scorm'));
151 * Returns an array of the array of popup display options
153 * @return array an array of popup display options
155 function scorm_get_popup_display_array() {
156 return array(0 => get_string('currentwindow', 'scorm'),
157 1 => get_string('popup', 'scorm'));
161 * Returns an array of the array of navigation buttons display options
163 * @return array an array of navigation buttons display options
165 function scorm_get_navigation_display_array() {
166 return array(SCORM_NAV_DISABLED
=> get_string('no'),
167 SCORM_NAV_UNDER_CONTENT
=> get_string('undercontent', 'scorm'),
168 SCORM_NAV_FLOATING
=> get_string('floating', 'scorm'));
172 * Returns an array of the array of attempt options
174 * @return array an array of attempt options
176 function scorm_get_attempts_array() {
177 $attempts = array(0 => get_string('nolimit', 'scorm'),
178 1 => get_string('attempt1', 'scorm'));
180 for ($i = 2; $i <= 6; $i++
) {
181 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
188 * Returns an array of the attempt status options
190 * @return array an array of attempt status options
192 function scorm_get_attemptstatus_array() {
193 return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO
=> get_string('no'),
194 SCORM_DISPLAY_ATTEMPTSTATUS_ALL
=> get_string('attemptstatusall', 'scorm'),
195 SCORM_DISPLAY_ATTEMPTSTATUS_MY
=> get_string('attemptstatusmy', 'scorm'),
196 SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY
=> get_string('attemptstatusentry', 'scorm'));
200 * Extracts scrom package, sets up all variables.
201 * Called whenever scorm changes
202 * @param object $scorm instance - fields are updated and changes saved into database
203 * @param bool $full force full update if true
206 function scorm_parse($scorm, $full) {
208 $cfgscorm = get_config('scorm');
210 if (!isset($scorm->cmid
)) {
211 $cm = get_coursemodule_from_instance('scorm', $scorm->id
);
212 $scorm->cmid
= $cm->id
;
214 $context = context_module
::instance($scorm->cmid
);
215 $newhash = $scorm->sha1hash
;
217 if ($scorm->scormtype
=== SCORM_TYPE_LOCAL
or $scorm->scormtype
=== SCORM_TYPE_LOCALSYNC
) {
219 $fs = get_file_storage();
220 $packagefile = false;
221 $packagefileimsmanifest = false;
223 if ($scorm->scormtype
=== SCORM_TYPE_LOCAL
) {
224 if ($packagefile = $fs->get_file($context->id
, 'mod_scorm', 'package', 0, '/', $scorm->reference
)) {
225 if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
226 $packagefile->import_external_file_contents();
228 $newhash = $packagefile->get_contenthash();
229 if (strtolower($packagefile->get_filename()) == 'imsmanifest.xml') {
230 $packagefileimsmanifest = true;
236 if (!$cfgscorm->allowtypelocalsync
) {
237 // Sorry - localsync disabled.
240 if ($scorm->reference
!== '' and (!$full or $scorm->sha1hash
!== sha1($scorm->reference
))) {
241 $fs->delete_area_files($context->id
, 'mod_scorm', 'package');
242 $filerecord = array('contextid' => $context->id
, 'component' => 'mod_scorm', 'filearea' => 'package',
243 'itemid' => 0, 'filepath' => '/');
244 if ($packagefile = $fs->create_file_from_url($filerecord, $scorm->reference
, array('calctimeout' => true))) {
245 $newhash = sha1($scorm->reference
);
253 if (!$full and $packagefile and $scorm->sha1hash
=== $newhash) {
254 if (strpos($scorm->version
, 'SCORM') !== false) {
255 if ($packagefileimsmanifest ||
$fs->get_file($context->id
, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
256 // No need to update.
259 } else if (strpos($scorm->version
, 'AICC') !== false) {
260 // TODO: add more sanity checks - something really exists in scorm_content area.
264 if (!$packagefileimsmanifest) {
265 // Now extract files.
266 $fs->delete_area_files($context->id
, 'mod_scorm', 'content');
268 $packer = get_file_packer('application/zip');
269 $packagefile->extract_to_storage($packer, $context->id
, 'mod_scorm', 'content', 0, '/');
275 if ($packagefileimsmanifest) {
276 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
277 // Direct link to imsmanifest.xml file.
278 if (!scorm_parse_scorm($scorm, $packagefile)) {
279 $scorm->version
= 'ERROR';
282 } else if ($manifest = $fs->get_file($context->id
, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
283 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
285 if (!scorm_parse_scorm($scorm, $manifest)) {
286 $scorm->version
= 'ERROR';
289 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
291 $result = scorm_parse_aicc($scorm);
293 $scorm->version
= 'ERROR';
295 $scorm->version
= 'AICC';
299 } else if ($scorm->scormtype
=== SCORM_TYPE_EXTERNAL
and $cfgscorm->allowtypeexternal
) {
300 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
301 // SCORM only, AICC can not be external.
302 if (!scorm_parse_scorm($scorm, $scorm->reference
)) {
303 $scorm->version
= 'ERROR';
305 $newhash = sha1($scorm->reference
);
307 } else if ($scorm->scormtype
=== SCORM_TYPE_AICCURL
and $cfgscorm->allowtypeexternalaicc
) {
308 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
310 $result = scorm_parse_aicc($scorm);
312 $scorm->version
= 'ERROR';
314 $scorm->version
= 'AICC';
318 // Sorry, disabled type.
323 $scorm->sha1hash
= $newhash;
324 $DB->update_record('scorm', $scorm);
328 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
329 if (!empty($haystacks)) {
330 foreach ($haystacks as $key => $element) {
332 if ($element->{$item} === $needle) {
336 if ($element->{$item} == $needle) {
345 function scorm_repeater($what, $times) {
350 for ($i = 0; $i < $times; $i++
) {
356 function scorm_external_link($link) {
357 // Check if a link is external.
359 $link = strtolower($link);
360 if (substr($link, 0, 7) == 'http://') {
362 } else if (substr($link, 0, 8) == 'https://') {
364 } else if (substr($link, 0, 4) == 'www.') {
371 * Returns an object containing all datas relative to the given sco ID
373 * @param integer $id The sco ID
374 * @return mixed (false if sco id does not exists)
376 function scorm_get_sco($id, $what=SCO_ALL
) {
379 if ($sco = $DB->get_record('scorm_scoes', array('id' => $id))) {
380 $sco = ($what == SCO_DATA
) ?
new stdClass() : $sco;
381 if (($what != SCO_ONLY
) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id)))) {
382 foreach ($scodatas as $scodata) {
383 $sco->{$scodata->name
} = $scodata->value
;
385 } else if (($what != SCO_ONLY
) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id))))) {
386 $sco->parameters
= '';
395 * Returns an object (array) containing all the scoes data related to the given sco ID
397 * @param integer $id The sco ID
398 * @param integer $organisation an organisation ID - defaults to false if not required
399 * @return mixed (false if there are no scoes or an array)
401 function scorm_get_scoes($id, $organisation=false) {
404 $queryarray = array('scorm' => $id);
405 if (!empty($organisation)) {
406 $queryarray['organization'] = $organisation;
408 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
409 // Drop keys so that it is a simple array as expected.
410 $scoes = array_values($scoes);
411 foreach ($scoes as $sco) {
412 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $sco->id
))) {
413 foreach ($scodatas as $scodata) {
414 $sco->{$scodata->name
} = $scodata->value
;
424 function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false, $trackdata = null) {
429 if ($forcecompleted) {
430 // TODO - this could be broadened to encompass SCORM 2004 in future.
431 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
432 if ($track = $DB->get_record_select('scorm_scoes_track',
433 'userid=? AND scormid=? AND scoid=? AND attempt=? '.
434 'AND element=\'cmi.core.score.raw\'',
435 array($userid, $scormid, $scoid, $attempt))) {
436 $value = 'completed';
439 if ($element == 'cmi.core.score.raw') {
440 if ($tracktest = $DB->get_record_select('scorm_scoes_track',
441 'userid=? AND scormid=? AND scoid=? AND attempt=? '.
442 'AND element=\'cmi.core.lesson_status\'',
443 array($userid, $scormid, $scoid, $attempt))) {
444 if ($tracktest->value
== "incomplete") {
445 $tracktest->value
= "completed";
446 $DB->update_record('scorm_scoes_track', $tracktest);
450 if (($element == 'cmi.success_status') && ($value == 'passed' ||
$value == 'failed')) {
451 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
452 $objectiveprogressstatus = true;
453 $objectivesatisfiedstatus = false;
454 if ($value == 'passed') {
455 $objectivesatisfiedstatus = true;
458 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
459 'scormid' => $scormid,
461 'attempt' => $attempt,
462 'element' => 'objectiveprogressstatus'))) {
463 $track->value
= $objectiveprogressstatus;
464 $track->timemodified
= time();
465 $DB->update_record('scorm_scoes_track', $track);
468 $track = new stdClass();
469 $track->userid
= $userid;
470 $track->scormid
= $scormid;
471 $track->scoid
= $scoid;
472 $track->attempt
= $attempt;
473 $track->element
= 'objectiveprogressstatus';
474 $track->value
= $objectiveprogressstatus;
475 $track->timemodified
= time();
476 $id = $DB->insert_record('scorm_scoes_track', $track);
478 if ($objectivesatisfiedstatus) {
479 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
480 'scormid' => $scormid,
482 'attempt' => $attempt,
483 'element' => 'objectivesatisfiedstatus'))) {
484 $track->value
= $objectivesatisfiedstatus;
485 $track->timemodified
= time();
486 $DB->update_record('scorm_scoes_track', $track);
489 $track = new stdClass();
490 $track->userid
= $userid;
491 $track->scormid
= $scormid;
492 $track->scoid
= $scoid;
493 $track->attempt
= $attempt;
494 $track->element
= 'objectivesatisfiedstatus';
495 $track->value
= $objectivesatisfiedstatus;
496 $track->timemodified
= time();
497 $id = $DB->insert_record('scorm_scoes_track', $track);
506 if ($trackdata !== null) {
507 if (isset($trackdata[$element])) {
508 $track = $trackdata[$element];
511 $track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
512 'scormid' => $scormid,
514 'attempt' => $attempt,
515 'element' => $element));
518 if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
519 if ($track->value
!= $value) {
520 $track->value
= $value;
521 $track->timemodified
= time();
522 $DB->update_record('scorm_scoes_track', $track);
527 $track = new stdClass();
528 $track->userid
= $userid;
529 $track->scormid
= $scormid;
530 $track->scoid
= $scoid;
531 $track->attempt
= $attempt;
532 $track->element
= $element;
533 $track->value
= $value;
534 $track->timemodified
= time();
535 $id = $DB->insert_record('scorm_scoes_track', $track);
538 if (strstr($element, '.score.raw') ||
539 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
540 && in_array($track->value
, array('completed', 'passed')))) {
541 $scorm = $DB->get_record('scorm', array('id' => $scormid));
542 include_once($CFG->dirroot
.'/mod/scorm/lib.php');
543 scorm_update_grades($scorm, $userid);
550 * simple quick function to return true/false if this user has tracks in this scorm
552 * @param integer $scormid The scorm ID
553 * @param integer $userid the users id
554 * @return boolean (false if there are no tracks)
556 function scorm_has_tracks($scormid, $userid) {
558 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
561 function scorm_get_tracks($scoid, $userid, $attempt='') {
562 // Gets all tracks of specified sco and user.
565 if (empty($attempt)) {
566 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id' => $scoid))) {
567 $attempt = scorm_get_last_attempt($scormid, $userid);
572 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid' => $userid, 'scoid' => $scoid,
573 'attempt' => $attempt), 'element ASC')) {
574 $usertrack = scorm_format_interactions($tracks);
575 $usertrack->userid
= $userid;
576 $usertrack->scoid
= $scoid;
584 * helper function to return a formatted list of interactions for reports.
586 * @param array $trackdata the records from scorm_scoes_track table
587 * @return object formatted list of interactions
589 function scorm_format_interactions($trackdata) {
590 $usertrack = new stdClass();
592 // Defined in order to unify scorm1.2 and scorm2004.
593 $usertrack->score_raw
= '';
594 $usertrack->status
= '';
595 $usertrack->total_time
= '00:00:00';
596 $usertrack->session_time
= '00:00:00';
597 $usertrack->timemodified
= 0;
599 foreach ($trackdata as $track) {
600 $element = $track->element
;
601 $usertrack->{$element} = $track->value
;
603 case 'cmi.core.lesson_status':
604 case 'cmi.completion_status':
605 if ($track->value
== 'not attempted') {
606 $track->value
= 'notattempted';
608 $usertrack->status
= $track->value
;
610 case 'cmi.core.score.raw':
611 case 'cmi.score.raw':
612 $usertrack->score_raw
= (float) sprintf('%2.2f', $track->value
);
614 case 'cmi.core.session_time':
615 case 'cmi.session_time':
616 $usertrack->session_time
= $track->value
;
618 case 'cmi.core.total_time':
619 case 'cmi.total_time':
620 $usertrack->total_time
= $track->value
;
623 if (isset($track->timemodified
) && ($track->timemodified
> $usertrack->timemodified
)) {
624 $usertrack->timemodified
= $track->timemodified
;
630 /* Find the start and finsh time for a a given SCO attempt
632 * @param int $scormid SCORM Id
633 * @param int $scoid SCO Id
634 * @param int $userid User Id
635 * @param int $attemt Attempt Id
637 * @return object start and finsh time EPOC secods
640 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
643 $timedata = new stdClass();
644 $params = array('userid' => $userid, 'scormid' => $scormid, 'attempt' => $attempt);
645 if (!empty($scoid)) {
646 $params['scoid'] = $scoid;
648 $tracks = $DB->get_records('scorm_scoes_track', $params, "timemodified ASC");
650 $tracks = array_values($tracks);
654 $timedata->start
= $tracks[0]->timemodified
;
656 $timedata->start
= false;
658 if ($tracks && $track = array_pop($tracks)) {
659 $timedata->finish
= $track->timemodified
;
661 $timedata->finish
= $timedata->start
;
666 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
668 $attemptscore = new stdClass();
669 $attemptscore->scoes
= 0;
670 $attemptscore->values
= 0;
671 $attemptscore->max
= 0;
672 $attemptscore->sum
= 0;
673 $attemptscore->lastmodify
= 0;
675 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id
), 'sortorder, id')) {
679 foreach ($scoes as $sco) {
680 if ($userdata = scorm_get_tracks($sco->id
, $userid, $attempt)) {
681 if (($userdata->status
== 'completed') ||
($userdata->status
== 'passed')) {
682 $attemptscore->scoes++
;
684 if (!empty($userdata->score_raw
) ||
(isset($scorm->type
) && $scorm->type
== 'sco' && isset($userdata->score_raw
))) {
685 $attemptscore->values++
;
686 $attemptscore->sum +
= $userdata->score_raw
;
687 $attemptscore->max
= ($userdata->score_raw
> $attemptscore->max
) ?
$userdata->score_raw
: $attemptscore->max
;
688 if (isset($userdata->timemodified
) && ($userdata->timemodified
> $attemptscore->lastmodify
)) {
689 $attemptscore->lastmodify
= $userdata->timemodified
;
691 $attemptscore->lastmodify
= 0;
696 switch ($scorm->grademethod
) {
698 $score = (float) $attemptscore->max
;
701 if ($attemptscore->values
> 0) {
702 $score = $attemptscore->sum
/ $attemptscore->values
;
708 $score = $attemptscore->sum
;
711 $score = $attemptscore->scoes
;
714 $score = $attemptscore->max
; // Remote Learner GRADEHIGHEST is default.
720 function scorm_grade_user($scorm, $userid) {
722 // Ensure we dont grade user beyond $scorm->maxattempt settings.
723 $lastattempt = scorm_get_last_attempt($scorm->id
, $userid);
724 if ($scorm->maxattempt
!= 0 && $lastattempt >= $scorm->maxattempt
) {
725 $lastattempt = $scorm->maxattempt
;
728 switch ($scorm->whatgrade
) {
730 return scorm_grade_user_attempt($scorm, $userid, 1);
733 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id
, $userid));
737 for ($attempt = 1; $attempt <= $lastattempt; $attempt++
) {
738 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
739 $maxscore = $attemptscore > $maxscore ?
$attemptscore : $maxscore;
745 $attemptcount = scorm_get_attempt_count($userid, $scorm, true, true);
746 if (empty($attemptcount)) {
749 $attemptcount = count($attemptcount);
751 $lastattempt = scorm_get_last_attempt($scorm->id
, $userid);
753 for ($attempt = 1; $attempt <= $lastattempt; $attempt++
) {
754 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
755 $sumscore +
= $attemptscore;
758 return round($sumscore / $attemptcount);
763 function scorm_count_launchable($scormid, $organization='') {
766 $sqlorganization = '';
767 $params = array($scormid);
768 if (!empty($organization)) {
769 $sqlorganization = " AND organization=?";
770 $params[] = $organization;
772 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".
773 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
778 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
780 * @param int $scormid the id of the scorm.
781 * @param int $userid the id of the user.
783 * @return int The attempt number to use.
785 function scorm_get_last_attempt($scormid, $userid) {
788 // Find the last attempt number for the given user id and scorm id.
789 $sql = "SELECT MAX(attempt)
790 FROM {scorm_scoes_track}
791 WHERE userid = ? AND scormid = ?";
792 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
793 if (empty($lastattempt)) {
801 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
803 * @param int $scormid the id of the scorm.
804 * @param int $userid the id of the user.
806 * @return int The attempt number to use.
808 function scorm_get_last_completed_attempt($scormid, $userid) {
811 // Find the last completed attempt number for the given user id and scorm id.
812 $sql = "SELECT MAX(attempt)
813 FROM {scorm_scoes_track}
814 WHERE userid = ? AND scormid = ?
815 AND (value='completed' OR value='passed')";
816 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
817 if (empty($lastattempt)) {
825 * Returns the full list of attempts a user has made.
827 * @param int $scormid the id of the scorm.
828 * @param int $userid the id of the user.
830 * @return array array of attemptids
832 function scorm_get_all_attempts($scormid, $userid) {
834 $attemptids = array();
835 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
836 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
837 foreach ($attempts as $attempt) {
838 $attemptids[] = $attempt->attempt
;
844 * Displays the entry form and toc if required.
846 * @param stdClass $user user object
847 * @param stdClass $scorm scorm object
848 * @param string $action base URL for the organizations select box
849 * @param stdClass $cm course module object
851 function scorm_print_launch ($user, $scorm, $action, $cm) {
852 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
854 if ($scorm->updatefreq
== SCORM_UPDATE_EVERYTIME
) {
855 scorm_parse($scorm, false);
858 $organization = optional_param('organization', '', PARAM_INT
);
860 if ($scorm->displaycoursestructure
== 1) {
861 echo $OUTPUT->box_start('generalbox boxaligncenter toc', 'toc');
862 echo html_writer
::div(get_string('contents', 'scorm'), 'structurehead');
864 if (empty($organization)) {
865 $organization = $scorm->launch
;
867 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
868 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
869 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
870 array($scorm->id
), 'sortorder, id', 'id,title')) {
871 if (count($orgs) > 1) {
872 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
873 $select->label
= get_string('organizations', 'scorm');
874 $select->class = 'scorm-center';
875 echo $OUTPUT->render($select);
879 if ($sco = scorm_get_sco($organization, SCO_ONLY
)) {
880 if (($sco->organization
== '') && ($sco->launch
== '')) {
881 $orgidentifier = $sco->identifier
;
883 $orgidentifier = $sco->organization
;
887 $scorm->version
= strtolower(clean_param($scorm->version
, PARAM_SAFEDIR
)); // Just to be safe.
888 if (!file_exists($CFG->dirroot
.'/mod/scorm/datamodels/'.$scorm->version
.'lib.php')) {
889 $scorm->version
= 'scorm_12';
891 require_once($CFG->dirroot
.'/mod/scorm/datamodels/'.$scorm->version
.'lib.php');
893 $result = scorm_get_toc($user, $scorm, $cm->id
, TOCFULLURL
, $orgidentifier);
894 $incomplete = $result->incomplete
;
896 // Do we want the TOC to be displayed?
897 if ($scorm->displaycoursestructure
== 1) {
899 echo $OUTPUT->box_end();
902 // Is this the first attempt ?
903 $attemptcount = scorm_get_attempt_count($user->id
, $scorm);
905 // Do not give the player launch FORM if the SCORM object is locked after the final attempt.
906 if ($scorm->lastattemptlock
== 0 ||
$result->attemptleft
> 0) {
907 echo html_writer
::start_div('scorm-center');
908 echo html_writer
::start_tag('form', array('id' => 'scormviewform',
910 'action' => $CFG->wwwroot
.'/mod/scorm/player.php'));
911 if ($scorm->hidebrowse
== 0) {
912 print_string('mode', 'scorm');
913 echo ': '.html_writer
::empty_tag('input', array('type' => 'radio', 'id' => 'b', 'name' => 'mode', 'value' => 'browse')).
914 html_writer
::label(get_string('browse', 'scorm'), 'b');
915 echo html_writer
::empty_tag('input', array('type' => 'radio',
916 'id' => 'n', 'name' => 'mode',
917 'value' => 'normal', 'checked' => 'checked')).
918 html_writer
::label(get_string('normal', 'scorm'), 'n');
921 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'mode', 'value' => 'normal'));
923 if ($scorm->forcenewattempt
== 1) {
924 if ($incomplete === false) {
925 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'newattempt', 'value' => 'on'));
927 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft
> 0)||
($scorm->maxattempt
== 0))) {
928 echo html_writer
::empty_tag('br');
929 echo html_writer
::checkbox('newattempt', 'on', false, '', array('id' => 'a'));
930 echo html_writer
::label(get_string('newattempt', 'scorm'), 'a');
932 if (!empty($scorm->popup
)) {
933 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'display', 'value' => 'popup'));
936 echo html_writer
::empty_tag('br');
937 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'scoid', 'value' => $scorm->launch
));
938 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'cm', 'value' => $cm->id
));
939 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'currentorg', 'value' => $orgidentifier));
940 echo html_writer
::empty_tag('input', array('type' => 'submit', 'value' => get_string('enter', 'scorm')));
941 echo html_writer
::end_tag('form');
942 echo html_writer
::end_div();
946 function scorm_simple_play($scorm, $user, $context, $cmid) {
951 if (has_capability('mod/scorm:viewreport', $context)) {
952 // If this user can view reports, don't skipview so they can see links to reports.
956 if ($scorm->updatefreq
== SCORM_UPDATE_EVERYTIME
) {
957 scorm_parse($scorm, false);
959 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
960 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id
), 'sortorder, id', 'id');
964 if ($sco = scorm_get_sco($scorm->launch
, SCO_ONLY
)) {
965 if (($sco->organization
== '') && ($sco->launch
== '')) {
966 $orgidentifier = $sco->identifier
;
968 $orgidentifier = $sco->organization
;
971 if ($scorm->skipview
>= SCORM_SKIPVIEW_FIRST
) {
972 $sco = current($scoes);
973 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id
,
974 'currentorg' => $orgidentifier,
975 'scoid' => $sco->id
));
976 if ($scorm->skipview
== SCORM_SKIPVIEW_ALWAYS ||
!scorm_has_tracks($scorm->id
, $user->id
)) {
977 if (!empty($scorm->forcenewattempt
)) {
978 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL
, $orgidentifier);
979 if ($result->incomplete
=== false) {
980 $url->param('newattempt', 'on');
990 function scorm_get_count_users($scormid, $groupingid=null) {
993 if (!empty($groupingid)) {
994 $sql = "SELECT COUNT(DISTINCT st.userid)
995 FROM {scorm_scoes_track} st
996 INNER JOIN {groups_members} gm ON st.userid = gm.userid
997 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
998 WHERE st.scormid = ? AND gg.groupingid = ?
1000 $params = array($scormid, $groupingid);
1002 $sql = "SELECT COUNT(DISTINCT st.userid)
1003 FROM {scorm_scoes_track} st
1004 WHERE st.scormid = ?
1006 $params = array($scormid);
1009 return ($DB->count_records_sql($sql, $params));
1013 * Build up the JavaScript representation of an array element
1015 * @param string $sversion SCORM API version
1016 * @param array $userdata User track data
1017 * @param string $elementname Name of array element to get values for
1018 * @param array $children list of sub elements of this array element that also need instantiating
1019 * @return Javascript array elements
1021 function scorm_reconstitute_array_element($sversion, $userdata, $elementname, $children) {
1022 // Reconstitute comments_from_learner and comments_from_lms.
1024 $currentsubelement = '';
1028 $scormseperator = '_';
1030 if (scorm_version_check($sversion, SCORM_13
)) { // Scorm 1.3 elements use a . instead of an _ .
1031 $scormseperator = '.';
1033 // Filter out the ones we want.
1034 $elementlist = array();
1035 foreach ($userdata as $element => $value) {
1036 if (substr($element, 0, strlen($elementname)) == $elementname) {
1037 $elementlist[$element] = $value;
1041 // Sort elements in .n array order.
1042 uksort($elementlist, "scorm_element_cmp");
1044 // Generate JavaScript.
1045 foreach ($elementlist as $element => $value) {
1046 if (scorm_version_check($sversion, SCORM_13
)) {
1047 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
1048 preg_match('/\.(N\d+)\./', $element, $matches);
1050 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
1051 preg_match('/\_(\d+)\./', $element, $matches);
1053 if (count($matches) > 0 && $current != $matches[1]) {
1054 if ($countsub > 0) {
1055 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
1057 $current = $matches[1];
1059 $currentsubelement = '';
1062 $end = strpos($element, $matches[1]) +
strlen($matches[1]);
1063 $subelement = substr($element, 0, $end);
1064 $return .= ' '.$subelement." = new Object();\n";
1065 // Now add the children.
1066 foreach ($children as $child) {
1067 $return .= ' '.$subelement.".".$child." = new Object();\n";
1068 $return .= ' '.$subelement.".".$child."._children = ".$child."_children;\n";
1072 // Now - flesh out the second level elements if there are any.
1073 if (scorm_version_check($sversion, SCORM_13
)) {
1074 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1075 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1077 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1078 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1081 // Check the sub element type.
1082 if (count($matches) > 0 && $currentsubelement != $matches[1]) {
1083 if ($countsub > 0) {
1084 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
1086 $currentsubelement = $matches[1];
1089 $end = strpos($element, $matches[1]) +
strlen($matches[1]);
1090 $subelement = substr($element, 0, $end);
1091 $return .= ' '.$subelement." = new Object();\n";
1094 // Now check the subelement subscript.
1095 if (count($matches) > 0 && $currentsub != $matches[2]) {
1096 $currentsub = $matches[2];
1098 $end = strrpos($element, $matches[2]) +
strlen($matches[2]);
1099 $subelement = substr($element, 0, $end);
1100 $return .= ' '.$subelement." = new Object();\n";
1103 $return .= ' '.$element.' = '.json_encode($value).";\n";
1105 if ($countsub > 0) {
1106 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
1109 $return .= ' '.$elementname.'._count = '.$count.";\n";
1115 * Build up the JavaScript representation of an array element
1117 * @param string $a left array element
1118 * @param string $b right array element
1119 * @return comparator - 0,1,-1
1121 function scorm_element_cmp($a, $b) {
1122 preg_match('/.*?(\d+)\./', $a, $matches);
1123 $left = intval($matches[1]);
1124 preg_match('/.?(\d+)\./', $b, $matches);
1125 $right = intval($matches[1]);
1126 if ($left < $right) {
1127 return -1; // Smaller.
1128 } else if ($left > $right) {
1129 return 1; // Bigger.
1131 // Look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern.
1132 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1133 $leftterm = intval($matches[2]);
1134 $left = intval($matches[3]);
1135 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1136 $rightterm = intval($matches[2]);
1137 $right = intval($matches[3]);
1138 if ($leftterm < $rightterm) {
1139 return -1; // Smaller.
1140 } else if ($leftterm > $rightterm) {
1141 return 1; // Bigger.
1143 if ($left < $right) {
1144 return -1; // Smaller.
1145 } else if ($left > $right) {
1146 return 1; // Bigger.
1151 // Fall back for no second level matches or second level matches are equal.
1152 return 0; // Equal to.
1157 * Generate the user attempt status string
1159 * @param object $user Current context user
1160 * @param object $scorm a moodle scrom object - mdl_scorm
1161 * @return string - Attempt status string
1163 function scorm_get_attempt_status($user, $scorm, $cm='') {
1164 global $DB, $PAGE, $OUTPUT;
1166 $attempts = scorm_get_attempt_count($user->id
, $scorm, true);
1167 if (empty($attempts)) {
1170 $attemptcount = count($attempts);
1173 $result = html_writer
::start_tag('p').get_string('noattemptsallowed', 'scorm').': ';
1174 if ($scorm->maxattempt
> 0) {
1175 $result .= $scorm->maxattempt
. html_writer
::empty_tag('br');
1177 $result .= get_string('unlimited').html_writer
::empty_tag('br');
1179 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . html_writer
::empty_tag('br');
1181 if ($scorm->maxattempt
== 1) {
1182 switch ($scorm->grademethod
) {
1184 $grademethod = get_string('gradehighest', 'scorm');
1187 $grademethod = get_string('gradeaverage', 'scorm');
1190 $grademethod = get_string('gradesum', 'scorm');
1193 $grademethod = get_string('gradescoes', 'scorm');
1197 switch ($scorm->whatgrade
) {
1198 case HIGHESTATTEMPT
:
1199 $grademethod = get_string('highestattempt', 'scorm');
1201 case AVERAGEATTEMPT
:
1202 $grademethod = get_string('averageattempt', 'scorm');
1205 $grademethod = get_string('firstattempt', 'scorm');
1208 $grademethod = get_string('lastattempt', 'scorm');
1213 if (!empty($attempts)) {
1215 foreach ($attempts as $attempt) {
1216 $gradereported = scorm_grade_user_attempt($scorm, $user->id
, $attempt->attemptnumber
);
1217 if ($scorm->grademethod
!== GRADESCOES
&& !empty($scorm->maxgrade
)) {
1218 $gradereported = $gradereported / $scorm->maxgrade
;
1219 $gradereported = number_format($gradereported * 100, 0) .'%';
1221 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .html_writer
::empty_tag('br');
1225 $calculatedgrade = scorm_grade_user($scorm, $user->id
);
1226 if ($scorm->grademethod
!== GRADESCOES
&& !empty($scorm->maxgrade
)) {
1227 $calculatedgrade = $calculatedgrade / $scorm->maxgrade
;
1228 $calculatedgrade = number_format($calculatedgrade * 100, 0) .'%';
1230 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1231 if (empty($attempts)) {
1232 $result .= html_writer
::empty_tag('br').get_string('gradereported', 'scorm').
1233 ': '.get_string('none').html_writer
::empty_tag('br');
1235 $result .= html_writer
::empty_tag('br').get_string('gradereported', 'scorm').
1236 ': '.$calculatedgrade.html_writer
::empty_tag('br');
1238 $result .= html_writer
::end_tag('p');
1239 if ($attemptcount >= $scorm->maxattempt
and $scorm->maxattempt
> 0) {
1240 $result .= html_writer
::tag('p', get_string('exceededmaxattempts', 'scorm'), array('class' => 'exceededmaxattempts'));
1243 $context = context_module
::instance($cm->id
);
1244 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1245 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id
, 'scormid' => $scorm->id
))) {
1246 // Check to see if any data is stored for this user.
1247 $deleteurl = new moodle_url($PAGE->url
, array('action' => 'delete', 'sesskey' => sesskey()));
1248 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1256 * Get SCORM attempt count
1258 * @param object $user Current context user
1259 * @param object $scorm a moodle scrom object - mdl_scorm
1260 * @param bool $returnobjects if true returns a object with attempts, if false returns count of attempts.
1261 * @param bool $ignoremissingcompletion - ignores attempts that haven't reported a grade/completion.
1262 * @return int - no. of attempts so far
1264 function scorm_get_attempt_count($userid, $scorm, $returnobjects = false, $ignoremissingcompletion = false) {
1267 // Historically attempts that don't report these elements haven't been included in the average attempts grading method
1268 // we may want to change this in future, but to avoid unexpected grade decreases we're leaving this in. MDL-43222 .
1269 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1270 $element = 'cmi.score.raw';
1271 } else if ($scorm->grademethod
== GRADESCOES
) {
1272 $element = 'cmi.core.lesson_status';
1274 $element = 'cmi.core.score.raw';
1277 if ($returnobjects) {
1278 $params = array('userid' => $userid, 'scormid' => $scorm->id
);
1279 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1280 $params['element'] = $element;
1282 $attempts = $DB->get_records('scorm_scoes_track', $params, 'attempt', 'DISTINCT attempt AS attemptnumber');
1285 $params = array($userid, $scorm->id
);
1286 $sql = "SELECT COUNT(DISTINCT attempt)
1287 FROM {scorm_scoes_track}
1288 WHERE userid = ? AND scormid = ?";
1289 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1290 $sql .= ' AND element = ?';
1291 $params[] = $element;
1294 $attemptscount = $DB->count_records_sql($sql, $params);
1295 return $attemptscount;
1300 * Figure out with this is a debug situation
1302 * @param object $scorm a moodle scrom object - mdl_scorm
1303 * @return boolean - debugging true/false
1305 function scorm_debugging($scorm) {
1307 $cfgscorm = get_config('scorm');
1309 if (!$cfgscorm->allowapidebug
) {
1312 $identifier = $USER->username
.':'.$scorm->name
;
1313 $test = $cfgscorm->apidebugmask
;
1314 // Check the regex is only a short list of safe characters.
1315 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1319 if (preg_match('/^'.$test.'/', $identifier)) {
1326 * Delete Scorm tracks for selected users
1328 * @param array $attemptids list of attempts that need to be deleted
1329 * @param stdClass $scorm instance
1331 * @return bool true deleted all responses, false failed deleting an attempt - stopped here
1333 function scorm_delete_responses($attemptids, $scorm) {
1334 if (!is_array($attemptids) ||
empty($attemptids)) {
1338 foreach ($attemptids as $num => $attemptid) {
1339 if (empty($attemptid)) {
1340 unset($attemptids[$num]);
1344 foreach ($attemptids as $attempt) {
1345 $keys = explode(':', $attempt);
1346 if (count($keys) == 2) {
1347 $userid = clean_param($keys[0], PARAM_INT
);
1348 $attemptid = clean_param($keys[1], PARAM_INT
);
1349 if (!$userid ||
!$attemptid ||
!scorm_delete_attempt($userid, $scorm, $attemptid)) {
1360 * Delete Scorm tracks for selected users
1362 * @param int $userid ID of User
1363 * @param stdClass $scorm Scorm object
1364 * @param int $attemptid user attempt that need to be deleted
1366 * @return bool true suceeded
1368 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1371 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id
, 'attempt' => $attemptid));
1372 $cm = get_coursemodule_from_instance('scorm', $scorm->id
);
1374 // Trigger instances list viewed event.
1375 $event = \mod_scorm\event\attempt_deleted
::create(array(
1376 'other' => array('attemptid' => $attemptid),
1377 'context' => context_module
::instance($cm->id
),
1378 'relateduserid' => $userid
1380 $event->add_record_snapshot('course_modules', $cm);
1381 $event->add_record_snapshot('scorm', $scorm);
1384 include_once('lib.php');
1385 scorm_update_grades($scorm, $userid, true);
1390 * Converts SCORM duration notation to human-readable format
1391 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1392 * @param $duration string SCORM duration
1393 * @return string human-readable date/time
1395 function scorm_format_duration($duration) {
1396 // Fetch date/time strings.
1397 $stryears = get_string('years');
1398 $strmonths = get_string('nummonths');
1399 $strdays = get_string('days');
1400 $strhours = get_string('hours');
1401 $strminutes = get_string('minutes');
1402 $strseconds = get_string('seconds');
1404 if ($duration[0] == 'P') {
1405 // If timestamp starts with 'P' - it's a SCORM 2004 format
1406 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1407 // and outputs filled sections, discarding leading zeroes and any format literals
1408 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
1409 $pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#',
1410 '#0*(\d+)Y#', '#0*(\d+)D#', '#P#', '#([A-Z])0+H#', '#([A-Z])[0.]+S#',
1411 '#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#',
1412 '#0*([\d.]+)S#', '#T#' );
1413 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ',
1414 '', '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ',
1415 '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1417 // Else we have SCORM 1.2 format there
1418 // first convert the timestamp to some SCORM 2004-like format for conveniency.
1419 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1420 // Then convert in the same way as SCORM 2004.
1421 $pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#',
1422 '#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
1423 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ',
1424 '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1427 $result = preg_replace($pattern, $replace, $duration);
1432 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='',
1433 $play=false, $organizationsco=null) {
1434 global $CFG, $DB, $PAGE, $OUTPUT;
1436 // Always pass the mode even if empty as that is what is done elsewhere and the urls have to match.
1437 $modestr = '&mode=';
1438 if ($mode != 'normal') {
1439 $modestr = '&mode='.$mode;
1443 $incomplete = false;
1445 if (!empty($organizationsco)) {
1446 $result[0] = $organizationsco;
1447 $result[0]->isvisible
= true;
1448 $result[0]->statusicon
= '';
1449 $result[0]->url
= '';
1452 if ($scoes = scorm_get_scoes($scorm->id
, $currentorg)) {
1453 // Retrieve user tracking data for each learning object.
1454 $usertracks = array();
1455 foreach ($scoes as $sco) {
1456 if (!empty($sco->launch
)) {
1457 if ($usertrack = scorm_get_tracks($sco->id
, $user->id
, $attempt)) {
1458 if ($usertrack->status
== '') {
1459 $usertrack->status
= 'notattempted';
1461 $usertracks[$sco->identifier
] = $usertrack;
1465 foreach ($scoes as $sco) {
1466 if (!isset($sco->isvisible
)) {
1467 $sco->isvisible
= true;
1470 if (empty($sco->title
)) {
1471 $sco->title
= $sco->identifier
;
1474 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1475 $sco->prereq
= true;
1477 $sco->prereq
= empty($sco->prerequisites
) ||
scorm_eval_prerequisites($sco->prerequisites
, $usertracks);
1480 if ($sco->isvisible
) {
1481 if (!empty($sco->launch
)) {
1482 if (empty($scoid) && ($mode != 'normal')) {
1486 if (isset($usertracks[$sco->identifier
])) {
1487 $usertrack = $usertracks[$sco->identifier
];
1488 $strstatus = get_string($usertrack->status
, 'scorm');
1490 if ($sco->scormtype
== 'sco') {
1491 $statusicon = html_writer
::img($OUTPUT->pix_url($usertrack->status
, 'scorm'), $strstatus,
1492 array('title' => $strstatus));
1494 $statusicon = html_writer
::img($OUTPUT->pix_url('asset', 'scorm'), get_string('assetlaunched', 'scorm'),
1495 array('title' => get_string('assetlaunched', 'scorm')));
1498 if (($usertrack->status
== 'notattempted') ||
1499 ($usertrack->status
== 'incomplete') ||
1500 ($usertrack->status
== 'browsed')) {
1502 if ($play && empty($scoid)) {
1507 $strsuspended = get_string('suspended', 'scorm');
1509 $exitvar = 'cmi.core.exit';
1511 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1512 $exitvar = 'cmi.exit';
1515 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1516 $statusicon = html_writer
::img($OUTPUT->pix_url('suspend', 'scorm'), $strstatus.' - '.$strsuspended,
1517 array('title' => $strstatus.' - '.$strsuspended));
1521 if ($play && empty($scoid)) {
1527 if ($sco->scormtype
== 'sco') {
1528 $statusicon = html_writer
::img($OUTPUT->pix_url('notattempted', 'scorm'),
1529 get_string('notattempted', 'scorm'),
1530 array('title' => get_string('notattempted', 'scorm')));
1532 $statusicon = html_writer
::img($OUTPUT->pix_url('asset', 'scorm'), get_string('asset', 'scorm'),
1533 array('title' => get_string('asset', 'scorm')));
1539 if (empty($statusicon)) {
1540 $sco->statusicon
= html_writer
::img($OUTPUT->pix_url('notattempted', 'scorm'), get_string('notattempted', 'scorm'),
1541 array('title' => get_string('notattempted', 'scorm')));
1543 $sco->statusicon
= $statusicon;
1546 $sco->url
= 'a='.$scorm->id
.'&scoid='.$sco->id
.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
1547 $sco->incomplete
= $incomplete;
1549 if (!in_array($sco->id
, array_keys($result))) {
1550 $result[$sco->id
] = $sco;
1555 // Get the parent scoes!
1556 $result = scorm_get_toc_get_parent_child($result, $currentorg);
1558 // Be safe, prevent warnings from showing up while returning array.
1559 if (!isset($scoid)) {
1563 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1566 function scorm_get_toc_get_parent_child(&$result, $currentorg) {
1569 // Organization is always the root, prevparent.
1570 if (!empty($currentorg)) {
1571 $prevparent = $currentorg;
1576 foreach ($result as $sco) {
1577 if ($sco->parent
== '/') {
1578 $final[$level][$sco->identifier
] = $sco;
1579 $prevparent = $sco->identifier
;
1580 unset($result[$sco->id
]);
1582 if ($sco->parent
== $prevparent) {
1583 $final[$level][$sco->identifier
] = $sco;
1584 $prevparent = $sco->identifier
;
1585 unset($result[$sco->id
]);
1587 if (!empty($final[$level])) {
1589 foreach ($final[$level] as $fin) {
1590 if ($sco->parent
== $fin->identifier
) {
1596 $final[$level][$sco->identifier
] = $sco;
1597 unset($result[$sco->id
]);
1601 $final[$level][$sco->identifier
] = $sco;
1602 unset($result[$sco->id
]);
1609 for ($i = 0; $i <= $level; $i++
) {
1611 foreach ($final[$i] as $ident => $sco) {
1612 if (empty($prevparent)) {
1613 $prevparent = $ident;
1615 if (!isset($final[$i][$prevparent]->children
)) {
1616 $final[$i][$prevparent]->children
= array();
1618 if ($sco->parent
== $prevparent) {
1619 $final[$i][$prevparent]->children
[] = $sco;
1620 $prevparent = $ident;
1623 foreach ($final[$i] as $identifier => $scoobj) {
1624 if ($identifier == $sco->parent
) {
1625 $parent = $identifier;
1629 if ($parent !== false) {
1630 $final[$i][$parent]->children
[] = $sco;
1637 for ($i = 0; $i <= $level; $i++
) {
1638 $keys = array_keys($final[$i]);
1639 $results[] = $final[$i][$keys[0]];
1645 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK
, $currentorg='',
1646 $attempt='', $play=false, $organizationsco=null, $children=false) {
1649 $result = new stdClass();
1650 $result->prerequisites
= true;
1651 $result->incomplete
= true;
1655 $attemptsmade = scorm_get_attempt_count($user->id
, $scorm);
1656 $result->attemptleft
= $scorm->maxattempt
== 0 ?
1 : $scorm->maxattempt
- $attemptsmade;
1660 $result->toc
= html_writer
::start_tag('ul');
1662 if (!$play && !empty($organizationsco)) {
1663 $result->toc
.= html_writer
::start_tag('li').$organizationsco->title
.html_writer
::end_tag('li');
1668 if (!empty($scoes)) {
1669 foreach ($scoes as $sco) {
1670 $result->toc
.= html_writer
::start_tag('li');
1673 $sco->isvisible
= true;
1675 if ($sco->isvisible
) {
1678 if (isset($usertracks[$sco->identifier
])) {
1679 $viewscore = has_capability('mod/scorm:viewscores', context_module
::instance($cmid));
1680 if (isset($usertracks[$sco->identifier
]->score_raw
) && $viewscore) {
1681 if ($usertracks[$sco->identifier
]->score_raw
!= '') {
1682 $score = '('.get_string('score', 'scorm').': '.$usertracks[$sco->identifier
]->score_raw
.')';
1687 if (!empty($sco->prereq
)) {
1688 if ($sco->id
== $scoid) {
1689 $result->prerequisites
= true;
1692 if (!empty($prevsco) && scorm_version_check($scorm->version
, SCORM_13
) && !empty($prevsco->hidecontinue
)) {
1693 if ($sco->scormtype
== 'sco') {
1694 $result->toc
.= html_writer
::span($sco->statusicon
.' '.format_string($sco->title
));
1696 $result->toc
.= html_writer
::span(' '.format_string($sco->title
));
1698 } else if ($toclink == TOCFULLURL
) {
1699 $url = $CFG->wwwroot
.'/mod/scorm/player.php?'.$sco->url
;
1700 if (!empty($sco->launch
)) {
1701 if ($sco->scormtype
== 'sco') {
1702 $result->toc
.= $sco->statusicon
.' ';
1703 $result->toc
.= html_writer
::link($url, format_string($sco->title
)).$score;
1705 $result->toc
.= ' '.html_writer
::link($url, format_string($sco->title
),
1706 array('data-scoid' => $sco->id
)).$score;
1709 if ($sco->scormtype
== 'sco') {
1710 $result->toc
.= $sco->statusicon
.' '.format_string($sco->title
).$score;
1712 $result->toc
.= ' '.format_string($sco->title
).$score;
1716 if (!empty($sco->launch
)) {
1717 if ($sco->scormtype
== 'sco') {
1718 $result->toc
.= html_writer
::tag('a', $sco->statusicon
.' '.
1719 format_string($sco->title
).' '.$score,
1720 array('data-scoid' => $sco->id
, 'title' => $sco->url
));
1722 $result->toc
.= html_writer
::tag('a', ' '.format_string($sco->title
).' '.$score,
1723 array('data-scoid' => $sco->id
, 'title' => $sco->url
));
1726 if ($sco->scormtype
== 'sco') {
1727 $result->toc
.= html_writer
::span($sco->statusicon
.' '.format_string($sco->title
));
1729 $result->toc
.= html_writer
::span(' '.format_string($sco->title
));
1736 if ($sco->scormtype
== 'sco') {
1737 $result->toc
.= html_writer
::span($sco->statusicon
.' '.format_string($sco->title
));
1739 $result->toc
.= ' '.format_string($sco->title
).html_writer
::end_span();
1742 if ($sco->scormtype
== 'sco') {
1743 $result->toc
.= $sco->statusicon
.' '.format_string($sco->title
);
1745 $result->toc
.= ' '.format_string($sco->title
);
1751 $result->toc
.= " ".format_string($sco->title
);
1754 if (!empty($sco->children
)) {
1755 $result->toc
.= html_writer
::start_tag('ul');
1756 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children
, $usertracks, $cmid,
1757 $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1759 // Is any of the children incomplete?
1760 $sco->incomplete
= $childresult->incomplete
;
1761 $result->toc
.= $childresult->toc
;
1762 $result->toc
.= html_writer
::end_tag('ul');
1763 $result->toc
.= html_writer
::end_tag('li');
1765 $result->toc
.= html_writer
::end_tag('li');
1769 $result->incomplete
= $sco->incomplete
;
1773 $result->toc
.= html_writer
::end_tag('ul');
1779 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null,
1780 $children=false, $level=0, $tocmenus=array()) {
1781 if (!empty($scoes)) {
1782 if (!empty($organizationsco) && !$children) {
1783 $tocmenus[$organizationsco->id
] = $organizationsco->title
;
1786 $parents[$level] = '/';
1787 foreach ($scoes as $sco) {
1788 if ($parents[$level] != $sco->parent
) {
1789 if ($newlevel = array_search($sco->parent
, $parents)) {
1793 while (($i > 0) && ($parents[$level] != $sco->parent
)) {
1797 if (($i == 0) && ($sco->parent
!= $currentorg)) {
1803 $parents[$level] = $sco->parent
;
1807 if ($sco->scormtype
== 'sco') {
1808 $tocmenus[$sco->id
] = scorm_repeater('−', $level) . '>' . format_string($sco->title
);
1811 if (!empty($sco->children
)) {
1812 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children
, $usertracks, $currentorg,
1813 $organizationsco, true, $level, $tocmenus);
1821 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK
, $currentorg='', $scoid='', $mode='normal',
1822 $attempt='', $play=false, $tocheader=false) {
1823 global $CFG, $DB, $OUTPUT;
1825 if (empty($attempt)) {
1826 $attempt = scorm_get_last_attempt($scorm->id
, $user->id
);
1829 $result = new stdClass();
1830 $organizationsco = null;
1833 $result->toc
= html_writer
::start_div('yui3-g-r', array('id' => 'scorm_layout'));
1834 $result->toc
.= html_writer
::start_div('yui3-u-1-5', array('id' => 'scorm_toc'));
1835 $result->toc
.= html_writer
::div('', '', array('id' => 'scorm_toc_title'));
1836 $result->toc
.= html_writer
::start_div('', array('id' => 'scorm_tree'));
1839 if (!empty($currentorg)) {
1840 $organizationsco = $DB->get_record('scorm_scoes', array('scorm' => $scorm->id
, 'identifier' => $currentorg));
1841 if (!empty($organizationsco->title
)) {
1843 $result->toctitle
= $organizationsco->title
;
1848 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1850 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children
, $scoes['usertracks'], $cmid,
1851 $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1854 $result->toc
.= $treeview->toc
;
1856 $result->toc
= $treeview->toc
;
1859 if (!empty($scoes['scoid'])) {
1860 $scoid = $scoes['scoid'];
1863 if (empty($scoid)) {
1864 // If this is a normal package with an org sco and child scos get the first child.
1865 if (!empty($scoes['scoes'][0]->children
)) {
1866 $result->sco
= $scoes['scoes'][0]->children
[0];
1867 } else { // This package only has one sco - it may be a simple external AICC package.
1868 $result->sco
= $scoes['scoes'][0];
1872 $result->sco
= scorm_get_sco($scoid);
1875 if ($scorm->hidetoc
== SCORM_TOC_POPUP
) {
1876 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children
, $scoes['usertracks'],
1877 $currentorg, $organizationsco);
1880 if ($mode != 'normal') {
1881 $modestr = '&mode='.$mode;
1884 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id
.'¤torg='.$currentorg.$modestr);
1885 $result->tocmenu
= $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco
->id
, null, "tocmenu");
1888 $result->prerequisites
= $treeview->prerequisites
;
1889 $result->incomplete
= $treeview->incomplete
;
1890 $result->attemptleft
= $treeview->attemptleft
;
1893 $result->toc
.= html_writer
::end_div().html_writer
::end_div();
1894 $result->toc
.= html_writer
::start_div('', array('id' => 'scorm_toc_toggle'));
1895 $result->toc
.= html_writer
::tag('button', '', array('id' => 'scorm_toc_toggle_btn')).html_writer
::end_div();
1896 $result->toc
.= html_writer
::start_div('', array('id' => 'scorm_content'));
1897 $result->toc
.= html_writer
::div('', '', array('id' => 'scorm_navpanel'));
1898 $result->toc
.= html_writer
::end_div().html_writer
::end_div();
1904 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1905 if (is_object($scoes)) {
1907 if (isset($sco->url
)) {
1908 $adlnav[$sco->id
]['identifier'] = $sco->identifier
;
1909 $adlnav[$sco->id
]['launch'] = $sco->launch
;
1910 $adlnav[$sco->id
]['title'] = $sco->title
;
1911 $adlnav[$sco->id
]['url'] = $sco->url
;
1912 $adlnav[$sco->id
]['parent'] = $sco->parent
;
1913 if (isset($sco->choice
)) {
1914 $adlnav[$sco->id
]['choice'] = $sco->choice
;
1916 if (isset($sco->flow
)) {
1917 $adlnav[$sco->id
]['flow'] = $sco->flow
;
1918 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1919 $adlnav[$sco->id
]['flow'] = $adlnav[$parentscoid]['flow'];
1921 if (isset($sco->isvisible
)) {
1922 $adlnav[$sco->id
]['isvisible'] = $sco->isvisible
;
1924 if (isset($sco->parameters
)) {
1925 $adlnav[$sco->id
]['parameters'] = $sco->parameters
;
1927 if (isset($sco->hidecontinue
)) {
1928 $adlnav[$sco->id
]['hidecontinue'] = $sco->hidecontinue
;
1930 if (isset($sco->hideprevious
)) {
1931 $adlnav[$sco->id
]['hideprevious'] = $sco->hideprevious
;
1933 if (isset($sco->hidesuspendall
)) {
1934 $adlnav[$sco->id
]['hidesuspendall'] = $sco->hidesuspendall
;
1936 if (!empty($parentscoid)) {
1937 $adlnav[$sco->id
]['parentscoid'] = $parentscoid;
1939 if (isset($adlnav['prevscoid'])) {
1940 $adlnav[$sco->id
]['prevscoid'] = $adlnav['prevscoid'];
1941 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id
;
1942 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent
) {
1943 $adlnav[$sco->id
]['prevsibling'] = $adlnav['prevscoid'];
1944 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id
;
1947 $adlnav['prevscoid'] = $sco->id
;
1948 $adlnav['prevparent'] = $sco->parent
;
1950 if (isset($sco->children
)) {
1951 foreach ($sco->children
as $children) {
1952 scorm_get_adlnav_json($children, $adlnav, $sco->id
);
1956 foreach ($scoes as $sco) {
1957 scorm_get_adlnav_json ($sco, $adlnav);
1959 unset($adlnav['prevscoid']);
1960 unset($adlnav['prevparent']);
1962 return json_encode($adlnav);
1966 * Check for the availability of a resource by URL.
1968 * Check is performed using an HTTP HEAD call.
1970 * @param $url string A valid URL
1971 * @return bool|string True if no issue is found. The error string message, otherwise
1973 function scorm_check_url($url) {
1975 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1976 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1977 $cmsg = $curl->head($url);
1978 $info = $curl->get_info();
1979 if (empty($info['http_code']) ||
$info['http_code'] != 200) {
1980 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
1987 * Check for a parameter in userdata and return it if it's set
1988 * or return the value from $ifempty if its empty
1990 * @param stdClass $userdata Contains user's data
1991 * @param string $param parameter that should be checked
1992 * @param string $ifempty value to be replaced with if $param is not set
1993 * @return string value from $userdata->$param if its not empty, or $ifempty
1995 function scorm_isset($userdata, $param, $ifempty = '') {
1996 if (isset($userdata->$param)) {
1997 return $userdata->$param;
2004 * Check if the current sco is launchable
2005 * If not, find the next launchable sco
2007 * @param stdClass $scorm Scorm object
2008 * @param integer $scoid id of scorm_scoes record.
2009 * @return integer scoid of correct sco to launch or empty if one cannot be found, which will trigger first sco.
2011 function scorm_check_launchable_sco($scorm, $scoid) {
2013 if ($sco = scorm_get_sco($scoid, SCO_ONLY
)) {
2014 if ($sco->launch
== '') {
2015 // This scoid might be a top level org that can't be launched, find the first launchable sco after this sco.
2016 $scoes = $DB->get_records_select('scorm_scoes',
2017 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).
2018 ' AND id > ?', array($scorm->id
, $sco->id
), 'sortorder, id', 'id', 0, 1);
2019 if (!empty($scoes)) {
2020 $sco = reset($scoes); // Get first item from the list.
2027 // Returning 0 will cause default behaviour which will find the first launchable sco in the package.
2032 * Check if a SCORM is available for the current user.
2034 * @param stdClass $scorm SCORM record
2035 * @param boolean $checkviewreportcap Check the scorm:viewreport cap
2036 * @param stdClass $context Module context, required if $checkviewreportcap is set to true
2037 * @return array status (available or not and possible warnings)
2040 function scorm_get_availability_status($scorm, $checkviewreportcap = false, $context = null) {
2043 $warnings = array();
2046 if (!empty($scorm->timeopen
) and $scorm->timeopen
> $timenow) {
2049 if (!empty($scorm->timeclose
) and $timenow > $scorm->timeclose
) {
2053 if (!$open or $closed) {
2054 if ($checkviewreportcap and !empty($context) and has_capability('mod/scorm:viewreport', $context)) {
2055 return array(true, $warnings);
2059 $warnings['notopenyet'] = userdate($scorm->timeopen
);
2062 $warnings['expired'] = userdate($scorm->timeclose
);
2064 return array(false, $warnings);
2067 // Scorm is available.
2068 return array(true, $warnings);
2072 * Requires a SCORM package to be available for the current user.
2074 * @param stdClass $scorm SCORM record
2075 * @param boolean $checkviewreportcap Check the scorm:viewreport cap
2076 * @param stdClass $context Module context, required if $checkviewreportcap is set to true
2077 * @throws moodle_exception
2080 function scorm_require_available($scorm, $checkviewreportcap = false, $context = null) {
2082 list($available, $warnings) = scorm_get_availability_status($scorm, $checkviewreportcap, $context);
2085 $reason = current(array_keys($warnings));
2086 throw new moodle_exception($reason, 'scorm', '', $warnings[$reason]);