3 require_once("$CFG->dirroot/mod/scorm/lib.php");
5 /// Constants and settings for module scorm
6 define('UPDATE_NEVER', '0');
7 define('UPDATE_ONCHANGE', '1');
8 define('UPDATE_EVERYDAY', '2');
9 define('UPDATE_EVERYTIME', '3');
12 define('SCO_DATA', 1);
13 define('SCO_ONLY', 2);
15 define('GRADESCOES', '0');
16 define('GRADEHIGHEST', '1');
17 define('GRADEAVERAGE', '2');
18 define('GRADESUM', '3');
20 define('HIGHESTATTEMPT', '0');
21 define('AVERAGEATTEMPT', '1');
22 define('FIRSTATTEMPT', '2');
23 define('LASTATTEMPT', '3');
25 /// Local Library of functions for module scorm
28 * Returns an array of the popup options for SCORM and each options default value
30 * @return array an array of popup options as the key and their defaults as the value
32 function scorm_get_popup_options_array(){
34 $cfg_scorm = get_config('scorm');
36 return array('resizable'=> isset($cfg_scorm->resizable) ? $cfg_scorm->resizable : 0,
37 'scrollbars'=> isset($cfg_scorm->scrollbars) ? $cfg_scorm->scrollbars : 0,
38 'directories'=> isset($cfg_scorm->directories) ? $cfg_scorm->directories : 0,
39 'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
40 'menubar'=> isset($cfg_scorm->menubar) ? $cfg_scorm->menubar : 0,
41 'toolbar'=> isset($cfg_scorm->toolbar) ? $cfg_scorm->toolbar : 0,
42 'status'=> isset($cfg_scorm->status) ? $cfg_scorm->status : 0);
46 * Returns an array of the array of what grade options
48 * @return array an array of what grade options
50 function scorm_get_grade_method_array(){
51 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
52 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
53 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
54 GRADESUM => get_string('gradesum', 'scorm'));
58 * Returns an array of the array of what grade options
60 * @return array an array of what grade options
62 function scorm_get_what_grade_array(){
63 return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
64 AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
65 FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
66 LASTATTEMPT => get_string('lastattempt', 'scorm'));
70 * Returns an array of the array of skip view options
72 * @return array an array of skip view options
74 function scorm_get_skip_view_array(){
75 return array(0 => get_string('never'),
76 1 => get_string('firstaccess','scorm'),
77 2 => get_string('always'));
81 * Returns an array of the array of hide table of contents options
83 * @return array an array of hide table of contents options
85 function scorm_get_hidetoc_array(){
86 return array(0 =>get_string('sided','scorm'),
87 1 => get_string('hidden','scorm'),
88 2 => get_string('popupmenu','scorm'));
92 * Returns an array of the array of update frequency options
94 * @return array an array of update frequency options
96 function scorm_get_updatefreq_array(){
97 return array(0 => get_string('never'),
98 1 => get_string('onchanges','scorm'),
99 2 => get_string('everyday','scorm'),
100 3 => get_string('everytime','scorm'));
104 * Returns an array of the array of popup display options
106 * @return array an array of popup display options
108 function scorm_get_popup_display_array(){
109 return array(0 => get_string('iframe', 'scorm'),
110 1 => get_string('popup', 'scorm'));
114 * Returns an array of the array of attempt options
116 * @return array an array of attempt options
118 function scorm_get_attempts_array(){
119 $attempts = array(0 => get_string('nolimit','scorm'),
120 1 => get_string('attempt1','scorm'));
122 for ($i=2; $i<=6; $i++) {
123 $attempts[$i] = get_string('attemptsx','scorm', $i);
129 * Extracts scrom package, sets up all variables.
130 * Called whenever scorm changes
131 * @param object $scorm instance - fields are updated and changes saved into database
132 * @param bool $full force full update if true
135 function scorm_parse($scorm, $full) {
137 $cfg_scorm = get_config('scorm');
139 if (!isset($scorm->cmid)) {
140 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
141 $scorm->cmid = $cm->id;
143 $context = get_context_instance(CONTEXT_MODULE, $scorm->cmid);
144 $newhash = $scorm->sha1hash;
146 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
148 $fs = get_file_storage();
149 $packagefile = false;
151 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
152 if ($packagefile = $fs->get_file($context->id, 'scorm_package', 0, '/', $scorm->reference)) {
153 $newhash = $packagefile->get_contenthash();
158 if (!$cfg_scorm->allowtypelocalsync) {
159 // sorry - localsync disabled
162 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
163 $fs->delete_area_files($context->id, 'scorm_package');
164 $file_record = array('contextid'=>$context->id, 'filearea'=>'scorm_package', 'itemid'=>0, 'filepath'=>'/');
165 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference)) {
166 $newhash = sha1($scorm->reference);
174 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
175 if (strpos($scorm->version, 'SCORM') !== false) {
176 if ($fs->get_file($context->id, 'scorm_content', 0, '/', 'imsmanifest.xml')) {
180 } else if (strpos($scorm->version, 'AICC') !== false) {
181 // TODO: add more sanity checks - something really exists in scorm_content area
187 $fs->delete_area_files($context->id, 'scorm_content');
189 $packer = get_file_packer('application/zip');
190 $packagefile->extract_to_storage($packer, $context->id, 'scorm_content', 0, '/');
197 if ($manifest = $fs->get_file($context->id, 'scorm_content', 0, '/', 'imsmanifest.xml')) {
198 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
200 if (!scorm_parse_scorm($scorm, $manifest)) {
201 $scorm->version = 'ERROR';
204 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
206 if (!scorm_parse_aicc($scorm)) {
207 $scorm->version = 'ERROR';
211 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
212 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
215 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
216 // SCORM only, AICC can not be external
217 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
218 $scorm->version = 'ERROR';
220 $newhash = sha1($scorm->reference);
222 } else if ($scorm->scormtype === SCORM_TYPE_IMSREPOSITORY and !empty($CFG->repositoryactivate) and $cfg_scorm->allowtypeimsrepository) {
223 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
226 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
227 if (!scorm_parse_scorm($scorm, $CFG->repository.substr($scorm->reference,1).'/imsmanifest.xml')) {
228 $scorm->version = 'ERROR';
230 $newhash = sha1($scorm->reference);
233 // sorry, disabled type
238 $scorm->sha1hash = $newhash;
239 $DB->update_record('scorm', $scorm);
243 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
244 if (!empty($haystacks)) {
245 foreach ($haystacks as $key => $element) {
247 if ($element->{$item} === $needle) {
251 if ($element->{$item} == $needle) {
260 function scorm_repeater($what, $times) {
265 for ($i=0; $i<$times;$i++) {
271 function scorm_external_link($link) {
272 // check if a link is external
274 $link = strtolower($link);
275 if (substr($link,0,7) == 'http://') {
277 } else if (substr($link,0,8) == 'https://') {
279 } else if (substr($link,0,4) == 'www.') {
286 * Returns an object containing all datas relative to the given sco ID
288 * @param integer $id The sco ID
289 * @return mixed (false if sco id does not exists)
292 function scorm_get_sco($id,$what=SCO_ALL) {
295 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
296 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
297 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
298 foreach ($scodatas as $scodata) {
299 $sco->{$scodata->name} = $scodata->value;
301 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
302 $sco->parameters = '';
311 * Returns an object (array) containing all the scoes data related to the given sco ID
313 * @param integer $id The sco ID
314 * @param integer $organisation an organisation ID - defaults to false if not required
315 * @return mixed (false if there are no scoes or an array)
318 function scorm_get_scoes($id,$organisation=false) {
321 $organizationsql = '';
322 $queryarray = array('scorm'=>$id);
323 if (!empty($organisation)) {
324 $queryarray['organization'] = $organisation;
326 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
327 // drop keys so that it is a simple array as expected
328 $scoes = array_values($scoes);
329 foreach ($scoes as $sco) {
330 if ($scodatas = $DB->get_records('scorm_scoes_data',array('scoid'=>$sco->id))) {
331 foreach ($scodatas as $scodata) {
332 $sco->{$scodata->name} = $scodata->value;
342 function scorm_insert_track($userid,$scormid,$scoid,$attempt,$element,$value,$forcecompleted=false) {
347 if ($forcecompleted) {
348 //TODO - this could be broadened to encompass SCORM 2004 in future
349 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
350 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))) {
351 $value = 'completed';
354 if ($element == 'cmi.core.score.raw') {
355 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))) {
356 if ($tracktest->value == "incomplete") {
357 $tracktest->value = "completed";
358 $idtest = $DB->update_record('scorm_scoes_track',$tracktest);
364 if ($track = $DB->get_record('scorm_scoes_track',array('userid'=>$userid, 'scormid'=>$scormid, 'scoid'=>$scoid, 'attempt'=>$attempt, 'element'=>$element))) {
365 $track->value = $value;
366 $track->timemodified = time();
367 $id = $DB->update_record('scorm_scoes_track',$track);
369 $track->userid = $userid;
370 $track->scormid = $scormid;
371 $track->scoid = $scoid;
372 $track->attempt = $attempt;
373 $track->element = $element;
374 $track->value = $value;
375 $track->timemodified = time();
376 $id = $DB->insert_record('scorm_scoes_track',$track);
379 if (strstr($element, '.score.raw') ||
380 (($element == 'cmi.core.lesson_status' || $element == 'cmi.completion_status') && ($track->value == 'completed' || $track->value == 'passed'))) {
381 $scorm = $DB->get_record('scorm', array('id' => $scormid));
382 $grademethod = $scorm->grademethod % 10;
383 include_once('lib.php');
384 scorm_update_grades($scorm, $userid);
390 function scorm_get_tracks($scoid,$userid,$attempt='') {
391 /// Gets all tracks of specified sco and user
394 if (empty($attempt)) {
395 if ($scormid = $DB->get_field('scorm_scoes','scorm', array('id'=>$scoid))) {
396 $attempt = scorm_get_last_attempt($scormid,$userid);
401 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid, 'attempt'=>$attempt),'element ASC')) {
402 $usertrack->userid = $userid;
403 $usertrack->scoid = $scoid;
404 // Defined in order to unify scorm1.2 and scorm2004
405 $usertrack->score_raw = '';
406 $usertrack->status = '';
407 $usertrack->total_time = '00:00:00';
408 $usertrack->session_time = '00:00:00';
409 $usertrack->timemodified = 0;
410 foreach ($tracks as $track) {
411 $element = $track->element;
412 $usertrack->{$element} = $track->value;
414 case 'cmi.core.lesson_status':
415 case 'cmi.completion_status':
416 if ($track->value == 'not attempted') {
417 $track->value = 'notattempted';
419 $usertrack->status = $track->value;
421 case 'cmi.core.score.raw':
422 case 'cmi.score.raw':
423 $usertrack->score_raw = $track->value;
425 case 'cmi.core.session_time':
426 case 'cmi.session_time':
427 $usertrack->session_time = $track->value;
429 case 'cmi.core.total_time':
430 case 'cmi.total_time':
431 $usertrack->total_time = $track->value;
434 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
435 $usertrack->timemodified = $track->timemodified;
438 if (is_array($usertrack)) {
447 function scorm_get_user_data($userid) {
449 /// Gets user info required to display the table of scorm results
452 return $DB->get_record('user', array('id'=>$userid),'firstname, lastname, picture');
455 function scorm_grade_user_attempt($scorm, $userid, $attempt=1, $time=false) {
457 $attemptscore = NULL;
458 $attemptscore->scoes = 0;
459 $attemptscore->values = 0;
460 $attemptscore->max = 0;
461 $attemptscore->sum = 0;
462 $attemptscore->lastmodify = 0;
464 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
468 // this treatment is necessary as the whatgrade field was not in the DB
469 // and so whatgrade and grademethod are combined in grademethod 10s are whatgrade
470 // and 1s are grademethod
471 $grademethod = $scorm->grademethod % 10;
473 foreach ($scoes as $sco) {
474 if ($userdata=scorm_get_tracks($sco->id, $userid,$attempt)) {
475 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
476 $attemptscore->scoes++;
478 if (!empty($userdata->score_raw)) {
479 $attemptscore->values++;
480 $attemptscore->sum += $userdata->score_raw;
481 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
482 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
483 $attemptscore->lastmodify = $userdata->timemodified;
485 $attemptscore->lastmodify = 0;
490 switch ($grademethod) {
492 $score = $attemptscore->max;
495 if ($attemptscore->values > 0) {
496 $score = $attemptscore->sum/$attemptscore->values;
502 $score = $attemptscore->sum;
505 $score = $attemptscore->scoes;
508 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
512 $result = new stdClass();
513 $result->score = $score;
514 $result->time = $attemptscore->lastmodify;
522 function scorm_grade_user($scorm, $userid, $time=false) {
523 // this treatment is necessary as the whatgrade field was not in the DB
524 // and so whatgrade and grademethod are combined in grademethod 10s are whatgrade
525 // and 1s are grademethod
526 $whatgrade = intval($scorm->grademethod / 10);
528 // insure we dont grade user beyond $scorm->maxattempt settings
529 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
530 if($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt){
531 $lastattempt = $scorm->maxattempt;
534 switch ($whatgrade) {
536 return scorm_grade_user_attempt($scorm, $userid, 1, $time);
539 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_attempt($scorm->id, $userid), $time);
544 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
545 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt, $time);
547 if ($attemptscore->score > $maxscore) {
548 $maxscore = $attemptscore->score;
549 $attempttime = $attemptscore->time;
552 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
556 $result = new stdClass();
557 $result->score = $maxscore;
558 $result->time = $attempttime;
565 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
567 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
568 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt, $time);
570 $sumscore += $attemptscore->score;
572 $sumscore += $attemptscore;
576 if ($lastattempt > 0) {
577 $score = $sumscore / $lastattempt;
583 $result = new stdClass();
584 $result->score = $score;
585 $result->time = $attemptscore->time;
594 function scorm_count_launchable($scormid,$organization='') {
597 $sqlorganization = '';
598 $params = array($scormid);
599 if (!empty($organization)) {
600 $sqlorganization = " AND organization=?";
601 $params[] = $organization;
603 $params []= ''; // empty launch
604 return $DB->count_records_select('scorm_scoes',"scorm = ? $sqlorganization AND launch <> ?", $params);
607 function scorm_get_last_attempt($scormid, $userid) {
610 /// Find the last attempt number for the given user id and scorm id
611 if ($lastattempt = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid), 'max(attempt) as a')) {
612 if (empty($lastattempt->a)) {
615 return $lastattempt->a;
622 function scorm_course_format_display($user,$course) {
625 $strupdate = get_string('update');
626 $strmodule = get_string('modulename','scorm');
627 $context = get_context_instance(CONTEXT_COURSE,$course->id);
629 echo '<div class="mod-scorm">';
630 if ($scorms = get_all_instances_in_course('scorm', $course)) {
631 // The module SCORM activity with the least id is the course
632 $scorm = current($scorms);
633 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
634 print_error('invalidcoursemodule');
637 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
638 if (has_capability('moodle/course:manageactivities', $context)) {
639 if (isediting($course->id)) {
640 // Display update icon
641 $path = $CFG->wwwroot.'/course';
642 $headertext .= '<span class="commands">'.
643 '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&sesskey='.sesskey().'">'.
644 '<img src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
646 $headertext .= '</td>';
647 // Display report link
648 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
649 if ($trackedusers->c > 0) {
650 $headertext .= '<td class="reportlink">'.
651 '<a '.$CFG->frametarget.'" href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
652 get_string('viewallreports','scorm',$trackedusers->c).'</a>';
654 $headertext .= '<td class="reportlink">'.get_string('noreports','scorm');
656 $colspan = ' colspan="2"';
658 $headertext .= '</td></tr><tr><td'.$colspan.'>'.format_text(get_string('summary').':<br />'.$scorm->summary).'</td></tr></table>';
659 print_simple_box($headertext,'','100%');
660 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm, '100%');
662 if (has_capability('moodle/course:update', $context)) {
663 // Create a new activity
664 redirect($CFG->wwwroot.'/course/mod.php?id='.$course->id.'&section=0&sesskey='.sesskey().'&add=scorm');
666 notify('Could not find a scorm course here');
672 function scorm_view_display ($user, $scorm, $action, $cm, $boxwidth='') {
675 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
676 scorm_parse($scorm, false);
679 $organization = optional_param('organization', '', PARAM_INT);
681 if($scorm->displaycoursestructure == 1) {
682 print_simple_box_start('center',$boxwidth);
684 <div class="structurehead"><?php print_string('contents','scorm') ?></div>
687 if (empty($organization)) {
688 $organization = $scorm->launch;
690 if ($orgs = $DB->get_records_menu('scorm_scoes', array('scorm'=>$scorm->id, 'organization'=>'', 'launch'=>''), 'id', 'id,title')) {
691 if (count($orgs) > 1) {
693 <div class='scorm-center'>
694 <?php print_string('organizations','scorm') ?>
695 <form id='changeorg' method='post' action='<?php echo $action ?>'>
696 <?php choose_from_menu($orgs, 'organization', "$organization", '','submit()') ?>
703 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
704 if (($sco->organization == '') && ($sco->launch == '')) {
705 $orgidentifier = $sco->identifier;
707 $orgidentifier = $sco->organization;
713 if ($org = $DB->get_record('scorm_scoes', array('id'=>$organization))) {
714 if (($org->organization == '') && ($org->launch == '')) {
715 $orgidentifier = $org->identifier;
717 $orgidentifier = $org->organization;
721 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
722 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
723 $scorm->version = 'scorm_12';
725 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
727 $result = scorm_get_toc($user,$scorm,'structlist',$orgidentifier);
728 $incomplete = $result->incomplete;
730 // do we want the TOC to be displayed?
731 if($scorm->displaycoursestructure == 1) {
733 print_simple_box_end();
736 // is this the first attempt ?
737 $attemptcount = scorm_get_attempt_count($user, $scorm);
739 // do not give the player launch FORM if the SCORM object is locked after the final attempt
740 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
742 <div class="scorm-center">
743 <form id="theform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
745 if ($scorm->hidebrowse == 0) {
746 print_string('mode','scorm');
747 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse','scorm').'</label>'."\n";
748 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal','scorm')."</label>\n";
750 echo '<input type="hidden" name="mode" value="normal" />'."\n";
752 if ($scorm->forcenewattempt == 1) {
753 if ($incomplete === false) {
754 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
756 } elseif ($attemptcount != 0 && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
759 <input type="checkbox" id="a" name="newattempt" />
760 <label for="a"><?php print_string('newattempt','scorm') ?></label>
765 <input type="hidden" name="scoid"/>
766 <input type="hidden" name="id" value="<?php echo $cm->id ?>"/>
767 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
768 <input type="submit" value="<?php print_string('enter','scorm') ?>" />
775 function scorm_simple_play($scorm,$user) {
780 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND launch <> ?', array($scorm->id, $DB->sql_empty()));
782 if ($scoes && (count($scoes) == 1)) {
783 if ($scorm->skipview >= 1) {
784 $sco = current($scoes);
785 if (scorm_get_tracks($sco->id,$user->id) === false) {
786 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
788 } else if ($scorm->skipview == 2) {
789 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
797 function scorm_simple_play($scorm,$user) {
800 if ($scoes = $DB->get_records_select('scorm_scoes','scorm=? AND launch<>""', array($scorm->id))) {
801 if (count($scoes) == 1) {
802 if ($scorm->skipview >= 1) {
803 $sco = current($scoes);
804 if (scorm_get_tracks($sco->id,$user->id) === false) {
805 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
807 } else if ($scorm->skipview == 2) {
808 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
818 function scorm_get_count_users($scormid, $groupingid=null) {
821 if (!empty($CFG->enablegroupings) && !empty($groupingid)) {
822 $sql = "SELECT COUNT(DISTINCT st.userid)
823 FROM {scorm_scoes_track} st
824 INNER JOIN {groups_members} gm ON st.userid = gm.userid
825 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
826 WHERE st.scormid = ? AND gg.groupingid = ?
828 $params = array($scormid, $groupingid);
830 $sql = "SELECT COUNT(DISTINCT st.userid)
831 FROM {scorm_scoes_track} st
834 $params = array($scormid);
837 return ($DB->count_records_sql($sql, $params));
841 * Build up the JavaScript representation of an array element
843 * @param string $sversion SCORM API version
844 * @param array $userdata User track data
845 * @param string $element_name Name of array element to get values for
846 * @param array $children list of sub elements of this array element that also need instantiating
849 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
850 // reconstitute comments_from_learner and comments_from_lms
852 $current_subelement = '';
857 // filter out the ones we want
858 $element_list = array();
859 foreach($userdata as $element => $value){
860 if (substr($element,0,strlen($element_name)) == $element_name) {
861 $element_list[$element] = $value;
865 // sort elements in .n array order
866 uksort($element_list, "scorm_element_cmp");
868 // generate JavaScript
869 foreach($element_list as $element => $value){
870 if ($sversion == 'scorm_13') {
871 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
872 preg_match('/\.(N\d+)\./', $element, $matches);
874 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
875 preg_match('/\_(\d+)\./', $element, $matches);
877 if (count($matches) > 0 && $current != $matches[1]) {
878 if ($count_sub > 0) {
879 echo ' '.$element_name.'_'.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
881 $current = $matches[1];
883 $current_subelement = '';
886 $end = strpos($element,$matches[1])+strlen($matches[1]);
887 $subelement = substr($element,0,$end);
888 echo ' '.$subelement." = new Object();\n";
889 // now add the children
890 foreach ($children as $child) {
891 echo ' '.$subelement.".".$child." = new Object();\n";
892 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
896 // now - flesh out the second level elements if there are any
897 if ($sversion == 'scorm_13') {
898 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
899 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
901 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
902 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
905 // check the sub element type
906 if (count($matches) > 0 && $current_subelement != $matches[1]) {
907 if ($count_sub > 0) {
908 echo ' '.$element_name.'_'.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
910 $current_subelement = $matches[1];
913 $end = strpos($element,$matches[1])+strlen($matches[1]);
914 $subelement = substr($element,0,$end);
915 echo ' '.$subelement." = new Object();\n";
918 // now check the subelement subscript
919 if (count($matches) > 0 && $current_sub != $matches[2]) {
920 $current_sub = $matches[2];
922 $end = strrpos($element,$matches[2])+strlen($matches[2]);
923 $subelement = substr($element,0,$end);
924 echo ' '.$subelement." = new Object();\n";
927 echo ' '.$element.' = \''.$value."';\n";
929 if ($count_sub > 0) {
930 echo ' '.$element_name.'_'.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
933 echo ' '.$element_name.'._count = '.$count.";\n";
938 * Build up the JavaScript representation of an array element
940 * @param string $a left array element
941 * @param string $b right array element
942 * @return comparator - 0,1,-1
944 function scorm_element_cmp($a, $b) {
945 preg_match('/.*?(\d+)\./', $a, $matches);
946 $left = intval($matches[1]);
947 preg_match('/.?(\d+)\./', $b, $matches);
948 $right = intval($matches[1]);
949 if ($left < $right) {
950 return -1; // smaller
951 } elseif ($left > $right) {
954 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
955 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
956 $leftterm = intval($matches[2]);
957 $left = intval($matches[3]);
958 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
959 $rightterm = intval($matches[2]);
960 $right = intval($matches[3]);
961 if ($leftterm < $rightterm) {
962 return -1; // smaller
963 } elseif ($leftterm > $rightterm) {
966 if ($left < $right) {
967 return -1; // smaller
968 } elseif ($left > $right) {
974 // fall back for no second level matches or second level matches are equal
975 return 0; // equal to
980 * Generate the user attempt status string
982 * @param object $user Current context user
983 * @param object $scorm a moodle scrom object - mdl_scorm
984 * @return string - Attempt status string
986 function scorm_get_attempt_status($user, $scorm) {
989 $attempts = $DB->get_records_select('scorm_scoes_track',"element='cmi.core.score.raw' AND userid=? AND scormid=?", array($user->id, $scorm->id),'attempt','attempt AS attemptnumber, value AS grade');
990 if(empty($attempts)) {
993 $attemptcount = count($attempts);
996 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
997 if ($scorm->maxattempt > 0) {
998 $result .= $scorm->maxattempt . '<BR>';
1000 $result .= get_string('unlimited').'<BR>';
1002 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<BR>';
1006 switch ($scorm->grademethod) {
1008 $grademethod = get_string('gradehighest', 'scorm');
1011 $grademethod = get_string('gradeaverage', 'scorm');
1014 $grademethod = get_string('gradesum', 'scorm');
1017 $grademethod = get_string('gradescoes', 'scorm');
1021 if(!empty($attempts)) {
1022 foreach($attempts as $attempt) {
1023 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1024 $result .= get_string('gradeforattempt', 'scorm').' ' . $attempt->attemptnumber . ': ' . $attempt->grade .'%<BR>';
1028 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1029 if(empty($attempts)) {
1030 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . get_string('none') . '<BR>';
1032 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . $gradereported . ($scorm->grademethod == GRADESCOES ? '' : '%') .'<BR>';
1035 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1036 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts','scorm').'</font></p>';
1042 * Get SCORM attempt count
1044 * @param object $user Current context user
1045 * @param object $scorm a moodle scrom object - mdl_scorm
1046 * @return int - no. of attempts so far
1048 function scorm_get_attempt_count($user, $scorm) {
1051 $element = 'cmi.core.score.raw';
1052 if ($scorm->version == 'scorm1_3') {
1053 $element = 'cmi.score.raw';
1055 $attempts = $DB->get_records_select('scorm_scoes_track',"element=? AND userid=? AND scormid=?", array($element, $user->id, $scorm->id),'attempt','attempt AS attemptnumber, value AS grade');
1056 if(!empty($attempts)) {
1057 $attemptcount = count($attempts);
1059 return $attemptcount;
1063 * Figure out with this is a debug situation
1065 * @param object $scorm a moodle scrom object - mdl_scorm
1066 * @return boolean - debugging true/false
1068 function scorm_debugging($scorm) {
1070 $cfg_scorm = get_config('scorm');
1072 if (!$cfg_scorm->allowapidebug) {
1075 $identifier = $USER->username.':'.$scorm->name;
1076 $test = $cfg_scorm->apidebugmask;
1077 // check the regex is only a short list of safe characters
1078 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1082 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1087 * Delete Scorm tracks for selected users
1089 * @param array $attemptids list of attempts that need to be deleted
1090 * @param int $scormid ID of Scorm
1092 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1094 function scorm_delete_responses($attemptids, $scormid) {
1095 if(!is_array($attemptids) || empty($attemptids)) {
1099 foreach($attemptids as $num => $attemptid) {
1100 if(empty($attemptid)) {
1101 unset($attemptids[$num]);
1105 foreach($attemptids as $attempt) {
1106 $keys = explode(':', $attempt);
1107 if (count($keys) == 2) {
1108 $userid = clean_param($keys[0], PARAM_INT);
1109 $attemptid = clean_param($keys[1], PARAM_INT);
1110 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scormid, $attemptid)) {
1121 * Delete Scorm tracks for selected users
1123 * @param int $userid ID of User
1124 * @param int $scormid ID of Scorm
1125 * @param int $attemptid user attempt that need to be deleted
1127 * return bool true suceeded
1129 function scorm_delete_attempt($userid, $scormid, $attemptid) {
1132 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid, 'attempt' => $attemptid));