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() {
75 $cfg_scorm = get_config('scorm');
77 return array('resizable'=> isset($cfg_scorm->resizable) ? $cfg_scorm->resizable : 0,
78 'scrollbars'=> isset($cfg_scorm->scrollbars) ? $cfg_scorm->scrollbars : 0,
79 'directories'=> isset($cfg_scorm->directories) ? $cfg_scorm->directories : 0,
80 'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
81 'menubar'=> isset($cfg_scorm->menubar) ? $cfg_scorm->menubar : 0,
82 'toolbar'=> isset($cfg_scorm->toolbar) ? $cfg_scorm->toolbar : 0,
83 'status'=> isset($cfg_scorm->status) ? $cfg_scorm->status : 0);
87 * Returns an array of the array of what grade options
89 * @return array an array of what grade options
91 function scorm_get_grade_method_array() {
92 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
93 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
94 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
95 GRADESUM => get_string('gradesum', 'scorm'));
99 * Returns an array of the array of what grade options
101 * @return array an array of what grade options
103 function scorm_get_what_grade_array() {
104 return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
105 AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
106 FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
107 LASTATTEMPT => get_string('lastattempt', 'scorm'));
111 * Returns an array of the array of skip view options
113 * @return array an array of skip view options
115 function scorm_get_skip_view_array() {
116 return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
117 SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
118 SCORM_SKIPVIEW_ALWAYS => get_string('always'));
122 * Returns an array of the array of hide table of contents options
124 * @return array an array of hide table of contents options
126 function scorm_get_hidetoc_array() {
127 return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
128 SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
129 SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
130 SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
134 * Returns an array of the array of update frequency options
136 * @return array an array of update frequency options
138 function scorm_get_updatefreq_array() {
139 return array(SCORM_UPDATE_NEVER => get_string('never'),
140 SCORM_UPDATE_EVERYDAY => get_string('everyday', 'scorm'),
141 SCORM_UPDATE_EVERYTIME => get_string('everytime', 'scorm'));
145 * Returns an array of the array of popup display options
147 * @return array an array of popup display options
149 function scorm_get_popup_display_array() {
150 return array(0 => get_string('currentwindow', 'scorm'),
151 1 => get_string('popup', 'scorm'));
155 * Returns an array of the array of attempt options
157 * @return array an array of attempt options
159 function scorm_get_attempts_array() {
160 $attempts = array(0 => get_string('nolimit', 'scorm'),
161 1 => get_string('attempt1', 'scorm'));
163 for ($i=2; $i<=6; $i++) {
164 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
171 * Returns an array of the attempt status options
173 * @return array an array of attempt status options
175 function scorm_get_attemptstatus_array() {
176 return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO => get_string('no'),
177 SCORM_DISPLAY_ATTEMPTSTATUS_ALL => get_string('attemptstatusall', 'scorm'),
178 SCORM_DISPLAY_ATTEMPTSTATUS_MY => get_string('attemptstatusmy', 'scorm'),
179 SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY => get_string('attemptstatusentry', 'scorm'));
183 * Extracts scrom package, sets up all variables.
184 * Called whenever scorm changes
185 * @param object $scorm instance - fields are updated and changes saved into database
186 * @param bool $full force full update if true
189 function scorm_parse($scorm, $full) {
191 $cfg_scorm = get_config('scorm');
193 if (!isset($scorm->cmid)) {
194 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
195 $scorm->cmid = $cm->id;
197 $context = context_module::instance($scorm->cmid);
198 $newhash = $scorm->sha1hash;
200 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
202 $fs = get_file_storage();
203 $packagefile = false;
205 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
206 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
207 $newhash = $packagefile->get_contenthash();
212 if (!$cfg_scorm->allowtypelocalsync) {
213 // sorry - localsync disabled
216 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
217 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
218 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
219 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
220 $newhash = sha1($scorm->reference);
228 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
229 if (strpos($scorm->version, 'SCORM') !== false) {
230 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
234 } else if (strpos($scorm->version, 'AICC') !== false) {
235 // TODO: add more sanity checks - something really exists in scorm_content area
241 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
243 $packer = get_file_packer('application/zip');
244 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
250 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
251 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
253 if (!scorm_parse_scorm($scorm, $manifest)) {
254 $scorm->version = 'ERROR';
257 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
259 if (!scorm_parse_aicc($scorm)) {
260 $scorm->version = 'ERROR';
262 $scorm->version = 'AICC';
265 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
266 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
267 // SCORM only, AICC can not be external
268 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
269 $scorm->version = 'ERROR';
271 $newhash = sha1($scorm->reference);
273 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfg_scorm->allowtypeexternalaicc) {
274 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
276 if (!scorm_parse_aicc($scorm)) {
277 $scorm->version = 'ERROR';
279 $scorm->version = 'AICC';
281 // sorry, disabled type
286 $scorm->sha1hash = $newhash;
287 $DB->update_record('scorm', $scorm);
291 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
292 if (!empty($haystacks)) {
293 foreach ($haystacks as $key => $element) {
295 if ($element->{$item} === $needle) {
299 if ($element->{$item} == $needle) {
308 function scorm_repeater($what, $times) {
313 for ($i=0; $i<$times; $i++) {
319 function scorm_external_link($link) {
320 // check if a link is external
322 $link = strtolower($link);
323 if (substr($link, 0, 7) == 'http://') {
325 } else if (substr($link, 0, 8) == 'https://') {
327 } else if (substr($link, 0, 4) == 'www.') {
334 * Returns an object containing all datas relative to the given sco ID
336 * @param integer $id The sco ID
337 * @return mixed (false if sco id does not exists)
339 function scorm_get_sco($id, $what=SCO_ALL) {
342 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
343 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
344 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
345 foreach ($scodatas as $scodata) {
346 $sco->{$scodata->name} = $scodata->value;
348 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
349 $sco->parameters = '';
358 * Returns an object (array) containing all the scoes data related to the given sco ID
360 * @param integer $id The sco ID
361 * @param integer $organisation an organisation ID - defaults to false if not required
362 * @return mixed (false if there are no scoes or an array)
364 function scorm_get_scoes($id, $organisation=false) {
367 $organizationsql = '';
368 $queryarray = array('scorm'=>$id);
369 if (!empty($organisation)) {
370 $queryarray['organization'] = $organisation;
372 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
373 // drop keys so that it is a simple array as expected
374 $scoes = array_values($scoes);
375 foreach ($scoes as $sco) {
376 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
377 foreach ($scodatas as $scodata) {
378 $sco->{$scodata->name} = $scodata->value;
388 function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
393 if ($forcecompleted) {
394 //TODO - this could be broadened to encompass SCORM 2004 in future
395 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
396 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))) {
397 $value = 'completed';
400 if ($element == 'cmi.core.score.raw') {
401 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))) {
402 if ($tracktest->value == "incomplete") {
403 $tracktest->value = "completed";
404 $DB->update_record('scorm_scoes_track', $tracktest);
408 if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
409 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
410 $objectiveprogressstatus = true;
411 $objectivesatisfiedstatus = false;
412 if ($value == 'passed') {
413 $objectivesatisfiedstatus = true;
416 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
417 'scormid' => $scormid,
419 'attempt' => $attempt,
420 'element' => 'objectiveprogressstatus'))) {
421 $track->value = $objectiveprogressstatus;
422 $track->timemodified = time();
423 $DB->update_record('scorm_scoes_track', $track);
426 $track = new stdClass();
427 $track->userid = $userid;
428 $track->scormid = $scormid;
429 $track->scoid = $scoid;
430 $track->attempt = $attempt;
431 $track->element = 'objectiveprogressstatus';
432 $track->value = $objectiveprogressstatus;
433 $track->timemodified = time();
434 $id = $DB->insert_record('scorm_scoes_track', $track);
436 if ($objectivesatisfiedstatus) {
437 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
438 'scormid' => $scormid,
440 'attempt' => $attempt,
441 'element' => 'objectivesatisfiedstatus'))) {
442 $track->value = $objectivesatisfiedstatus;
443 $track->timemodified = time();
444 $DB->update_record('scorm_scoes_track', $track);
447 $track = new stdClass();
448 $track->userid = $userid;
449 $track->scormid = $scormid;
450 $track->scoid = $scoid;
451 $track->attempt = $attempt;
452 $track->element = 'objectivesatisfiedstatus';
453 $track->value = $objectivesatisfiedstatus;
454 $track->timemodified = time();
455 $id = $DB->insert_record('scorm_scoes_track', $track);
457 $filepath = $CFG->dataroot."\\temp\\tempfile.txt";
458 $fh = fopen($filepath, "a+");
460 $string = ob_get_clean();
461 fwrite($fh, $string);
470 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
471 'scormid' => $scormid,
473 'attempt' => $attempt,
474 'element' => $element))) {
475 if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
476 $track->value = $value;
477 $track->timemodified = time();
478 $DB->update_record('scorm_scoes_track', $track);
482 $track = new stdClass();
483 $track->userid = $userid;
484 $track->scormid = $scormid;
485 $track->scoid = $scoid;
486 $track->attempt = $attempt;
487 $track->element = $element;
488 $track->value = $value;
489 $track->timemodified = time();
490 $id = $DB->insert_record('scorm_scoes_track', $track);
493 if (strstr($element, '.score.raw') ||
494 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
495 && in_array($track->value, array('completed', 'passed')))) {
496 $scorm = $DB->get_record('scorm', array('id' => $scormid));
497 include_once($CFG->dirroot.'/mod/scorm/lib.php');
498 scorm_update_grades($scorm, $userid);
505 * simple quick function to return true/false if this user has tracks in this scorm
507 * @param integer $scormid The scorm ID
508 * @param integer $userid the users id
509 * @return boolean (false if there are no tracks)
511 function scorm_has_tracks($scormid, $userid) {
513 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
516 function scorm_get_tracks($scoid, $userid, $attempt='') {
517 /// Gets all tracks of specified sco and user
520 if (empty($attempt)) {
521 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
522 $attempt = scorm_get_last_attempt($scormid, $userid);
527 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid, 'attempt'=>$attempt), 'element ASC')) {
528 $usertrack = new stdClass();
529 $usertrack->userid = $userid;
530 $usertrack->scoid = $scoid;
531 // Defined in order to unify scorm1.2 and scorm2004
532 $usertrack->score_raw = '';
533 $usertrack->status = '';
534 $usertrack->total_time = '00:00:00';
535 $usertrack->session_time = '00:00:00';
536 $usertrack->timemodified = 0;
537 foreach ($tracks as $track) {
538 $element = $track->element;
539 $usertrack->{$element} = $track->value;
541 case 'cmi.core.lesson_status':
542 case 'cmi.completion_status':
543 if ($track->value == 'not attempted') {
544 $track->value = 'notattempted';
546 $usertrack->status = $track->value;
548 case 'cmi.core.score.raw':
549 case 'cmi.score.raw':
550 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
552 case 'cmi.core.session_time':
553 case 'cmi.session_time':
554 $usertrack->session_time = $track->value;
556 case 'cmi.core.total_time':
557 case 'cmi.total_time':
558 $usertrack->total_time = $track->value;
561 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
562 $usertrack->timemodified = $track->timemodified;
565 if (is_array($usertrack)) {
575 /* Find the start and finsh time for a a given SCO attempt
577 * @param int $scormid SCORM Id
578 * @param int $scoid SCO Id
579 * @param int $userid User Id
580 * @param int $attemt Attempt Id
582 * @return object start and finsh time EPOC secods
585 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
588 $timedata = new stdClass();
589 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
590 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
592 $tracks = array_values($tracks);
596 $timedata->start = $tracks[0]->timemodified;
598 $timedata->start = false;
600 if ($tracks && $track = array_pop($tracks)) {
601 $timedata->finish = $track->timemodified;
603 $timedata->finish = $timedata->start;
609 function scorm_get_user_data($userid) {
611 /// Gets user info required to display the table of scorm results
614 return $DB->get_record('user', array('id'=>$userid), user_picture::fields());
617 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
619 $attemptscore = new stdClass();
620 $attemptscore->scoes = 0;
621 $attemptscore->values = 0;
622 $attemptscore->max = 0;
623 $attemptscore->sum = 0;
624 $attemptscore->lastmodify = 0;
626 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
630 foreach ($scoes as $sco) {
631 if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
632 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
633 $attemptscore->scoes++;
635 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
636 $attemptscore->values++;
637 $attemptscore->sum += $userdata->score_raw;
638 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
639 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
640 $attemptscore->lastmodify = $userdata->timemodified;
642 $attemptscore->lastmodify = 0;
647 switch ($scorm->grademethod) {
649 $score = (float) $attemptscore->max;
652 if ($attemptscore->values > 0) {
653 $score = $attemptscore->sum/$attemptscore->values;
659 $score = $attemptscore->sum;
662 $score = $attemptscore->scoes;
665 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
671 function scorm_grade_user($scorm, $userid) {
673 // ensure we dont grade user beyond $scorm->maxattempt settings
674 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
675 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
676 $lastattempt = $scorm->maxattempt;
679 switch ($scorm->whatgrade) {
681 return scorm_grade_user_attempt($scorm, $userid, 1);
684 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
688 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
689 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
690 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
696 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
697 if (empty($attemptcount)) {
700 $attemptcount = count($attemptcount);
702 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
704 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
705 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
706 $sumscore += $attemptscore;
709 return round($sumscore / $attemptcount);
714 function scorm_count_launchable($scormid, $organization='') {
717 $sqlorganization = '';
718 $params = array($scormid);
719 if (!empty($organization)) {
720 $sqlorganization = " AND organization=?";
721 $params[] = $organization;
723 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
727 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
729 * @param int $scormid the id of the scorm.
730 * @param int $userid the id of the user.
732 * @return int The attempt number to use.
734 function scorm_get_last_attempt($scormid, $userid) {
737 /// Find the last attempt number for the given user id and scorm id
738 $sql = "SELECT MAX(attempt)
739 FROM {scorm_scoes_track}
740 WHERE userid = ? AND scormid = ?";
741 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
742 if (empty($lastattempt)) {
750 * Returns the last completed attempt used - if no completed 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_completed_attempt($scormid, $userid) {
760 /// Find the last completed 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 AND (value='completed' OR value='passed')";
765 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
766 if (empty($lastattempt)) {
773 function scorm_course_format_display($user, $course) {
774 global $CFG, $DB, $PAGE, $OUTPUT;
776 $strupdate = get_string('update');
777 $context = context_course::instance($course->id);
779 echo '<div class="mod-scorm">';
780 if ($scorms = get_all_instances_in_course('scorm', $course)) {
781 // The module SCORM activity with the least id is the course
782 $scorm = current($scorms);
783 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
784 print_error('invalidcoursemodule');
786 $contextmodule = context_module::instance($cm->id);
787 if ((has_capability('mod/scorm:skipview', $contextmodule))) {
788 scorm_simple_play($scorm, $user, $contextmodule, $cm->id);
791 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
792 if (has_capability('moodle/course:manageactivities', $context)) {
793 if ($PAGE->user_is_editing()) {
794 // Display update icon
795 $path = $CFG->wwwroot.'/course';
796 $headertext .= '<span class="commands">'.
797 '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&sesskey='.sesskey().'">'.
798 '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
800 $headertext .= '</td>';
801 // Display report link
802 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
803 if ($trackedusers->c > 0) {
804 $headertext .= '<td class="reportlink">'.
805 '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
806 get_string('viewallreports', 'scorm', $trackedusers->c).'</a>';
808 $headertext .= '<td class="reportlink">'.get_string('noreports', 'scorm');
810 $colspan = ' colspan="2"';
812 $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
813 echo $OUTPUT->box($headertext, 'generalbox boxwidthwide');
814 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm);
816 if (has_capability('moodle/course:update', $context)) {
817 // Create a new activity
818 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'section'=>'0', 'sesskey'=>sesskey(),'add'=>'scorm'));
821 echo $OUTPUT->notification('Could not find a scorm course here');
827 function scorm_view_display ($user, $scorm, $action, $cm) {
828 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
830 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
831 scorm_parse($scorm, false);
834 $organization = optional_param('organization', '', PARAM_INT);
836 if ($scorm->displaycoursestructure == 1) {
837 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
839 <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
842 if (empty($organization)) {
843 $organization = $scorm->launch;
845 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
846 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
847 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
848 array($scorm->id), 'id', 'id,title')) {
849 if (count($orgs) > 1) {
850 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
851 $select->label = get_string('organizations', 'scorm');
852 $select->class = 'scorm-center';
853 echo $OUTPUT->render($select);
857 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
858 if (($sco->organization == '') && ($sco->launch == '')) {
859 $orgidentifier = $sco->identifier;
861 $orgidentifier = $sco->organization;
865 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
866 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
867 $scorm->version = 'scorm_12';
869 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
871 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
872 $incomplete = $result->incomplete;
874 // do we want the TOC to be displayed?
875 if ($scorm->displaycoursestructure == 1) {
877 echo $OUTPUT->box_end();
880 // is this the first attempt ?
881 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
883 // do not give the player launch FORM if the SCORM object is locked after the final attempt
884 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
886 <div class="scorm-center">
887 <form id="scormviewform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
889 if ($scorm->hidebrowse == 0) {
890 print_string('mode', 'scorm');
891 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
892 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
894 echo '<input type="hidden" name="mode" value="normal" />'."\n";
896 if ($scorm->forcenewattempt == 1) {
897 if ($incomplete === false) {
898 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
900 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
903 <input type="checkbox" id="a" name="newattempt" />
904 <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
907 if ($COURSE->format != 'scorm' && !empty($scorm->popup)) {
908 echo '<input type="hidden" name="display" value="popup" />'."\n";
912 <input type="hidden" name="scoid"/>
913 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
914 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
915 <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
922 function scorm_simple_play($scorm, $user, $context, $cmid) {
927 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
931 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
932 scorm_parse($scorm, false);
934 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
938 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
939 if (($sco->organization == '') && ($sco->launch == '')) {
940 $orgidentifier = $sco->identifier;
942 $orgidentifier = $sco->organization;
945 if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
946 $sco = current($scoes);
947 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
948 'currentorg'=>$orgidentifier,
950 if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
951 if (!empty($scorm->forcenewattempt)) {
952 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
953 if ($result->incomplete === false) {
954 $url->param('newattempt','on');
964 function scorm_get_count_users($scormid, $groupingid=null) {
967 if (!empty($groupingid)) {
968 $sql = "SELECT COUNT(DISTINCT st.userid)
969 FROM {scorm_scoes_track} st
970 INNER JOIN {groups_members} gm ON st.userid = gm.userid
971 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
972 WHERE st.scormid = ? AND gg.groupingid = ?
974 $params = array($scormid, $groupingid);
976 $sql = "SELECT COUNT(DISTINCT st.userid)
977 FROM {scorm_scoes_track} st
980 $params = array($scormid);
983 return ($DB->count_records_sql($sql, $params));
987 * Build up the JavaScript representation of an array element
989 * @param string $sversion SCORM API version
990 * @param array $userdata User track data
991 * @param string $element_name Name of array element to get values for
992 * @param array $children list of sub elements of this array element that also need instantiating
995 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
996 // reconstitute comments_from_learner and comments_from_lms
998 $current_subelement = '';
1002 $scormseperator = '_';
1003 if (scorm_version_check($sversion, SCORM_13)) { //scorm 1.3 elements use a . instead of an _
1004 $scormseperator = '.';
1006 // filter out the ones we want
1007 $element_list = array();
1008 foreach ($userdata as $element => $value) {
1009 if (substr($element, 0, strlen($element_name)) == $element_name) {
1010 $element_list[$element] = $value;
1014 // sort elements in .n array order
1015 uksort($element_list, "scorm_element_cmp");
1017 // generate JavaScript
1018 foreach ($element_list as $element => $value) {
1019 if (scorm_version_check($sversion, SCORM_13)) {
1020 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
1021 preg_match('/\.(N\d+)\./', $element, $matches);
1023 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
1024 preg_match('/\_(\d+)\./', $element, $matches);
1026 if (count($matches) > 0 && $current != $matches[1]) {
1027 if ($count_sub > 0) {
1028 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1030 $current = $matches[1];
1032 $current_subelement = '';
1035 $end = strpos($element, $matches[1])+strlen($matches[1]);
1036 $subelement = substr($element, 0, $end);
1037 echo ' '.$subelement." = new Object();\n";
1038 // now add the children
1039 foreach ($children as $child) {
1040 echo ' '.$subelement.".".$child." = new Object();\n";
1041 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
1045 // now - flesh out the second level elements if there are any
1046 if (scorm_version_check($sversion, SCORM_13)) {
1047 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1048 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1050 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1051 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1054 // check the sub element type
1055 if (count($matches) > 0 && $current_subelement != $matches[1]) {
1056 if ($count_sub > 0) {
1057 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1059 $current_subelement = $matches[1];
1062 $end = strpos($element, $matches[1])+strlen($matches[1]);
1063 $subelement = substr($element, 0, $end);
1064 echo ' '.$subelement." = new Object();\n";
1067 // now check the subelement subscript
1068 if (count($matches) > 0 && $current_sub != $matches[2]) {
1069 $current_sub = $matches[2];
1071 $end = strrpos($element, $matches[2])+strlen($matches[2]);
1072 $subelement = substr($element, 0, $end);
1073 echo ' '.$subelement." = new Object();\n";
1076 echo ' '.$element.' = \''.$value."';\n";
1078 if ($count_sub > 0) {
1079 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1082 echo ' '.$element_name.'._count = '.$count.";\n";
1087 * Build up the JavaScript representation of an array element
1089 * @param string $a left array element
1090 * @param string $b right array element
1091 * @return comparator - 0,1,-1
1093 function scorm_element_cmp($a, $b) {
1094 preg_match('/.*?(\d+)\./', $a, $matches);
1095 $left = intval($matches[1]);
1096 preg_match('/.?(\d+)\./', $b, $matches);
1097 $right = intval($matches[1]);
1098 if ($left < $right) {
1099 return -1; // smaller
1100 } else if ($left > $right) {
1103 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1104 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1105 $leftterm = intval($matches[2]);
1106 $left = intval($matches[3]);
1107 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1108 $rightterm = intval($matches[2]);
1109 $right = intval($matches[3]);
1110 if ($leftterm < $rightterm) {
1111 return -1; // smaller
1112 } else if ($leftterm > $rightterm) {
1115 if ($left < $right) {
1116 return -1; // smaller
1117 } else if ($left > $right) {
1123 // fall back for no second level matches or second level matches are equal
1124 return 0; // equal to
1129 * Generate the user attempt status string
1131 * @param object $user Current context user
1132 * @param object $scorm a moodle scrom object - mdl_scorm
1133 * @return string - Attempt status string
1135 function scorm_get_attempt_status($user, $scorm, $cm='') {
1136 global $DB, $PAGE, $OUTPUT;
1138 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
1139 if (empty($attempts)) {
1142 $attemptcount = count($attempts);
1145 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1146 if ($scorm->maxattempt > 0) {
1147 $result .= $scorm->maxattempt . '<br />';
1149 $result .= get_string('unlimited').'<br />';
1151 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1153 if ($scorm->maxattempt == 1) {
1154 switch ($scorm->grademethod) {
1156 $grademethod = get_string('gradehighest', 'scorm');
1159 $grademethod = get_string('gradeaverage', 'scorm');
1162 $grademethod = get_string('gradesum', 'scorm');
1165 $grademethod = get_string('gradescoes', 'scorm');
1169 switch ($scorm->whatgrade) {
1170 case HIGHESTATTEMPT:
1171 $grademethod = get_string('highestattempt', 'scorm');
1173 case AVERAGEATTEMPT:
1174 $grademethod = get_string('averageattempt', 'scorm');
1177 $grademethod = get_string('firstattempt', 'scorm');
1180 $grademethod = get_string('lastattempt', 'scorm');
1185 if (!empty($attempts)) {
1187 foreach ($attempts as $attempt) {
1188 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1189 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1190 $gradereported = $gradereported/$scorm->maxgrade;
1191 $gradereported = number_format($gradereported*100, 0) .'%';
1193 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1197 $calculatedgrade = scorm_grade_user($scorm, $user->id);
1198 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1199 $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1200 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1202 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1203 if (empty($attempts)) {
1204 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1206 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1209 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1210 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1213 $context = context_module::instance($cm->id);
1214 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1215 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
1216 //check to see if any data is stored for this user:
1217 $deleteurl = new moodle_url($PAGE->url, array('action'=>'delete', 'sesskey' => sesskey()));
1218 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1227 * Get SCORM attempt count
1229 * @param object $user Current context user
1230 * @param object $scorm a moodle scrom object - mdl_scorm
1231 * @param bool $attempts return the list of attempts
1232 * @return int - no. of attempts so far
1234 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1237 $element = 'cmi.core.score.raw';
1238 if ($scorm->grademethod == GRADESCOES) {
1239 $element = 'cmi.core.lesson_status';
1241 if (scorm_version_check($scorm->version, SCORM_13)) {
1242 $element = 'cmi.score.raw';
1244 $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id), 'attempt', 'DISTINCT attempt AS attemptnumber');
1245 if ($attempts_only) {
1248 if (!empty($attempts)) {
1249 $attemptcount = count($attempts);
1251 return $attemptcount;
1255 * Figure out with this is a debug situation
1257 * @param object $scorm a moodle scrom object - mdl_scorm
1258 * @return boolean - debugging true/false
1260 function scorm_debugging($scorm) {
1262 $cfg_scorm = get_config('scorm');
1264 if (!$cfg_scorm->allowapidebug) {
1267 $identifier = $USER->username.':'.$scorm->name;
1268 $test = $cfg_scorm->apidebugmask;
1269 // check the regex is only a short list of safe characters
1270 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1274 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1279 * Delete Scorm tracks for selected users
1281 * @param array $attemptids list of attempts that need to be deleted
1282 * @param int $scorm instance
1284 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1286 function scorm_delete_responses($attemptids, $scorm) {
1287 if (!is_array($attemptids) || empty($attemptids)) {
1291 foreach ($attemptids as $num => $attemptid) {
1292 if (empty($attemptid)) {
1293 unset($attemptids[$num]);
1297 foreach ($attemptids as $attempt) {
1298 $keys = explode(':', $attempt);
1299 if (count($keys) == 2) {
1300 $userid = clean_param($keys[0], PARAM_INT);
1301 $attemptid = clean_param($keys[1], PARAM_INT);
1302 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
1313 * Delete Scorm tracks for selected users
1315 * @param int $userid ID of User
1316 * @param int $scormid ID of Scorm
1317 * @param int $attemptid user attempt that need to be deleted
1319 * return bool true suceeded
1321 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1324 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1325 include_once('lib.php');
1326 scorm_update_grades($scorm, $userid, true);
1331 * Converts SCORM duration notation to human-readable format
1332 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1333 * @param $duration string SCORM duration
1334 * @return string human-readable date/time
1336 function scorm_format_duration($duration) {
1337 // fetch date/time strings
1338 $stryears = get_string('years');
1339 $strmonths = get_string('nummonths');
1340 $strdays = get_string('days');
1341 $strhours = get_string('hours');
1342 $strminutes = get_string('minutes');
1343 $strseconds = get_string('seconds');
1345 if ($duration[0] == 'P') {
1346 // if timestamp starts with 'P' - it's a SCORM 2004 format
1347 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1348 // and outputs filled sections, discarding leading zeroes and any format literals
1349 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1350 $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#',
1351 '#([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#' );
1352 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1353 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1355 // else we have SCORM 1.2 format there
1356 // first convert the timestamp to some SCORM 2004-like format for conveniency
1357 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1358 // then convert in the same way as SCORM 2004
1359 $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#' );
1360 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1363 $result = preg_replace($pattern, $replace, $duration);
1368 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1369 global $CFG, $DB, $PAGE, $OUTPUT;
1372 if ($mode == 'browse') {
1373 $modestr = '&mode='.$mode;
1377 $incomplete = false;
1379 if (!empty($organizationsco)) {
1380 $result[0] = $organizationsco;
1381 $result[0]->isvisible = true;
1382 $result[0]->statusicon = '';
1383 $result[0]->url = '';
1386 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1387 // Retrieve user tracking data for each learning object.
1388 $usertracks = array();
1389 foreach ($scoes as $sco) {
1390 if (!empty($sco->launch)) {
1391 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
1392 if ($usertrack->status == '') {
1393 $usertrack->status = 'notattempted';
1395 $usertracks[$sco->identifier] = $usertrack;
1399 foreach ($scoes as $sco) {
1400 if (!isset($sco->isvisible)) {
1401 $sco->isvisible = true;
1404 if (empty($sco->title)) {
1405 $sco->title = $sco->identifier;
1408 if (scorm_version_check($scorm->version, SCORM_13)) {
1409 $sco->prereq = true;
1411 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1414 if ($sco->isvisible) {
1415 if (!empty($sco->launch)) {
1416 if (empty($scoid) && ($mode != 'normal')) {
1420 if (isset($usertracks[$sco->identifier])) {
1421 $usertrack = $usertracks[$sco->identifier];
1422 $strstatus = get_string($usertrack->status,'scorm');
1424 if ($sco->scormtype == 'sco') {
1425 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1427 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1430 if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1432 if ($play && empty($scoid)) {
1437 $strsuspended = get_string('suspended', 'scorm');
1439 $exitvar = 'cmi.core.exit';
1441 if (scorm_version_check($scorm->version, SCORM_13)) {
1442 $exitvar = 'cmi.exit';
1445 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1446 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1450 if ($play && empty($scoid)) {
1456 if ($sco->scormtype == 'sco') {
1457 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1459 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1465 if (empty($statusicon)) {
1466 $sco->statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1468 $sco->statusicon = $statusicon;
1471 $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
1472 $sco->incomplete = $incomplete;
1474 if (!in_array($sco->id, array_keys($result))) {
1475 $result[$sco->id] = $sco;
1480 // Get the parent scoes!
1481 $result = scorm_get_toc_get_parent_child($result);
1483 // Be safe, prevent warnings from showing up while returning array
1484 if (!isset($scoid)) {
1488 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1491 function scorm_get_toc_get_parent_child(&$result) {
1497 foreach ($result as $sco) {
1498 if ($sco->parent == '/') {
1499 $final[$level][$sco->identifier] = $sco;
1500 $prevparent = $sco->identifier;
1501 unset($result[$sco->id]);
1503 if ($sco->parent == $prevparent) {
1504 $final[$level][$sco->identifier] = $sco;
1505 $prevparent = $sco->identifier;
1506 unset($result[$sco->id]);
1508 if (!empty($final[$level])) {
1510 foreach ($final[$level] as $fin) {
1511 if ($sco->parent == $fin->identifier) {
1517 $final[$level][$sco->identifier] = $sco;
1518 unset($result[$sco->id]);
1522 $final[$level][$sco->identifier] = $sco;
1523 unset($result[$sco->id]);
1530 for ($i = 0; $i <= $level; $i++) {
1532 foreach ($final[$i] as $ident => $sco) {
1533 if (empty($prevparent)) {
1534 $prevparent = $ident;
1536 if (!isset($final[$i][$prevparent]->children)) {
1537 $final[$i][$prevparent]->children = array();
1539 if ($sco->parent == $prevparent) {
1540 $final[$i][$prevparent]->children[] = $sco;
1541 $prevparent = $ident;
1544 foreach ($final[$i] as $identifier => $scoobj) {
1545 if ($identifier == $sco->parent) {
1546 $parent = $identifier;
1550 if ($parent !== false) {
1551 $final[$i][$parent]->children[] = $sco;
1558 for ($i = 0; $i <= $level; $i++) {
1559 $keys = array_keys($final[$i]);
1560 $results[] = $final[$i][$keys[0]];
1566 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1569 $result = new stdClass();
1570 $result->prerequisites = true;
1571 $result->incomplete = true;
1575 $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1576 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
1580 $result->toc = "<ul>\n";
1582 if (!$play && !empty($organizationsco)) {
1583 $result->toc .= "\t<li>".$organizationsco->title."</li>\n";
1588 if (!empty($scoes)) {
1589 foreach ($scoes as $sco) {
1590 $result->toc .= "\t<li>\n";
1593 $sco->isvisible = true;
1595 if ($sco->isvisible) {
1598 if (isset($usertracks[$sco->identifier])) {
1599 $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
1600 if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1601 if ($usertracks[$sco->identifier]->score_raw != '') {
1602 $score = '('.get_string('score','scorm').': '.$usertracks[$sco->identifier]->score_raw.')';
1607 if (!empty($sco->prereq)) {
1608 if ($sco->id == $scoid) {
1609 $result->prerequisites = true;
1612 if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1613 if ($sco->scormtype == 'sco') {
1614 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1616 $result->toc .= '<span> '.format_string($sco->title).'</span>';
1618 } else if ($toclink == TOCFULLURL) {
1619 $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
1620 if (!empty($sco->launch)) {
1621 if ($sco->scormtype == 'sco') {
1622 $result->toc .= $sco->statusicon.' <a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1624 $result->toc .= ' <a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1627 if ($sco->scormtype == 'sco') {
1628 $result->toc .= $sco->statusicon.' '.format_string($sco->title).$score."\n";
1630 $result->toc .= ' '.format_string($sco->title).$score."\n";
1634 if (!empty($sco->launch)) {
1635 if ($sco->scormtype == 'sco') {
1636 $result->toc .= '<a title="'.$sco->url.'">'.$sco->statusicon.' '.format_string($sco->title).' '.$score.'</a>';
1638 $result->toc .= '<a title="'.$sco->url.'"> '.format_string($sco->title).' '.$score.'</a>';
1641 if ($sco->scormtype == 'sco') {
1642 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1644 $result->toc .= '<span> '.format_string($sco->title).'</span>';
1651 if ($sco->scormtype == 'sco') {
1652 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1654 $result->toc .= ' '.format_string($sco->title).'</span>';
1657 if ($sco->scormtype == 'sco') {
1658 $result->toc .= $sco->statusicon.' '.format_string($sco->title)."\n";
1660 $result->toc .= ' '.format_string($sco->title)."\n";
1666 $result->toc .= "\t\t ".format_string($sco->title)."\n";
1669 if (!empty($sco->children)) {
1670 $result->toc .= "\n\t\t<ul>\n";
1671 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1672 $result->toc .= $childresult->toc;
1673 $result->toc .= "\t\t</ul>\n";
1674 $result->toc .= "\t</li>\n";
1676 $result->toc .= "\t</li>\n";
1680 $result->incomplete = $sco->incomplete;
1684 $result->toc .= "</ul>\n";
1690 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1691 if (!empty($scoes)) {
1692 if (!empty($organizationsco) && !$children) {
1693 $tocmenus[$organizationsco->id] = $organizationsco->title;
1696 $parents[$level]='/';
1697 foreach ($scoes as $sco) {
1698 if ($parents[$level] != $sco->parent) {
1699 if ($newlevel = array_search($sco->parent, $parents)) {
1703 while (($i > 0) && ($parents[$level] != $sco->parent)) {
1707 if (($i == 0) && ($sco->parent != $currentorg)) {
1713 $parents[$level] = $sco->parent;
1718 if ($sco->scormtype == 'sco') {
1719 $tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
1722 if ($sco->scormtype == 'sco') {
1723 $tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
1727 if (!empty($sco->children)) {
1728 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1736 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1737 global $CFG, $DB, $OUTPUT;
1739 if (empty($attempt)) {
1740 $attempt = scorm_get_attempt_count($user->id, $scorm);
1743 $result = new stdClass();
1744 $organizationsco = null;
1747 $result->toc = "<div id=\"scorm_layout\">\n";
1748 $result->toc .= "<div id=\"scorm_toc\">\n";
1749 $result->toc .= "<div id=\"scorm_tree\">\n";
1752 if (!empty($currentorg)) {
1753 $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id, 'identifier'=>$currentorg));
1754 if (!empty($organizationsco->title)) {
1756 $result->toctitle = $organizationsco->title;
1761 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1763 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1766 $result->toc .= $treeview->toc;
1768 $result->toc = $treeview->toc;
1771 if (!empty($scoes['scoid'])) {
1772 $scoid = $scoes['scoid'];
1775 if (empty($scoid)) {
1776 $result->sco = $scoes['scoes'][0]->children[0];
1778 $result->sco = scorm_get_sco($scoid);
1781 if ($scorm->hidetoc == SCORM_TOC_POPUP) {
1782 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $currentorg, $organizationsco);
1785 if ($mode == 'browse') {
1786 $modestr = '&mode='.$mode;
1789 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'¤torg='.$currentorg.$modestr);
1790 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
1793 $result->prerequisites = $treeview->prerequisites;
1794 $result->incomplete = $treeview->incomplete;
1795 $result->attemptleft = $treeview->attemptleft;
1798 $result->toc .= "</div></div></div>\n";
1799 $result->toc .= "<div id=\"scorm_navpanel\"></div>\n";
1805 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1806 if (is_object($scoes)) {
1808 if (isset($sco->url)) {
1809 $adlnav[$sco->id]['identifier'] = $sco->identifier;
1810 $adlnav[$sco->id]['launch'] = $sco->launch;
1811 $adlnav[$sco->id]['title'] = $sco->title;
1812 $adlnav[$sco->id]['url'] = $sco->url;
1813 $adlnav[$sco->id]['parent'] = $sco->parent;
1814 if (isset($sco->choice)) {
1815 $adlnav[$sco->id]['choice'] = $sco->choice;
1817 if (isset($sco->flow)) {
1818 $adlnav[$sco->id]['flow'] = $sco->flow;
1819 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1820 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1822 if (isset($sco->isvisible)) {
1823 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1825 if (isset($sco->parameters)) {
1826 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1828 if (isset($sco->hidecontinue)) {
1829 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1831 if (isset($sco->hideprevious)) {
1832 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1834 if (isset($sco->hidesuspendall)) {
1835 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1837 if (!empty($parentscoid)) {
1838 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1840 if (isset($adlnav['prevscoid'])) {
1841 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1842 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1843 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1844 $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1845 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1848 $adlnav['prevscoid'] = $sco->id;
1849 $adlnav['prevparent'] = $sco->parent;
1851 if (isset($sco->children)) {
1852 foreach ($sco->children as $children) {
1853 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1857 foreach ($scoes as $sco) {
1858 scorm_get_adlnav_json ($sco, $adlnav);
1860 unset($adlnav['prevscoid']);
1861 unset($adlnav['prevparent']);
1863 return json_encode($adlnav);
1867 * Check for the availability of a resource by URL.
1869 * Check is performed using an HTTP HEAD call.
1871 * @param $url string A valid URL
1872 * @return bool|string True if no issue is found. The error string message, otherwise
1874 function scorm_check_url($url) {
1877 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1878 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1879 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1881 $cmsg = $curl->head($url);
1882 $info = $curl->get_info();
1883 if (empty($info['http_code']) || $info['http_code'] != 200) {
1884 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));