2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 require_once("$CFG->dirroot/mod/scorm/lib.php");
18 require_once("$CFG->libdir/filelib.php");
20 /// Constants and settings for module scorm
21 define('SCORM_UPDATE_NEVER', '0');
22 define('SCORM_UPDATE_EVERYDAY', '2');
23 define('SCORM_UPDATE_EVERYTIME', '3');
25 define('SCORM_SKIPVIEW_NEVER', '0');
26 define('SCORM_SKIPVIEW_FIRST', '1');
27 define('SCORM_SKIPVIEW_ALWAYS', '2');
30 define('SCO_DATA', 1);
31 define('SCO_ONLY', 2);
33 define('GRADESCOES', '0');
34 define('GRADEHIGHEST', '1');
35 define('GRADEAVERAGE', '2');
36 define('GRADESUM', '3');
38 define('HIGHESTATTEMPT', '0');
39 define('AVERAGEATTEMPT', '1');
40 define('FIRSTATTEMPT', '2');
41 define('LASTATTEMPT', '3');
43 define('TOCJSLINK', 1);
44 define('TOCFULLURL', 2);
46 /// Local Library of functions for module scorm
50 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class scorm_package_file_info extends file_info_stored {
54 public function get_parent() {
55 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
56 return $this->browser->get_file_info($this->context);
58 return parent::get_parent();
60 public function get_visible_name() {
61 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
62 return $this->topvisiblename;
64 return parent::get_visible_name();
69 * Returns an array of the popup options for SCORM and each options default value
71 * @return array an array of popup options as the key and their defaults as the value
73 function scorm_get_popup_options_array() {
74 $cfgscorm = get_config('scorm');
76 return array('scrollbars'=> isset($cfgscorm->scrollbars) ? $cfgscorm->scrollbars : 0,
77 'directories'=> isset($cfgscorm->directories) ? $cfgscorm->directories : 0,
78 'location'=> isset($cfgscorm->location) ? $cfgscorm->location : 0,
79 'menubar'=> isset($cfgscorm->menubar) ? $cfgscorm->menubar : 0,
80 'toolbar'=> isset($cfgscorm->toolbar) ? $cfgscorm->toolbar : 0,
81 'status'=> isset($cfgscorm->status) ? $cfgscorm->status : 0);
85 * Returns an array of the array of what grade options
87 * @return array an array of what grade options
89 function scorm_get_grade_method_array() {
90 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
91 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
92 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
93 GRADESUM => get_string('gradesum', 'scorm'));
97 * Returns an array of the array of what grade options
99 * @return array an array of what grade options
101 function scorm_get_what_grade_array() {
102 return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
103 AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
104 FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
105 LASTATTEMPT => get_string('lastattempt', 'scorm'));
109 * Returns an array of the array of skip view options
111 * @return array an array of skip view options
113 function scorm_get_skip_view_array() {
114 return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
115 SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
116 SCORM_SKIPVIEW_ALWAYS => get_string('always'));
120 * Returns an array of the array of hide table of contents options
122 * @return array an array of hide table of contents options
124 function scorm_get_hidetoc_array() {
125 return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
126 SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
127 SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
128 SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
132 * Returns an array of the array of update frequency options
134 * @return array an array of update frequency options
136 function scorm_get_updatefreq_array() {
137 return array(SCORM_UPDATE_NEVER => get_string('never'),
138 SCORM_UPDATE_EVERYDAY => get_string('everyday', 'scorm'),
139 SCORM_UPDATE_EVERYTIME => get_string('everytime', 'scorm'));
143 * Returns an array of the array of popup display options
145 * @return array an array of popup display options
147 function scorm_get_popup_display_array() {
148 return array(0 => get_string('currentwindow', 'scorm'),
149 1 => get_string('popup', 'scorm'));
153 * Returns an array of the array of attempt options
155 * @return array an array of attempt options
157 function scorm_get_attempts_array() {
158 $attempts = array(0 => get_string('nolimit', 'scorm'),
159 1 => get_string('attempt1', 'scorm'));
161 for ($i=2; $i<=6; $i++) {
162 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
169 * Returns an array of the attempt status options
171 * @return array an array of attempt status options
173 function scorm_get_attemptstatus_array() {
174 return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO => get_string('no'),
175 SCORM_DISPLAY_ATTEMPTSTATUS_ALL => get_string('attemptstatusall', 'scorm'),
176 SCORM_DISPLAY_ATTEMPTSTATUS_MY => get_string('attemptstatusmy', 'scorm'),
177 SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY => get_string('attemptstatusentry', 'scorm'));
181 * Extracts scrom package, sets up all variables.
182 * Called whenever scorm changes
183 * @param object $scorm instance - fields are updated and changes saved into database
184 * @param bool $full force full update if true
187 function scorm_parse($scorm, $full) {
189 $cfg_scorm = get_config('scorm');
191 if (!isset($scorm->cmid)) {
192 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
193 $scorm->cmid = $cm->id;
195 $context = context_module::instance($scorm->cmid);
196 $newhash = $scorm->sha1hash;
198 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
200 $fs = get_file_storage();
201 $packagefile = false;
203 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
204 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
205 if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
206 $packagefile->import_external_file_contents();
208 $newhash = $packagefile->get_contenthash();
213 if (!$cfg_scorm->allowtypelocalsync) {
214 // sorry - localsync disabled
217 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
218 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
219 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
220 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
221 $newhash = sha1($scorm->reference);
229 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
230 if (strpos($scorm->version, 'SCORM') !== false) {
231 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
235 } else if (strpos($scorm->version, 'AICC') !== false) {
236 // TODO: add more sanity checks - something really exists in scorm_content area
242 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
244 $packer = get_file_packer('application/zip');
245 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
251 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
252 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
254 if (!scorm_parse_scorm($scorm, $manifest)) {
255 $scorm->version = 'ERROR';
258 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
260 if (!scorm_parse_aicc($scorm)) {
261 $scorm->version = 'ERROR';
263 $scorm->version = 'AICC';
266 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
267 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
268 // SCORM only, AICC can not be external
269 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
270 $scorm->version = 'ERROR';
272 $newhash = sha1($scorm->reference);
274 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfg_scorm->allowtypeexternalaicc) {
275 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
277 if (!scorm_parse_aicc($scorm)) {
278 $scorm->version = 'ERROR';
280 $scorm->version = 'AICC';
282 // sorry, disabled type
287 $scorm->sha1hash = $newhash;
288 $DB->update_record('scorm', $scorm);
292 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
293 if (!empty($haystacks)) {
294 foreach ($haystacks as $key => $element) {
296 if ($element->{$item} === $needle) {
300 if ($element->{$item} == $needle) {
309 function scorm_repeater($what, $times) {
314 for ($i=0; $i<$times; $i++) {
320 function scorm_external_link($link) {
321 // check if a link is external
323 $link = strtolower($link);
324 if (substr($link, 0, 7) == 'http://') {
326 } else if (substr($link, 0, 8) == 'https://') {
328 } else if (substr($link, 0, 4) == 'www.') {
335 * Returns an object containing all datas relative to the given sco ID
337 * @param integer $id The sco ID
338 * @return mixed (false if sco id does not exists)
340 function scorm_get_sco($id, $what=SCO_ALL) {
343 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
344 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
345 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
346 foreach ($scodatas as $scodata) {
347 $sco->{$scodata->name} = $scodata->value;
349 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
350 $sco->parameters = '';
359 * Returns an object (array) containing all the scoes data related to the given sco ID
361 * @param integer $id The sco ID
362 * @param integer $organisation an organisation ID - defaults to false if not required
363 * @return mixed (false if there are no scoes or an array)
365 function scorm_get_scoes($id, $organisation=false) {
368 $queryarray = array('scorm'=>$id);
369 if (!empty($organisation)) {
370 $queryarray['organization'] = $organisation;
372 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
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,
528 'attempt'=>$attempt), 'element ASC')) {
529 $usertrack = scorm_format_interactions($tracks);
530 $usertrack->userid = $userid;
531 $usertrack->scoid = $scoid;
539 * helper function to return a formatted list of interactions for reports.
541 * @param array $trackdata the records from scorm_scoes_track table
542 * @return object formatted list of interactions
544 function scorm_format_interactions($trackdata) {
545 $usertrack = new stdClass();
547 // Defined in order to unify scorm1.2 and scorm2004.
548 $usertrack->score_raw = '';
549 $usertrack->status = '';
550 $usertrack->total_time = '00:00:00';
551 $usertrack->session_time = '00:00:00';
552 $usertrack->timemodified = 0;
554 foreach ($trackdata as $track) {
555 $element = $track->element;
556 $usertrack->{$element} = $track->value;
558 case 'cmi.core.lesson_status':
559 case 'cmi.completion_status':
560 if ($track->value == 'not attempted') {
561 $track->value = 'notattempted';
563 $usertrack->status = $track->value;
565 case 'cmi.core.score.raw':
566 case 'cmi.score.raw':
567 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
569 case 'cmi.core.session_time':
570 case 'cmi.session_time':
571 $usertrack->session_time = $track->value;
573 case 'cmi.core.total_time':
574 case 'cmi.total_time':
575 $usertrack->total_time = $track->value;
578 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
579 $usertrack->timemodified = $track->timemodified;
585 /* Find the start and finsh time for a a given SCO attempt
587 * @param int $scormid SCORM Id
588 * @param int $scoid SCO Id
589 * @param int $userid User Id
590 * @param int $attemt Attempt Id
592 * @return object start and finsh time EPOC secods
595 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
598 $timedata = new stdClass();
599 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
600 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
602 $tracks = array_values($tracks);
606 $timedata->start = $tracks[0]->timemodified;
608 $timedata->start = false;
610 if ($tracks && $track = array_pop($tracks)) {
611 $timedata->finish = $track->timemodified;
613 $timedata->finish = $timedata->start;
618 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
620 $attemptscore = new stdClass();
621 $attemptscore->scoes = 0;
622 $attemptscore->values = 0;
623 $attemptscore->max = 0;
624 $attemptscore->sum = 0;
625 $attemptscore->lastmodify = 0;
627 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
631 foreach ($scoes as $sco) {
632 if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
633 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
634 $attemptscore->scoes++;
636 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
637 $attemptscore->values++;
638 $attemptscore->sum += $userdata->score_raw;
639 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
640 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
641 $attemptscore->lastmodify = $userdata->timemodified;
643 $attemptscore->lastmodify = 0;
648 switch ($scorm->grademethod) {
650 $score = (float) $attemptscore->max;
653 if ($attemptscore->values > 0) {
654 $score = $attemptscore->sum/$attemptscore->values;
660 $score = $attemptscore->sum;
663 $score = $attemptscore->scoes;
666 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
672 function scorm_grade_user($scorm, $userid) {
674 // ensure we dont grade user beyond $scorm->maxattempt settings
675 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
676 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
677 $lastattempt = $scorm->maxattempt;
680 switch ($scorm->whatgrade) {
682 return scorm_grade_user_attempt($scorm, $userid, 1);
685 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
689 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
690 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
691 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
697 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
698 if (empty($attemptcount)) {
701 $attemptcount = count($attemptcount);
703 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
705 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
706 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
707 $sumscore += $attemptscore;
710 return round($sumscore / $attemptcount);
715 function scorm_count_launchable($scormid, $organization='') {
718 $sqlorganization = '';
719 $params = array($scormid);
720 if (!empty($organization)) {
721 $sqlorganization = " AND organization=?";
722 $params[] = $organization;
724 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
728 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
730 * @param int $scormid the id of the scorm.
731 * @param int $userid the id of the user.
733 * @return int The attempt number to use.
735 function scorm_get_last_attempt($scormid, $userid) {
738 /// Find the last attempt number for the given user id and scorm id
739 $sql = "SELECT MAX(attempt)
740 FROM {scorm_scoes_track}
741 WHERE userid = ? AND scormid = ?";
742 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
743 if (empty($lastattempt)) {
751 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
753 * @param int $scormid the id of the scorm.
754 * @param int $userid the id of the user.
756 * @return int The attempt number to use.
758 function scorm_get_last_completed_attempt($scormid, $userid) {
761 /// Find the last completed attempt number for the given user id and scorm id
762 $sql = "SELECT MAX(attempt)
763 FROM {scorm_scoes_track}
764 WHERE userid = ? AND scormid = ?
765 AND (value='completed' OR value='passed')";
766 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
767 if (empty($lastattempt)) {
775 * Returns the full list of attempts a user has made.
777 * @param int $scormid the id of the scorm.
778 * @param int $userid the id of the user.
780 * @return array array of attemptids
782 function scorm_get_all_attempts($scormid, $userid) {
784 $attemptids = array();
785 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
786 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
787 foreach ($attempts as $attempt) {
788 $attemptids[] = $attempt->attempt;
793 function scorm_view_display ($user, $scorm, $action, $cm) {
794 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
796 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
797 scorm_parse($scorm, false);
800 $organization = optional_param('organization', '', PARAM_INT);
802 if ($scorm->displaycoursestructure == 1) {
803 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
805 <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
808 if (empty($organization)) {
809 $organization = $scorm->launch;
811 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
812 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
813 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
814 array($scorm->id), 'sortorder, id', 'id,title')) {
815 if (count($orgs) > 1) {
816 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
817 $select->label = get_string('organizations', 'scorm');
818 $select->class = 'scorm-center';
819 echo $OUTPUT->render($select);
823 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
824 if (($sco->organization == '') && ($sco->launch == '')) {
825 $orgidentifier = $sco->identifier;
827 $orgidentifier = $sco->organization;
831 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
832 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
833 $scorm->version = 'scorm_12';
835 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
837 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
838 $incomplete = $result->incomplete;
840 // do we want the TOC to be displayed?
841 if ($scorm->displaycoursestructure == 1) {
843 echo $OUTPUT->box_end();
846 // is this the first attempt ?
847 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
849 // do not give the player launch FORM if the SCORM object is locked after the final attempt
850 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
852 <div class="scorm-center">
853 <form id="scormviewform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
855 if ($scorm->hidebrowse == 0) {
856 print_string('mode', 'scorm');
857 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
858 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
860 echo '<input type="hidden" name="mode" value="normal" />'."\n";
862 if ($scorm->forcenewattempt == 1) {
863 if ($incomplete === false) {
864 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
866 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
869 <input type="checkbox" id="a" name="newattempt" />
870 <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
873 if (!empty($scorm->popup)) {
874 echo '<input type="hidden" name="display" value="popup" />'."\n";
878 <input type="hidden" name="scoid"/>
879 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
880 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
881 <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
888 function scorm_simple_play($scorm, $user, $context, $cmid) {
893 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
897 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
898 scorm_parse($scorm, false);
900 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
901 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
905 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
906 if (($sco->organization == '') && ($sco->launch == '')) {
907 $orgidentifier = $sco->identifier;
909 $orgidentifier = $sco->organization;
912 if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
913 $sco = current($scoes);
914 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
915 'currentorg'=>$orgidentifier,
917 if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
918 if (!empty($scorm->forcenewattempt)) {
919 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
920 if ($result->incomplete === false) {
921 $url->param('newattempt','on');
931 function scorm_get_count_users($scormid, $groupingid=null) {
934 if (!empty($groupingid)) {
935 $sql = "SELECT COUNT(DISTINCT st.userid)
936 FROM {scorm_scoes_track} st
937 INNER JOIN {groups_members} gm ON st.userid = gm.userid
938 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
939 WHERE st.scormid = ? AND gg.groupingid = ?
941 $params = array($scormid, $groupingid);
943 $sql = "SELECT COUNT(DISTINCT st.userid)
944 FROM {scorm_scoes_track} st
947 $params = array($scormid);
950 return ($DB->count_records_sql($sql, $params));
954 * Build up the JavaScript representation of an array element
956 * @param string $sversion SCORM API version
957 * @param array $userdata User track data
958 * @param string $element_name Name of array element to get values for
959 * @param array $children list of sub elements of this array element that also need instantiating
962 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
963 // reconstitute comments_from_learner and comments_from_lms
965 $current_subelement = '';
969 $scormseperator = '_';
970 if (scorm_version_check($sversion, SCORM_13)) { //scorm 1.3 elements use a . instead of an _
971 $scormseperator = '.';
973 // filter out the ones we want
974 $element_list = array();
975 foreach ($userdata as $element => $value) {
976 if (substr($element, 0, strlen($element_name)) == $element_name) {
977 $element_list[$element] = $value;
981 // sort elements in .n array order
982 uksort($element_list, "scorm_element_cmp");
984 // generate JavaScript
985 foreach ($element_list as $element => $value) {
986 if (scorm_version_check($sversion, SCORM_13)) {
987 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
988 preg_match('/\.(N\d+)\./', $element, $matches);
990 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
991 preg_match('/\_(\d+)\./', $element, $matches);
993 if (count($matches) > 0 && $current != $matches[1]) {
994 if ($count_sub > 0) {
995 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
997 $current = $matches[1];
999 $current_subelement = '';
1002 $end = strpos($element, $matches[1])+strlen($matches[1]);
1003 $subelement = substr($element, 0, $end);
1004 echo ' '.$subelement." = new Object();\n";
1005 // now add the children
1006 foreach ($children as $child) {
1007 echo ' '.$subelement.".".$child." = new Object();\n";
1008 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
1012 // now - flesh out the second level elements if there are any
1013 if (scorm_version_check($sversion, SCORM_13)) {
1014 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1015 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1017 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1018 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1021 // check the sub element type
1022 if (count($matches) > 0 && $current_subelement != $matches[1]) {
1023 if ($count_sub > 0) {
1024 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1026 $current_subelement = $matches[1];
1029 $end = strpos($element, $matches[1])+strlen($matches[1]);
1030 $subelement = substr($element, 0, $end);
1031 echo ' '.$subelement." = new Object();\n";
1034 // now check the subelement subscript
1035 if (count($matches) > 0 && $current_sub != $matches[2]) {
1036 $current_sub = $matches[2];
1038 $end = strrpos($element, $matches[2])+strlen($matches[2]);
1039 $subelement = substr($element, 0, $end);
1040 echo ' '.$subelement." = new Object();\n";
1043 echo ' '.$element.' = \''.$value."';\n";
1045 if ($count_sub > 0) {
1046 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1049 echo ' '.$element_name.'._count = '.$count.";\n";
1054 * Build up the JavaScript representation of an array element
1056 * @param string $a left array element
1057 * @param string $b right array element
1058 * @return comparator - 0,1,-1
1060 function scorm_element_cmp($a, $b) {
1061 preg_match('/.*?(\d+)\./', $a, $matches);
1062 $left = intval($matches[1]);
1063 preg_match('/.?(\d+)\./', $b, $matches);
1064 $right = intval($matches[1]);
1065 if ($left < $right) {
1066 return -1; // smaller
1067 } else if ($left > $right) {
1070 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1071 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1072 $leftterm = intval($matches[2]);
1073 $left = intval($matches[3]);
1074 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1075 $rightterm = intval($matches[2]);
1076 $right = intval($matches[3]);
1077 if ($leftterm < $rightterm) {
1078 return -1; // smaller
1079 } else if ($leftterm > $rightterm) {
1082 if ($left < $right) {
1083 return -1; // smaller
1084 } else if ($left > $right) {
1090 // fall back for no second level matches or second level matches are equal
1091 return 0; // equal to
1096 * Generate the user attempt status string
1098 * @param object $user Current context user
1099 * @param object $scorm a moodle scrom object - mdl_scorm
1100 * @return string - Attempt status string
1102 function scorm_get_attempt_status($user, $scorm, $cm='') {
1103 global $DB, $PAGE, $OUTPUT;
1105 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
1106 if (empty($attempts)) {
1109 $attemptcount = count($attempts);
1112 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1113 if ($scorm->maxattempt > 0) {
1114 $result .= $scorm->maxattempt . '<br />';
1116 $result .= get_string('unlimited').'<br />';
1118 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1120 if ($scorm->maxattempt == 1) {
1121 switch ($scorm->grademethod) {
1123 $grademethod = get_string('gradehighest', 'scorm');
1126 $grademethod = get_string('gradeaverage', 'scorm');
1129 $grademethod = get_string('gradesum', 'scorm');
1132 $grademethod = get_string('gradescoes', 'scorm');
1136 switch ($scorm->whatgrade) {
1137 case HIGHESTATTEMPT:
1138 $grademethod = get_string('highestattempt', 'scorm');
1140 case AVERAGEATTEMPT:
1141 $grademethod = get_string('averageattempt', 'scorm');
1144 $grademethod = get_string('firstattempt', 'scorm');
1147 $grademethod = get_string('lastattempt', 'scorm');
1152 if (!empty($attempts)) {
1154 foreach ($attempts as $attempt) {
1155 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1156 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1157 $gradereported = $gradereported/$scorm->maxgrade;
1158 $gradereported = number_format($gradereported*100, 0) .'%';
1160 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1164 $calculatedgrade = scorm_grade_user($scorm, $user->id);
1165 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1166 $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1167 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1169 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1170 if (empty($attempts)) {
1171 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1173 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1176 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1177 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1180 $context = context_module::instance($cm->id);
1181 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1182 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
1183 //check to see if any data is stored for this user:
1184 $deleteurl = new moodle_url($PAGE->url, array('action'=>'delete', 'sesskey' => sesskey()));
1185 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1194 * Get SCORM attempt count
1196 * @param object $user Current context user
1197 * @param object $scorm a moodle scrom object - mdl_scorm
1198 * @param bool $attempts return the list of attempts
1199 * @return int - no. of attempts so far
1201 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1204 $element = 'cmi.core.score.raw';
1205 if ($scorm->grademethod == GRADESCOES) {
1206 $element = 'cmi.core.lesson_status';
1208 if (scorm_version_check($scorm->version, SCORM_13)) {
1209 $element = 'cmi.score.raw';
1211 $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id), 'attempt', 'DISTINCT attempt AS attemptnumber');
1212 if ($attempts_only) {
1215 if (!empty($attempts)) {
1216 $attemptcount = count($attempts);
1218 return $attemptcount;
1222 * Figure out with this is a debug situation
1224 * @param object $scorm a moodle scrom object - mdl_scorm
1225 * @return boolean - debugging true/false
1227 function scorm_debugging($scorm) {
1229 $cfg_scorm = get_config('scorm');
1231 if (!$cfg_scorm->allowapidebug) {
1234 $identifier = $USER->username.':'.$scorm->name;
1235 $test = $cfg_scorm->apidebugmask;
1236 // check the regex is only a short list of safe characters
1237 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1241 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1246 * Delete Scorm tracks for selected users
1248 * @param array $attemptids list of attempts that need to be deleted
1249 * @param int $scorm instance
1251 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1253 function scorm_delete_responses($attemptids, $scorm) {
1254 if (!is_array($attemptids) || empty($attemptids)) {
1258 foreach ($attemptids as $num => $attemptid) {
1259 if (empty($attemptid)) {
1260 unset($attemptids[$num]);
1264 foreach ($attemptids as $attempt) {
1265 $keys = explode(':', $attempt);
1266 if (count($keys) == 2) {
1267 $userid = clean_param($keys[0], PARAM_INT);
1268 $attemptid = clean_param($keys[1], PARAM_INT);
1269 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
1280 * Delete Scorm tracks for selected users
1282 * @param int $userid ID of User
1283 * @param int $scormid ID of Scorm
1284 * @param int $attemptid user attempt that need to be deleted
1286 * return bool true suceeded
1288 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1291 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1292 include_once('lib.php');
1293 scorm_update_grades($scorm, $userid, true);
1298 * Converts SCORM duration notation to human-readable format
1299 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1300 * @param $duration string SCORM duration
1301 * @return string human-readable date/time
1303 function scorm_format_duration($duration) {
1304 // fetch date/time strings
1305 $stryears = get_string('years');
1306 $strmonths = get_string('nummonths');
1307 $strdays = get_string('days');
1308 $strhours = get_string('hours');
1309 $strminutes = get_string('minutes');
1310 $strseconds = get_string('seconds');
1312 if ($duration[0] == 'P') {
1313 // if timestamp starts with 'P' - it's a SCORM 2004 format
1314 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1315 // and outputs filled sections, discarding leading zeroes and any format literals
1316 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1317 $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#',
1318 '#([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#' );
1319 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1320 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1322 // else we have SCORM 1.2 format there
1323 // first convert the timestamp to some SCORM 2004-like format for conveniency
1324 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1325 // then convert in the same way as SCORM 2004
1326 $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#' );
1327 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1330 $result = preg_replace($pattern, $replace, $duration);
1335 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1336 global $CFG, $DB, $PAGE, $OUTPUT;
1339 if ($mode != 'normal') {
1340 $modestr = '&mode='.$mode;
1344 $incomplete = false;
1346 if (!empty($organizationsco)) {
1347 $result[0] = $organizationsco;
1348 $result[0]->isvisible = true;
1349 $result[0]->statusicon = '';
1350 $result[0]->url = '';
1353 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1354 // Retrieve user tracking data for each learning object.
1355 $usertracks = array();
1356 foreach ($scoes as $sco) {
1357 if (!empty($sco->launch)) {
1358 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
1359 if ($usertrack->status == '') {
1360 $usertrack->status = 'notattempted';
1362 $usertracks[$sco->identifier] = $usertrack;
1366 foreach ($scoes as $sco) {
1367 if (!isset($sco->isvisible)) {
1368 $sco->isvisible = true;
1371 if (empty($sco->title)) {
1372 $sco->title = $sco->identifier;
1375 if (scorm_version_check($scorm->version, SCORM_13)) {
1376 $sco->prereq = true;
1378 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1381 if ($sco->isvisible) {
1382 if (!empty($sco->launch)) {
1383 if (empty($scoid) && ($mode != 'normal')) {
1387 if (isset($usertracks[$sco->identifier])) {
1388 $usertrack = $usertracks[$sco->identifier];
1389 $strstatus = get_string($usertrack->status,'scorm');
1391 if ($sco->scormtype == 'sco') {
1392 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1394 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1397 if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1399 if ($play && empty($scoid)) {
1404 $strsuspended = get_string('suspended', 'scorm');
1406 $exitvar = 'cmi.core.exit';
1408 if (scorm_version_check($scorm->version, SCORM_13)) {
1409 $exitvar = 'cmi.exit';
1412 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1413 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1417 if ($play && empty($scoid)) {
1423 if ($sco->scormtype == 'sco') {
1424 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1426 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1432 if (empty($statusicon)) {
1433 $sco->statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1435 $sco->statusicon = $statusicon;
1438 $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
1439 $sco->incomplete = $incomplete;
1441 if (!in_array($sco->id, array_keys($result))) {
1442 $result[$sco->id] = $sco;
1447 // Get the parent scoes!
1448 $result = scorm_get_toc_get_parent_child($result);
1450 // Be safe, prevent warnings from showing up while returning array
1451 if (!isset($scoid)) {
1455 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1458 function scorm_get_toc_get_parent_child(&$result) {
1463 foreach ($result as $sco) {
1464 if ($sco->parent == '/') {
1465 $final[$level][$sco->identifier] = $sco;
1466 $prevparent = $sco->identifier;
1467 unset($result[$sco->id]);
1469 if ($sco->parent == $prevparent) {
1470 $final[$level][$sco->identifier] = $sco;
1471 $prevparent = $sco->identifier;
1472 unset($result[$sco->id]);
1474 if (!empty($final[$level])) {
1476 foreach ($final[$level] as $fin) {
1477 if ($sco->parent == $fin->identifier) {
1483 $final[$level][$sco->identifier] = $sco;
1484 unset($result[$sco->id]);
1488 $final[$level][$sco->identifier] = $sco;
1489 unset($result[$sco->id]);
1496 for ($i = 0; $i <= $level; $i++) {
1498 foreach ($final[$i] as $ident => $sco) {
1499 if (empty($prevparent)) {
1500 $prevparent = $ident;
1502 if (!isset($final[$i][$prevparent]->children)) {
1503 $final[$i][$prevparent]->children = array();
1505 if ($sco->parent == $prevparent) {
1506 $final[$i][$prevparent]->children[] = $sco;
1507 $prevparent = $ident;
1510 foreach ($final[$i] as $identifier => $scoobj) {
1511 if ($identifier == $sco->parent) {
1512 $parent = $identifier;
1516 if ($parent !== false) {
1517 $final[$i][$parent]->children[] = $sco;
1524 for ($i = 0; $i <= $level; $i++) {
1525 $keys = array_keys($final[$i]);
1526 $results[] = $final[$i][$keys[0]];
1532 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1535 $result = new stdClass();
1536 $result->prerequisites = true;
1537 $result->incomplete = true;
1541 $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1542 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
1546 $result->toc = "<ul>\n";
1548 if (!$play && !empty($organizationsco)) {
1549 $result->toc .= "\t<li>".$organizationsco->title."</li>\n";
1554 if (!empty($scoes)) {
1555 foreach ($scoes as $sco) {
1556 $result->toc .= "\t<li>\n";
1559 $sco->isvisible = true;
1561 if ($sco->isvisible) {
1564 if (isset($usertracks[$sco->identifier])) {
1565 $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
1566 if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1567 if ($usertracks[$sco->identifier]->score_raw != '') {
1568 $score = '('.get_string('score','scorm').': '.$usertracks[$sco->identifier]->score_raw.')';
1573 if (!empty($sco->prereq)) {
1574 if ($sco->id == $scoid) {
1575 $result->prerequisites = true;
1578 if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1579 if ($sco->scormtype == 'sco') {
1580 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1582 $result->toc .= '<span> '.format_string($sco->title).'</span>';
1584 } else if ($toclink == TOCFULLURL) {
1585 $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
1586 if (!empty($sco->launch)) {
1587 if ($sco->scormtype == 'sco') {
1588 $result->toc .= $sco->statusicon.' <a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1590 $result->toc .= ' <a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1593 if ($sco->scormtype == 'sco') {
1594 $result->toc .= $sco->statusicon.' '.format_string($sco->title).$score."\n";
1596 $result->toc .= ' '.format_string($sco->title).$score."\n";
1600 if (!empty($sco->launch)) {
1601 if ($sco->scormtype == 'sco') {
1602 $result->toc .= '<a title="'.$sco->url.'">'.$sco->statusicon.' '.format_string($sco->title).' '.$score.'</a>';
1604 $result->toc .= '<a title="'.$sco->url.'"> '.format_string($sco->title).' '.$score.'</a>';
1607 if ($sco->scormtype == 'sco') {
1608 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1610 $result->toc .= '<span> '.format_string($sco->title).'</span>';
1617 if ($sco->scormtype == 'sco') {
1618 $result->toc .= '<span>'.$sco->statusicon.' '.format_string($sco->title).'</span>';
1620 $result->toc .= ' '.format_string($sco->title).'</span>';
1623 if ($sco->scormtype == 'sco') {
1624 $result->toc .= $sco->statusicon.' '.format_string($sco->title)."\n";
1626 $result->toc .= ' '.format_string($sco->title)."\n";
1632 $result->toc .= "\t\t ".format_string($sco->title)."\n";
1635 if (!empty($sco->children)) {
1636 $result->toc .= "\n\t\t<ul>\n";
1637 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1638 $result->toc .= $childresult->toc;
1639 $result->toc .= "\t\t</ul>\n";
1640 $result->toc .= "\t</li>\n";
1642 $result->toc .= "\t</li>\n";
1646 $result->incomplete = $sco->incomplete;
1650 $result->toc .= "</ul>\n";
1656 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1657 if (!empty($scoes)) {
1658 if (!empty($organizationsco) && !$children) {
1659 $tocmenus[$organizationsco->id] = $organizationsco->title;
1662 $parents[$level]='/';
1663 foreach ($scoes as $sco) {
1664 if ($parents[$level] != $sco->parent) {
1665 if ($newlevel = array_search($sco->parent, $parents)) {
1669 while (($i > 0) && ($parents[$level] != $sco->parent)) {
1673 if (($i == 0) && ($sco->parent != $currentorg)) {
1679 $parents[$level] = $sco->parent;
1684 if ($sco->scormtype == 'sco') {
1685 $tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
1688 if ($sco->scormtype == 'sco') {
1689 $tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
1693 if (!empty($sco->children)) {
1694 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1702 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1703 global $CFG, $DB, $OUTPUT;
1705 if (empty($attempt)) {
1706 $attempt = scorm_get_attempt_count($user->id, $scorm);
1709 $result = new stdClass();
1710 $organizationsco = null;
1713 $result->toc = "<div id=\"scorm_layout\">\n";
1714 $result->toc .= "<div id=\"scorm_toc\">\n";
1715 $result->toc .= "<div id=\"scorm_tree\">\n";
1718 if (!empty($currentorg)) {
1719 $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id, 'identifier'=>$currentorg));
1720 if (!empty($organizationsco->title)) {
1722 $result->toctitle = $organizationsco->title;
1727 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1729 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1732 $result->toc .= $treeview->toc;
1734 $result->toc = $treeview->toc;
1737 if (!empty($scoes['scoid'])) {
1738 $scoid = $scoes['scoid'];
1741 if (empty($scoid)) {
1742 $result->sco = $scoes['scoes'][0]->children[0];
1744 $result->sco = scorm_get_sco($scoid);
1747 if ($scorm->hidetoc == SCORM_TOC_POPUP) {
1748 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $currentorg, $organizationsco);
1751 if ($mode != 'normal') {
1752 $modestr = '&mode='.$mode;
1755 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'¤torg='.$currentorg.$modestr);
1756 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
1759 $result->prerequisites = $treeview->prerequisites;
1760 $result->incomplete = $treeview->incomplete;
1761 $result->attemptleft = $treeview->attemptleft;
1764 $result->toc .= "</div></div></div>\n";
1765 $result->toc .= "<div id=\"scorm_navpanel\"></div>\n";
1771 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1772 if (is_object($scoes)) {
1774 if (isset($sco->url)) {
1775 $adlnav[$sco->id]['identifier'] = $sco->identifier;
1776 $adlnav[$sco->id]['launch'] = $sco->launch;
1777 $adlnav[$sco->id]['title'] = $sco->title;
1778 $adlnav[$sco->id]['url'] = $sco->url;
1779 $adlnav[$sco->id]['parent'] = $sco->parent;
1780 if (isset($sco->choice)) {
1781 $adlnav[$sco->id]['choice'] = $sco->choice;
1783 if (isset($sco->flow)) {
1784 $adlnav[$sco->id]['flow'] = $sco->flow;
1785 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1786 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1788 if (isset($sco->isvisible)) {
1789 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1791 if (isset($sco->parameters)) {
1792 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1794 if (isset($sco->hidecontinue)) {
1795 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1797 if (isset($sco->hideprevious)) {
1798 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1800 if (isset($sco->hidesuspendall)) {
1801 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1803 if (!empty($parentscoid)) {
1804 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1806 if (isset($adlnav['prevscoid'])) {
1807 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1808 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1809 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1810 $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1811 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1814 $adlnav['prevscoid'] = $sco->id;
1815 $adlnav['prevparent'] = $sco->parent;
1817 if (isset($sco->children)) {
1818 foreach ($sco->children as $children) {
1819 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1823 foreach ($scoes as $sco) {
1824 scorm_get_adlnav_json ($sco, $adlnav);
1826 unset($adlnav['prevscoid']);
1827 unset($adlnav['prevparent']);
1829 return json_encode($adlnav);
1833 * Check for the availability of a resource by URL.
1835 * Check is performed using an HTTP HEAD call.
1837 * @param $url string A valid URL
1838 * @return bool|string True if no issue is found. The error string message, otherwise
1840 function scorm_check_url($url) {
1843 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1844 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1845 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1847 $cmsg = $curl->head($url);
1848 $info = $curl->get_info();
1849 if (empty($info['http_code']) || $info['http_code'] != 200) {
1850 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));