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 if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
208 $packagefile->import_external_file_contents();
210 $newhash = $packagefile->get_contenthash();
215 if (!$cfg_scorm->allowtypelocalsync) {
216 // sorry - localsync disabled
219 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
220 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
221 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
222 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
223 $newhash = sha1($scorm->reference);
231 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
232 if (strpos($scorm->version, 'SCORM') !== false) {
233 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
237 } else if (strpos($scorm->version, 'AICC') !== false) {
238 // TODO: add more sanity checks - something really exists in scorm_content area
244 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
246 $packer = get_file_packer('application/zip');
247 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
253 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
254 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
256 if (!scorm_parse_scorm($scorm, $manifest)) {
257 $scorm->version = 'ERROR';
260 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
262 if (!scorm_parse_aicc($scorm)) {
263 $scorm->version = 'ERROR';
265 $scorm->version = 'AICC';
268 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
269 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
270 // SCORM only, AICC can not be external
271 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
272 $scorm->version = 'ERROR';
274 $newhash = sha1($scorm->reference);
276 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfg_scorm->allowtypeexternalaicc) {
277 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
279 if (!scorm_parse_aicc($scorm)) {
280 $scorm->version = 'ERROR';
282 $scorm->version = 'AICC';
284 // sorry, disabled type
289 $scorm->sha1hash = $newhash;
290 $DB->update_record('scorm', $scorm);
294 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
295 if (!empty($haystacks)) {
296 foreach ($haystacks as $key => $element) {
298 if ($element->{$item} === $needle) {
302 if ($element->{$item} == $needle) {
311 function scorm_repeater($what, $times) {
316 for ($i=0; $i<$times; $i++) {
322 function scorm_external_link($link) {
323 // check if a link is external
325 $link = strtolower($link);
326 if (substr($link, 0, 7) == 'http://') {
328 } else if (substr($link, 0, 8) == 'https://') {
330 } else if (substr($link, 0, 4) == 'www.') {
337 * Returns an object containing all datas relative to the given sco ID
339 * @param integer $id The sco ID
340 * @return mixed (false if sco id does not exists)
342 function scorm_get_sco($id, $what=SCO_ALL) {
345 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
346 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
347 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
348 foreach ($scodatas as $scodata) {
349 $sco->{$scodata->name} = $scodata->value;
351 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
352 $sco->parameters = '';
361 * Returns an object (array) containing all the scoes data related to the given sco ID
363 * @param integer $id The sco ID
364 * @param integer $organisation an organisation ID - defaults to false if not required
365 * @return mixed (false if there are no scoes or an array)
367 function scorm_get_scoes($id, $organisation=false) {
370 $queryarray = array('scorm'=>$id);
371 if (!empty($organisation)) {
372 $queryarray['organization'] = $organisation;
374 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
375 // Drop keys so that it is a simple array as expected.
376 $scoes = array_values($scoes);
377 foreach ($scoes as $sco) {
378 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
379 foreach ($scodatas as $scodata) {
380 $sco->{$scodata->name} = $scodata->value;
390 function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
395 if ($forcecompleted) {
396 //TODO - this could be broadened to encompass SCORM 2004 in future
397 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
398 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))) {
399 $value = 'completed';
402 if ($element == 'cmi.core.score.raw') {
403 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))) {
404 if ($tracktest->value == "incomplete") {
405 $tracktest->value = "completed";
406 $DB->update_record('scorm_scoes_track', $tracktest);
410 if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
411 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
412 $objectiveprogressstatus = true;
413 $objectivesatisfiedstatus = false;
414 if ($value == 'passed') {
415 $objectivesatisfiedstatus = true;
418 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
419 'scormid' => $scormid,
421 'attempt' => $attempt,
422 'element' => 'objectiveprogressstatus'))) {
423 $track->value = $objectiveprogressstatus;
424 $track->timemodified = time();
425 $DB->update_record('scorm_scoes_track', $track);
428 $track = new stdClass();
429 $track->userid = $userid;
430 $track->scormid = $scormid;
431 $track->scoid = $scoid;
432 $track->attempt = $attempt;
433 $track->element = 'objectiveprogressstatus';
434 $track->value = $objectiveprogressstatus;
435 $track->timemodified = time();
436 $id = $DB->insert_record('scorm_scoes_track', $track);
438 if ($objectivesatisfiedstatus) {
439 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
440 'scormid' => $scormid,
442 'attempt' => $attempt,
443 'element' => 'objectivesatisfiedstatus'))) {
444 $track->value = $objectivesatisfiedstatus;
445 $track->timemodified = time();
446 $DB->update_record('scorm_scoes_track', $track);
449 $track = new stdClass();
450 $track->userid = $userid;
451 $track->scormid = $scormid;
452 $track->scoid = $scoid;
453 $track->attempt = $attempt;
454 $track->element = 'objectivesatisfiedstatus';
455 $track->value = $objectivesatisfiedstatus;
456 $track->timemodified = time();
457 $id = $DB->insert_record('scorm_scoes_track', $track);
459 $filepath = $CFG->dataroot."\\temp\\tempfile.txt";
460 $fh = fopen($filepath, "a+");
462 $string = ob_get_clean();
463 fwrite($fh, $string);
472 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
473 'scormid' => $scormid,
475 'attempt' => $attempt,
476 'element' => $element))) {
477 if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
478 $track->value = $value;
479 $track->timemodified = time();
480 $DB->update_record('scorm_scoes_track', $track);
484 $track = new stdClass();
485 $track->userid = $userid;
486 $track->scormid = $scormid;
487 $track->scoid = $scoid;
488 $track->attempt = $attempt;
489 $track->element = $element;
490 $track->value = $value;
491 $track->timemodified = time();
492 $id = $DB->insert_record('scorm_scoes_track', $track);
495 if (strstr($element, '.score.raw') ||
496 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
497 && in_array($track->value, array('completed', 'passed')))) {
498 $scorm = $DB->get_record('scorm', array('id' => $scormid));
499 include_once($CFG->dirroot.'/mod/scorm/lib.php');
500 scorm_update_grades($scorm, $userid);
507 * simple quick function to return true/false if this user has tracks in this scorm
509 * @param integer $scormid The scorm ID
510 * @param integer $userid the users id
511 * @return boolean (false if there are no tracks)
513 function scorm_has_tracks($scormid, $userid) {
515 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
518 function scorm_get_tracks($scoid, $userid, $attempt='') {
519 // Gets all tracks of specified sco and user.
522 if (empty($attempt)) {
523 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
524 $attempt = scorm_get_last_attempt($scormid, $userid);
529 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid,
530 'attempt'=>$attempt), 'element ASC')) {
531 $usertrack = scorm_format_interactions($tracks);
532 $usertrack->userid = $userid;
533 $usertrack->scoid = $scoid;
541 * helper function to return a formatted list of interactions for reports.
543 * @param array $trackdata the records from scorm_scoes_track table
544 * @return object formatted list of interactions
546 function scorm_format_interactions($trackdata) {
547 $usertrack = new stdClass();
549 // Defined in order to unify scorm1.2 and scorm2004.
550 $usertrack->score_raw = '';
551 $usertrack->status = '';
552 $usertrack->total_time = '00:00:00';
553 $usertrack->session_time = '00:00:00';
554 $usertrack->timemodified = 0;
556 foreach ($trackdata as $track) {
557 $element = $track->element;
558 $usertrack->{$element} = $track->value;
560 case 'cmi.core.lesson_status':
561 case 'cmi.completion_status':
562 if ($track->value == 'not attempted') {
563 $track->value = 'notattempted';
565 $usertrack->status = $track->value;
567 case 'cmi.core.score.raw':
568 case 'cmi.score.raw':
569 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
571 case 'cmi.core.session_time':
572 case 'cmi.session_time':
573 $usertrack->session_time = $track->value;
575 case 'cmi.core.total_time':
576 case 'cmi.total_time':
577 $usertrack->total_time = $track->value;
580 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
581 $usertrack->timemodified = $track->timemodified;
587 /* Find the start and finsh time for a a given SCO attempt
589 * @param int $scormid SCORM Id
590 * @param int $scoid SCO Id
591 * @param int $userid User Id
592 * @param int $attemt Attempt Id
594 * @return object start and finsh time EPOC secods
597 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
600 $timedata = new stdClass();
601 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
602 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
604 $tracks = array_values($tracks);
608 $timedata->start = $tracks[0]->timemodified;
610 $timedata->start = false;
612 if ($tracks && $track = array_pop($tracks)) {
613 $timedata->finish = $track->timemodified;
615 $timedata->finish = $timedata->start;
620 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
622 $attemptscore = new stdClass();
623 $attemptscore->scoes = 0;
624 $attemptscore->values = 0;
625 $attemptscore->max = 0;
626 $attemptscore->sum = 0;
627 $attemptscore->lastmodify = 0;
629 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
633 foreach ($scoes as $sco) {
634 if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
635 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
636 $attemptscore->scoes++;
638 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
639 $attemptscore->values++;
640 $attemptscore->sum += $userdata->score_raw;
641 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
642 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
643 $attemptscore->lastmodify = $userdata->timemodified;
645 $attemptscore->lastmodify = 0;
650 switch ($scorm->grademethod) {
652 $score = (float) $attemptscore->max;
655 if ($attemptscore->values > 0) {
656 $score = $attemptscore->sum/$attemptscore->values;
662 $score = $attemptscore->sum;
665 $score = $attemptscore->scoes;
668 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
674 function scorm_grade_user($scorm, $userid) {
676 // ensure we dont grade user beyond $scorm->maxattempt settings
677 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
678 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
679 $lastattempt = $scorm->maxattempt;
682 switch ($scorm->whatgrade) {
684 return scorm_grade_user_attempt($scorm, $userid, 1);
687 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
691 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
692 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
693 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
699 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
700 if (empty($attemptcount)) {
703 $attemptcount = count($attemptcount);
705 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
707 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
708 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
709 $sumscore += $attemptscore;
712 return round($sumscore / $attemptcount);
717 function scorm_count_launchable($scormid, $organization='') {
720 $sqlorganization = '';
721 $params = array($scormid);
722 if (!empty($organization)) {
723 $sqlorganization = " AND organization=?";
724 $params[] = $organization;
726 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
730 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
732 * @param int $scormid the id of the scorm.
733 * @param int $userid the id of the user.
735 * @return int The attempt number to use.
737 function scorm_get_last_attempt($scormid, $userid) {
740 /// Find the last attempt number for the given user id and scorm id
741 $sql = "SELECT MAX(attempt)
742 FROM {scorm_scoes_track}
743 WHERE userid = ? AND scormid = ?";
744 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
745 if (empty($lastattempt)) {
753 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
755 * @param int $scormid the id of the scorm.
756 * @param int $userid the id of the user.
758 * @return int The attempt number to use.
760 function scorm_get_last_completed_attempt($scormid, $userid) {
763 /// Find the last completed attempt number for the given user id and scorm id
764 $sql = "SELECT MAX(attempt)
765 FROM {scorm_scoes_track}
766 WHERE userid = ? AND scormid = ?
767 AND (value='completed' OR value='passed')";
768 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
769 if (empty($lastattempt)) {
777 * Returns the full list of attempts a user has made.
779 * @param int $scormid the id of the scorm.
780 * @param int $userid the id of the user.
782 * @return array array of attemptids
784 function scorm_get_all_attempts($scormid, $userid) {
786 $attemptids = array();
787 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
788 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
789 foreach ($attempts as $attempt) {
790 $attemptids[] = $attempt->attempt;
795 function scorm_view_display ($user, $scorm, $action, $cm) {
796 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
798 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
799 scorm_parse($scorm, false);
802 $organization = optional_param('organization', '', PARAM_INT);
804 if ($scorm->displaycoursestructure == 1) {
805 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
807 <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
810 if (empty($organization)) {
811 $organization = $scorm->launch;
813 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
814 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
815 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
816 array($scorm->id), 'sortorder, id', 'id,title')) {
817 if (count($orgs) > 1) {
818 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
819 $select->label = get_string('organizations', 'scorm');
820 $select->class = 'scorm-center';
821 echo $OUTPUT->render($select);
825 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
826 if (($sco->organization == '') && ($sco->launch == '')) {
827 $orgidentifier = $sco->identifier;
829 $orgidentifier = $sco->organization;
833 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
834 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
835 $scorm->version = 'scorm_12';
837 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
839 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
840 $incomplete = $result->incomplete;
842 // do we want the TOC to be displayed?
843 if ($scorm->displaycoursestructure == 1) {
845 echo $OUTPUT->box_end();
848 // is this the first attempt ?
849 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
851 // do not give the player launch FORM if the SCORM object is locked after the final attempt
852 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
854 <div class="scorm-center">
855 <form id="scormviewform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
857 if ($scorm->hidebrowse == 0) {
858 print_string('mode', 'scorm');
859 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
860 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
862 echo '<input type="hidden" name="mode" value="normal" />'."\n";
864 if ($scorm->forcenewattempt == 1) {
865 if ($incomplete === false) {
866 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
868 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
871 <input type="checkbox" id="a" name="newattempt" />
872 <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
875 if (!empty($scorm->popup)) {
876 echo '<input type="hidden" name="display" value="popup" />'."\n";
880 <input type="hidden" name="scoid"/>
881 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
882 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
883 <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
890 function scorm_simple_play($scorm, $user, $context, $cmid) {
895 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
899 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
900 scorm_parse($scorm, false);
902 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
903 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
907 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
908 if (($sco->organization == '') && ($sco->launch == '')) {
909 $orgidentifier = $sco->identifier;
911 $orgidentifier = $sco->organization;
914 if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
915 $sco = current($scoes);
916 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
917 'currentorg'=>$orgidentifier,
919 if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
920 if (!empty($scorm->forcenewattempt)) {
921 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
922 if ($result->incomplete === false) {
923 $url->param('newattempt','on');
933 function scorm_get_count_users($scormid, $groupingid=null) {
936 if (!empty($groupingid)) {
937 $sql = "SELECT COUNT(DISTINCT st.userid)
938 FROM {scorm_scoes_track} st
939 INNER JOIN {groups_members} gm ON st.userid = gm.userid
940 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
941 WHERE st.scormid = ? AND gg.groupingid = ?
943 $params = array($scormid, $groupingid);
945 $sql = "SELECT COUNT(DISTINCT st.userid)
946 FROM {scorm_scoes_track} st
949 $params = array($scormid);
952 return ($DB->count_records_sql($sql, $params));
956 * Build up the JavaScript representation of an array element
958 * @param string $sversion SCORM API version
959 * @param array $userdata User track data
960 * @param string $element_name Name of array element to get values for
961 * @param array $children list of sub elements of this array element that also need instantiating
964 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
965 // reconstitute comments_from_learner and comments_from_lms
967 $current_subelement = '';
971 $scormseperator = '_';
972 if (scorm_version_check($sversion, SCORM_13)) { //scorm 1.3 elements use a . instead of an _
973 $scormseperator = '.';
975 // filter out the ones we want
976 $element_list = array();
977 foreach ($userdata as $element => $value) {
978 if (substr($element, 0, strlen($element_name)) == $element_name) {
979 $element_list[$element] = $value;
983 // sort elements in .n array order
984 uksort($element_list, "scorm_element_cmp");
986 // generate JavaScript
987 foreach ($element_list as $element => $value) {
988 if (scorm_version_check($sversion, SCORM_13)) {
989 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
990 preg_match('/\.(N\d+)\./', $element, $matches);
992 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
993 preg_match('/\_(\d+)\./', $element, $matches);
995 if (count($matches) > 0 && $current != $matches[1]) {
996 if ($count_sub > 0) {
997 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
999 $current = $matches[1];
1001 $current_subelement = '';
1004 $end = strpos($element, $matches[1])+strlen($matches[1]);
1005 $subelement = substr($element, 0, $end);
1006 echo ' '.$subelement." = new Object();\n";
1007 // now add the children
1008 foreach ($children as $child) {
1009 echo ' '.$subelement.".".$child." = new Object();\n";
1010 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
1014 // now - flesh out the second level elements if there are any
1015 if (scorm_version_check($sversion, SCORM_13)) {
1016 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1017 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1019 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1020 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1023 // check the sub element type
1024 if (count($matches) > 0 && $current_subelement != $matches[1]) {
1025 if ($count_sub > 0) {
1026 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1028 $current_subelement = $matches[1];
1031 $end = strpos($element, $matches[1])+strlen($matches[1]);
1032 $subelement = substr($element, 0, $end);
1033 echo ' '.$subelement." = new Object();\n";
1036 // now check the subelement subscript
1037 if (count($matches) > 0 && $current_sub != $matches[2]) {
1038 $current_sub = $matches[2];
1040 $end = strrpos($element, $matches[2])+strlen($matches[2]);
1041 $subelement = substr($element, 0, $end);
1042 echo ' '.$subelement." = new Object();\n";
1045 echo ' '.$element.' = \''.$value."';\n";
1047 if ($count_sub > 0) {
1048 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1051 echo ' '.$element_name.'._count = '.$count.";\n";
1056 * Build up the JavaScript representation of an array element
1058 * @param string $a left array element
1059 * @param string $b right array element
1060 * @return comparator - 0,1,-1
1062 function scorm_element_cmp($a, $b) {
1063 preg_match('/.*?(\d+)\./', $a, $matches);
1064 $left = intval($matches[1]);
1065 preg_match('/.?(\d+)\./', $b, $matches);
1066 $right = intval($matches[1]);
1067 if ($left < $right) {
1068 return -1; // smaller
1069 } else if ($left > $right) {
1072 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1073 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1074 $leftterm = intval($matches[2]);
1075 $left = intval($matches[3]);
1076 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1077 $rightterm = intval($matches[2]);
1078 $right = intval($matches[3]);
1079 if ($leftterm < $rightterm) {
1080 return -1; // smaller
1081 } else if ($leftterm > $rightterm) {
1084 if ($left < $right) {
1085 return -1; // smaller
1086 } else if ($left > $right) {
1092 // fall back for no second level matches or second level matches are equal
1093 return 0; // equal to
1098 * Generate the user attempt status string
1100 * @param object $user Current context user
1101 * @param object $scorm a moodle scrom object - mdl_scorm
1102 * @return string - Attempt status string
1104 function scorm_get_attempt_status($user, $scorm, $cm='') {
1105 global $DB, $PAGE, $OUTPUT;
1107 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
1108 if (empty($attempts)) {
1111 $attemptcount = count($attempts);
1114 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1115 if ($scorm->maxattempt > 0) {
1116 $result .= $scorm->maxattempt . '<br />';
1118 $result .= get_string('unlimited').'<br />';
1120 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1122 if ($scorm->maxattempt == 1) {
1123 switch ($scorm->grademethod) {
1125 $grademethod = get_string('gradehighest', 'scorm');
1128 $grademethod = get_string('gradeaverage', 'scorm');
1131 $grademethod = get_string('gradesum', 'scorm');
1134 $grademethod = get_string('gradescoes', 'scorm');
1138 switch ($scorm->whatgrade) {
1139 case HIGHESTATTEMPT:
1140 $grademethod = get_string('highestattempt', 'scorm');
1142 case AVERAGEATTEMPT:
1143 $grademethod = get_string('averageattempt', 'scorm');
1146 $grademethod = get_string('firstattempt', 'scorm');
1149 $grademethod = get_string('lastattempt', 'scorm');
1154 if (!empty($attempts)) {
1156 foreach ($attempts as $attempt) {
1157 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1158 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1159 $gradereported = $gradereported/$scorm->maxgrade;
1160 $gradereported = number_format($gradereported*100, 0) .'%';
1162 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1166 $calculatedgrade = scorm_grade_user($scorm, $user->id);
1167 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1168 $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1169 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1171 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1172 if (empty($attempts)) {
1173 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1175 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1178 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1179 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1182 $context = context_module::instance($cm->id);
1183 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1184 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
1185 //check to see if any data is stored for this user:
1186 $deleteurl = new moodle_url($PAGE->url, array('action'=>'delete', 'sesskey' => sesskey()));
1187 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1196 * Get SCORM attempt count
1198 * @param object $user Current context user
1199 * @param object $scorm a moodle scrom object - mdl_scorm
1200 * @param bool $attempts return the list of attempts
1201 * @return int - no. of attempts so far
1203 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1206 $element = 'cmi.core.score.raw';
1207 if ($scorm->grademethod == GRADESCOES) {
1208 $element = 'cmi.core.lesson_status';
1210 if (scorm_version_check($scorm->version, SCORM_13)) {
1211 $element = 'cmi.score.raw';
1213 $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id), 'attempt', 'DISTINCT attempt AS attemptnumber');
1214 if ($attempts_only) {
1217 if (!empty($attempts)) {
1218 $attemptcount = count($attempts);
1220 return $attemptcount;
1224 * Figure out with this is a debug situation
1226 * @param object $scorm a moodle scrom object - mdl_scorm
1227 * @return boolean - debugging true/false
1229 function scorm_debugging($scorm) {
1231 $cfg_scorm = get_config('scorm');
1233 if (!$cfg_scorm->allowapidebug) {
1236 $identifier = $USER->username.':'.$scorm->name;
1237 $test = $cfg_scorm->apidebugmask;
1238 // check the regex is only a short list of safe characters
1239 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1243 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1248 * Delete Scorm tracks for selected users
1250 * @param array $attemptids list of attempts that need to be deleted
1251 * @param int $scorm instance
1253 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1255 function scorm_delete_responses($attemptids, $scorm) {
1256 if (!is_array($attemptids) || empty($attemptids)) {
1260 foreach ($attemptids as $num => $attemptid) {
1261 if (empty($attemptid)) {
1262 unset($attemptids[$num]);
1266 foreach ($attemptids as $attempt) {
1267 $keys = explode(':', $attempt);
1268 if (count($keys) == 2) {
1269 $userid = clean_param($keys[0], PARAM_INT);
1270 $attemptid = clean_param($keys[1], PARAM_INT);
1271 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
1282 * Delete Scorm tracks for selected users
1284 * @param int $userid ID of User
1285 * @param int $scormid ID of Scorm
1286 * @param int $attemptid user attempt that need to be deleted
1288 * return bool true suceeded
1290 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1293 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1294 include_once('lib.php');
1295 scorm_update_grades($scorm, $userid, true);
1300 * Converts SCORM duration notation to human-readable format
1301 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1302 * @param $duration string SCORM duration
1303 * @return string human-readable date/time
1305 function scorm_format_duration($duration) {
1306 // fetch date/time strings
1307 $stryears = get_string('years');
1308 $strmonths = get_string('nummonths');
1309 $strdays = get_string('days');
1310 $strhours = get_string('hours');
1311 $strminutes = get_string('minutes');
1312 $strseconds = get_string('seconds');
1314 if ($duration[0] == 'P') {
1315 // if timestamp starts with 'P' - it's a SCORM 2004 format
1316 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1317 // and outputs filled sections, discarding leading zeroes and any format literals
1318 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1319 $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#',
1320 '#([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#' );
1321 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1322 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1324 // else we have SCORM 1.2 format there
1325 // first convert the timestamp to some SCORM 2004-like format for conveniency
1326 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1327 // then convert in the same way as SCORM 2004
1328 $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#' );
1329 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1332 $result = preg_replace($pattern, $replace, $duration);
1337 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1338 global $CFG, $DB, $PAGE, $OUTPUT;
1341 if ($mode != 'normal') {
1342 $modestr = '&mode='.$mode;
1346 $incomplete = false;
1348 if (!empty($organizationsco)) {
1349 $result[0] = $organizationsco;
1350 $result[0]->isvisible = true;
1351 $result[0]->statusicon = '';
1352 $result[0]->url = '';
1355 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1356 // Retrieve user tracking data for each learning object.
1357 $usertracks = array();
1358 foreach ($scoes as $sco) {
1359 if (!empty($sco->launch)) {
1360 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
1361 if ($usertrack->status == '') {
1362 $usertrack->status = 'notattempted';
1364 $usertracks[$sco->identifier] = $usertrack;
1368 foreach ($scoes as $sco) {
1369 if (!isset($sco->isvisible)) {
1370 $sco->isvisible = true;
1373 if (empty($sco->title)) {
1374 $sco->title = $sco->identifier;
1377 if (scorm_version_check($scorm->version, SCORM_13)) {
1378 $sco->prereq = true;
1380 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1383 if ($sco->isvisible) {
1384 if (!empty($sco->launch)) {
1385 if (empty($scoid) && ($mode != 'normal')) {
1389 if (isset($usertracks[$sco->identifier])) {
1390 $usertrack = $usertracks[$sco->identifier];
1391 $strstatus = get_string($usertrack->status,'scorm');
1393 if ($sco->scormtype == 'sco') {
1394 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1396 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1399 if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1401 if ($play && empty($scoid)) {
1406 $strsuspended = get_string('suspended', 'scorm');
1408 $exitvar = 'cmi.core.exit';
1410 if (scorm_version_check($scorm->version, SCORM_13)) {
1411 $exitvar = 'cmi.exit';
1414 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1415 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1419 if ($play && empty($scoid)) {
1425 if ($sco->scormtype == 'sco') {
1426 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1428 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1434 if (empty($statusicon)) {
1435 $sco->statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1437 $sco->statusicon = $statusicon;
1440 $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
1441 $sco->incomplete = $incomplete;
1443 if (!in_array($sco->id, array_keys($result))) {
1444 $result[$sco->id] = $sco;
1449 // Get the parent scoes!
1450 $result = scorm_get_toc_get_parent_child($result);
1452 // Be safe, prevent warnings from showing up while returning array
1453 if (!isset($scoid)) {
1457 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1460 function scorm_get_toc_get_parent_child(&$result) {
1465 foreach ($result as $sco) {
1466 if ($sco->parent == '/') {
1467 $final[$level][$sco->identifier] = $sco;
1468 $prevparent = $sco->identifier;
1469 unset($result[$sco->id]);
1471 if ($sco->parent == $prevparent) {
1472 $final[$level][$sco->identifier] = $sco;
1473 $prevparent = $sco->identifier;
1474 unset($result[$sco->id]);
1476 if (!empty($final[$level])) {
1478 foreach ($final[$level] as $fin) {
1479 if ($sco->parent == $fin->identifier) {
1485 $final[$level][$sco->identifier] = $sco;
1486 unset($result[$sco->id]);
1490 $final[$level][$sco->identifier] = $sco;
1491 unset($result[$sco->id]);
1498 for ($i = 0; $i <= $level; $i++) {
1500 foreach ($final[$i] as $ident => $sco) {
1501 if (empty($prevparent)) {
1502 $prevparent = $ident;
1504 if (!isset($final[$i][$prevparent]->children)) {
1505 $final[$i][$prevparent]->children = array();
1507 if ($sco->parent == $prevparent) {
1508 $final[$i][$prevparent]->children[] = $sco;
1509 $prevparent = $ident;
1512 foreach ($final[$i] as $identifier => $scoobj) {
1513 if ($identifier == $sco->parent) {
1514 $parent = $identifier;
1518 if ($parent !== false) {
1519 $final[$i][$parent]->children[] = $sco;
1526 for ($i = 0; $i <= $level; $i++) {
1527 $keys = array_keys($final[$i]);
1528 $results[] = $final[$i][$keys[0]];
1534 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1537 $result = new stdClass();
1538 $result->prerequisites = true;
1539 $result->incomplete = true;
1543 $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1544 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
1548 $result->toc = "<ul>\n";
1550 if (!$play && !empty($organizationsco)) {
1551 $result->toc .= "\t<li>".$organizationsco->title."</li>\n";
1556 if (!empty($scoes)) {
1557 foreach ($scoes as $sco) {
1558 $result->toc .= "\t<li>\n";
1561 $sco->isvisible = true;
1563 if ($sco->isvisible) {
1566 if (isset($usertracks[$sco->identifier])) {
1567 $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
1568 if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1569 if ($usertracks[$sco->identifier]->score_raw != '') {
1570 $score = '('.get_string('score','scorm').': '.$usertracks[$sco->identifier]->score_raw.')';
1575 if (!empty($sco->prereq)) {
1576 if ($sco->id == $scoid) {
1577 $result->prerequisites = true;
1580 if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1581 if ($sco->scormtype == 'sco') {
1582 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1584 $result->toc .= '<span> '.format_string($sco->title).'</span>';
1586 } else if ($toclink == TOCFULLURL) {
1587 $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
1588 if (!empty($sco->launch)) {
1589 if ($sco->scormtype == 'sco') {
1590 $result->toc .= $sco->statusicon.' <a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1592 $result->toc .= ' <a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1595 if ($sco->scormtype == 'sco') {
1596 $result->toc .= $sco->statusicon.' '.format_string($sco->title).$score."\n";
1598 $result->toc .= ' '.format_string($sco->title).$score."\n";
1602 if (!empty($sco->launch)) {
1603 if ($sco->scormtype == 'sco') {
1604 $result->toc .= '<a title="'.$sco->url.'">'.$sco->statusicon.' '.format_string($sco->title).' '.$score.'</a>';
1606 $result->toc .= '<a title="'.$sco->url.'"> '.format_string($sco->title).' '.$score.'</a>';
1609 if ($sco->scormtype == 'sco') {
1610 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1612 $result->toc .= '<span> '.format_string($sco->title).'</span>';
1619 if ($sco->scormtype == 'sco') {
1620 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1622 $result->toc .= ' '.format_string($sco->title).'</span>';
1625 if ($sco->scormtype == 'sco') {
1626 $result->toc .= $sco->statusicon.' '.format_string($sco->title)."\n";
1628 $result->toc .= ' '.format_string($sco->title)."\n";
1634 $result->toc .= "\t\t ".format_string($sco->title)."\n";
1637 if (!empty($sco->children)) {
1638 $result->toc .= "\n\t\t<ul>\n";
1639 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1640 $result->toc .= $childresult->toc;
1641 $result->toc .= "\t\t</ul>\n";
1642 $result->toc .= "\t</li>\n";
1644 $result->toc .= "\t</li>\n";
1648 $result->incomplete = $sco->incomplete;
1652 $result->toc .= "</ul>\n";
1658 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1659 if (!empty($scoes)) {
1660 if (!empty($organizationsco) && !$children) {
1661 $tocmenus[$organizationsco->id] = $organizationsco->title;
1664 $parents[$level]='/';
1665 foreach ($scoes as $sco) {
1666 if ($parents[$level] != $sco->parent) {
1667 if ($newlevel = array_search($sco->parent, $parents)) {
1671 while (($i > 0) && ($parents[$level] != $sco->parent)) {
1675 if (($i == 0) && ($sco->parent != $currentorg)) {
1681 $parents[$level] = $sco->parent;
1686 if ($sco->scormtype == 'sco') {
1687 $tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
1690 if ($sco->scormtype == 'sco') {
1691 $tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
1695 if (!empty($sco->children)) {
1696 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1704 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1705 global $CFG, $DB, $OUTPUT;
1707 if (empty($attempt)) {
1708 $attempt = scorm_get_attempt_count($user->id, $scorm);
1711 $result = new stdClass();
1712 $organizationsco = null;
1715 $result->toc = "<div id=\"scorm_layout\">\n";
1716 $result->toc .= "<div id=\"scorm_toc\">\n";
1717 $result->toc .= "<div id=\"scorm_tree\">\n";
1720 if (!empty($currentorg)) {
1721 $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id, 'identifier'=>$currentorg));
1722 if (!empty($organizationsco->title)) {
1724 $result->toctitle = $organizationsco->title;
1729 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1731 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1734 $result->toc .= $treeview->toc;
1736 $result->toc = $treeview->toc;
1739 if (!empty($scoes['scoid'])) {
1740 $scoid = $scoes['scoid'];
1743 if (empty($scoid)) {
1744 $result->sco = $scoes['scoes'][0]->children[0];
1746 $result->sco = scorm_get_sco($scoid);
1749 if ($scorm->hidetoc == SCORM_TOC_POPUP) {
1750 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $currentorg, $organizationsco);
1753 if ($mode != 'normal') {
1754 $modestr = '&mode='.$mode;
1757 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'¤torg='.$currentorg.$modestr);
1758 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
1761 $result->prerequisites = $treeview->prerequisites;
1762 $result->incomplete = $treeview->incomplete;
1763 $result->attemptleft = $treeview->attemptleft;
1766 $result->toc .= "</div></div></div>\n";
1767 $result->toc .= "<div id=\"scorm_navpanel\"></div>\n";
1773 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1774 if (is_object($scoes)) {
1776 if (isset($sco->url)) {
1777 $adlnav[$sco->id]['identifier'] = $sco->identifier;
1778 $adlnav[$sco->id]['launch'] = $sco->launch;
1779 $adlnav[$sco->id]['title'] = $sco->title;
1780 $adlnav[$sco->id]['url'] = $sco->url;
1781 $adlnav[$sco->id]['parent'] = $sco->parent;
1782 if (isset($sco->choice)) {
1783 $adlnav[$sco->id]['choice'] = $sco->choice;
1785 if (isset($sco->flow)) {
1786 $adlnav[$sco->id]['flow'] = $sco->flow;
1787 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1788 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1790 if (isset($sco->isvisible)) {
1791 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1793 if (isset($sco->parameters)) {
1794 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1796 if (isset($sco->hidecontinue)) {
1797 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1799 if (isset($sco->hideprevious)) {
1800 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1802 if (isset($sco->hidesuspendall)) {
1803 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1805 if (!empty($parentscoid)) {
1806 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1808 if (isset($adlnav['prevscoid'])) {
1809 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1810 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1811 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1812 $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1813 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1816 $adlnav['prevscoid'] = $sco->id;
1817 $adlnav['prevparent'] = $sco->parent;
1819 if (isset($sco->children)) {
1820 foreach ($sco->children as $children) {
1821 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1825 foreach ($scoes as $sco) {
1826 scorm_get_adlnav_json ($sco, $adlnav);
1828 unset($adlnav['prevscoid']);
1829 unset($adlnav['prevparent']);
1831 return json_encode($adlnav);
1835 * Check for the availability of a resource by URL.
1837 * Check is performed using an HTTP HEAD call.
1839 * @param $url string A valid URL
1840 * @return bool|string True if no issue is found. The error string message, otherwise
1842 function scorm_check_url($url) {
1845 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1846 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1847 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1849 $cmsg = $curl->head($url);
1850 $info = $curl->get_info();
1851 if (empty($info['http_code']) || $info['http_code'] != 200) {
1852 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));