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/>.
17 require_once("$CFG->dirroot/mod/scorm/lib.php");
18 require_once("$CFG->libdir/filelib.php");
20 /// Constants and settings for module scorm
21 define('SCORM_UPDATE_NEVER', '0');
22 define('SCORM_UPDATE_EVERYDAY', '2');
23 define('SCORM_UPDATE_EVERYTIME', '3');
25 define('SCORM_SKIPVIEW_NEVER', '0');
26 define('SCORM_SKIPVIEW_FIRST', '1');
27 define('SCORM_SKIPVIEW_ALWAYS', '2');
30 define('SCO_DATA', 1);
31 define('SCO_ONLY', 2);
33 define('GRADESCOES', '0');
34 define('GRADEHIGHEST', '1');
35 define('GRADEAVERAGE', '2');
36 define('GRADESUM', '3');
38 define('HIGHESTATTEMPT', '0');
39 define('AVERAGEATTEMPT', '1');
40 define('FIRSTATTEMPT', '2');
41 define('LASTATTEMPT', '3');
43 define('TOCJSLINK', 1);
44 define('TOCFULLURL', 2);
46 /// Local Library of functions for module scorm
50 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class scorm_package_file_info
extends file_info_stored
{
54 public function get_parent() {
55 if ($this->lf
->get_filepath() === '/' and $this->lf
->get_filename() === '.') {
56 return $this->browser
->get_file_info($this->context
);
58 return parent
::get_parent();
60 public function get_visible_name() {
61 if ($this->lf
->get_filepath() === '/' and $this->lf
->get_filename() === '.') {
62 return $this->topvisiblename
;
64 return parent
::get_visible_name();
69 * Returns an array of the popup options for SCORM and each options default value
71 * @return array an array of popup options as the key and their defaults as the value
73 function scorm_get_popup_options_array() {
74 $cfgscorm = get_config('scorm');
76 return array('scrollbars'=> isset($cfgscorm->scrollbars
) ?
$cfgscorm->scrollbars
: 0,
77 'directories'=> isset($cfgscorm->directories
) ?
$cfgscorm->directories
: 0,
78 'location'=> isset($cfgscorm->location
) ?
$cfgscorm->location
: 0,
79 'menubar'=> isset($cfgscorm->menubar
) ?
$cfgscorm->menubar
: 0,
80 'toolbar'=> isset($cfgscorm->toolbar
) ?
$cfgscorm->toolbar
: 0,
81 'status'=> isset($cfgscorm->status
) ?
$cfgscorm->status
: 0);
85 * Returns an array of the array of what grade options
87 * @return array an array of what grade options
89 function scorm_get_grade_method_array() {
90 return array (GRADESCOES
=> get_string('gradescoes', 'scorm'),
91 GRADEHIGHEST
=> get_string('gradehighest', 'scorm'),
92 GRADEAVERAGE
=> get_string('gradeaverage', 'scorm'),
93 GRADESUM
=> get_string('gradesum', 'scorm'));
97 * Returns an array of the array of what grade options
99 * @return array an array of what grade options
101 function scorm_get_what_grade_array() {
102 return array (HIGHESTATTEMPT
=> get_string('highestattempt', 'scorm'),
103 AVERAGEATTEMPT
=> get_string('averageattempt', 'scorm'),
104 FIRSTATTEMPT
=> get_string('firstattempt', 'scorm'),
105 LASTATTEMPT
=> get_string('lastattempt', 'scorm'));
109 * Returns an array of the array of skip view options
111 * @return array an array of skip view options
113 function scorm_get_skip_view_array() {
114 return array(SCORM_SKIPVIEW_NEVER
=> get_string('never'),
115 SCORM_SKIPVIEW_FIRST
=> get_string('firstaccess', 'scorm'),
116 SCORM_SKIPVIEW_ALWAYS
=> get_string('always'));
120 * Returns an array of the array of hide table of contents options
122 * @return array an array of hide table of contents options
124 function scorm_get_hidetoc_array() {
125 return array(SCORM_TOC_SIDE
=> get_string('sided', 'scorm'),
126 SCORM_TOC_HIDDEN
=> get_string('hidden', 'scorm'),
127 SCORM_TOC_POPUP
=> get_string('popupmenu', 'scorm'),
128 SCORM_TOC_DISABLED
=> get_string('disabled', 'scorm'));
132 * Returns an array of the array of update frequency options
134 * @return array an array of update frequency options
136 function scorm_get_updatefreq_array() {
137 return array(SCORM_UPDATE_NEVER
=> get_string('never'),
138 SCORM_UPDATE_EVERYDAY
=> get_string('everyday', 'scorm'),
139 SCORM_UPDATE_EVERYTIME
=> get_string('everytime', 'scorm'));
143 * Returns an array of the array of popup display options
145 * @return array an array of popup display options
147 function scorm_get_popup_display_array() {
148 return array(0 => get_string('currentwindow', 'scorm'),
149 1 => get_string('popup', 'scorm'));
153 * Returns an array of the array of navigation buttons display options
155 * @return array an array of navigation buttons display options
157 function scorm_get_navigation_display_array() {
158 return array(SCORM_NAV_DISABLED
=> get_string('no'),
159 SCORM_NAV_UNDER_CONTENT
=> get_string('undercontent', 'scorm'),
160 SCORM_NAV_FLOATING
=> get_string('floating', 'scorm'));
164 * Returns an array of the array of attempt options
166 * @return array an array of attempt options
168 function scorm_get_attempts_array() {
169 $attempts = array(0 => get_string('nolimit', 'scorm'),
170 1 => get_string('attempt1', 'scorm'));
172 for ($i=2; $i<=6; $i++
) {
173 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
180 * Returns an array of the attempt status options
182 * @return array an array of attempt status options
184 function scorm_get_attemptstatus_array() {
185 return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO
=> get_string('no'),
186 SCORM_DISPLAY_ATTEMPTSTATUS_ALL
=> get_string('attemptstatusall', 'scorm'),
187 SCORM_DISPLAY_ATTEMPTSTATUS_MY
=> get_string('attemptstatusmy', 'scorm'),
188 SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY
=> get_string('attemptstatusentry', 'scorm'));
192 * Extracts scrom package, sets up all variables.
193 * Called whenever scorm changes
194 * @param object $scorm instance - fields are updated and changes saved into database
195 * @param bool $full force full update if true
198 function scorm_parse($scorm, $full) {
200 $cfg_scorm = get_config('scorm');
202 if (!isset($scorm->cmid
)) {
203 $cm = get_coursemodule_from_instance('scorm', $scorm->id
);
204 $scorm->cmid
= $cm->id
;
206 $context = context_module
::instance($scorm->cmid
);
207 $newhash = $scorm->sha1hash
;
209 if ($scorm->scormtype
=== SCORM_TYPE_LOCAL
or $scorm->scormtype
=== SCORM_TYPE_LOCALSYNC
) {
211 $fs = get_file_storage();
212 $packagefile = false;
213 $packagefileimsmanifest = false;
215 if ($scorm->scormtype
=== SCORM_TYPE_LOCAL
) {
216 if ($packagefile = $fs->get_file($context->id
, 'mod_scorm', 'package', 0, '/', $scorm->reference
)) {
217 if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
218 $packagefile->import_external_file_contents();
220 $newhash = $packagefile->get_contenthash();
221 if (strtolower($packagefile->get_filename()) == 'imsmanifest.xml') {
222 $packagefileimsmanifest = true;
228 if (!$cfg_scorm->allowtypelocalsync
) {
229 // sorry - localsync disabled
232 if ($scorm->reference
!== '' and (!$full or $scorm->sha1hash
!== sha1($scorm->reference
))) {
233 $fs->delete_area_files($context->id
, 'mod_scorm', 'package');
234 $file_record = array('contextid'=>$context->id
, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
235 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference
, array('calctimeout' => true))) {
236 $newhash = sha1($scorm->reference
);
244 if (!$full and $packagefile and $scorm->sha1hash
=== $newhash) {
245 if (strpos($scorm->version
, 'SCORM') !== false) {
246 if ($packagefileimsmanifest ||
$fs->get_file($context->id
, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
247 // No need to update.
250 } else if (strpos($scorm->version
, 'AICC') !== false) {
251 // TODO: add more sanity checks - something really exists in scorm_content area
255 if (!$packagefileimsmanifest) {
256 // Now extract files.
257 $fs->delete_area_files($context->id
, 'mod_scorm', 'content');
259 $packer = get_file_packer('application/zip');
260 $packagefile->extract_to_storage($packer, $context->id
, 'mod_scorm', 'content', 0, '/');
266 if ($packagefileimsmanifest) {
267 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
268 // Direct link to imsmanifest.xml file.
269 if (!scorm_parse_scorm($scorm, $packagefile)) {
270 $scorm->version
= 'ERROR';
273 } else if ($manifest = $fs->get_file($context->id
, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
274 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
276 if (!scorm_parse_scorm($scorm, $manifest)) {
277 $scorm->version
= 'ERROR';
280 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
282 if (!scorm_parse_aicc($scorm)) {
283 $scorm->version
= 'ERROR';
285 $scorm->version
= 'AICC';
288 } else if ($scorm->scormtype
=== SCORM_TYPE_EXTERNAL
and $cfg_scorm->allowtypeexternal
) {
289 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
290 // SCORM only, AICC can not be external
291 if (!scorm_parse_scorm($scorm, $scorm->reference
)) {
292 $scorm->version
= 'ERROR';
294 $newhash = sha1($scorm->reference
);
296 } else if ($scorm->scormtype
=== SCORM_TYPE_AICCURL
and $cfg_scorm->allowtypeexternalaicc
) {
297 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
299 if (!scorm_parse_aicc($scorm)) {
300 $scorm->version
= 'ERROR';
302 $scorm->version
= 'AICC';
304 // sorry, disabled type
309 $scorm->sha1hash
= $newhash;
310 $DB->update_record('scorm', $scorm);
314 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
315 if (!empty($haystacks)) {
316 foreach ($haystacks as $key => $element) {
318 if ($element->{$item} === $needle) {
322 if ($element->{$item} == $needle) {
331 function scorm_repeater($what, $times) {
336 for ($i=0; $i<$times; $i++
) {
342 function scorm_external_link($link) {
343 // check if a link is external
345 $link = strtolower($link);
346 if (substr($link, 0, 7) == 'http://') {
348 } else if (substr($link, 0, 8) == 'https://') {
350 } else if (substr($link, 0, 4) == 'www.') {
357 * Returns an object containing all datas relative to the given sco ID
359 * @param integer $id The sco ID
360 * @return mixed (false if sco id does not exists)
362 function scorm_get_sco($id, $what=SCO_ALL
) {
365 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
366 $sco = ($what == SCO_DATA
) ?
new stdClass() : $sco;
367 if (($what != SCO_ONLY
) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
368 foreach ($scodatas as $scodata) {
369 $sco->{$scodata->name
} = $scodata->value
;
371 } else if (($what != SCO_ONLY
) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
372 $sco->parameters
= '';
381 * Returns an object (array) containing all the scoes data related to the given sco ID
383 * @param integer $id The sco ID
384 * @param integer $organisation an organisation ID - defaults to false if not required
385 * @return mixed (false if there are no scoes or an array)
387 function scorm_get_scoes($id, $organisation=false) {
390 $queryarray = array('scorm'=>$id);
391 if (!empty($organisation)) {
392 $queryarray['organization'] = $organisation;
394 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
395 // Drop keys so that it is a simple array as expected.
396 $scoes = array_values($scoes);
397 foreach ($scoes as $sco) {
398 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id
))) {
399 foreach ($scodatas as $scodata) {
400 $sco->{$scodata->name
} = $scodata->value
;
410 function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
415 if ($forcecompleted) {
416 //TODO - this could be broadened to encompass SCORM 2004 in future
417 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
418 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))) {
419 $value = 'completed';
422 if ($element == 'cmi.core.score.raw') {
423 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))) {
424 if ($tracktest->value
== "incomplete") {
425 $tracktest->value
= "completed";
426 $DB->update_record('scorm_scoes_track', $tracktest);
430 if (($element == 'cmi.success_status') && ($value == 'passed' ||
$value == 'failed')) {
431 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
432 $objectiveprogressstatus = true;
433 $objectivesatisfiedstatus = false;
434 if ($value == 'passed') {
435 $objectivesatisfiedstatus = true;
438 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
439 'scormid' => $scormid,
441 'attempt' => $attempt,
442 'element' => 'objectiveprogressstatus'))) {
443 $track->value
= $objectiveprogressstatus;
444 $track->timemodified
= time();
445 $DB->update_record('scorm_scoes_track', $track);
448 $track = new stdClass();
449 $track->userid
= $userid;
450 $track->scormid
= $scormid;
451 $track->scoid
= $scoid;
452 $track->attempt
= $attempt;
453 $track->element
= 'objectiveprogressstatus';
454 $track->value
= $objectiveprogressstatus;
455 $track->timemodified
= time();
456 $id = $DB->insert_record('scorm_scoes_track', $track);
458 if ($objectivesatisfiedstatus) {
459 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
460 'scormid' => $scormid,
462 'attempt' => $attempt,
463 'element' => 'objectivesatisfiedstatus'))) {
464 $track->value
= $objectivesatisfiedstatus;
465 $track->timemodified
= time();
466 $DB->update_record('scorm_scoes_track', $track);
469 $track = new stdClass();
470 $track->userid
= $userid;
471 $track->scormid
= $scormid;
472 $track->scoid
= $scoid;
473 $track->attempt
= $attempt;
474 $track->element
= 'objectivesatisfiedstatus';
475 $track->value
= $objectivesatisfiedstatus;
476 $track->timemodified
= time();
477 $id = $DB->insert_record('scorm_scoes_track', $track);
479 $filepath = $CFG->dataroot
."\\temp\\tempfile.txt";
480 $fh = fopen($filepath, "a+");
482 $string = ob_get_clean();
483 fwrite($fh, $string);
492 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
493 'scormid' => $scormid,
495 'attempt' => $attempt,
496 'element' => $element))) {
497 if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
498 $track->value
= $value;
499 $track->timemodified
= time();
500 $DB->update_record('scorm_scoes_track', $track);
504 $track = new stdClass();
505 $track->userid
= $userid;
506 $track->scormid
= $scormid;
507 $track->scoid
= $scoid;
508 $track->attempt
= $attempt;
509 $track->element
= $element;
510 $track->value
= $value;
511 $track->timemodified
= time();
512 $id = $DB->insert_record('scorm_scoes_track', $track);
515 if (strstr($element, '.score.raw') ||
516 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
517 && in_array($track->value
, array('completed', 'passed')))) {
518 $scorm = $DB->get_record('scorm', array('id' => $scormid));
519 include_once($CFG->dirroot
.'/mod/scorm/lib.php');
520 scorm_update_grades($scorm, $userid);
527 * simple quick function to return true/false if this user has tracks in this scorm
529 * @param integer $scormid The scorm ID
530 * @param integer $userid the users id
531 * @return boolean (false if there are no tracks)
533 function scorm_has_tracks($scormid, $userid) {
535 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
538 function scorm_get_tracks($scoid, $userid, $attempt='') {
539 // Gets all tracks of specified sco and user.
542 if (empty($attempt)) {
543 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
544 $attempt = scorm_get_last_attempt($scormid, $userid);
549 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid,
550 'attempt'=>$attempt), 'element ASC')) {
551 $usertrack = scorm_format_interactions($tracks);
552 $usertrack->userid
= $userid;
553 $usertrack->scoid
= $scoid;
561 * helper function to return a formatted list of interactions for reports.
563 * @param array $trackdata the records from scorm_scoes_track table
564 * @return object formatted list of interactions
566 function scorm_format_interactions($trackdata) {
567 $usertrack = new stdClass();
569 // Defined in order to unify scorm1.2 and scorm2004.
570 $usertrack->score_raw
= '';
571 $usertrack->status
= '';
572 $usertrack->total_time
= '00:00:00';
573 $usertrack->session_time
= '00:00:00';
574 $usertrack->timemodified
= 0;
576 foreach ($trackdata as $track) {
577 $element = $track->element
;
578 $usertrack->{$element} = $track->value
;
580 case 'cmi.core.lesson_status':
581 case 'cmi.completion_status':
582 if ($track->value
== 'not attempted') {
583 $track->value
= 'notattempted';
585 $usertrack->status
= $track->value
;
587 case 'cmi.core.score.raw':
588 case 'cmi.score.raw':
589 $usertrack->score_raw
= (float) sprintf('%2.2f', $track->value
);
591 case 'cmi.core.session_time':
592 case 'cmi.session_time':
593 $usertrack->session_time
= $track->value
;
595 case 'cmi.core.total_time':
596 case 'cmi.total_time':
597 $usertrack->total_time
= $track->value
;
600 if (isset($track->timemodified
) && ($track->timemodified
> $usertrack->timemodified
)) {
601 $usertrack->timemodified
= $track->timemodified
;
607 /* Find the start and finsh time for a a given SCO attempt
609 * @param int $scormid SCORM Id
610 * @param int $scoid SCO Id
611 * @param int $userid User Id
612 * @param int $attemt Attempt Id
614 * @return object start and finsh time EPOC secods
617 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
620 $timedata = new stdClass();
621 $sql = !empty($scoid) ?
"userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
622 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
624 $tracks = array_values($tracks);
628 $timedata->start
= $tracks[0]->timemodified
;
630 $timedata->start
= false;
632 if ($tracks && $track = array_pop($tracks)) {
633 $timedata->finish
= $track->timemodified
;
635 $timedata->finish
= $timedata->start
;
640 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
642 $attemptscore = new stdClass();
643 $attemptscore->scoes
= 0;
644 $attemptscore->values
= 0;
645 $attemptscore->max
= 0;
646 $attemptscore->sum
= 0;
647 $attemptscore->lastmodify
= 0;
649 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id
), 'sortorder, id')) {
653 foreach ($scoes as $sco) {
654 if ($userdata=scorm_get_tracks($sco->id
, $userid, $attempt)) {
655 if (($userdata->status
== 'completed') ||
($userdata->status
== 'passed')) {
656 $attemptscore->scoes++
;
658 if (!empty($userdata->score_raw
) ||
(isset($scorm->type
) && $scorm->type
=='sco' && isset($userdata->score_raw
))) {
659 $attemptscore->values++
;
660 $attemptscore->sum +
= $userdata->score_raw
;
661 $attemptscore->max
= ($userdata->score_raw
> $attemptscore->max
)?
$userdata->score_raw
:$attemptscore->max
;
662 if (isset($userdata->timemodified
) && ($userdata->timemodified
> $attemptscore->lastmodify
)) {
663 $attemptscore->lastmodify
= $userdata->timemodified
;
665 $attemptscore->lastmodify
= 0;
670 switch ($scorm->grademethod
) {
672 $score = (float) $attemptscore->max
;
675 if ($attemptscore->values
> 0) {
676 $score = $attemptscore->sum
/$attemptscore->values
;
682 $score = $attemptscore->sum
;
685 $score = $attemptscore->scoes
;
688 $score = $attemptscore->max
; // Remote Learner GRADEHIGHEST is default
694 function scorm_grade_user($scorm, $userid) {
696 // ensure we dont grade user beyond $scorm->maxattempt settings
697 $lastattempt = scorm_get_last_attempt($scorm->id
, $userid);
698 if ($scorm->maxattempt
!= 0 && $lastattempt >= $scorm->maxattempt
) {
699 $lastattempt = $scorm->maxattempt
;
702 switch ($scorm->whatgrade
) {
704 return scorm_grade_user_attempt($scorm, $userid, 1);
707 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id
, $userid));
711 for ($attempt = 1; $attempt <= $lastattempt; $attempt++
) {
712 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
713 $maxscore = $attemptscore > $maxscore ?
$attemptscore: $maxscore;
719 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
720 if (empty($attemptcount)) {
723 $attemptcount = count($attemptcount);
725 $lastattempt = scorm_get_last_attempt($scorm->id
, $userid);
727 for ($attempt = 1; $attempt <= $lastattempt; $attempt++
) {
728 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
729 $sumscore +
= $attemptscore;
732 return round($sumscore / $attemptcount);
737 function scorm_count_launchable($scormid, $organization='') {
740 $sqlorganization = '';
741 $params = array($scormid);
742 if (!empty($organization)) {
743 $sqlorganization = " AND organization=?";
744 $params[] = $organization;
746 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
750 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
752 * @param int $scormid the id of the scorm.
753 * @param int $userid the id of the user.
755 * @return int The attempt number to use.
757 function scorm_get_last_attempt($scormid, $userid) {
760 /// Find the last attempt number for the given user id and scorm id
761 $sql = "SELECT MAX(attempt)
762 FROM {scorm_scoes_track}
763 WHERE userid = ? AND scormid = ?";
764 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
765 if (empty($lastattempt)) {
773 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
775 * @param int $scormid the id of the scorm.
776 * @param int $userid the id of the user.
778 * @return int The attempt number to use.
780 function scorm_get_last_completed_attempt($scormid, $userid) {
783 /// Find the last completed attempt number for the given user id and scorm id
784 $sql = "SELECT MAX(attempt)
785 FROM {scorm_scoes_track}
786 WHERE userid = ? AND scormid = ?
787 AND (value='completed' OR value='passed')";
788 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
789 if (empty($lastattempt)) {
797 * Returns the full list of attempts a user has made.
799 * @param int $scormid the id of the scorm.
800 * @param int $userid the id of the user.
802 * @return array array of attemptids
804 function scorm_get_all_attempts($scormid, $userid) {
806 $attemptids = array();
807 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
808 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
809 foreach ($attempts as $attempt) {
810 $attemptids[] = $attempt->attempt
;
815 function scorm_view_display ($user, $scorm, $action, $cm) {
816 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
818 if ($scorm->scormtype
!= SCORM_TYPE_LOCAL
&& $scorm->updatefreq
== SCORM_UPDATE_EVERYTIME
) {
819 scorm_parse($scorm, false);
822 $organization = optional_param('organization', '', PARAM_INT
);
824 if ($scorm->displaycoursestructure
== 1) {
825 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
827 <div
class="structurehead"><?php
print_string('contents', 'scorm') ?
></div
>
830 if (empty($organization)) {
831 $organization = $scorm->launch
;
833 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
834 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
835 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
836 array($scorm->id
), 'sortorder, id', 'id,title')) {
837 if (count($orgs) > 1) {
838 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
839 $select->label
= get_string('organizations', 'scorm');
840 $select->class = 'scorm-center';
841 echo $OUTPUT->render($select);
845 if ($sco = scorm_get_sco($organization, SCO_ONLY
)) {
846 if (($sco->organization
== '') && ($sco->launch
== '')) {
847 $orgidentifier = $sco->identifier
;
849 $orgidentifier = $sco->organization
;
853 $scorm->version
= strtolower(clean_param($scorm->version
, PARAM_SAFEDIR
)); // Just to be safe
854 if (!file_exists($CFG->dirroot
.'/mod/scorm/datamodels/'.$scorm->version
.'lib.php')) {
855 $scorm->version
= 'scorm_12';
857 require_once($CFG->dirroot
.'/mod/scorm/datamodels/'.$scorm->version
.'lib.php');
859 $result = scorm_get_toc($user, $scorm, $cm->id
, TOCFULLURL
, $orgidentifier);
860 $incomplete = $result->incomplete
;
862 // do we want the TOC to be displayed?
863 if ($scorm->displaycoursestructure
== 1) {
865 echo $OUTPUT->box_end();
868 // is this the first attempt ?
869 $attemptcount = scorm_get_attempt_count($user->id
, $scorm);
871 // do not give the player launch FORM if the SCORM object is locked after the final attempt
872 if ($scorm->lastattemptlock
== 0 ||
$result->attemptleft
> 0) {
874 <div
class="scorm-center">
875 <form id
="scormviewform" method
="post" action
="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
877 if ($scorm->hidebrowse
== 0) {
878 print_string('mode', 'scorm');
879 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
880 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
882 echo '<input type="hidden" name="mode" value="normal" />'."\n";
884 if ($scorm->forcenewattempt
== 1) {
885 if ($incomplete === false) {
886 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
888 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft
> 0)||
($scorm->maxattempt
== 0))) {
891 <input type
="checkbox" id
="a" name
="newattempt" />
892 <label
for="a"><?php
print_string('newattempt', 'scorm') ?
></label
>
895 if (!empty($scorm->popup
)) {
896 echo '<input type="hidden" name="display" value="popup" />'."\n";
900 <input type
="hidden" name
="scoid"/>
901 <input type
="hidden" name
="cm" value
="<?php echo $cm->id ?>"/>
902 <input type
="hidden" name
="currentorg" value
="<?php echo $orgidentifier ?>" />
903 <input type
="submit" value
="<?php print_string('enter', 'scorm') ?>" />
910 function scorm_simple_play($scorm, $user, $context, $cmid) {
915 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
919 if ($scorm->scormtype
!= SCORM_TYPE_LOCAL
&& $scorm->updatefreq
== SCORM_UPDATE_EVERYTIME
) {
920 scorm_parse($scorm, false);
922 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
923 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id
), 'sortorder, id', 'id');
927 if ($sco = scorm_get_sco($scorm->launch
, SCO_ONLY
)) {
928 if (($sco->organization
== '') && ($sco->launch
== '')) {
929 $orgidentifier = $sco->identifier
;
931 $orgidentifier = $sco->organization
;
934 if ($scorm->skipview
>= SCORM_SKIPVIEW_FIRST
) {
935 $sco = current($scoes);
936 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id
,
937 'currentorg'=>$orgidentifier,
939 if ($scorm->skipview
== SCORM_SKIPVIEW_ALWAYS ||
!scorm_has_tracks($scorm->id
, $user->id
)) {
940 if (!empty($scorm->forcenewattempt
)) {
941 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL
, $orgidentifier);
942 if ($result->incomplete
=== false) {
943 $url->param('newattempt','on');
953 function scorm_get_count_users($scormid, $groupingid=null) {
956 if (!empty($groupingid)) {
957 $sql = "SELECT COUNT(DISTINCT st.userid)
958 FROM {scorm_scoes_track} st
959 INNER JOIN {groups_members} gm ON st.userid = gm.userid
960 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
961 WHERE st.scormid = ? AND gg.groupingid = ?
963 $params = array($scormid, $groupingid);
965 $sql = "SELECT COUNT(DISTINCT st.userid)
966 FROM {scorm_scoes_track} st
969 $params = array($scormid);
972 return ($DB->count_records_sql($sql, $params));
976 * Build up the JavaScript representation of an array element
978 * @param string $sversion SCORM API version
979 * @param array $userdata User track data
980 * @param string $element_name Name of array element to get values for
981 * @param array $children list of sub elements of this array element that also need instantiating
984 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
985 // reconstitute comments_from_learner and comments_from_lms
987 $current_subelement = '';
991 $scormseperator = '_';
992 if (scorm_version_check($sversion, SCORM_13
)) { //scorm 1.3 elements use a . instead of an _
993 $scormseperator = '.';
995 // filter out the ones we want
996 $element_list = array();
997 foreach ($userdata as $element => $value) {
998 if (substr($element, 0, strlen($element_name)) == $element_name) {
999 $element_list[$element] = $value;
1003 // sort elements in .n array order
1004 uksort($element_list, "scorm_element_cmp");
1006 // generate JavaScript
1007 foreach ($element_list as $element => $value) {
1008 if (scorm_version_check($sversion, SCORM_13
)) {
1009 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
1010 preg_match('/\.(N\d+)\./', $element, $matches);
1012 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
1013 preg_match('/\_(\d+)\./', $element, $matches);
1015 if (count($matches) > 0 && $current != $matches[1]) {
1016 if ($count_sub > 0) {
1017 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1019 $current = $matches[1];
1021 $current_subelement = '';
1024 $end = strpos($element, $matches[1])+
strlen($matches[1]);
1025 $subelement = substr($element, 0, $end);
1026 echo ' '.$subelement." = new Object();\n";
1027 // now add the children
1028 foreach ($children as $child) {
1029 echo ' '.$subelement.".".$child." = new Object();\n";
1030 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
1034 // now - flesh out the second level elements if there are any
1035 if (scorm_version_check($sversion, SCORM_13
)) {
1036 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1037 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1039 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1040 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1043 // check the sub element type
1044 if (count($matches) > 0 && $current_subelement != $matches[1]) {
1045 if ($count_sub > 0) {
1046 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1048 $current_subelement = $matches[1];
1051 $end = strpos($element, $matches[1])+
strlen($matches[1]);
1052 $subelement = substr($element, 0, $end);
1053 echo ' '.$subelement." = new Object();\n";
1056 // now check the subelement subscript
1057 if (count($matches) > 0 && $current_sub != $matches[2]) {
1058 $current_sub = $matches[2];
1060 $end = strrpos($element, $matches[2])+
strlen($matches[2]);
1061 $subelement = substr($element, 0, $end);
1062 echo ' '.$subelement." = new Object();\n";
1065 echo ' '.$element.' = \''.$value."';\n";
1067 if ($count_sub > 0) {
1068 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1071 echo ' '.$element_name.'._count = '.$count.";\n";
1076 * Build up the JavaScript representation of an array element
1078 * @param string $a left array element
1079 * @param string $b right array element
1080 * @return comparator - 0,1,-1
1082 function scorm_element_cmp($a, $b) {
1083 preg_match('/.*?(\d+)\./', $a, $matches);
1084 $left = intval($matches[1]);
1085 preg_match('/.?(\d+)\./', $b, $matches);
1086 $right = intval($matches[1]);
1087 if ($left < $right) {
1088 return -1; // smaller
1089 } else if ($left > $right) {
1092 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1093 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1094 $leftterm = intval($matches[2]);
1095 $left = intval($matches[3]);
1096 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1097 $rightterm = intval($matches[2]);
1098 $right = intval($matches[3]);
1099 if ($leftterm < $rightterm) {
1100 return -1; // smaller
1101 } else if ($leftterm > $rightterm) {
1104 if ($left < $right) {
1105 return -1; // smaller
1106 } else if ($left > $right) {
1112 // fall back for no second level matches or second level matches are equal
1113 return 0; // equal to
1118 * Generate the user attempt status string
1120 * @param object $user Current context user
1121 * @param object $scorm a moodle scrom object - mdl_scorm
1122 * @return string - Attempt status string
1124 function scorm_get_attempt_status($user, $scorm, $cm='') {
1125 global $DB, $PAGE, $OUTPUT;
1127 $attempts = scorm_get_attempt_count($user->id
, $scorm, true);
1128 if (empty($attempts)) {
1131 $attemptcount = count($attempts);
1134 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1135 if ($scorm->maxattempt
> 0) {
1136 $result .= $scorm->maxattempt
. '<br />';
1138 $result .= get_string('unlimited').'<br />';
1140 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1142 if ($scorm->maxattempt
== 1) {
1143 switch ($scorm->grademethod
) {
1145 $grademethod = get_string('gradehighest', 'scorm');
1148 $grademethod = get_string('gradeaverage', 'scorm');
1151 $grademethod = get_string('gradesum', 'scorm');
1154 $grademethod = get_string('gradescoes', 'scorm');
1158 switch ($scorm->whatgrade
) {
1159 case HIGHESTATTEMPT
:
1160 $grademethod = get_string('highestattempt', 'scorm');
1162 case AVERAGEATTEMPT
:
1163 $grademethod = get_string('averageattempt', 'scorm');
1166 $grademethod = get_string('firstattempt', 'scorm');
1169 $grademethod = get_string('lastattempt', 'scorm');
1174 if (!empty($attempts)) {
1176 foreach ($attempts as $attempt) {
1177 $gradereported = scorm_grade_user_attempt($scorm, $user->id
, $attempt->attemptnumber
);
1178 if ($scorm->grademethod
!== GRADESCOES
&& !empty($scorm->maxgrade
)) {
1179 $gradereported = $gradereported/$scorm->maxgrade
;
1180 $gradereported = number_format($gradereported*100, 0) .'%';
1182 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1186 $calculatedgrade = scorm_grade_user($scorm, $user->id
);
1187 if ($scorm->grademethod
!== GRADESCOES
&& !empty($scorm->maxgrade
)) {
1188 $calculatedgrade = $calculatedgrade/$scorm->maxgrade
;
1189 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1191 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1192 if (empty($attempts)) {
1193 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1195 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1198 if ($attemptcount >= $scorm->maxattempt
and $scorm->maxattempt
> 0) {
1199 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1202 $context = context_module
::instance($cm->id
);
1203 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1204 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id
, 'scormid' => $scorm->id
))) {
1205 //check to see if any data is stored for this user:
1206 $deleteurl = new moodle_url($PAGE->url
, array('action'=>'delete', 'sesskey' => sesskey()));
1207 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1216 * Get SCORM attempt count
1218 * @param object $user Current context user
1219 * @param object $scorm a moodle scrom object - mdl_scorm
1220 * @param bool $attempts return the list of attempts
1221 * @return int - no. of attempts so far
1223 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1226 $element = 'cmi.core.score.raw';
1227 if ($scorm->grademethod
== GRADESCOES
) {
1228 $element = 'cmi.core.lesson_status';
1230 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1231 $element = 'cmi.score.raw';
1233 $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id
), 'attempt', 'DISTINCT attempt AS attemptnumber');
1234 if ($attempts_only) {
1237 if (!empty($attempts)) {
1238 $attemptcount = count($attempts);
1240 return $attemptcount;
1244 * Figure out with this is a debug situation
1246 * @param object $scorm a moodle scrom object - mdl_scorm
1247 * @return boolean - debugging true/false
1249 function scorm_debugging($scorm) {
1251 $cfg_scorm = get_config('scorm');
1253 if (!$cfg_scorm->allowapidebug
) {
1256 $identifier = $USER->username
.':'.$scorm->name
;
1257 $test = $cfg_scorm->apidebugmask
;
1258 // check the regex is only a short list of safe characters
1259 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1263 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1268 * Delete Scorm tracks for selected users
1270 * @param array $attemptids list of attempts that need to be deleted
1271 * @param int $scorm instance
1273 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1275 function scorm_delete_responses($attemptids, $scorm) {
1276 if (!is_array($attemptids) ||
empty($attemptids)) {
1280 foreach ($attemptids as $num => $attemptid) {
1281 if (empty($attemptid)) {
1282 unset($attemptids[$num]);
1286 foreach ($attemptids as $attempt) {
1287 $keys = explode(':', $attempt);
1288 if (count($keys) == 2) {
1289 $userid = clean_param($keys[0], PARAM_INT
);
1290 $attemptid = clean_param($keys[1], PARAM_INT
);
1291 if (!$userid ||
!$attemptid ||
!scorm_delete_attempt($userid, $scorm, $attemptid)) {
1302 * Delete Scorm tracks for selected users
1304 * @param int $userid ID of User
1305 * @param int $scormid ID of Scorm
1306 * @param int $attemptid user attempt that need to be deleted
1308 * return bool true suceeded
1310 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1313 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id
, 'attempt' => $attemptid));
1314 include_once('lib.php');
1315 scorm_update_grades($scorm, $userid, true);
1320 * Converts SCORM duration notation to human-readable format
1321 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1322 * @param $duration string SCORM duration
1323 * @return string human-readable date/time
1325 function scorm_format_duration($duration) {
1326 // fetch date/time strings
1327 $stryears = get_string('years');
1328 $strmonths = get_string('nummonths');
1329 $strdays = get_string('days');
1330 $strhours = get_string('hours');
1331 $strminutes = get_string('minutes');
1332 $strseconds = get_string('seconds');
1334 if ($duration[0] == 'P') {
1335 // if timestamp starts with 'P' - it's a SCORM 2004 format
1336 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1337 // and outputs filled sections, discarding leading zeroes and any format literals
1338 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1339 $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#',
1340 '#([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#' );
1341 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1342 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1344 // else we have SCORM 1.2 format there
1345 // first convert the timestamp to some SCORM 2004-like format for conveniency
1346 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1347 // then convert in the same way as SCORM 2004
1348 $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#' );
1349 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1352 $result = preg_replace($pattern, $replace, $duration);
1357 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1358 global $CFG, $DB, $PAGE, $OUTPUT;
1361 if ($mode != 'normal') {
1362 $modestr = '&mode='.$mode;
1366 $incomplete = false;
1368 if (!empty($organizationsco)) {
1369 $result[0] = $organizationsco;
1370 $result[0]->isvisible
= true;
1371 $result[0]->statusicon
= '';
1372 $result[0]->url
= '';
1375 if ($scoes = scorm_get_scoes($scorm->id
, $currentorg)){
1376 // Retrieve user tracking data for each learning object.
1377 $usertracks = array();
1378 foreach ($scoes as $sco) {
1379 if (!empty($sco->launch
)) {
1380 if ($usertrack = scorm_get_tracks($sco->id
, $user->id
, $attempt)) {
1381 if ($usertrack->status
== '') {
1382 $usertrack->status
= 'notattempted';
1384 $usertracks[$sco->identifier
] = $usertrack;
1388 foreach ($scoes as $sco) {
1389 if (!isset($sco->isvisible
)) {
1390 $sco->isvisible
= true;
1393 if (empty($sco->title
)) {
1394 $sco->title
= $sco->identifier
;
1397 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1398 $sco->prereq
= true;
1400 $sco->prereq
= empty($sco->prerequisites
) ||
scorm_eval_prerequisites($sco->prerequisites
, $usertracks);
1403 if ($sco->isvisible
) {
1404 if (!empty($sco->launch
)) {
1405 if (empty($scoid) && ($mode != 'normal')) {
1409 if (isset($usertracks[$sco->identifier
])) {
1410 $usertrack = $usertracks[$sco->identifier
];
1411 $strstatus = get_string($usertrack->status
,'scorm');
1413 if ($sco->scormtype
== 'sco') {
1414 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status
, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1416 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1419 if (($usertrack->status
== 'notattempted') ||
($usertrack->status
== 'incomplete') ||
($usertrack->status
== 'browsed')) {
1421 if ($play && empty($scoid)) {
1426 $strsuspended = get_string('suspended', 'scorm');
1428 $exitvar = 'cmi.core.exit';
1430 if (scorm_version_check($scorm->version
, SCORM_13
)) {
1431 $exitvar = 'cmi.exit';
1434 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1435 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1439 if ($play && empty($scoid)) {
1445 if ($sco->scormtype
== 'sco') {
1446 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1448 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1454 if (empty($statusicon)) {
1455 $sco->statusicon
= '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1457 $sco->statusicon
= $statusicon;
1460 $sco->url
= 'a='.$scorm->id
.'&scoid='.$sco->id
.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
1461 $sco->incomplete
= $incomplete;
1463 if (!in_array($sco->id
, array_keys($result))) {
1464 $result[$sco->id
] = $sco;
1469 // Get the parent scoes!
1470 $result = scorm_get_toc_get_parent_child($result, $currentorg);
1472 // Be safe, prevent warnings from showing up while returning array
1473 if (!isset($scoid)) {
1477 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1480 function scorm_get_toc_get_parent_child(&$result, $currentorg) {
1483 // Organization is always the root, prevparent.
1484 if (!empty($currentorg)) {
1485 $prevparent = $currentorg;
1490 foreach ($result as $sco) {
1491 if ($sco->parent
== '/') {
1492 $final[$level][$sco->identifier
] = $sco;
1493 $prevparent = $sco->identifier
;
1494 unset($result[$sco->id
]);
1496 if ($sco->parent
== $prevparent) {
1497 $final[$level][$sco->identifier
] = $sco;
1498 $prevparent = $sco->identifier
;
1499 unset($result[$sco->id
]);
1501 if (!empty($final[$level])) {
1503 foreach ($final[$level] as $fin) {
1504 if ($sco->parent
== $fin->identifier
) {
1510 $final[$level][$sco->identifier
] = $sco;
1511 unset($result[$sco->id
]);
1515 $final[$level][$sco->identifier
] = $sco;
1516 unset($result[$sco->id
]);
1523 for ($i = 0; $i <= $level; $i++
) {
1525 foreach ($final[$i] as $ident => $sco) {
1526 if (empty($prevparent)) {
1527 $prevparent = $ident;
1529 if (!isset($final[$i][$prevparent]->children
)) {
1530 $final[$i][$prevparent]->children
= array();
1532 if ($sco->parent
== $prevparent) {
1533 $final[$i][$prevparent]->children
[] = $sco;
1534 $prevparent = $ident;
1537 foreach ($final[$i] as $identifier => $scoobj) {
1538 if ($identifier == $sco->parent
) {
1539 $parent = $identifier;
1543 if ($parent !== false) {
1544 $final[$i][$parent]->children
[] = $sco;
1551 for ($i = 0; $i <= $level; $i++
) {
1552 $keys = array_keys($final[$i]);
1553 $results[] = $final[$i][$keys[0]];
1559 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK
, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1562 $result = new stdClass();
1563 $result->prerequisites
= true;
1564 $result->incomplete
= true;
1568 $attemptsmade = scorm_get_attempt_count($user->id
, $scorm);
1569 $result->attemptleft
= $scorm->maxattempt
== 0 ?
1 : $scorm->maxattempt
- $attemptsmade;
1573 $result->toc
= "<ul>\n";
1575 if (!$play && !empty($organizationsco)) {
1576 $result->toc
.= "\t<li>".$organizationsco->title
."</li>\n";
1581 if (!empty($scoes)) {
1582 foreach ($scoes as $sco) {
1583 $result->toc
.= "\t<li>\n";
1586 $sco->isvisible
= true;
1588 if ($sco->isvisible
) {
1591 if (isset($usertracks[$sco->identifier
])) {
1592 $viewscore = has_capability('mod/scorm:viewscores', context_module
::instance($cmid));
1593 if (isset($usertracks[$sco->identifier
]->score_raw
) && $viewscore) {
1594 if ($usertracks[$sco->identifier
]->score_raw
!= '') {
1595 $score = '('.get_string('score','scorm').': '.$usertracks[$sco->identifier
]->score_raw
.')';
1600 if (!empty($sco->prereq
)) {
1601 if ($sco->id
== $scoid) {
1602 $result->prerequisites
= true;
1605 if (!empty($prevsco) && scorm_version_check($scorm->version
, SCORM_13
) && !empty($prevsco->hidecontinue
)) {
1606 if ($sco->scormtype
== 'sco') {
1607 $result->toc
.= '<span>'.$sco->statusicon
.' '.format_string($sco->title
).'</span>';
1609 $result->toc
.= '<span> '.format_string($sco->title
).'</span>';
1611 } else if ($toclink == TOCFULLURL
) {
1612 $url = $CFG->wwwroot
.'/mod/scorm/player.php?'.$sco->url
;
1613 if (!empty($sco->launch
)) {
1614 if ($sco->scormtype
== 'sco') {
1615 $result->toc
.= $sco->statusicon
.' <a href="'.$url.'">'.format_string($sco->title
).'</a>'.$score."\n";
1617 $result->toc
.= ' <a data-scoid="'.$sco->id
.'" href="'.$url.'">'.format_string($sco->title
).'</a>'.$score."\n";
1620 if ($sco->scormtype
== 'sco') {
1621 $result->toc
.= $sco->statusicon
.' '.format_string($sco->title
).$score."\n";
1623 $result->toc
.= ' '.format_string($sco->title
).$score."\n";
1627 if (!empty($sco->launch
)) {
1628 if ($sco->scormtype
== 'sco') {
1629 $result->toc
.= '<a data-scoid="'.$sco->id
.'" title="'.$sco->url
.'">'.$sco->statusicon
.' '.format_string($sco->title
).' '.$score.'</a>';
1631 $result->toc
.= '<a data-scoid="'.$sco->id
.'" title="'.$sco->url
.'"> '.format_string($sco->title
).' '.$score.'</a>';
1634 if ($sco->scormtype
== 'sco') {
1635 $result->toc
.= '<span>'.$sco->statusicon
.' '.format_string($sco->title
).'</span>';
1637 $result->toc
.= '<span> '.format_string($sco->title
).'</span>';
1644 if ($sco->scormtype
== 'sco') {
1645 $result->toc
.= '<span>'.$sco->statusicon
.' '.format_string($sco->title
).'</span>';
1647 $result->toc
.= ' '.format_string($sco->title
).'</span>';
1650 if ($sco->scormtype
== 'sco') {
1651 $result->toc
.= $sco->statusicon
.' '.format_string($sco->title
)."\n";
1653 $result->toc
.= ' '.format_string($sco->title
)."\n";
1659 $result->toc
.= "\t\t ".format_string($sco->title
)."\n";
1662 if (!empty($sco->children
)) {
1663 $result->toc
.= "\n\t\t<ul>\n";
1664 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children
, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1665 $result->toc
.= $childresult->toc
;
1666 $result->toc
.= "\t\t</ul>\n";
1667 $result->toc
.= "\t</li>\n";
1669 $result->toc
.= "\t</li>\n";
1673 $result->incomplete
= $sco->incomplete
;
1677 $result->toc
.= "</ul>\n";
1683 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1684 if (!empty($scoes)) {
1685 if (!empty($organizationsco) && !$children) {
1686 $tocmenus[$organizationsco->id
] = $organizationsco->title
;
1689 $parents[$level]='/';
1690 foreach ($scoes as $sco) {
1691 if ($parents[$level] != $sco->parent
) {
1692 if ($newlevel = array_search($sco->parent
, $parents)) {
1696 while (($i > 0) && ($parents[$level] != $sco->parent
)) {
1700 if (($i == 0) && ($sco->parent
!= $currentorg)) {
1706 $parents[$level] = $sco->parent
;
1711 if ($sco->scormtype
== 'sco') {
1712 $tocmenus[$sco->id
] = scorm_repeater('−', $level) . '>' . format_string($sco->title
);
1715 if ($sco->scormtype
== 'sco') {
1716 $tocmenus[$sco->id
] = scorm_repeater('−', $level) . '>' . format_string($sco->title
);
1720 if (!empty($sco->children
)) {
1721 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children
, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1729 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK
, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1730 global $CFG, $DB, $OUTPUT;
1732 if (empty($attempt)) {
1733 $attempt = scorm_get_attempt_count($user->id
, $scorm);
1736 $result = new stdClass();
1737 $organizationsco = null;
1740 $result->toc
= "<div id=\"scorm_layout\" class=\"yui3-g-r\">\n";
1741 $result->toc
.= "<div id=\"scorm_toc\" class=\"yui3-u-1-5\">\n";
1742 $result->toc
.= "<div id=\"scorm_toc_title\"></div>\n";
1743 $result->toc
.= "<div id=\"scorm_tree\">\n";
1746 if (!empty($currentorg)) {
1747 $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id
, 'identifier'=>$currentorg));
1748 if (!empty($organizationsco->title
)) {
1750 $result->toctitle
= $organizationsco->title
;
1755 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1757 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children
, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1760 $result->toc
.= $treeview->toc
;
1762 $result->toc
= $treeview->toc
;
1765 if (!empty($scoes['scoid'])) {
1766 $scoid = $scoes['scoid'];
1769 if (empty($scoid)) {
1770 $result->sco
= $scoes['scoes'][0]->children
[0];
1772 $result->sco
= scorm_get_sco($scoid);
1775 if ($scorm->hidetoc
== SCORM_TOC_POPUP
) {
1776 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children
, $scoes['usertracks'], $currentorg, $organizationsco);
1779 if ($mode != 'normal') {
1780 $modestr = '&mode='.$mode;
1783 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id
.'¤torg='.$currentorg.$modestr);
1784 $result->tocmenu
= $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco
->id
, null, "tocmenu");
1787 $result->prerequisites
= $treeview->prerequisites
;
1788 $result->incomplete
= $treeview->incomplete
;
1789 $result->attemptleft
= $treeview->attemptleft
;
1792 $result->toc
.= "</div></div>\n";
1793 $result->toc
.= "<div id=\"scorm_toc_toggle\">\n";
1794 $result->toc
.= "<button id=\"scorm_toc_toggle_btn\"></button></div>\n";
1795 $result->toc
.= "<div id=\"scorm_content\">";
1796 $result->toc
.= "<div id=\"scorm_navpanel\"></div>\n";
1797 $result->toc
.= "</div></div>\n";
1803 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1804 if (is_object($scoes)) {
1806 if (isset($sco->url
)) {
1807 $adlnav[$sco->id
]['identifier'] = $sco->identifier
;
1808 $adlnav[$sco->id
]['launch'] = $sco->launch
;
1809 $adlnav[$sco->id
]['title'] = $sco->title
;
1810 $adlnav[$sco->id
]['url'] = $sco->url
;
1811 $adlnav[$sco->id
]['parent'] = $sco->parent
;
1812 if (isset($sco->choice
)) {
1813 $adlnav[$sco->id
]['choice'] = $sco->choice
;
1815 if (isset($sco->flow
)) {
1816 $adlnav[$sco->id
]['flow'] = $sco->flow
;
1817 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1818 $adlnav[$sco->id
]['flow'] = $adlnav[$parentscoid]['flow'];
1820 if (isset($sco->isvisible
)) {
1821 $adlnav[$sco->id
]['isvisible'] = $sco->isvisible
;
1823 if (isset($sco->parameters
)) {
1824 $adlnav[$sco->id
]['parameters'] = $sco->parameters
;
1826 if (isset($sco->hidecontinue
)) {
1827 $adlnav[$sco->id
]['hidecontinue'] = $sco->hidecontinue
;
1829 if (isset($sco->hideprevious
)) {
1830 $adlnav[$sco->id
]['hideprevious'] = $sco->hideprevious
;
1832 if (isset($sco->hidesuspendall
)) {
1833 $adlnav[$sco->id
]['hidesuspendall'] = $sco->hidesuspendall
;
1835 if (!empty($parentscoid)) {
1836 $adlnav[$sco->id
]['parentscoid'] = $parentscoid;
1838 if (isset($adlnav['prevscoid'])) {
1839 $adlnav[$sco->id
]['prevscoid'] = $adlnav['prevscoid'];
1840 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id
;
1841 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent
) {
1842 $adlnav[$sco->id
]['prevsibling'] = $adlnav['prevscoid'];
1843 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id
;
1846 $adlnav['prevscoid'] = $sco->id
;
1847 $adlnav['prevparent'] = $sco->parent
;
1849 if (isset($sco->children
)) {
1850 foreach ($sco->children
as $children) {
1851 scorm_get_adlnav_json($children, $adlnav, $sco->id
);
1855 foreach ($scoes as $sco) {
1856 scorm_get_adlnav_json ($sco, $adlnav);
1858 unset($adlnav['prevscoid']);
1859 unset($adlnav['prevparent']);
1861 return json_encode($adlnav);
1865 * Check for the availability of a resource by URL.
1867 * Check is performed using an HTTP HEAD call.
1869 * @param $url string A valid URL
1870 * @return bool|string True if no issue is found. The error string message, otherwise
1872 function scorm_check_url($url) {
1875 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1876 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1877 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1879 $cmsg = $curl->head($url);
1880 $info = $curl->get_info();
1881 if (empty($info['http_code']) ||
$info['http_code'] != 200) {
1882 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));