SCORM MDL-25781 fix links in TOC on view.php
[moodle.git] / mod / scorm / locallib.php
CommitLineData
e5dd8e3b 1<?php
f69db63e 2
9528568b 3require_once("$CFG->dirroot/mod/scorm/lib.php");
64f93798 4require_once("$CFG->libdir/filelib.php");
9528568b 5
a30b6819 6/// Constants and settings for module scorm
a679d64d 7define('UPDATE_NEVER', '0');
8define('UPDATE_ONCHANGE', '1');
9define('UPDATE_EVERYDAY', '2');
10define('UPDATE_EVERYTIME', '3');
11
b3659259 12define('SCO_ALL', 0);
13define('SCO_DATA', 1);
14define('SCO_ONLY', 2);
a30b6819 15
16define('GRADESCOES', '0');
17define('GRADEHIGHEST', '1');
18define('GRADEAVERAGE', '2');
19define('GRADESUM', '3');
a30b6819 20
21define('HIGHESTATTEMPT', '0');
22define('AVERAGEATTEMPT', '1');
23define('FIRSTATTEMPT', '2');
24define('LASTATTEMPT', '3');
a30b6819 25
08868f58
DM
26define('TOCJSLINK', 1);
27define('TOCFULLURL', 2);
28
9528568b 29/// Local Library of functions for module scorm
a30b6819 30
64f93798
PS
31/**
32 * @package mod-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
35 */
36class 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);
40 }
41 return parent::get_parent();
42 }
43 public function get_visible_name() {
44 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
45 return $this->topvisiblename;
46 }
47 return parent::get_visible_name();
48 }
49}
50
30fc6e2d 51/**
52 * Returns an array of the popup options for SCORM and each options default value
7554f671 53 *
30fc6e2d 54 * @return array an array of popup options as the key and their defaults as the value
55 */
56function scorm_get_popup_options_array(){
57 global $CFG;
58 $cfg_scorm = get_config('scorm');
7554f671 59
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,
1adc77e6 63 'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
7554f671 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);
30fc6e2d 67}
68
69/**
70 * Returns an array of the array of what grade options
7554f671 71 *
30fc6e2d 72 * @return array an array of what grade options
73 */
74function 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'),
7554f671 78 GRADESUM => get_string('gradesum', 'scorm'));
30fc6e2d 79}
80
81/**
82 * Returns an array of the array of what grade options
7554f671 83 *
30fc6e2d 84 * @return array an array of what grade options
85 */
86function 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'));
91}
92
93/**
94 * Returns an array of the array of skip view options
7554f671 95 *
30fc6e2d 96 * @return array an array of skip view options
97 */
98function scorm_get_skip_view_array(){
99 return array(0 => get_string('never'),
100 1 => get_string('firstaccess','scorm'),
101 2 => get_string('always'));
102}
103
104/**
105 * Returns an array of the array of hide table of contents options
7554f671 106 *
30fc6e2d 107 * @return array an array of hide table of contents options
108 */
109function scorm_get_hidetoc_array(){
110 return array(0 =>get_string('sided','scorm'),
111 1 => get_string('hidden','scorm'),
112 2 => get_string('popupmenu','scorm'));
113}
114
115/**
116 * Returns an array of the array of update frequency options
7554f671 117 *
30fc6e2d 118 * @return array an array of update frequency options
119 */
120function 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'));
125}
126
127/**
128 * Returns an array of the array of popup display options
7554f671 129 *
30fc6e2d 130 * @return array an array of popup display options
131 */
132function scorm_get_popup_display_array(){
d67eb434 133 return array(0 => get_string('currentwindow', 'scorm'),
30fc6e2d 134 1 => get_string('popup', 'scorm'));
135}
136
137/**
138 * Returns an array of the array of attempt options
7554f671 139 *
30fc6e2d 140 * @return array an array of attempt options
141 */
142function scorm_get_attempts_array(){
143 $attempts = array(0 => get_string('nolimit','scorm'),
144 1 => get_string('attempt1','scorm'));
7554f671 145
30fc6e2d 146 for ($i=2; $i<=6; $i++) {
147 $attempts[$i] = get_string('attemptsx','scorm', $i);
148 }
7554f671 149
30fc6e2d 150 return $attempts;
151}
9528568b 152/**
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
157 * @return void
158 */
159function scorm_parse($scorm, $full) {
160 global $CFG, $DB;
30fc6e2d 161 $cfg_scorm = get_config('scorm');
8aee93f1 162
9528568b 163 if (!isset($scorm->cmid)) {
164 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
165 $scorm->cmid = $cm->id;
166 }
167 $context = get_context_instance(CONTEXT_MODULE, $scorm->cmid);
168 $newhash = $scorm->sha1hash;
a30b6819 169
9528568b 170 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
a30b6819 171
9528568b 172 $fs = get_file_storage();
173 $packagefile = false;
f69db63e 174
9528568b 175 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
64f93798 176 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
9528568b 177 $newhash = $packagefile->get_contenthash();
178 } else {
179 $newhash = null;
180 }
181 } else {
30fc6e2d 182 if (!$cfg_scorm->allowtypelocalsync) {
9528568b 183 // sorry - localsync disabled
184 return;
185 }
186 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
64f93798
PS
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'=>'/');
9528568b 189 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference)) {
190 $newhash = sha1($scorm->reference);
5c1ac70c 191 } else {
9528568b 192 $newhash = null;
5c1ac70c 193 }
f69db63e 194 }
195 }
f69db63e 196
9528568b 197 if ($packagefile) {
198 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
199 if (strpos($scorm->version, 'SCORM') !== false) {
64f93798 200 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 201 // no need to update
202 return;
e4aa175a 203 }
9528568b 204 } else if (strpos($scorm->version, 'AICC') !== false) {
205 // TODO: add more sanity checks - something really exists in scorm_content area
206 return;
207 }
208 }
209
210 // now extract files
64f93798 211 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
9528568b 212
213 $packer = get_file_packer('application/zip');
64f93798 214 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
9528568b 215
216 } else if (!$full) {
217 return;
218 }
219
220
64f93798 221 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 222 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
223 // SCORM
224 if (!scorm_parse_scorm($scorm, $manifest)) {
225 $scorm->version = 'ERROR';
226 }
227 } else {
228 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
229 // AICC
230 if (!scorm_parse_aicc($scorm)) {
231 $scorm->version = 'ERROR';
232 }
233 }
234
30fc6e2d 235 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
9528568b 236 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
237 return;
238 }
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';
243 }
244 $newhash = sha1($scorm->reference);
245
30fc6e2d 246 } else if ($scorm->scormtype === SCORM_TYPE_IMSREPOSITORY and !empty($CFG->repositoryactivate) and $cfg_scorm->allowtypeimsrepository) {
9528568b 247 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
248 return;
249 }
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';
253 }
254 $newhash = sha1($scorm->reference);
255
e4aa175a 256 } else {
9528568b 257 // sorry, disabled type
258 return;
e4aa175a 259 }
9528568b 260
261 $scorm->revision++;
262 $scorm->sha1hash = $newhash;
263 $DB->update_record('scorm', $scorm);
e4aa175a 264}
265
9528568b 266
2b3447c3 267function scorm_array_search($item, $needle, $haystacks, $strict=false) {
268 if (!empty($haystacks)) {
269 foreach ($haystacks as $key => $element) {
270 if ($strict) {
271 if ($element->{$item} === $needle) {
272 return $key;
273 }
274 } else {
275 if ($element->{$item} == $needle) {
276 return $key;
e4aa175a 277 }
278 }
e4aa175a 279 }
280 }
2b3447c3 281 return false;
e4aa175a 282}
283
2b3447c3 284function scorm_repeater($what, $times) {
285 if ($times <= 0) {
286 return null;
287 }
288 $return = '';
289 for ($i=0; $i<$times;$i++) {
290 $return .= $what;
291 }
292 return $return;
293}
e4aa175a 294
2b3447c3 295function scorm_external_link($link) {
296// check if a link is external
297 $result = false;
298 $link = strtolower($link);
299 if (substr($link,0,7) == 'http://') {
300 $result = true;
301 } else if (substr($link,0,8) == 'https://') {
302 $result = true;
303 } else if (substr($link,0,4) == 'www.') {
304 $result = true;
305 }
306 return $result;
e4aa175a 307}
308
b3659259 309/**
310* Returns an object containing all datas relative to the given sco ID
311*
312* @param integer $id The sco ID
313* @return mixed (false if sco id does not exists)
314*/
bd3523a5 315
b3659259 316function scorm_get_sco($id,$what=SCO_ALL) {
bf347041 317 global $DB;
318
319 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
b3659259 320 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
bf347041 321 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
b3659259 322 foreach ($scodatas as $scodata) {
c31f631b 323 $sco->{$scodata->name} = $scodata->value;
b3659259 324 }
bf347041 325 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
9528568b 326 $sco->parameters = '';
b3659259 327 }
328 return $sco;
329 } else {
330 return false;
331 }
332}
82605bea 333
334/**
335* Returns an object (array) containing all the scoes data related to the given sco ID
336*
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)
340*/
341
342function scorm_get_scoes($id,$organisation=false) {
b44c704f 343 global $DB;
344
82605bea 345 $organizationsql = '';
b44c704f 346 $queryarray = array('scorm'=>$id);
82605bea 347 if (!empty($organisation)) {
b44c704f 348 $queryarray['organization'] = $organisation;
82605bea 349 }
b44c704f 350 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
82605bea 351 // drop keys so that it is a simple array as expected
352 $scoes = array_values($scoes);
353 foreach ($scoes as $sco) {
b44c704f 354 if ($scodatas = $DB->get_records('scorm_scoes_data',array('scoid'=>$sco->id))) {
82605bea 355 foreach ($scodatas as $scodata) {
2fd0e9fe 356 $sco->{$scodata->name} = $scodata->value;
82605bea 357 }
358 }
359 }
360 return $scoes;
361 } else {
362 return false;
363 }
364}
365
6381fa56 366function scorm_insert_track($userid,$scormid,$scoid,$attempt,$element,$value,$forcecompleted=false) {
86996ffe 367 global $DB, $CFG;
bf347041 368
e4aa175a 369 $id = null;
6381fa56 370
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';
376 }
377 }
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";
dd88de0e 382 $DB->update_record('scorm_scoes_track',$tracktest);
6381fa56 383 }
384 }
385 }
386 }
387
bf347041 388 if ($track = $DB->get_record('scorm_scoes_track',array('userid'=>$userid, 'scormid'=>$scormid, 'scoid'=>$scoid, 'attempt'=>$attempt, 'element'=>$element))) {
d1818fdc
DM
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();
dd88de0e
PS
392 $DB->update_record('scorm_scoes_track',$track);
393 $id = $track->id;
d1818fdc 394 }
e4aa175a 395 } else {
396 $track->userid = $userid;
397 $track->scormid = $scormid;
398 $track->scoid = $scoid;
399 $track->attempt = $attempt;
400 $track->element = $element;
898b2823 401 $track->value = addslashes_js($value);
e4aa175a 402 $track->timemodified = time();
bf347041 403 $id = $DB->insert_record('scorm_scoes_track',$track);
e4aa175a 404 }
9528568b 405
9528568b 406 if (strstr($element, '.score.raw') ||
a0b36684 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));
86996ffe 409 include_once($CFG->dirroot.'/mod/scorm/lib.php');
7f7946fd 410 scorm_update_grades($scorm, $userid);
d23121ab 411 }
9528568b 412
e4aa175a 413 return $id;
414}
415
e4aa175a 416function scorm_get_tracks($scoid,$userid,$attempt='') {
e4aa175a 417/// Gets all tracks of specified sco and user
bf347041 418 global $CFG, $DB;
e4aa175a 419
420 if (empty($attempt)) {
bf347041 421 if ($scormid = $DB->get_field('scorm_scoes','scorm', array('id'=>$scoid))) {
e4aa175a 422 $attempt = scorm_get_last_attempt($scormid,$userid);
423 } else {
424 $attempt = 1;
425 }
426 }
bf347041 427 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid, 'attempt'=>$attempt),'element ASC')) {
39790bd8 428 $usertrack = new stdClass();
e4aa175a 429 $usertrack->userid = $userid;
9528568b 430 $usertrack->scoid = $scoid;
a30b6819 431 // Defined in order to unify scorm1.2 and scorm2004
e4aa175a 432 $usertrack->score_raw = '';
e4aa175a 433 $usertrack->status = '';
e4aa175a 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;
fd8a6a73 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?
e4aa175a 440 $usertrack->{$element} = $track->value;
441 switch ($element) {
f69db63e 442 case 'cmi.core.lesson_status':
443 case 'cmi.completion_status':
444 if ($track->value == 'not attempted') {
445 $track->value = 'notattempted';
9528568b 446 }
f69db63e 447 $usertrack->status = $track->value;
9528568b 448 break;
e4aa175a 449 case 'cmi.core.score.raw':
450 case 'cmi.score.raw':
0d55dd4d 451 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
9528568b 452 break;
e4aa175a 453 case 'cmi.core.session_time':
454 case 'cmi.session_time':
455 $usertrack->session_time = $track->value;
9528568b 456 break;
e4aa175a 457 case 'cmi.core.total_time':
458 case 'cmi.total_time':
459 $usertrack->total_time = $track->value;
9528568b 460 break;
461 }
e4aa175a 462 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
463 $usertrack->timemodified = $track->timemodified;
9528568b 464 }
3505e82b 465 }
9528568b 466 if (is_array($usertrack)) {
07b905ae 467 ksort($usertrack);
468 }
e4aa175a 469 return $usertrack;
470 } else {
471 return false;
472 }
473}
474
51c1c4e1 475
476/* Find the start and finsh time for a a given SCO attempt
477 *
478 * @param int $scormid SCORM Id
479 * @param int $scoid SCO Id
480 * @param int $userid User Id
481 * @param int $attemt Attempt Id
482 *
483 * @return object start and finsh time EPOC secods
484 *
485 */
486function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
4454447d 487 global $DB;
51c1c4e1 488
39790bd8 489 $timedata = new stdClass();
51c1c4e1 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");
492 if ($tracks) {
493 $tracks = array_values($tracks);
494 }
495
c86a91d5 496 if ($tracks) {
51c1c4e1 497 $timedata->start = $tracks[0]->timemodified;
498 }
499 else {
500 $timedata->start = false;
501 }
502 if ($tracks && $track = array_pop($tracks)) {
503 $timedata->finish = $track->timemodified;
504 }
505 else {
506 $timedata->finish = $timedata->start;
507 }
508 return $timedata;
509}
510
511
2b3447c3 512function scorm_get_user_data($userid) {
bf347041 513 global $DB;
2b3447c3 514/// Gets user info required to display the table of scorm results
515/// for report.php
e4aa175a 516
bf347041 517 return $DB->get_record('user', array('id'=>$userid),'firstname, lastname, picture');
2b3447c3 518}
e4aa175a 519
c0f6b608 520function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
bf347041 521 global $DB;
9528568b 522 $attemptscore = NULL;
a30b6819 523 $attemptscore->scoes = 0;
524 $attemptscore->values = 0;
525 $attemptscore->max = 0;
526 $attemptscore->sum = 0;
527 $attemptscore->lastmodify = 0;
9528568b 528
bf347041 529 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
a30b6819 530 return NULL;
e4aa175a 531 }
e4aa175a 532
9528568b 533 foreach ($scoes as $sco) {
2b3447c3 534 if ($userdata=scorm_get_tracks($sco->id, $userid,$attempt)) {
535 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
a30b6819 536 $attemptscore->scoes++;
9528568b 537 }
5c2aa157 538 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
a30b6819 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;
544 } else {
545 $attemptscore->lastmodify = 0;
546 }
9528568b 547 }
548 }
e4aa175a 549 }
03751efe 550 switch ($scorm->grademethod) {
a30b6819 551 case GRADEHIGHEST:
0d55dd4d 552 $score = (float) $attemptscore->max;
9528568b 553 break;
a30b6819 554 case GRADEAVERAGE:
555 if ($attemptscore->values > 0) {
556 $score = $attemptscore->sum/$attemptscore->values;
5c1ac70c 557 } else {
a30b6819 558 $score = 0;
9528568b 559 }
560 break;
a30b6819 561 case GRADESUM:
562 $score = $attemptscore->sum;
9528568b 563 break;
a30b6819 564 case GRADESCOES:
565 $score = $attemptscore->scoes;
7ef16bf9 566 break;
567 default:
568 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
5c1ac70c 569 }
a30b6819 570
c0f6b608 571 return $score;
a30b6819 572}
573
8c5516dc 574function scorm_grade_user($scorm, $userid) {
a30b6819 575
03751efe 576 // ensure we dont grade user beyond $scorm->maxattempt settings
7ce6eb87 577 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
578 if($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt){
579 $lastattempt = $scorm->maxattempt;
580 }
581
03751efe 582 switch ($scorm->whatgrade) {
a30b6819 583 case FIRSTATTEMPT:
8c5516dc 584 return scorm_grade_user_attempt($scorm, $userid, 1);
9528568b 585 break;
a30b6819 586 case LASTATTEMPT:
8c5516dc 587 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
a30b6819 588 break;
589 case HIGHESTATTEMPT:
a30b6819 590 $maxscore = 0;
591 $attempttime = 0;
592 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
593 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
594 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
a30b6819 595 }
8c5516dc
DM
596 return $maxscore;
597
a30b6819 598 break;
599 case AVERAGEATTEMPT:
b1ca5d31 600 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
b1ca5d31
DM
601 if (empty($attemptcount)) {
602 return 0;
603 } else {
604 $attemptcount = count($attemptcount);
605 }
a30b6819 606 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
607 $sumscore = 0;
608 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
609 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
610 $sumscore += $attemptscore;
a30b6819 611 }
612
b1ca5d31 613 return round($sumscore / $attemptcount);
a30b6819 614 break;
615 }
e4aa175a 616}
617
8e45ba45 618function scorm_count_launchable($scormid,$organization='') {
bf347041 619 global $DB;
620
621 $sqlorganization = '';
622 $params = array($scormid);
8e45ba45 623 if (!empty($organization)) {
bf347041 624 $sqlorganization = " AND organization=?";
625 $params[] = $organization;
8e45ba45 626 }
84ab3289 627 return $DB->count_records_select('scorm_scoes',"scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
e4aa175a 628}
629
2b3447c3 630function scorm_get_last_attempt($scormid, $userid) {
bf347041 631 global $DB;
632
2b3447c3 633/// Find the last attempt number for the given user id and scorm id
bf347041 634 if ($lastattempt = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid), 'max(attempt) as a')) {
2b3447c3 635 if (empty($lastattempt->a)) {
636 return '1';
637 } else {
638 return $lastattempt->a;
e4aa175a 639 }
6381fa56 640 } else {
641 return false;
e4aa175a 642 }
e4aa175a 643}
644
2276208a
DM
645function scorm_get_last_completed_attempt($scormid, $userid) {
646 global $DB;
647
648/// Find the last attempt number for the given user id and scorm id
ed98c4e9 649 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')) {
2276208a
DM
650 if (empty($lastattempt->a)) {
651 return '1';
652 } else {
653 return $lastattempt->a;
654 }
655 } else {
656 return false;
657 }
658}
659
e4aa175a 660function scorm_course_format_display($user,$course) {
f2a1963c 661 global $CFG, $DB, $PAGE, $OUTPUT;
e4aa175a 662
663 $strupdate = get_string('update');
664 $strmodule = get_string('modulename','scorm');
77bf0c29 665 $context = get_context_instance(CONTEXT_COURSE,$course->id);
e4aa175a 666
667 echo '<div class="mod-scorm">';
668 if ($scorms = get_all_instances_in_course('scorm', $course)) {
9528568b 669 // The module SCORM activity with the least id is the course
e4aa175a 670 $scorm = current($scorms);
671 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
08b56f93 672 print_error('invalidcoursemodule');
e4aa175a 673 }
674 $colspan = '';
675 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
2b3447c3 676 if (has_capability('moodle/course:manageactivities', $context)) {
830dd6e9 677 if ($PAGE->user_is_editing()) {
e4aa175a 678 // Display update icon
679 $path = $CFG->wwwroot.'/course';
680 $headertext .= '<span class="commands">'.
681 '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&amp;sesskey='.sesskey().'">'.
b5d0cafc 682 '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
e4aa175a 683 }
684 $headertext .= '</td>';
685 // Display report link
bf347041 686 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
e4aa175a 687 if ($trackedusers->c > 0) {
688 $headertext .= '<td class="reportlink">'.
4aea3cc7 689 '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
e4aa175a 690 get_string('viewallreports','scorm',$trackedusers->c).'</a>';
691 } else {
692 $headertext .= '<td class="reportlink">'.get_string('noreports','scorm');
693 }
694 $colspan = ' colspan="2"';
9528568b 695 }
d0bcf735 696 $options = (object)array('noclean'=>true);
ac3668bf 697 $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
6aff538a 698 echo $OUTPUT->box($headertext,'generalbox boxwidthwide');
e4aa175a 699 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm, '100%');
700 } else {
0d699c24 701 if (has_capability('moodle/course:update', $context)) {
e4aa175a 702 // Create a new activity
2b3447c3 703 redirect($CFG->wwwroot.'/course/mod.php?id='.$course->id.'&amp;section=0&sesskey='.sesskey().'&amp;add=scorm');
e4aa175a 704 } else {
6aff538a 705 echo $OUTPUT->notification('Could not find a scorm course here');
e4aa175a 706 }
707 }
708 echo '</div>';
709}
710
2b3447c3 711function scorm_view_display ($user, $scorm, $action, $cm, $boxwidth='') {
4eeec9ac 712 global $CFG, $DB, $PAGE, $OUTPUT;
ab3b00e1 713
9528568b 714 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
715 scorm_parse($scorm, false);
ab3b00e1 716 }
717
e4aa175a 718 $organization = optional_param('organization', '', PARAM_INT);
719
6381fa56 720 if($scorm->displaycoursestructure == 1) {
6aff538a 721 echo $OUTPUT->box_start('generalbox boxaligncenter');
e4aa175a 722?>
29a43013 723 <div class="structurehead"><?php print_string('contents','scorm') ?></div>
e4aa175a 724<?php
6381fa56 725 }
e4aa175a 726 if (empty($organization)) {
727 $organization = $scorm->launch;
728 }
2e3c31bc 729 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
84ab3289
DM
730 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
731 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
732 array($scorm->id),'id','id,title')) {
e4aa175a 733 if (count($orgs) > 1) {
edc28287 734 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
2e3c31bc 735 $select->label = get_string('organizations','scorm');
edc28287
PS
736 $select->class = 'scorm-center';
737 echo $OUTPUT->render($select);
e4aa175a 738 }
739 }
740 $orgidentifier = '';
b3659259 741 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
742 if (($sco->organization == '') && ($sco->launch == '')) {
743 $orgidentifier = $sco->identifier;
e4aa175a 744 } else {
b3659259 745 $orgidentifier = $sco->organization;
e4aa175a 746 }
747 }
28ffbff3 748
749/*
750 $orgidentifier = '';
bf347041 751 if ($org = $DB->get_record('scorm_scoes', array('id'=>$organization))) {
28ffbff3 752 if (($org->organization == '') && ($org->launch == '')) {
753 $orgidentifier = $org->identifier;
754 } else {
755 $orgidentifier = $org->organization;
756 }
757 }*/
758
2b3447c3 759 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
dbe7e6f6 760 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
761 $scorm->version = 'scorm_12';
762 }
2b3447c3 763 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
764
08868f58 765 $result = scorm_get_toc($user,$scorm,TOCFULLURL,$orgidentifier);
e4aa175a 766 $incomplete = $result->incomplete;
28ffbff3 767
6381fa56 768 // do we want the TOC to be displayed?
769 if($scorm->displaycoursestructure == 1) {
770 echo $result->toc;
6aff538a 771 echo $OUTPUT->box_end();
6381fa56 772 }
7554f671 773
6381fa56 774 // is this the first attempt ?
b1ca5d31 775 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
7554f671 776
6381fa56 777 // do not give the player launch FORM if the SCORM object is locked after the final attempt
778 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
e4aa175a 779?>
52a9a9b5 780 <div class="scorm-center">
4675994a 781 <form id="theform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
e4aa175a 782 <?php
e4aa175a 783 if ($scorm->hidebrowse == 0) {
8949f8df 784 print_string('mode','scorm');
e4aa175a 785 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse','scorm').'</label>'."\n";
76ea4fb4 786 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal','scorm')."</label>\n";
e4aa175a 787 } else {
76ea4fb4 788 echo '<input type="hidden" name="mode" value="normal" />'."\n";
e4aa175a 789 }
6381fa56 790 if ($scorm->forcenewattempt == 1) {
791 if ($incomplete === false) {
792 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
793 }
773a7468 794 } elseif (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
e4aa175a 795?>
6381fa56 796 <br />
797 <input type="checkbox" id="a" name="newattempt" />
798 <label for="a"><?php print_string('newattempt','scorm') ?></label>
e4aa175a 799<?php
800 }
801 ?>
802 <br />
4675994a 803 <input type="hidden" name="scoid"/>
3d00d6ab 804 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
e4aa175a 805 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
2b600d16 806 <input type="submit" value="<?php print_string('enter','scorm') ?>" />
e4aa175a 807 </form>
808 </div>
809<?php
6381fa56 810 }
e4aa175a 811}
6280b17a 812
489797d9 813function scorm_simple_play($scorm,$user, $context) {
bf347041 814 global $DB;
815
9316beca 816 $result = false;
817
818 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
819 scorm_parse($scorm, false);
820 }
64f93798 821 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
489797d9
DM
822 return $result;
823 }
9316beca 824
84ab3289 825 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
9316beca 826
7325b016 827 if ($scoes) {
9316beca 828 if ($scorm->skipview >= 1) {
829 $sco = current($scoes);
830 if (scorm_get_tracks($sco->id,$user->id) === false) {
831 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
832 $result = true;
833 } else if ($scorm->skipview == 2) {
834 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
835 $result = true;
836 }
837 }
838 }
839 return $result;
28ffbff3 840}
d8c9d8a1 841
842function scorm_get_count_users($scormid, $groupingid=null) {
bf347041 843 global $CFG, $DB;
9528568b 844
98da6021 845 if (!empty($groupingid)) {
d8c9d8a1 846 $sql = "SELECT COUNT(DISTINCT st.userid)
bf347041 847 FROM {scorm_scoes_track} st
848 INNER JOIN {groups_members} gm ON st.userid = gm.userid
9528568b 849 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
bf347041 850 WHERE st.scormid = ? AND gg.groupingid = ?
d8c9d8a1 851 ";
bf347041 852 $params = array($scormid, $groupingid);
d8c9d8a1 853 } else {
854 $sql = "SELECT COUNT(DISTINCT st.userid)
9528568b 855 FROM {scorm_scoes_track} st
bf347041 856 WHERE st.scormid = ?
d8c9d8a1 857 ";
bf347041 858 $params = array($scormid);
d8c9d8a1 859 }
9528568b 860
bf347041 861 return ($DB->count_records_sql($sql, $params));
d8c9d8a1 862}
863
527af457 864/**
865* Build up the JavaScript representation of an array element
866*
867* @param string $sversion SCORM API version
868* @param array $userdata User track data
869* @param string $element_name Name of array element to get values for
870* @param array $children list of sub elements of this array element that also need instantiating
871* @return None
7554f671 872*/
527af457 873function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
874 // reconstitute comments_from_learner and comments_from_lms
875 $current = '';
bf34ac0f 876 $current_subelement = '';
877 $current_sub = '';
527af457 878 $count = 0;
bf34ac0f 879 $count_sub = 0;
6b635d44
DM
880 $scormseperator = '_';
881 if ($sversion == 'scorm_13') { //scorm 1.3 elements use a . instead of an _
882 $scormseperator = '.';
883 }
527af457 884 // filter out the ones we want
885 $element_list = array();
886 foreach($userdata as $element => $value){
887 if (substr($element,0,strlen($element_name)) == $element_name) {
888 $element_list[$element] = $value;
889 }
890 }
7554f671 891
527af457 892 // sort elements in .n array order
893 uksort($element_list, "scorm_element_cmp");
7554f671 894
527af457 895 // generate JavaScript
896 foreach($element_list as $element => $value){
897 if ($sversion == 'scorm_13') {
b6293233 898 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
527af457 899 preg_match('/\.(N\d+)\./', $element, $matches);
900 } else {
b6293233 901 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
527af457 902 preg_match('/\_(\d+)\./', $element, $matches);
903 }
904 if (count($matches) > 0 && $current != $matches[1]) {
bf34ac0f 905 if ($count_sub > 0) {
6b635d44 906 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 907 }
7554f671 908 $current = $matches[1];
527af457 909 $count++;
bf34ac0f 910 $current_subelement = '';
911 $current_sub = '';
912 $count_sub = 0;
527af457 913 $end = strpos($element,$matches[1])+strlen($matches[1]);
914 $subelement = substr($element,0,$end);
915 echo ' '.$subelement." = new Object();\n";
916 // now add the children
917 foreach ($children as $child) {
918 echo ' '.$subelement.".".$child." = new Object();\n";
919 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
920 }
921 }
7554f671 922
bf34ac0f 923 // now - flesh out the second level elements if there are any
924 if ($sversion == 'scorm_13') {
b6293233 925 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
bf34ac0f 926 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
927 } else {
b6293233 928 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
bf34ac0f 929 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
930 }
7554f671 931
bf34ac0f 932 // check the sub element type
933 if (count($matches) > 0 && $current_subelement != $matches[1]) {
934 if ($count_sub > 0) {
03e9a122 935 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 936 }
937 $current_subelement = $matches[1];
938 $current_sub = '';
939 $count_sub = 0;
940 $end = strpos($element,$matches[1])+strlen($matches[1]);
941 $subelement = substr($element,0,$end);
942 echo ' '.$subelement." = new Object();\n";
943 }
7554f671 944
bf34ac0f 945 // now check the subelement subscript
946 if (count($matches) > 0 && $current_sub != $matches[2]) {
7554f671 947 $current_sub = $matches[2];
bf34ac0f 948 $count_sub++;
949 $end = strrpos($element,$matches[2])+strlen($matches[2]);
950 $subelement = substr($element,0,$end);
951 echo ' '.$subelement." = new Object();\n";
952 }
7554f671 953
527af457 954 echo ' '.$element.' = \''.$value."';\n";
955 }
bf34ac0f 956 if ($count_sub > 0) {
6b635d44 957 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 958 }
527af457 959 if ($count > 0) {
960 echo ' '.$element_name.'._count = '.$count.";\n";
961 }
962}
963
964/**
965* Build up the JavaScript representation of an array element
966*
967* @param string $a left array element
968* @param string $b right array element
969* @return comparator - 0,1,-1
7554f671 970*/
527af457 971function scorm_element_cmp($a, $b) {
bf34ac0f 972 preg_match('/.*?(\d+)\./', $a, $matches);
527af457 973 $left = intval($matches[1]);
bf34ac0f 974 preg_match('/.?(\d+)\./', $b, $matches);
527af457 975 $right = intval($matches[1]);
976 if ($left < $right) {
977 return -1; // smaller
978 } elseif ($left > $right) {
979 return 1; // bigger
980 } else {
bf34ac0f 981 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
982 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
983 $leftterm = intval($matches[2]);
984 $left = intval($matches[3]);
985 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
986 $rightterm = intval($matches[2]);
987 $right = intval($matches[3]);
988 if ($leftterm < $rightterm) {
989 return -1; // smaller
990 } elseif ($leftterm > $rightterm) {
991 return 1; // bigger
992 } else {
993 if ($left < $right) {
994 return -1; // smaller
995 } elseif ($left > $right) {
996 return 1; // bigger
997 }
998 }
999 }
1000 }
1001 // fall back for no second level matches or second level matches are equal
527af457 1002 return 0; // equal to
1003 }
1004}
6381fa56 1005
1006/**
1007* Generate the user attempt status string
1008*
1009* @param object $user Current context user
1010* @param object $scorm a moodle scrom object - mdl_scorm
1011* @return string - Attempt status string
7554f671 1012*/
6381fa56 1013function scorm_get_attempt_status($user, $scorm) {
1014 global $DB;
7554f671 1015
b1ca5d31 1016 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
6381fa56 1017 if(empty($attempts)) {
1018 $attemptcount = 0;
1019 } else {
1020 $attemptcount = count($attempts);
1021 }
7554f671 1022
6381fa56 1023 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1024 if ($scorm->maxattempt > 0) {
1025 $result .= $scorm->maxattempt . '<BR>';
1026 } else {
1027 $result .= get_string('unlimited').'<BR>';
1028 }
1029 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<BR>';
1030
1031 $gradereported = 0;
1032 $gradesum = 0;
b1ca5d31
DM
1033 if ($scorm->maxattempt == 1) {
1034 switch ($scorm->grademethod) {
1035 case GRADEHIGHEST:
1036 $grademethod = get_string('gradehighest', 'scorm');
1037 break;
1038 case GRADEAVERAGE:
1039 $grademethod = get_string('gradeaverage', 'scorm');
1040 break;
1041 case GRADESUM:
1042 $grademethod = get_string('gradesum', 'scorm');
1043 break;
1044 case GRADESCOES:
1045 $grademethod = get_string('gradescoes', 'scorm');
1046 break;
1047 }
1048 } else {
1049 switch ($scorm->whatgrade) {
1050 case HIGHESTATTEMPT:
1051 $grademethod = get_string('highestattempt', 'scorm');
1052 break;
1053 case AVERAGEATTEMPT:
1054 $grademethod = get_string('averageattempt', 'scorm');
1055 break;
1056 case FIRSTATTEMPT:
1057 $grademethod = get_string('firstattempt', 'scorm');
1058 break;
1059 case LASTATTEMPT:
1060 $grademethod = get_string('lastattempt', 'scorm');
1061 break;
1062 }
1063 }
7554f671 1064
6381fa56 1065 if(!empty($attempts)) {
b1ca5d31 1066 $i = 1;
6381fa56 1067 foreach($attempts as $attempt) {
1068 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
b1ca5d31
DM
1069 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'%<BR>';
1070 $i++;
6381fa56 1071 }
1072 }
b1ca5d31 1073 $calculatedgrade = scorm_grade_user($scorm, $user->id);
6381fa56 1074 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1075 if(empty($attempts)) {
1076 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . get_string('none') . '<BR>';
1077 } else {
b1ca5d31 1078 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . $calculatedgrade . ($scorm->grademethod == GRADESCOES ? '' : '%') .'<BR>';
6381fa56 1079 }
1080 $result .= '</p>';
1081 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1082 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts','scorm').'</font></p>';
1083 }
1084 return $result;
1085}
1086
1087/**
1088* Get SCORM attempt count
1089*
1090* @param object $user Current context user
1091* @param object $scorm a moodle scrom object - mdl_scorm
e24445c7 1092* @param bool $attempts return the list of attempts
6381fa56 1093* @return int - no. of attempts so far
7554f671 1094*/
b1ca5d31 1095function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
6381fa56 1096 global $DB;
1097 $attemptcount = 0;
1098 $element = 'cmi.core.score.raw';
78b203ca
DM
1099 if ($scorm->grademethod == GRADESCOES) {
1100 $element = 'cmi.core.lesson_status';
1101 }
6381fa56 1102 if ($scorm->version == 'scorm1_3') {
1103 $element = 'cmi.score.raw';
1104 }
b1ca5d31 1105 $attempts = $DB->get_records_select('scorm_scoes_track',"element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id),'attempt','DISTINCT attempt AS attemptnumber');
e24445c7
PH
1106 if ($attempts_only) {
1107 return $attempts;
1108 }
6381fa56 1109 if(!empty($attempts)) {
1110 $attemptcount = count($attempts);
1111 }
1112 return $attemptcount;
1113}
1881df27 1114
1115/**
1116* Figure out with this is a debug situation
1117*
1118* @param object $scorm a moodle scrom object - mdl_scorm
1119* @return boolean - debugging true/false
7554f671 1120*/
1881df27 1121function scorm_debugging($scorm) {
1122 global $CFG, $USER;
30fc6e2d 1123 $cfg_scorm = get_config('scorm');
7554f671 1124
30fc6e2d 1125 if (!$cfg_scorm->allowapidebug) {
1881df27 1126 return false;
1127 }
1128 $identifier = $USER->username.':'.$scorm->name;
30fc6e2d 1129 $test = $cfg_scorm->apidebugmask;
1881df27 1130 // check the regex is only a short list of safe characters
1131 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1132 return false;
1133 }
1134 $res = false;
1135 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1136 return $res;
1137}
7554f671 1138
1139/**
1140* Delete Scorm tracks for selected users
1141*
1142* @param array $attemptids list of attempts that need to be deleted
8716cc35 1143* @param int $scorm instance
7554f671 1144*
1145* return bool true deleted all responses, false failed deleting an attempt - stopped here
1146*/
8716cc35 1147function scorm_delete_responses($attemptids, $scorm) {
7554f671 1148 if(!is_array($attemptids) || empty($attemptids)) {
1149 return false;
1150 }
1151
1152 foreach($attemptids as $num => $attemptid) {
1153 if(empty($attemptid)) {
1154 unset($attemptids[$num]);
1155 }
1156 }
1157
1158 foreach($attemptids as $attempt) {
1159 $keys = explode(':', $attempt);
1160 if (count($keys) == 2) {
1161 $userid = clean_param($keys[0], PARAM_INT);
1162 $attemptid = clean_param($keys[1], PARAM_INT);
8716cc35 1163 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
7554f671 1164 return false;
1165 }
1166 } else {
1167 return false;
1168 }
1169 }
1170 return true;
1171}
1172
1173/**
1174* Delete Scorm tracks for selected users
1175*
1176* @param int $userid ID of User
1177* @param int $scormid ID of Scorm
1178* @param int $attemptid user attempt that need to be deleted
1179*
1180* return bool true suceeded
1181*/
8716cc35 1182function scorm_delete_attempt($userid, $scorm, $attemptid) {
7554f671 1183 global $DB;
1184
8716cc35
DM
1185 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1186 include_once('lib.php');
1187 scorm_update_grades($scorm, $userid, true);
7554f671 1188 return true;
1189}
00c1677a
DM
1190
1191/**
2700b283 1192 * Converts SCORM duration notation to human-readable format
00c1677a 1193 * The function works with both SCORM 1.2 and SCORM 2004 time formats
2700b283 1194 * @param $duration string SCORM duration
00c1677a
DM
1195 * @return string human-readable date/time
1196 */
2700b283 1197function scorm_format_duration($duration) {
00c1677a 1198 // fetch date/time strings
119d64ee 1199 $stryears = get_string('years');
00c1677a 1200 $strmonths = get_string('nummonths');
119d64ee
DM
1201 $strdays = get_string('days');
1202 $strhours = get_string('hours');
1203 $strminutes = get_string('minutes');
1204 $strseconds = get_string('seconds');
64f93798 1205
2700b283 1206 if ($duration[0] == 'P') {
00c1677a
DM
1207 // if timestamp starts with 'P' - it's a SCORM 2004 format
1208 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1209 // and outputs filled sections, discarding leading zeroes and any format literals
1210 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1211 $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#',
1212 '#([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#' );
119d64ee
DM
1213 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1214 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
00c1677a
DM
1215 } else {
1216 // else we have SCORM 1.2 format there
1217 // first convert the timestamp to some SCORM 2004-like format for conveniency
2700b283 1218 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
00c1677a
DM
1219 // then convert in the same way as SCORM 2004
1220 $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#' );
119d64ee 1221 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
00c1677a
DM
1222 //$pattern = '##';
1223 //$replace = '';
1224 }
64f93798 1225
2700b283 1226 $result = preg_replace($pattern, $replace, $duration);
00c1677a
DM
1227
1228 return $result;
1229}