3 require_once("$CFG->dirroot/mod/scorm/lib.php");
4 require_once("$CFG->libdir/filelib.php");
6 /// Constants and settings for module scorm
7 define('UPDATE_NEVER', '0');
8 define('UPDATE_ONCHANGE', '1');
9 define('UPDATE_EVERYDAY', '2');
10 define('UPDATE_EVERYTIME', '3');
13 define('SCO_DATA', 1);
14 define('SCO_ONLY', 2);
16 define('GRADESCOES', '0');
17 define('GRADEHIGHEST', '1');
18 define('GRADEAVERAGE', '2');
19 define('GRADESUM', '3');
21 define('HIGHESTATTEMPT', '0');
22 define('AVERAGEATTEMPT', '1');
23 define('FIRSTATTEMPT', '2');
24 define('LASTATTEMPT', '3');
26 define('TOCJSLINK', 1);
27 define('TOCFULLURL', 2);
29 /// Local Library of functions for module scorm
33 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class scorm_package_file_info extends file_info_stored {
37 public function get_parent() {
38 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
39 return $this->browser->get_file_info($this->context);
41 return parent::get_parent();
43 public function get_visible_name() {
44 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
45 return $this->topvisiblename;
47 return parent::get_visible_name();
52 * Returns an array of the popup options for SCORM and each options default value
54 * @return array an array of popup options as the key and their defaults as the value
56 function scorm_get_popup_options_array(){
58 $cfg_scorm = get_config('scorm');
60 return array('resizable'=> isset($cfg_scorm->resizable) ? $cfg_scorm->resizable : 0,
61 'scrollbars'=> isset($cfg_scorm->scrollbars) ? $cfg_scorm->scrollbars : 0,
62 'directories'=> isset($cfg_scorm->directories) ? $cfg_scorm->directories : 0,
63 'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
64 'menubar'=> isset($cfg_scorm->menubar) ? $cfg_scorm->menubar : 0,
65 'toolbar'=> isset($cfg_scorm->toolbar) ? $cfg_scorm->toolbar : 0,
66 'status'=> isset($cfg_scorm->status) ? $cfg_scorm->status : 0);
70 * Returns an array of the array of what grade options
72 * @return array an array of what grade options
74 function scorm_get_grade_method_array(){
75 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
76 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
77 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
78 GRADESUM => get_string('gradesum', 'scorm'));
82 * Returns an array of the array of what grade options
84 * @return array an array of what grade options
86 function scorm_get_what_grade_array(){
87 return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
88 AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
89 FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
90 LASTATTEMPT => get_string('lastattempt', 'scorm'));
94 * Returns an array of the array of skip view options
96 * @return array an array of skip view options
98 function scorm_get_skip_view_array(){
99 return array(0 => get_string('never'),
100 1 => get_string('firstaccess','scorm'),
101 2 => get_string('always'));
105 * Returns an array of the array of hide table of contents options
107 * @return array an array of hide table of contents options
109 function scorm_get_hidetoc_array(){
110 return array(0 =>get_string('sided','scorm'),
111 1 => get_string('hidden','scorm'),
112 2 => get_string('popupmenu','scorm'));
116 * Returns an array of the array of update frequency options
118 * @return array an array of update frequency options
120 function scorm_get_updatefreq_array(){
121 return array(0 => get_string('never'),
122 1 => get_string('onchanges','scorm'),
123 2 => get_string('everyday','scorm'),
124 3 => get_string('everytime','scorm'));
128 * Returns an array of the array of popup display options
130 * @return array an array of popup display options
132 function scorm_get_popup_display_array(){
133 return array(0 => get_string('currentwindow', 'scorm'),
134 1 => get_string('popup', 'scorm'));
138 * Returns an array of the array of attempt options
140 * @return array an array of attempt options
142 function scorm_get_attempts_array(){
143 $attempts = array(0 => get_string('nolimit','scorm'),
144 1 => get_string('attempt1','scorm'));
146 for ($i=2; $i<=6; $i++) {
147 $attempts[$i] = get_string('attemptsx','scorm', $i);
153 * Extracts scrom package, sets up all variables.
154 * Called whenever scorm changes
155 * @param object $scorm instance - fields are updated and changes saved into database
156 * @param bool $full force full update if true
159 function scorm_parse($scorm, $full) {
161 $cfg_scorm = get_config('scorm');
163 if (!isset($scorm->cmid)) {
164 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
165 $scorm->cmid = $cm->id;
167 $context = get_context_instance(CONTEXT_MODULE, $scorm->cmid);
168 $newhash = $scorm->sha1hash;
170 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
172 $fs = get_file_storage();
173 $packagefile = false;
175 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
176 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
177 $newhash = $packagefile->get_contenthash();
182 if (!$cfg_scorm->allowtypelocalsync) {
183 // sorry - localsync disabled
186 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
187 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
188 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
189 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference)) {
190 $newhash = sha1($scorm->reference);
198 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
199 if (strpos($scorm->version, 'SCORM') !== false) {
200 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
204 } else if (strpos($scorm->version, 'AICC') !== false) {
205 // TODO: add more sanity checks - something really exists in scorm_content area
211 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
213 $packer = get_file_packer('application/zip');
214 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
221 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
222 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
224 if (!scorm_parse_scorm($scorm, $manifest)) {
225 $scorm->version = 'ERROR';
228 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
230 if (!scorm_parse_aicc($scorm)) {
231 $scorm->version = 'ERROR';
235 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
236 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
239 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
240 // SCORM only, AICC can not be external
241 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
242 $scorm->version = 'ERROR';
244 $newhash = sha1($scorm->reference);
246 } else if ($scorm->scormtype === SCORM_TYPE_IMSREPOSITORY and !empty($CFG->repositoryactivate) and $cfg_scorm->allowtypeimsrepository) {
247 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
250 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
251 if (!scorm_parse_scorm($scorm, $CFG->repository.substr($scorm->reference,1).'/imsmanifest.xml')) {
252 $scorm->version = 'ERROR';
254 $newhash = sha1($scorm->reference);
257 // sorry, disabled type
262 $scorm->sha1hash = $newhash;
263 $DB->update_record('scorm', $scorm);
267 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
268 if (!empty($haystacks)) {
269 foreach ($haystacks as $key => $element) {
271 if ($element->{$item} === $needle) {
275 if ($element->{$item} == $needle) {
284 function scorm_repeater($what, $times) {
289 for ($i=0; $i<$times;$i++) {
295 function scorm_external_link($link) {
296 // check if a link is external
298 $link = strtolower($link);
299 if (substr($link,0,7) == 'http://') {
301 } else if (substr($link,0,8) == 'https://') {
303 } else if (substr($link,0,4) == 'www.') {
310 * Returns an object containing all datas relative to the given sco ID
312 * @param integer $id The sco ID
313 * @return mixed (false if sco id does not exists)
316 function scorm_get_sco($id,$what=SCO_ALL) {
319 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
320 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
321 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
322 foreach ($scodatas as $scodata) {
323 $sco->{$scodata->name} = $scodata->value;
325 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
326 $sco->parameters = '';
335 * Returns an object (array) containing all the scoes data related to the given sco ID
337 * @param integer $id The sco ID
338 * @param integer $organisation an organisation ID - defaults to false if not required
339 * @return mixed (false if there are no scoes or an array)
342 function scorm_get_scoes($id,$organisation=false) {
345 $organizationsql = '';
346 $queryarray = array('scorm'=>$id);
347 if (!empty($organisation)) {
348 $queryarray['organization'] = $organisation;
350 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
351 // drop keys so that it is a simple array as expected
352 $scoes = array_values($scoes);
353 foreach ($scoes as $sco) {
354 if ($scodatas = $DB->get_records('scorm_scoes_data',array('scoid'=>$sco->id))) {
355 foreach ($scodatas as $scodata) {
356 $sco->{$scodata->name} = $scodata->value;
366 function scorm_insert_track($userid,$scormid,$scoid,$attempt,$element,$value,$forcecompleted=false) {
371 if ($forcecompleted) {
372 //TODO - this could be broadened to encompass SCORM 2004 in future
373 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
374 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))) {
375 $value = 'completed';
378 if ($element == 'cmi.core.score.raw') {
379 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))) {
380 if ($tracktest->value == "incomplete") {
381 $tracktest->value = "completed";
382 $DB->update_record('scorm_scoes_track',$tracktest);
388 if ($track = $DB->get_record('scorm_scoes_track',array('userid'=>$userid, 'scormid'=>$scormid, 'scoid'=>$scoid, 'attempt'=>$attempt, 'element'=>$element))) {
389 if ($element != 'x.start.time' ) { //don't update x.start.time - keep the original value.
390 $track->value = addslashes_js($value);
391 $track->timemodified = time();
392 $DB->update_record('scorm_scoes_track',$track);
396 $track->userid = $userid;
397 $track->scormid = $scormid;
398 $track->scoid = $scoid;
399 $track->attempt = $attempt;
400 $track->element = $element;
401 $track->value = addslashes_js($value);
402 $track->timemodified = time();
403 $id = $DB->insert_record('scorm_scoes_track',$track);
406 if (strstr($element, '.score.raw') ||
407 (($element == 'cmi.core.lesson_status' || $element == 'cmi.completion_status') && ($track->value == 'completed' || $track->value == 'passed'))) {
408 $scorm = $DB->get_record('scorm', array('id' => $scormid));
409 include_once($CFG->dirroot.'/mod/scorm/lib.php');
410 scorm_update_grades($scorm, $userid);
416 function scorm_get_tracks($scoid,$userid,$attempt='') {
417 /// Gets all tracks of specified sco and user
420 if (empty($attempt)) {
421 if ($scormid = $DB->get_field('scorm_scoes','scorm', array('id'=>$scoid))) {
422 $attempt = scorm_get_last_attempt($scormid,$userid);
427 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid, 'attempt'=>$attempt),'element ASC')) {
428 $usertrack = new stdClass();
429 $usertrack->userid = $userid;
430 $usertrack->scoid = $scoid;
431 // Defined in order to unify scorm1.2 and scorm2004
432 $usertrack->score_raw = '';
433 $usertrack->status = '';
434 $usertrack->total_time = '00:00:00';
435 $usertrack->session_time = '00:00:00';
436 $usertrack->timemodified = 0;
437 foreach ($tracks as $track) {
438 $element = $track->element;
439 $track->value = stripslashes($track->value); // TODO: this is probably wrong, the stripslashes() has undefined meaning now; was this related to JS quoting or magic quotes?
440 $usertrack->{$element} = $track->value;
442 case 'cmi.core.lesson_status':
443 case 'cmi.completion_status':
444 if ($track->value == 'not attempted') {
445 $track->value = 'notattempted';
447 $usertrack->status = $track->value;
449 case 'cmi.core.score.raw':
450 case 'cmi.score.raw':
451 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
453 case 'cmi.core.session_time':
454 case 'cmi.session_time':
455 $usertrack->session_time = $track->value;
457 case 'cmi.core.total_time':
458 case 'cmi.total_time':
459 $usertrack->total_time = $track->value;
462 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
463 $usertrack->timemodified = $track->timemodified;
466 if (is_array($usertrack)) {
476 /* Find the start and finsh time for a a given SCO attempt
478 * @param int $scormid SCORM Id
479 * @param int $scoid SCO Id
480 * @param int $userid User Id
481 * @param int $attemt Attempt Id
483 * @return object start and finsh time EPOC secods
486 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
489 $timedata = new stdClass();
490 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
491 $tracks = $DB->get_records_select('scorm_scoes_track',"$sql ORDER BY timemodified ASC");
493 $tracks = array_values($tracks);
497 $timedata->start = $tracks[0]->timemodified;
500 $timedata->start = false;
502 if ($tracks && $track = array_pop($tracks)) {
503 $timedata->finish = $track->timemodified;
506 $timedata->finish = $timedata->start;
512 function scorm_get_user_data($userid) {
514 /// Gets user info required to display the table of scorm results
517 return $DB->get_record('user', array('id'=>$userid),'firstname, lastname, picture');
520 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
522 $attemptscore = NULL;
523 $attemptscore->scoes = 0;
524 $attemptscore->values = 0;
525 $attemptscore->max = 0;
526 $attemptscore->sum = 0;
527 $attemptscore->lastmodify = 0;
529 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
533 foreach ($scoes as $sco) {
534 if ($userdata=scorm_get_tracks($sco->id, $userid,$attempt)) {
535 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
536 $attemptscore->scoes++;
538 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
539 $attemptscore->values++;
540 $attemptscore->sum += $userdata->score_raw;
541 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
542 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
543 $attemptscore->lastmodify = $userdata->timemodified;
545 $attemptscore->lastmodify = 0;
550 switch ($scorm->grademethod) {
552 $score = (float) $attemptscore->max;
555 if ($attemptscore->values > 0) {
556 $score = $attemptscore->sum/$attemptscore->values;
562 $score = $attemptscore->sum;
565 $score = $attemptscore->scoes;
568 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
574 function scorm_grade_user($scorm, $userid) {
576 // ensure we dont grade user beyond $scorm->maxattempt settings
577 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
578 if($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt){
579 $lastattempt = $scorm->maxattempt;
582 switch ($scorm->whatgrade) {
584 return scorm_grade_user_attempt($scorm, $userid, 1);
587 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
591 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
592 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
593 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
599 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
600 if (empty($attemptcount)) {
603 $attemptcount = count($attemptcount);
605 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
607 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
608 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
609 $sumscore += $attemptscore;
612 return round($sumscore / $attemptcount);
617 function scorm_count_launchable($scormid,$organization='') {
620 $sqlorganization = '';
621 $params = array($scormid);
622 if (!empty($organization)) {
623 $sqlorganization = " AND organization=?";
624 $params[] = $organization;
626 return $DB->count_records_select('scorm_scoes',"scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
629 function scorm_get_last_attempt($scormid, $userid) {
632 /// Find the last attempt number for the given user id and scorm id
633 if ($lastattempt = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid), 'max(attempt) as a')) {
634 if (empty($lastattempt->a)) {
637 return $lastattempt->a;
644 function scorm_get_last_completed_attempt($scormid, $userid) {
647 /// Find the last attempt number for the given user id and scorm id
648 if ($lastattempt = $DB->get_record_select('scorm_scoes_track', "userid = ? AND scormid = ? AND (value='completed' OR value='passed')", array($userid, $scormid), 'max(attempt) as a')) {
649 if (empty($lastattempt->a)) {
652 return $lastattempt->a;
659 function scorm_course_format_display($user,$course) {
660 global $CFG, $DB, $PAGE, $OUTPUT;
662 $strupdate = get_string('update');
663 $context = get_context_instance(CONTEXT_COURSE,$course->id);
665 echo '<div class="mod-scorm">';
666 if ($scorms = get_all_instances_in_course('scorm', $course)) {
667 // The module SCORM activity with the least id is the course
668 $scorm = current($scorms);
669 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
670 print_error('invalidcoursemodule');
673 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
674 if (has_capability('moodle/course:manageactivities', $context)) {
675 if ($PAGE->user_is_editing()) {
676 // Display update icon
677 $path = $CFG->wwwroot.'/course';
678 $headertext .= '<span class="commands">'.
679 '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&sesskey='.sesskey().'">'.
680 '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
682 $headertext .= '</td>';
683 // Display report link
684 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
685 if ($trackedusers->c > 0) {
686 $headertext .= '<td class="reportlink">'.
687 '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
688 get_string('viewallreports','scorm',$trackedusers->c).'</a>';
690 $headertext .= '<td class="reportlink">'.get_string('noreports','scorm');
692 $colspan = ' colspan="2"';
694 $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
695 echo $OUTPUT->box($headertext,'generalbox boxwidthwide');
696 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm);
698 if (has_capability('moodle/course:update', $context)) {
699 // Create a new activity
700 redirect($CFG->wwwroot.'/course/mod.php?id='.$course->id.'&section=0&sesskey='.sesskey().'&add=scorm');
702 echo $OUTPUT->notification('Could not find a scorm course here');
708 function scorm_view_display ($user, $scorm, $action, $cm) {
709 global $CFG, $DB, $PAGE, $OUTPUT;
711 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
712 scorm_parse($scorm, false);
715 $organization = optional_param('organization', '', PARAM_INT);
717 if($scorm->displaycoursestructure == 1) {
718 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
720 <div class="structurehead"><?php print_string('contents','scorm') ?></div>
723 if (empty($organization)) {
724 $organization = $scorm->launch;
726 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
727 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
728 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
729 array($scorm->id),'id','id,title')) {
730 if (count($orgs) > 1) {
731 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
732 $select->label = get_string('organizations','scorm');
733 $select->class = 'scorm-center';
734 echo $OUTPUT->render($select);
738 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
739 if (($sco->organization == '') && ($sco->launch == '')) {
740 $orgidentifier = $sco->identifier;
742 $orgidentifier = $sco->organization;
746 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
747 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
748 $scorm->version = 'scorm_12';
750 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
752 $result = scorm_get_toc($user,$scorm,$cm->id,TOCFULLURL,$orgidentifier);
753 $incomplete = $result->incomplete;
755 // do we want the TOC to be displayed?
756 if($scorm->displaycoursestructure == 1) {
758 echo $OUTPUT->box_end();
761 // is this the first attempt ?
762 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
764 // do not give the player launch FORM if the SCORM object is locked after the final attempt
765 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
767 <div class="scorm-center">
768 <form id="theform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
770 if ($scorm->hidebrowse == 0) {
771 print_string('mode','scorm');
772 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse','scorm').'</label>'."\n";
773 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal','scorm')."</label>\n";
775 echo '<input type="hidden" name="mode" value="normal" />'."\n";
777 if ($scorm->forcenewattempt == 1) {
778 if ($incomplete === false) {
779 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
781 } elseif (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
784 <input type="checkbox" id="a" name="newattempt" />
785 <label for="a"><?php print_string('newattempt','scorm') ?></label>
790 <input type="hidden" name="scoid"/>
791 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
792 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
793 <input type="submit" value="<?php print_string('enter','scorm') ?>" />
800 function scorm_simple_play($scorm,$user, $context) {
805 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
806 scorm_parse($scorm, false);
808 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
812 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
815 if ($scorm->skipview >= 1) {
816 $sco = current($scoes);
817 if (scorm_get_tracks($sco->id,$user->id) === false) {
818 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
820 } else if ($scorm->skipview == 2) {
821 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
829 function scorm_get_count_users($scormid, $groupingid=null) {
832 if (!empty($groupingid)) {
833 $sql = "SELECT COUNT(DISTINCT st.userid)
834 FROM {scorm_scoes_track} st
835 INNER JOIN {groups_members} gm ON st.userid = gm.userid
836 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
837 WHERE st.scormid = ? AND gg.groupingid = ?
839 $params = array($scormid, $groupingid);
841 $sql = "SELECT COUNT(DISTINCT st.userid)
842 FROM {scorm_scoes_track} st
845 $params = array($scormid);
848 return ($DB->count_records_sql($sql, $params));
852 * Build up the JavaScript representation of an array element
854 * @param string $sversion SCORM API version
855 * @param array $userdata User track data
856 * @param string $element_name Name of array element to get values for
857 * @param array $children list of sub elements of this array element that also need instantiating
860 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
861 // reconstitute comments_from_learner and comments_from_lms
863 $current_subelement = '';
867 $scormseperator = '_';
868 if ($sversion == 'scorm_13') { //scorm 1.3 elements use a . instead of an _
869 $scormseperator = '.';
871 // filter out the ones we want
872 $element_list = array();
873 foreach($userdata as $element => $value){
874 if (substr($element,0,strlen($element_name)) == $element_name) {
875 $element_list[$element] = $value;
879 // sort elements in .n array order
880 uksort($element_list, "scorm_element_cmp");
882 // generate JavaScript
883 foreach($element_list as $element => $value){
884 if ($sversion == 'scorm_13') {
885 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
886 preg_match('/\.(N\d+)\./', $element, $matches);
888 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
889 preg_match('/\_(\d+)\./', $element, $matches);
891 if (count($matches) > 0 && $current != $matches[1]) {
892 if ($count_sub > 0) {
893 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
895 $current = $matches[1];
897 $current_subelement = '';
900 $end = strpos($element,$matches[1])+strlen($matches[1]);
901 $subelement = substr($element,0,$end);
902 echo ' '.$subelement." = new Object();\n";
903 // now add the children
904 foreach ($children as $child) {
905 echo ' '.$subelement.".".$child." = new Object();\n";
906 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
910 // now - flesh out the second level elements if there are any
911 if ($sversion == 'scorm_13') {
912 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
913 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
915 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
916 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
919 // check the sub element type
920 if (count($matches) > 0 && $current_subelement != $matches[1]) {
921 if ($count_sub > 0) {
922 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
924 $current_subelement = $matches[1];
927 $end = strpos($element,$matches[1])+strlen($matches[1]);
928 $subelement = substr($element,0,$end);
929 echo ' '.$subelement." = new Object();\n";
932 // now check the subelement subscript
933 if (count($matches) > 0 && $current_sub != $matches[2]) {
934 $current_sub = $matches[2];
936 $end = strrpos($element,$matches[2])+strlen($matches[2]);
937 $subelement = substr($element,0,$end);
938 echo ' '.$subelement." = new Object();\n";
941 echo ' '.$element.' = \''.$value."';\n";
943 if ($count_sub > 0) {
944 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
947 echo ' '.$element_name.'._count = '.$count.";\n";
952 * Build up the JavaScript representation of an array element
954 * @param string $a left array element
955 * @param string $b right array element
956 * @return comparator - 0,1,-1
958 function scorm_element_cmp($a, $b) {
959 preg_match('/.*?(\d+)\./', $a, $matches);
960 $left = intval($matches[1]);
961 preg_match('/.?(\d+)\./', $b, $matches);
962 $right = intval($matches[1]);
963 if ($left < $right) {
964 return -1; // smaller
965 } elseif ($left > $right) {
968 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
969 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
970 $leftterm = intval($matches[2]);
971 $left = intval($matches[3]);
972 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
973 $rightterm = intval($matches[2]);
974 $right = intval($matches[3]);
975 if ($leftterm < $rightterm) {
976 return -1; // smaller
977 } elseif ($leftterm > $rightterm) {
980 if ($left < $right) {
981 return -1; // smaller
982 } elseif ($left > $right) {
988 // fall back for no second level matches or second level matches are equal
989 return 0; // equal to
994 * Generate the user attempt status string
996 * @param object $user Current context user
997 * @param object $scorm a moodle scrom object - mdl_scorm
998 * @return string - Attempt status string
1000 function scorm_get_attempt_status($user, $scorm) {
1003 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
1004 if(empty($attempts)) {
1007 $attemptcount = count($attempts);
1010 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1011 if ($scorm->maxattempt > 0) {
1012 $result .= $scorm->maxattempt . '<BR>';
1014 $result .= get_string('unlimited').'<BR>';
1016 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<BR>';
1018 if ($scorm->maxattempt == 1) {
1019 switch ($scorm->grademethod) {
1021 $grademethod = get_string('gradehighest', 'scorm');
1024 $grademethod = get_string('gradeaverage', 'scorm');
1027 $grademethod = get_string('gradesum', 'scorm');
1030 $grademethod = get_string('gradescoes', 'scorm');
1034 switch ($scorm->whatgrade) {
1035 case HIGHESTATTEMPT:
1036 $grademethod = get_string('highestattempt', 'scorm');
1038 case AVERAGEATTEMPT:
1039 $grademethod = get_string('averageattempt', 'scorm');
1042 $grademethod = get_string('firstattempt', 'scorm');
1045 $grademethod = get_string('lastattempt', 'scorm');
1050 if(!empty($attempts)) {
1052 foreach($attempts as $attempt) {
1053 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1054 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'%<BR>';
1058 $calculatedgrade = scorm_grade_user($scorm, $user->id);
1059 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1060 if(empty($attempts)) {
1061 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . get_string('none') . '<BR>';
1063 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . $calculatedgrade . ($scorm->grademethod == GRADESCOES ? '' : '%') .'<BR>';
1066 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1067 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts','scorm').'</font></p>';
1073 * Get SCORM attempt count
1075 * @param object $user Current context user
1076 * @param object $scorm a moodle scrom object - mdl_scorm
1077 * @param bool $attempts return the list of attempts
1078 * @return int - no. of attempts so far
1080 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1083 $element = 'cmi.core.score.raw';
1084 if ($scorm->grademethod == GRADESCOES) {
1085 $element = 'cmi.core.lesson_status';
1087 if ($scorm->version == 'scorm1_3') {
1088 $element = 'cmi.score.raw';
1090 $attempts = $DB->get_records_select('scorm_scoes_track',"element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id),'attempt','DISTINCT attempt AS attemptnumber');
1091 if ($attempts_only) {
1094 if(!empty($attempts)) {
1095 $attemptcount = count($attempts);
1097 return $attemptcount;
1101 * Figure out with this is a debug situation
1103 * @param object $scorm a moodle scrom object - mdl_scorm
1104 * @return boolean - debugging true/false
1106 function scorm_debugging($scorm) {
1108 $cfg_scorm = get_config('scorm');
1110 if (!$cfg_scorm->allowapidebug) {
1113 $identifier = $USER->username.':'.$scorm->name;
1114 $test = $cfg_scorm->apidebugmask;
1115 // check the regex is only a short list of safe characters
1116 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1120 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1125 * Delete Scorm tracks for selected users
1127 * @param array $attemptids list of attempts that need to be deleted
1128 * @param int $scorm instance
1130 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1132 function scorm_delete_responses($attemptids, $scorm) {
1133 if(!is_array($attemptids) || empty($attemptids)) {
1137 foreach($attemptids as $num => $attemptid) {
1138 if(empty($attemptid)) {
1139 unset($attemptids[$num]);
1143 foreach($attemptids as $attempt) {
1144 $keys = explode(':', $attempt);
1145 if (count($keys) == 2) {
1146 $userid = clean_param($keys[0], PARAM_INT);
1147 $attemptid = clean_param($keys[1], PARAM_INT);
1148 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
1159 * Delete Scorm tracks for selected users
1161 * @param int $userid ID of User
1162 * @param int $scormid ID of Scorm
1163 * @param int $attemptid user attempt that need to be deleted
1165 * return bool true suceeded
1167 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1170 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1171 include_once('lib.php');
1172 scorm_update_grades($scorm, $userid, true);
1177 * Converts SCORM duration notation to human-readable format
1178 * The function works with both SCORM 1.2 and SCORM 2004 time formats
1179 * @param $duration string SCORM duration
1180 * @return string human-readable date/time
1182 function scorm_format_duration($duration) {
1183 // fetch date/time strings
1184 $stryears = get_string('years');
1185 $strmonths = get_string('nummonths');
1186 $strdays = get_string('days');
1187 $strhours = get_string('hours');
1188 $strminutes = get_string('minutes');
1189 $strseconds = get_string('seconds');
1191 if ($duration[0] == 'P') {
1192 // if timestamp starts with 'P' - it's a SCORM 2004 format
1193 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1194 // and outputs filled sections, discarding leading zeroes and any format literals
1195 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1196 $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#',
1197 '#([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#' );
1198 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1199 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1201 // else we have SCORM 1.2 format there
1202 // first convert the timestamp to some SCORM 2004-like format for conveniency
1203 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1204 // then convert in the same way as SCORM 2004
1205 $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#' );
1206 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1209 $result = preg_replace($pattern, $replace, $duration);