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 $cfg_scorm = 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 (!$cfg_scorm->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 $file_record = array('contextid'=>$context->id
, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
243 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference
, array('calctimeout' => true))) {
244 $newhash = sha1($scorm->reference
);
252 if (!$full and $packagefile and $scorm->sha1hash
=== $newhash) {
253 if (strpos($scorm->version
, 'SCORM') !== false) {
254 if ($packagefileimsmanifest ||
$fs->get_file($context->id
, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
255 // No need to update.
258 } else if (strpos($scorm->version
, 'AICC') !== false) {
259 // TODO: add more sanity checks - something really exists in scorm_content area
263 if (!$packagefileimsmanifest) {
264 // Now extract files.
265 $fs->delete_area_files($context->id
, 'mod_scorm', 'content');
267 $packer = get_file_packer('application/zip');
268 $packagefile->extract_to_storage($packer, $context->id
, 'mod_scorm', 'content', 0, '/');
274 if ($packagefileimsmanifest) {
275 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
276 // Direct link to imsmanifest.xml file.
277 if (!scorm_parse_scorm($scorm, $packagefile)) {
278 $scorm->version
= 'ERROR';
281 } else if ($manifest = $fs->get_file($context->id
, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
282 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
284 if (!scorm_parse_scorm($scorm, $manifest)) {
285 $scorm->version
= 'ERROR';
288 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
290 if (!scorm_parse_aicc($scorm)) {
291 $scorm->version
= 'ERROR';
293 $scorm->version
= 'AICC';
296 } else if ($scorm->scormtype
=== SCORM_TYPE_EXTERNAL
and $cfg_scorm->allowtypeexternal
) {
297 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
298 // SCORM only, AICC can not be external
299 if (!scorm_parse_scorm($scorm, $scorm->reference
)) {
300 $scorm->version
= 'ERROR';
302 $newhash = sha1($scorm->reference
);
304 } else if ($scorm->scormtype
=== SCORM_TYPE_AICCURL
and $cfg_scorm->allowtypeexternalaicc
) {
305 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
307 if (!scorm_parse_aicc($scorm)) {
308 $scorm->version
= 'ERROR';
310 $scorm->version
= 'AICC';
312 // sorry, disabled type
317 $scorm->sha1hash
= $newhash;
318 $DB->update_record('scorm', $scorm);
322 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
323 if (!empty($haystacks)) {
324 foreach ($haystacks as $key => $element) {
326 if ($element->{$item} === $needle) {
330 if ($element->{$item} == $needle) {
339 function scorm_repeater($what, $times) {
344 for ($i=0; $i<$times; $i++
) {
350 function scorm_external_link($link) {
351 // check if a link is external
353 $link = strtolower($link);
354 if (substr($link, 0, 7) == 'http://') {
356 } else if (substr($link, 0, 8) == 'https://') {
358 } else if (substr($link, 0, 4) == 'www.') {
365 * Returns an object containing all datas relative to the given sco ID
367 * @param integer $id The sco ID
368 * @return mixed (false if sco id does not exists)
370 function scorm_get_sco($id, $what=SCO_ALL
) {
373 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
374 $sco = ($what == SCO_DATA
) ?
new stdClass() : $sco;
375 if (($what != SCO_ONLY
) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
376 foreach ($scodatas as $scodata) {
377 $sco->{$scodata->name
} = $scodata->value
;
379 } else if (($what != SCO_ONLY
) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
380 $sco->parameters
= '';
389 * Returns an object (array) containing all the scoes data related to the given sco ID
391 * @param integer $id The sco ID
392 * @param integer $organisation an organisation ID - defaults to false if not required
393 * @return mixed (false if there are no scoes or an array)
395 function scorm_get_scoes($id, $organisation=false) {
398 $queryarray = array('scorm'=>$id);
399 if (!empty($organisation)) {
400 $queryarray['organization'] = $organisation;
402 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
403 // Drop keys so that it is a simple array as expected.
404 $scoes = array_values($scoes);
405 foreach ($scoes as $sco) {
406 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id
))) {
407 foreach ($scodatas as $scodata) {
408 $sco->{$scodata->name
} = $scodata->value
;
418 function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
423 if ($forcecompleted) {
424 //TODO - this could be broadened to encompass SCORM 2004 in future
425 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
426 if ($track = $DB->get_record_select('scorm_scoes_track', 'userid=? AND scormid=? AND scoid=? AND attempt=? AND element=\'cmi.core.score.raw\'', array($userid, $scormid, $scoid, $attempt))) {
427 $value = 'completed';
430 if ($element == 'cmi.core.score.raw') {
431 if ($tracktest = $DB->get_record_select('scorm_scoes_track', 'userid=? AND scormid=? AND scoid=? AND attempt=? AND element=\'cmi.core.lesson_status\'', array($userid, $scormid, $scoid, $attempt))) {
432 if ($tracktest->value
== "incomplete") {
433 $tracktest->value
= "completed";
434 $DB->update_record('scorm_scoes_track', $tracktest);
438 if (($element == 'cmi.success_status') && ($value == 'passed' ||
$value == 'failed')) {
439 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
440 $objectiveprogressstatus = true;
441 $objectivesatisfiedstatus = false;
442 if ($value == 'passed') {
443 $objectivesatisfiedstatus = true;
446 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
447 'scormid' => $scormid,
449 'attempt' => $attempt,
450 'element' => 'objectiveprogressstatus'))) {
451 $track->value
= $objectiveprogressstatus;
452 $track->timemodified
= time();
453 $DB->update_record('scorm_scoes_track', $track);
456 $track = new stdClass();
457 $track->userid
= $userid;
458 $track->scormid
= $scormid;
459 $track->scoid
= $scoid;
460 $track->attempt
= $attempt;
461 $track->element
= 'objectiveprogressstatus';
462 $track->value
= $objectiveprogressstatus;
463 $track->timemodified
= time();
464 $id = $DB->insert_record('scorm_scoes_track', $track);
466 if ($objectivesatisfiedstatus) {
467 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
468 'scormid' => $scormid,
470 'attempt' => $attempt,
471 'element' => 'objectivesatisfiedstatus'))) {
472 $track->value
= $objectivesatisfiedstatus;
473 $track->timemodified
= time();
474 $DB->update_record('scorm_scoes_track', $track);
477 $track = new stdClass();
478 $track->userid
= $userid;
479 $track->scormid
= $scormid;
480 $track->scoid
= $scoid;
481 $track->attempt
= $attempt;
482 $track->element
= 'objectivesatisfiedstatus';
483 $track->value
= $objectivesatisfiedstatus;
484 $track->timemodified
= time();
485 $id = $DB->insert_record('scorm_scoes_track', $track);
487 $filepath = $CFG->dataroot
."\\temp\\tempfile.txt";
488 $fh = fopen($filepath, "a+");
490 $string = ob_get_clean();
491 fwrite($fh, $string);
500 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
501 'scormid' => $scormid,
503 'attempt' => $attempt,
504 'element' => $element))) {
505 if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
506 $track->value
= $value;
507 $track->timemodified
= time();
508 $DB->update_record('scorm_scoes_track', $track);
512 $track = new stdClass();
513 $track->userid
= $userid;
514 $track->scormid
= $scormid;
515 $track->scoid
= $scoid;
516 $track->attempt
= $attempt;
517 $track->element
= $element;
518 $track->value
= $value;
519 $track->timemodified
= time();
520 $id = $DB->insert_record('scorm_scoes_track', $track);
523 if (strstr($element, '.score.raw') ||
524 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
525 && in_array($track->value
, array('completed', 'passed')))) {
526 $scorm = $DB->get_record('scorm', array('id' => $scormid));
527 include_once($CFG->dirroot
.'/mod/scorm/lib.php');
528 scorm_update_grades($scorm, $userid);
535 * simple quick function to return true/false if this user has tracks in this scorm
537 * @param integer $scormid The scorm ID
538 * @param integer $userid the users id
539 * @return boolean (false if there are no tracks)
541 function scorm_has_tracks($scormid, $userid) {
543 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
546 function scorm_get_tracks($scoid, $userid, $attempt='') {
547 // Gets all tracks of specified sco and user.
550 if (empty($attempt)) {
551 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
552 $attempt = scorm_get_last_attempt($scormid, $userid);
557 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid,
558 'attempt'=>$attempt), 'element ASC')) {
559 $usertrack = scorm_format_interactions($tracks);
560 $usertrack->userid
= $userid;
561 $usertrack->scoid
= $scoid;
569 * helper function to return a formatted list of interactions for reports.
571 * @param array $trackdata the records from scorm_scoes_track table
572 * @return object formatted list of interactions
574 function scorm_format_interactions($trackdata) {
575 $usertrack = new stdClass();
577 // Defined in order to unify scorm1.2 and scorm2004.
578 $usertrack->score_raw
= '';
579 $usertrack->status
= '';
580 $usertrack->total_time
= '00:00:00';
581 $usertrack->session_time
= '00:00:00';
582 $usertrack->timemodified
= 0;
584 foreach ($trackdata as $track) {
585 $element = $track->element
;
586 $usertrack->{$element} = $track->value
;
588 case 'cmi.core.lesson_status':
589 case 'cmi.completion_status':
590 if ($track->value
== 'not attempted') {
591 $track->value
= 'notattempted';
593 $usertrack->status
= $track->value
;
595 case 'cmi.core.score.raw':
596 case 'cmi.score.raw':
597 $usertrack->score_raw
= (float) sprintf('%2.2f', $track->value
);
599 case 'cmi.core.session_time':
600 case 'cmi.session_time':
601 $usertrack->session_time
= $track->value
;
603 case 'cmi.core.total_time':
604 case 'cmi.total_time':
605 $usertrack->total_time
= $track->value
;
608 if (isset($track->timemodified
) && ($track->timemodified
> $usertrack->timemodified
)) {
609 $usertrack->timemodified
= $track->timemodified
;
615 /* Find the start and finsh time for a a given SCO attempt
617 * @param int $scormid SCORM Id
618 * @param int $scoid SCO Id
619 * @param int $userid User Id
620 * @param int $attemt Attempt Id
622 * @return object start and finsh time EPOC secods
625 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
628 $timedata = new stdClass();
629 $sql = !empty($scoid) ?
"userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
630 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
632 $tracks = array_values($tracks);
636 $timedata->start
= $tracks[0]->timemodified
;
638 $timedata->start
= false;
640 if ($tracks && $track = array_pop($tracks)) {
641 $timedata->finish
= $track->timemodified
;
643 $timedata->finish
= $timedata->start
;
648 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
650 $attemptscore = new stdClass();
651 $attemptscore->scoes
= 0;
652 $attemptscore->values
= 0;
653 $attemptscore->max
= 0;
654 $attemptscore->sum
= 0;
655 $attemptscore->lastmodify
= 0;
657 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id
), 'sortorder, id')) {
661 foreach ($scoes as $sco) {
662 if ($userdata=scorm_get_tracks($sco->id
, $userid, $attempt)) {
663 if (($userdata->status
== 'completed') ||
($userdata->status
== 'passed')) {
664 $attemptscore->scoes++
;
666 if (!empty($userdata->score_raw
) ||
(isset($scorm->type
) && $scorm->type
=='sco' && isset($userdata->score_raw
))) {
667 $attemptscore->values++
;
668 $attemptscore->sum +
= $userdata->score_raw
;
669 $attemptscore->max
= ($userdata->score_raw
> $attemptscore->max
)?
$userdata->score_raw
:$attemptscore->max
;
670 if (isset($userdata->timemodified
) && ($userdata->timemodified
> $attemptscore->lastmodify
)) {
671 $attemptscore->lastmodify
= $userdata->timemodified
;
673 $attemptscore->lastmodify
= 0;
678 switch ($scorm->grademethod
) {
680 $score = (float) $attemptscore->max
;
683 if ($attemptscore->values
> 0) {
684 $score = $attemptscore->sum
/$attemptscore->values
;
690 $score = $attemptscore->sum
;
693 $score = $attemptscore->scoes
;
696 $score = $attemptscore->max
; // Remote Learner GRADEHIGHEST is default
702 function scorm_grade_user($scorm, $userid) {
704 // ensure we dont grade user beyond $scorm->maxattempt settings
705 $lastattempt = scorm_get_last_attempt($scorm->id
, $userid);
706 if ($scorm->maxattempt
!= 0 && $lastattempt >= $scorm->maxattempt
) {
707 $lastattempt = $scorm->maxattempt
;
710 switch ($scorm->whatgrade
) {
712 return scorm_grade_user_attempt($scorm, $userid, 1);
715 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id
, $userid));
719 for ($attempt = 1; $attempt <= $lastattempt; $attempt++
) {
720 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
721 $maxscore = $attemptscore > $maxscore ?
$attemptscore: $maxscore;
727 $attemptcount = scorm_get_attempt_count($userid, $scorm, true, true);
728 if (empty($attemptcount)) {
731 $attemptcount = count($attemptcount);
733 $lastattempt = scorm_get_last_attempt($scorm->id
, $userid);
735 for ($attempt = 1; $attempt <= $lastattempt; $attempt++
) {
736 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
737 $sumscore +
= $attemptscore;
740 return round($sumscore / $attemptcount);
745 function scorm_count_launchable($scormid, $organization='') {
748 $sqlorganization = '';
749 $params = array($scormid);
750 if (!empty($organization)) {
751 $sqlorganization = " AND organization=?";
752 $params[] = $organization;
754 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
758 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
760 * @param int $scormid the id of the scorm.
761 * @param int $userid the id of the user.
763 * @return int The attempt number to use.
765 function scorm_get_last_attempt($scormid, $userid) {
768 /// Find the last attempt number for the given user id and scorm id
769 $sql = "SELECT MAX(attempt)
770 FROM {scorm_scoes_track}
771 WHERE userid = ? AND scormid = ?";
772 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
773 if (empty($lastattempt)) {
781 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
783 * @param int $scormid the id of the scorm.
784 * @param int $userid the id of the user.
786 * @return int The attempt number to use.
788 function scorm_get_last_completed_attempt($scormid, $userid) {
791 /// Find the last completed attempt number for the given user id and scorm id
792 $sql = "SELECT MAX(attempt)
793 FROM {scorm_scoes_track}
794 WHERE userid = ? AND scormid = ?
795 AND (value='completed' OR value='passed')";
796 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
797 if (empty($lastattempt)) {
805 * Returns the full list of attempts a user has made.
807 * @param int $scormid the id of the scorm.
808 * @param int $userid the id of the user.
810 * @return array array of attemptids
812 function scorm_get_all_attempts($scormid, $userid) {
814 $attemptids = array();
815 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
816 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
817 foreach ($attempts as $attempt) {
818 $attemptids[] = $attempt->attempt
;
823 function scorm_view_display ($user, $scorm, $action, $cm) {
824 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
826 if ($scorm->scormtype
!= SCORM_TYPE_LOCAL
&& $scorm->updatefreq
== SCORM_UPDATE_EVERYTIME
) {
827 scorm_parse($scorm, false);
830 $organization = optional_param('organization', '', PARAM_INT
);
832 if ($scorm->displaycoursestructure
== 1) {
833 echo $OUTPUT->box_start('generalbox boxaligncenter toc', 'toc');
835 <div
class="structurehead"><?php
print_string('contents', 'scorm') ?
></div
>
838 if (empty($organization)) {
839 $organization = $scorm->launch
;
841 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
842 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
843 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
844 array($scorm->id
), 'sortorder, id', 'id,title')) {
845 if (count($orgs) > 1) {
846 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
847 $select->label
= get_string('organizations', 'scorm');
848 $select->class = 'scorm-center';
849 echo $OUTPUT->render($select);
853 if ($sco = scorm_get_sco($organization, SCO_ONLY
)) {
854 if (($sco->organization
== '') && ($sco->launch
== '')) {
855 $orgidentifier = $sco->identifier
;
857 $orgidentifier = $sco->organization
;
861 $scorm->version
= strtolower(clean_param($scorm->version
, PARAM_SAFEDIR
)); // Just to be safe
862 if (!file_exists($CFG->dirroot
.'/mod/scorm/datamodels/'.$scorm->version
.'lib.php')) {
863 $scorm->version
= 'scorm_12';
865 require_once($CFG->dirroot
.'/mod/scorm/datamodels/'.$scorm->version
.'lib.php');
867 $result = scorm_get_toc($user, $scorm, $cm->id
, TOCFULLURL
, $orgidentifier);
868 $incomplete = $result->incomplete
;
870 // do we want the TOC to be displayed?
871 if ($scorm->displaycoursestructure
== 1) {
873 echo $OUTPUT->box_end();
876 // is this the first attempt ?
877 $attemptcount = scorm_get_attempt_count($user->id
, $scorm);
879 // do not give the player launch FORM if the SCORM object is locked after the final attempt
880 if ($scorm->lastattemptlock
== 0 ||
$result->attemptleft
> 0) {
882 <div
class="scorm-center">
883 <form id
="scormviewform" method
="post" action
="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
885 if ($scorm->hidebrowse
== 0) {
886 print_string('mode', 'scorm');
887 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
888 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
890 echo '<input type="hidden" name="mode" value="normal" />'."\n";
892 if ($scorm->forcenewattempt
== 1) {
893 if ($incomplete === false) {
894 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
896 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft
> 0)||
($scorm->maxattempt
== 0))) {
899 <input type
="checkbox" id
="a" name
="newattempt" />
900 <label
for="a"><?php
print_string('newattempt', 'scorm') ?
></label
>
903 if (!empty($scorm->popup
)) {
904 echo '<input type="hidden" name="display" value="popup" />'."\n";
908 <input type
="hidden" name
="scoid" value
="<?php echo $scorm->launch ?>" />
909 <input type
="hidden" name
="cm" value
="<?php echo $cm->id ?>"/>
910 <input type
="hidden" name
="currentorg" value
="<?php echo $orgidentifier ?>" />
911 <input type
="submit" value
="<?php print_string('enter', 'scorm') ?>" />
918 function scorm_simple_play($scorm, $user, $context, $cmid) {
923 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
927 if ($scorm->scormtype
!= SCORM_TYPE_LOCAL
&& $scorm->updatefreq
== SCORM_UPDATE_EVERYTIME
) {
928 scorm_parse($scorm, false);
930 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
931 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id
), 'sortorder, id', 'id');
935 if ($sco = scorm_get_sco($scorm->launch
, SCO_ONLY
)) {
936 if (($sco->organization
== '') && ($sco->launch
== '')) {
937 $orgidentifier = $sco->identifier
;
939 $orgidentifier = $sco->organization
;
942 if ($scorm->skipview
>= SCORM_SKIPVIEW_FIRST
) {
943 $sco = current($scoes);
944 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id
,
945 'currentorg'=>$orgidentifier,
947 if ($scorm->skipview
== SCORM_SKIPVIEW_ALWAYS ||
!scorm_has_tracks($scorm->id
, $user->id
)) {
948 if (!empty($scorm->forcenewattempt
)) {
949 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL
, $orgidentifier);
950 if ($result->incomplete
=== false) {
951 $url->param('newattempt','on');
961 function scorm_get_count_users($scormid, $groupingid=null) {
964 if (!empty($groupingid)) {
965 $sql = "SELECT COUNT(DISTINCT st.userid)
966 FROM {scorm_scoes_track} st
967 INNER JOIN {groups_members} gm ON st.userid = gm.userid
968 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
969 WHERE st.scormid = ? AND gg.groupingid = ?
971 $params = array($scormid, $groupingid);
973 $sql = "SELECT COUNT(DISTINCT st.userid)
974 FROM {scorm_scoes_track} st
977 $params = array($scormid);
980 return ($DB->count_records_sql($sql, $params));
984 * Build up the JavaScript representation of an array element
986 * @param string $sversion SCORM API version
987 * @param array $userdata User track data
988 * @param string $element_name Name of array element to get values for
989 * @param array $children list of sub elements of this array element that also need instantiating
992 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
993 // reconstitute comments_from_learner and comments_from_lms
995 $current_subelement = '';
999 $scormseperator = '_';
1000 if (scorm_version_check($sversion, SCORM_13
)) { //scorm 1.3 elements use a . instead of an _
1001 $scormseperator = '.';
1003 // filter out the ones we want
1004 $element_list = array();
1005 foreach ($userdata as $element => $value) {
1006 if (substr($element, 0, strlen($element_name)) == $element_name) {
1007 $element_list[$element] = $value;
1011 // sort elements in .n array order
1012 uksort($element_list, "scorm_element_cmp");
1014 // generate JavaScript
1015 foreach ($element_list as $element => $value) {
1016 if (scorm_version_check($sversion, SCORM_13
)) {
1017 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
1018 preg_match('/\.(N\d+)\./', $element, $matches);
1020 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
1021 preg_match('/\_(\d+)\./', $element, $matches);
1023 if (count($matches) > 0 && $current != $matches[1]) {
1024 if ($count_sub > 0) {
1025 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1027 $current = $matches[1];
1029 $current_subelement = '';
1032 $end = strpos($element, $matches[1])+
strlen($matches[1]);
1033 $subelement = substr($element, 0, $end);
1034 echo ' '.$subelement." = new Object();\n";
1035 // now add the children
1036 foreach ($children as $child) {
1037 echo ' '.$subelement.".".$child." = new Object();\n";
1038 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
1042 // now - flesh out the second level elements if there are any
1043 if (scorm_version_check($sversion, SCORM_13
)) {
1044 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1045 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1047 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1048 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1051 // check the sub element type
1052 if (count($matches) > 0 && $current_subelement != $matches[1]) {
1053 if ($count_sub > 0) {
1054 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1056 $current_subelement = $matches[1];
1059 $end = strpos($element, $matches[1])+
strlen($matches[1]);
1060 $subelement = substr($element, 0, $end);
1061 echo ' '.$subelement." = new Object();\n";
1064 // now check the subelement subscript
1065 if (count($matches) > 0 && $current_sub != $matches[2]) {
1066 $current_sub = $matches[2];
1068 $end = strrpos($element, $matches[2])+
strlen($matches[2]);
1069 $subelement = substr($element, 0, $end);
1070 echo ' '.$subelement." = new Object();\n";
1073 echo ' '.$element.' = \''.$value."';\n";
1075 if ($count_sub > 0) {
1076 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1079 echo ' '.$element_name.'._count = '.$count.";\n";
1084 * Build up the JavaScript representation of an array element
1086 * @param string $a left array element
1087 * @param string $b right array element
1088 * @return comparator - 0,1,-1
1090 function scorm_element_cmp($a, $b) {
1091 preg_match('/.*?(\d+)\./', $a, $matches);
1092 $left = intval($matches[1]);
1093 preg_match('/.?(\d+)\./', $b, $matches);
1094 $right = intval($matches[1]);
1095 if ($left < $right) {
1096 return -1; // smaller
1097 } else if ($left > $right) {
1100 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1101 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1102 $leftterm = intval($matches[2]);
1103 $left = intval($matches[3]);
1104 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1105 $rightterm = intval($matches[2]);
1106 $right = intval($matches[3]);
1107 if ($leftterm < $rightterm) {
1108 return -1; // smaller
1109 } else if ($leftterm > $rightterm) {
1112 if ($left < $right) {
1113 return -1; // smaller
1114 } else if ($left > $right) {
1120 // fall back for no second level matches or second level matches are equal
1121 return 0; // equal to
1126 * Generate the user attempt status string
1128 * @param object $user Current context user
1129 * @param object $scorm a moodle scrom object - mdl_scorm
1130 * @return string - Attempt status string
1132 function scorm_get_attempt_status($user, $scorm, $cm='') {
1133 global $DB, $PAGE, $OUTPUT;
1135 $attempts = scorm_get_attempt_count($user->id
, $scorm, true);
1136 if (empty($attempts)) {
1139 $attemptcount = count($attempts);
1142 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1143 if ($scorm->maxattempt
> 0) {
1144 $result .= $scorm->maxattempt
. '<br />';
1146 $result .= get_string('unlimited').'<br />';
1148 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1150 if ($scorm->maxattempt
== 1) {
1151 switch ($scorm->grademethod
) {
1153 $grademethod = get_string('gradehighest', 'scorm');
1156 $grademethod = get_string('gradeaverage', 'scorm');
1159 $grademethod = get_string('gradesum', 'scorm');
1162 $grademethod = get_string('gradescoes', 'scorm');
1166 switch ($scorm->whatgrade
) {
1167 case HIGHESTATTEMPT
:
1168 $grademethod = get_string('highestattempt', 'scorm');
1170 case AVERAGEATTEMPT
:
1171 $grademethod = get_string('averageattempt', 'scorm');
1174 $grademethod = get_string('firstattempt', 'scorm');
1177 $grademethod = get_string('lastattempt', 'scorm');
1182 if (!empty($attempts)) {
1184 foreach ($attempts as $attempt) {
1185 $gradereported = scorm_grade_user_attempt($scorm, $user->id
, $attempt->attemptnumber
);
1186 if ($scorm->grademethod
!== GRADESCOES
&& !empty($scorm->maxgrade
)) {
1187 $gradereported = $gradereported/$scorm->maxgrade
;
1188 $gradereported = number_format($gradereported*100, 0) .'%';
1190 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1194 $calculatedgrade = scorm_grade_user($scorm, $user->id
);
1195 if ($scorm->grademethod
!== GRADESCOES
&& !empty($scorm->maxgrade
)) {
1196 $calculatedgrade = $calculatedgrade/$scorm->maxgrade
;
1197 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1199 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1200 if (empty($attempts)) {
1201 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1203 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1206 if ($attemptcount >= $scorm->maxattempt
and $scorm->maxattempt
> 0) {
1207 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1210 $context = context_module
::instance($cm->id
);
1211 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1212 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id
, 'scormid' => $scorm->id
))) {
1213 //check to see if any data is stored for this user:
1214 $deleteurl = new moodle_url($PAGE->url
, array('action'=>'delete', 'sesskey' => sesskey()));
1215 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1224 * Get SCORM attempt count
1226 * @param object $user Current context user
1227 * @param object $scorm a moodle scrom object - mdl_scorm
1228 * @param bool $returnobjects if true returns a object with attempts, if false returns count of attempts.
1229 * @param bool $ignoremissingcompletion - ignores attempts that haven't reported a grade/completion.
1230 * @return int - no. of attempts so far
1232 function scorm_get_attempt_count($userid, $scorm, $returnobjects = false, $ignoremissingcompletion = false) {
1235 // Historically attempts that don't report these elements haven't been included in the average attempts grading method
1236 // we may want to change this in future, but to avoid unexpected grade decreases we're leaving this in. MDL-43222
1237 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1238 $element = 'cmi.score.raw';
1239 } else if ($scorm->grademethod
== GRADESCOES
) {
1240 $element = 'cmi.core.lesson_status';
1242 $element = 'cmi.core.score.raw';
1245 if ($returnobjects) {
1246 $params = array('userid' => $userid, 'scormid' => $scorm->id
);
1247 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1248 $params['element'] = $element;
1250 $attempts = $DB->get_records('scorm_scoes_track', $params, 'attempt', 'DISTINCT attempt AS attemptnumber');
1253 $params = array($userid, $scorm->id
);
1254 $sql = "SELECT COUNT(DISTINCT attempt)
1255 FROM {scorm_scoes_track}
1256 WHERE userid = ? AND scormid = ?";
1257 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1258 $sql .= ' AND element = ?';
1259 $params[] = $element;
1262 $attemptscount = $DB->count_records_sql($sql, $params);
1263 return $attemptscount;
1268 * Figure out with this is a debug situation
1270 * @param object $scorm a moodle scrom object - mdl_scorm
1271 * @return boolean - debugging true/false
1273 function scorm_debugging($scorm) {
1275 $cfg_scorm = get_config('scorm');
1277 if (!$cfg_scorm->allowapidebug
) {
1280 $identifier = $USER->username
.':'.$scorm->name
;
1281 $test = $cfg_scorm->apidebugmask
;
1282 // check the regex is only a short list of safe characters
1283 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1287 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1292 * Delete Scorm tracks for selected users
1294 * @param array $attemptids list of attempts that need to be deleted
1295 * @param stdClass $scorm instance
1297 * @return bool true deleted all responses, false failed deleting an attempt - stopped here
1299 function scorm_delete_responses($attemptids, $scorm) {
1300 if (!is_array($attemptids) ||
empty($attemptids)) {
1304 foreach ($attemptids as $num => $attemptid) {
1305 if (empty($attemptid)) {
1306 unset($attemptids[$num]);
1310 foreach ($attemptids as $attempt) {
1311 $keys = explode(':', $attempt);
1312 if (count($keys) == 2) {
1313 $userid = clean_param($keys[0], PARAM_INT
);
1314 $attemptid = clean_param($keys[1], PARAM_INT
);
1315 if (!$userid ||
!$attemptid ||
!scorm_delete_attempt($userid, $scorm, $attemptid)) {
1326 * Delete Scorm tracks for selected users
1328 * @param int $userid ID of User
1329 * @param stdClass $scorm Scorm object
1330 * @param int $attemptid user attempt that need to be deleted
1332 * @return bool true suceeded
1334 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1337 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id
, 'attempt' => $attemptid));
1338 $cm = get_coursemodule_from_instance('scorm', $scorm->id
);
1340 // Trigger instances list viewed event.
1341 $event = \mod_scorm\event\attempt_deleted
::create(array(
1342 'other' => array('attemptid' => $attemptid),
1343 'context' => context_module
::instance($cm->id
),
1344 'relateduserid' => $userid
1346 $event->add_record_snapshot('course_modules', $cm);
1347 $event->add_record_snapshot('scorm', $scorm);
1350 include_once('lib.php');
1351 scorm_update_grades($scorm, $userid, true);
1356 * Converts SCORM duration notation to human-readable format
1357 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1358 * @param $duration string SCORM duration
1359 * @return string human-readable date/time
1361 function scorm_format_duration($duration) {
1362 // fetch date/time strings
1363 $stryears = get_string('years');
1364 $strmonths = get_string('nummonths');
1365 $strdays = get_string('days');
1366 $strhours = get_string('hours');
1367 $strminutes = get_string('minutes');
1368 $strseconds = get_string('seconds');
1370 if ($duration[0] == 'P') {
1371 // if timestamp starts with 'P' - it's a SCORM 2004 format
1372 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1373 // and outputs filled sections, discarding leading zeroes and any format literals
1374 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1375 $pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#', '#0*(\d+)Y#', '#0*(\d+)D#', '#P#',
1376 '#([A-Z])0+H#', '#([A-Z])[0.]+S#', '#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
1377 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1378 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1380 // else we have SCORM 1.2 format there
1381 // first convert the timestamp to some SCORM 2004-like format for conveniency
1382 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1383 // then convert in the same way as SCORM 2004
1384 $pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#', '#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
1385 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1388 $result = preg_replace($pattern, $replace, $duration);
1393 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1394 global $CFG, $DB, $PAGE, $OUTPUT;
1397 if ($mode != 'normal') {
1398 $modestr = '&mode='.$mode;
1402 $incomplete = false;
1404 if (!empty($organizationsco)) {
1405 $result[0] = $organizationsco;
1406 $result[0]->isvisible
= true;
1407 $result[0]->statusicon
= '';
1408 $result[0]->url
= '';
1411 if ($scoes = scorm_get_scoes($scorm->id
, $currentorg)){
1412 // Retrieve user tracking data for each learning object.
1413 $usertracks = array();
1414 foreach ($scoes as $sco) {
1415 if (!empty($sco->launch
)) {
1416 if ($usertrack = scorm_get_tracks($sco->id
, $user->id
, $attempt)) {
1417 if ($usertrack->status
== '') {
1418 $usertrack->status
= 'notattempted';
1420 $usertracks[$sco->identifier
] = $usertrack;
1424 foreach ($scoes as $sco) {
1425 if (!isset($sco->isvisible
)) {
1426 $sco->isvisible
= true;
1429 if (empty($sco->title
)) {
1430 $sco->title
= $sco->identifier
;
1433 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1434 $sco->prereq
= true;
1436 $sco->prereq
= empty($sco->prerequisites
) ||
scorm_eval_prerequisites($sco->prerequisites
, $usertracks);
1439 if ($sco->isvisible
) {
1440 if (!empty($sco->launch
)) {
1441 if (empty($scoid) && ($mode != 'normal')) {
1445 if (isset($usertracks[$sco->identifier
])) {
1446 $usertrack = $usertracks[$sco->identifier
];
1447 $strstatus = get_string($usertrack->status
,'scorm');
1449 if ($sco->scormtype
== 'sco') {
1450 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status
, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1452 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1455 if (($usertrack->status
== 'notattempted') ||
($usertrack->status
== 'incomplete') ||
($usertrack->status
== 'browsed')) {
1457 if ($play && empty($scoid)) {
1462 $strsuspended = get_string('suspended', 'scorm');
1464 $exitvar = 'cmi.core.exit';
1466 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1467 $exitvar = 'cmi.exit';
1470 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1471 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1475 if ($play && empty($scoid)) {
1481 if ($sco->scormtype
== 'sco') {
1482 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1484 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1490 if (empty($statusicon)) {
1491 $sco->statusicon
= '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1493 $sco->statusicon
= $statusicon;
1496 $sco->url
= 'a='.$scorm->id
.'&scoid='.$sco->id
.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
1497 $sco->incomplete
= $incomplete;
1499 if (!in_array($sco->id
, array_keys($result))) {
1500 $result[$sco->id
] = $sco;
1505 // Get the parent scoes!
1506 $result = scorm_get_toc_get_parent_child($result, $currentorg);
1508 // Be safe, prevent warnings from showing up while returning array
1509 if (!isset($scoid)) {
1513 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1516 function scorm_get_toc_get_parent_child(&$result, $currentorg) {
1519 // Organization is always the root, prevparent.
1520 if (!empty($currentorg)) {
1521 $prevparent = $currentorg;
1526 foreach ($result as $sco) {
1527 if ($sco->parent
== '/') {
1528 $final[$level][$sco->identifier
] = $sco;
1529 $prevparent = $sco->identifier
;
1530 unset($result[$sco->id
]);
1532 if ($sco->parent
== $prevparent) {
1533 $final[$level][$sco->identifier
] = $sco;
1534 $prevparent = $sco->identifier
;
1535 unset($result[$sco->id
]);
1537 if (!empty($final[$level])) {
1539 foreach ($final[$level] as $fin) {
1540 if ($sco->parent
== $fin->identifier
) {
1546 $final[$level][$sco->identifier
] = $sco;
1547 unset($result[$sco->id
]);
1551 $final[$level][$sco->identifier
] = $sco;
1552 unset($result[$sco->id
]);
1559 for ($i = 0; $i <= $level; $i++
) {
1561 foreach ($final[$i] as $ident => $sco) {
1562 if (empty($prevparent)) {
1563 $prevparent = $ident;
1565 if (!isset($final[$i][$prevparent]->children
)) {
1566 $final[$i][$prevparent]->children
= array();
1568 if ($sco->parent
== $prevparent) {
1569 $final[$i][$prevparent]->children
[] = $sco;
1570 $prevparent = $ident;
1573 foreach ($final[$i] as $identifier => $scoobj) {
1574 if ($identifier == $sco->parent
) {
1575 $parent = $identifier;
1579 if ($parent !== false) {
1580 $final[$i][$parent]->children
[] = $sco;
1587 for ($i = 0; $i <= $level; $i++
) {
1588 $keys = array_keys($final[$i]);
1589 $results[] = $final[$i][$keys[0]];
1595 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK
, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1598 $result = new stdClass();
1599 $result->prerequisites
= true;
1600 $result->incomplete
= true;
1604 $attemptsmade = scorm_get_attempt_count($user->id
, $scorm);
1605 $result->attemptleft
= $scorm->maxattempt
== 0 ?
1 : $scorm->maxattempt
- $attemptsmade;
1609 $result->toc
= "<ul>\n";
1611 if (!$play && !empty($organizationsco)) {
1612 $result->toc
.= "\t<li>".$organizationsco->title
."</li>\n";
1617 if (!empty($scoes)) {
1618 foreach ($scoes as $sco) {
1619 $result->toc
.= "\t<li>\n";
1622 $sco->isvisible
= true;
1624 if ($sco->isvisible
) {
1627 if (isset($usertracks[$sco->identifier
])) {
1628 $viewscore = has_capability('mod/scorm:viewscores', context_module
::instance($cmid));
1629 if (isset($usertracks[$sco->identifier
]->score_raw
) && $viewscore) {
1630 if ($usertracks[$sco->identifier
]->score_raw
!= '') {
1631 $score = '('.get_string('score','scorm').': '.$usertracks[$sco->identifier
]->score_raw
.')';
1636 if (!empty($sco->prereq
)) {
1637 if ($sco->id
== $scoid) {
1638 $result->prerequisites
= true;
1641 if (!empty($prevsco) && scorm_version_check($scorm->version
, SCORM_13
) && !empty($prevsco->hidecontinue
)) {
1642 if ($sco->scormtype
== 'sco') {
1643 $result->toc
.= '<span>'.$sco->statusicon
.' '.format_string($sco->title
).'</span>';
1645 $result->toc
.= '<span> '.format_string($sco->title
).'</span>';
1647 } else if ($toclink == TOCFULLURL
) {
1648 $url = $CFG->wwwroot
.'/mod/scorm/player.php?'.$sco->url
;
1649 if (!empty($sco->launch
)) {
1650 if ($sco->scormtype
== 'sco') {
1651 $result->toc
.= $sco->statusicon
.' <a href="'.$url.'">'.format_string($sco->title
).'</a>'.$score."\n";
1653 $result->toc
.= ' <a data-scoid="'.$sco->id
.'" href="'.$url.'">'.format_string($sco->title
).'</a>'.$score."\n";
1656 if ($sco->scormtype
== 'sco') {
1657 $result->toc
.= $sco->statusicon
.' '.format_string($sco->title
).$score."\n";
1659 $result->toc
.= ' '.format_string($sco->title
).$score."\n";
1663 if (!empty($sco->launch
)) {
1664 if ($sco->scormtype
== 'sco') {
1665 $result->toc
.= '<a data-scoid="'.$sco->id
.'" title="'.$sco->url
.'">'.$sco->statusicon
.' '.format_string($sco->title
).' '.$score.'</a>';
1667 $result->toc
.= '<a data-scoid="'.$sco->id
.'" title="'.$sco->url
.'"> '.format_string($sco->title
).' '.$score.'</a>';
1670 if ($sco->scormtype
== 'sco') {
1671 $result->toc
.= '<span>'.$sco->statusicon
.' '.format_string($sco->title
).'</span>';
1673 $result->toc
.= '<span> '.format_string($sco->title
).'</span>';
1680 if ($sco->scormtype
== 'sco') {
1681 $result->toc
.= '<span>'.$sco->statusicon
.' '.format_string($sco->title
).'</span>';
1683 $result->toc
.= ' '.format_string($sco->title
).'</span>';
1686 if ($sco->scormtype
== 'sco') {
1687 $result->toc
.= $sco->statusicon
.' '.format_string($sco->title
)."\n";
1689 $result->toc
.= ' '.format_string($sco->title
)."\n";
1695 $result->toc
.= "\t\t ".format_string($sco->title
)."\n";
1698 if (!empty($sco->children
)) {
1699 $result->toc
.= "\n\t\t<ul>\n";
1700 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children
, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1701 $result->toc
.= $childresult->toc
;
1702 $result->toc
.= "\t\t</ul>\n";
1703 $result->toc
.= "\t</li>\n";
1705 $result->toc
.= "\t</li>\n";
1709 $result->incomplete
= $sco->incomplete
;
1713 $result->toc
.= "</ul>\n";
1719 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1720 if (!empty($scoes)) {
1721 if (!empty($organizationsco) && !$children) {
1722 $tocmenus[$organizationsco->id
] = $organizationsco->title
;
1725 $parents[$level]='/';
1726 foreach ($scoes as $sco) {
1727 if ($parents[$level] != $sco->parent
) {
1728 if ($newlevel = array_search($sco->parent
, $parents)) {
1732 while (($i > 0) && ($parents[$level] != $sco->parent
)) {
1736 if (($i == 0) && ($sco->parent
!= $currentorg)) {
1742 $parents[$level] = $sco->parent
;
1747 if ($sco->scormtype
== 'sco') {
1748 $tocmenus[$sco->id
] = scorm_repeater('−', $level) . '>' . format_string($sco->title
);
1751 if ($sco->scormtype
== 'sco') {
1752 $tocmenus[$sco->id
] = scorm_repeater('−', $level) . '>' . format_string($sco->title
);
1756 if (!empty($sco->children
)) {
1757 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children
, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1765 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK
, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1766 global $CFG, $DB, $OUTPUT;
1768 if (empty($attempt)) {
1769 $attempt = scorm_get_last_attempt($scorm->id
, $user->id
);
1772 $result = new stdClass();
1773 $organizationsco = null;
1776 $result->toc
= "<div id=\"scorm_layout\" class=\"yui3-g-r\">\n";
1777 $result->toc
.= "<div id=\"scorm_toc\" class=\"yui3-u-1-5\">\n";
1778 $result->toc
.= "<div id=\"scorm_toc_title\"></div>\n";
1779 $result->toc
.= "<div id=\"scorm_tree\">\n";
1782 if (!empty($currentorg)) {
1783 $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id
, 'identifier'=>$currentorg));
1784 if (!empty($organizationsco->title
)) {
1786 $result->toctitle
= $organizationsco->title
;
1791 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1793 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children
, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1796 $result->toc
.= $treeview->toc
;
1798 $result->toc
= $treeview->toc
;
1801 if (!empty($scoes['scoid'])) {
1802 $scoid = $scoes['scoid'];
1805 if (empty($scoid)) {
1806 $result->sco
= $scoes['scoes'][0]->children
[0];
1808 $result->sco
= scorm_get_sco($scoid);
1811 if ($scorm->hidetoc
== SCORM_TOC_POPUP
) {
1812 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children
, $scoes['usertracks'], $currentorg, $organizationsco);
1815 if ($mode != 'normal') {
1816 $modestr = '&mode='.$mode;
1819 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id
.'¤torg='.$currentorg.$modestr);
1820 $result->tocmenu
= $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco
->id
, null, "tocmenu");
1823 $result->prerequisites
= $treeview->prerequisites
;
1824 $result->incomplete
= $treeview->incomplete
;
1825 $result->attemptleft
= $treeview->attemptleft
;
1828 $result->toc
.= "</div></div>\n";
1829 $result->toc
.= "<div id=\"scorm_toc_toggle\">\n";
1830 $result->toc
.= "<button id=\"scorm_toc_toggle_btn\"></button></div>\n";
1831 $result->toc
.= "<div id=\"scorm_content\">";
1832 $result->toc
.= "<div id=\"scorm_navpanel\"></div>\n";
1833 $result->toc
.= "</div></div>\n";
1839 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1840 if (is_object($scoes)) {
1842 if (isset($sco->url
)) {
1843 $adlnav[$sco->id
]['identifier'] = $sco->identifier
;
1844 $adlnav[$sco->id
]['launch'] = $sco->launch
;
1845 $adlnav[$sco->id
]['title'] = $sco->title
;
1846 $adlnav[$sco->id
]['url'] = $sco->url
;
1847 $adlnav[$sco->id
]['parent'] = $sco->parent
;
1848 if (isset($sco->choice
)) {
1849 $adlnav[$sco->id
]['choice'] = $sco->choice
;
1851 if (isset($sco->flow
)) {
1852 $adlnav[$sco->id
]['flow'] = $sco->flow
;
1853 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1854 $adlnav[$sco->id
]['flow'] = $adlnav[$parentscoid]['flow'];
1856 if (isset($sco->isvisible
)) {
1857 $adlnav[$sco->id
]['isvisible'] = $sco->isvisible
;
1859 if (isset($sco->parameters
)) {
1860 $adlnav[$sco->id
]['parameters'] = $sco->parameters
;
1862 if (isset($sco->hidecontinue
)) {
1863 $adlnav[$sco->id
]['hidecontinue'] = $sco->hidecontinue
;
1865 if (isset($sco->hideprevious
)) {
1866 $adlnav[$sco->id
]['hideprevious'] = $sco->hideprevious
;
1868 if (isset($sco->hidesuspendall
)) {
1869 $adlnav[$sco->id
]['hidesuspendall'] = $sco->hidesuspendall
;
1871 if (!empty($parentscoid)) {
1872 $adlnav[$sco->id
]['parentscoid'] = $parentscoid;
1874 if (isset($adlnav['prevscoid'])) {
1875 $adlnav[$sco->id
]['prevscoid'] = $adlnav['prevscoid'];
1876 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id
;
1877 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent
) {
1878 $adlnav[$sco->id
]['prevsibling'] = $adlnav['prevscoid'];
1879 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id
;
1882 $adlnav['prevscoid'] = $sco->id
;
1883 $adlnav['prevparent'] = $sco->parent
;
1885 if (isset($sco->children
)) {
1886 foreach ($sco->children
as $children) {
1887 scorm_get_adlnav_json($children, $adlnav, $sco->id
);
1891 foreach ($scoes as $sco) {
1892 scorm_get_adlnav_json ($sco, $adlnav);
1894 unset($adlnav['prevscoid']);
1895 unset($adlnav['prevparent']);
1897 return json_encode($adlnav);
1901 * Check for the availability of a resource by URL.
1903 * Check is performed using an HTTP HEAD call.
1905 * @param $url string A valid URL
1906 * @return bool|string True if no issue is found. The error string message, otherwise
1908 function scorm_check_url($url) {
1910 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1911 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1912 $cmsg = $curl->head($url);
1913 $info = $curl->get_info();
1914 if (empty($info['http_code']) ||
$info['http_code'] != 200) {
1915 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));