Merge branch 'm20_MDL-26176_cleanup' of github.com:danmarsden/moodle
[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
7cc7cf58
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;
a30b6819 591 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
592 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
593 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
a30b6819 594 }
8c5516dc
DM
595 return $maxscore;
596
a30b6819 597 break;
598 case AVERAGEATTEMPT:
b1ca5d31 599 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
b1ca5d31
DM
600 if (empty($attemptcount)) {
601 return 0;
602 } else {
603 $attemptcount = count($attemptcount);
604 }
a30b6819 605 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
606 $sumscore = 0;
607 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
608 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
609 $sumscore += $attemptscore;
a30b6819 610 }
611
b1ca5d31 612 return round($sumscore / $attemptcount);
a30b6819 613 break;
614 }
e4aa175a 615}
616
8e45ba45 617function scorm_count_launchable($scormid,$organization='') {
bf347041 618 global $DB;
619
620 $sqlorganization = '';
621 $params = array($scormid);
8e45ba45 622 if (!empty($organization)) {
bf347041 623 $sqlorganization = " AND organization=?";
624 $params[] = $organization;
8e45ba45 625 }
84ab3289 626 return $DB->count_records_select('scorm_scoes',"scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
e4aa175a 627}
628
2b3447c3 629function scorm_get_last_attempt($scormid, $userid) {
bf347041 630 global $DB;
631
2b3447c3 632/// Find the last attempt number for the given user id and scorm id
bf347041 633 if ($lastattempt = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid), 'max(attempt) as a')) {
2b3447c3 634 if (empty($lastattempt->a)) {
635 return '1';
636 } else {
637 return $lastattempt->a;
e4aa175a 638 }
6381fa56 639 } else {
640 return false;
e4aa175a 641 }
e4aa175a 642}
643
2276208a
DM
644function scorm_get_last_completed_attempt($scormid, $userid) {
645 global $DB;
646
647/// Find the last attempt number for the given user id and scorm id
ed98c4e9 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')) {
2276208a
DM
649 if (empty($lastattempt->a)) {
650 return '1';
651 } else {
652 return $lastattempt->a;
653 }
654 } else {
655 return false;
656 }
657}
658
e4aa175a 659function scorm_course_format_display($user,$course) {
f2a1963c 660 global $CFG, $DB, $PAGE, $OUTPUT;
e4aa175a 661
662 $strupdate = get_string('update');
77bf0c29 663 $context = get_context_instance(CONTEXT_COURSE,$course->id);
e4aa175a 664
665 echo '<div class="mod-scorm">';
666 if ($scorms = get_all_instances_in_course('scorm', $course)) {
9528568b 667 // The module SCORM activity with the least id is the course
e4aa175a 668 $scorm = current($scorms);
669 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
08b56f93 670 print_error('invalidcoursemodule');
e4aa175a 671 }
672 $colspan = '';
673 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
2b3447c3 674 if (has_capability('moodle/course:manageactivities', $context)) {
830dd6e9 675 if ($PAGE->user_is_editing()) {
e4aa175a 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.'&amp;sesskey='.sesskey().'">'.
b5d0cafc 680 '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
e4aa175a 681 }
682 $headertext .= '</td>';
683 // Display report link
bf347041 684 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
e4aa175a 685 if ($trackedusers->c > 0) {
686 $headertext .= '<td class="reportlink">'.
4aea3cc7 687 '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
e4aa175a 688 get_string('viewallreports','scorm',$trackedusers->c).'</a>';
689 } else {
690 $headertext .= '<td class="reportlink">'.get_string('noreports','scorm');
691 }
692 $colspan = ' colspan="2"';
9528568b 693 }
ac3668bf 694 $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
6aff538a 695 echo $OUTPUT->box($headertext,'generalbox boxwidthwide');
39340358 696 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm);
e4aa175a 697 } else {
0d699c24 698 if (has_capability('moodle/course:update', $context)) {
e4aa175a 699 // Create a new activity
2b3447c3 700 redirect($CFG->wwwroot.'/course/mod.php?id='.$course->id.'&amp;section=0&sesskey='.sesskey().'&amp;add=scorm');
e4aa175a 701 } else {
6aff538a 702 echo $OUTPUT->notification('Could not find a scorm course here');
e4aa175a 703 }
704 }
705 echo '</div>';
706}
707
39340358 708function scorm_view_display ($user, $scorm, $action, $cm) {
4eeec9ac 709 global $CFG, $DB, $PAGE, $OUTPUT;
ab3b00e1 710
9528568b 711 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
712 scorm_parse($scorm, false);
ab3b00e1 713 }
714
e4aa175a 715 $organization = optional_param('organization', '', PARAM_INT);
716
6381fa56 717 if($scorm->displaycoursestructure == 1) {
6aff538a 718 echo $OUTPUT->box_start('generalbox boxaligncenter');
e4aa175a 719?>
29a43013 720 <div class="structurehead"><?php print_string('contents','scorm') ?></div>
e4aa175a 721<?php
6381fa56 722 }
e4aa175a 723 if (empty($organization)) {
724 $organization = $scorm->launch;
725 }
2e3c31bc 726 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
84ab3289
DM
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')) {
e4aa175a 730 if (count($orgs) > 1) {
edc28287 731 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
2e3c31bc 732 $select->label = get_string('organizations','scorm');
edc28287
PS
733 $select->class = 'scorm-center';
734 echo $OUTPUT->render($select);
e4aa175a 735 }
736 }
737 $orgidentifier = '';
b3659259 738 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
739 if (($sco->organization == '') && ($sco->launch == '')) {
740 $orgidentifier = $sco->identifier;
e4aa175a 741 } else {
b3659259 742 $orgidentifier = $sco->organization;
e4aa175a 743 }
744 }
28ffbff3 745
2b3447c3 746 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
dbe7e6f6 747 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
748 $scorm->version = 'scorm_12';
749 }
2b3447c3 750 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
751
7cc7cf58 752 $result = scorm_get_toc($user,$scorm,TOCFULLURL,$orgidentifier);
e4aa175a 753 $incomplete = $result->incomplete;
28ffbff3 754
6381fa56 755 // do we want the TOC to be displayed?
756 if($scorm->displaycoursestructure == 1) {
757 echo $result->toc;
6aff538a 758 echo $OUTPUT->box_end();
6381fa56 759 }
7554f671 760
6381fa56 761 // is this the first attempt ?
b1ca5d31 762 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
7554f671 763
6381fa56 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) {
e4aa175a 766?>
52a9a9b5 767 <div class="scorm-center">
4675994a 768 <form id="theform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
e4aa175a 769 <?php
e4aa175a 770 if ($scorm->hidebrowse == 0) {
8949f8df 771 print_string('mode','scorm');
e4aa175a 772 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse','scorm').'</label>'."\n";
76ea4fb4 773 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal','scorm')."</label>\n";
e4aa175a 774 } else {
76ea4fb4 775 echo '<input type="hidden" name="mode" value="normal" />'."\n";
e4aa175a 776 }
6381fa56 777 if ($scorm->forcenewattempt == 1) {
778 if ($incomplete === false) {
779 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
780 }
773a7468 781 } elseif (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
e4aa175a 782?>
6381fa56 783 <br />
784 <input type="checkbox" id="a" name="newattempt" />
785 <label for="a"><?php print_string('newattempt','scorm') ?></label>
e4aa175a 786<?php
787 }
788 ?>
789 <br />
4675994a 790 <input type="hidden" name="scoid"/>
3d00d6ab 791 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
e4aa175a 792 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
2b600d16 793 <input type="submit" value="<?php print_string('enter','scorm') ?>" />
e4aa175a 794 </form>
795 </div>
796<?php
6381fa56 797 }
e4aa175a 798}
6280b17a 799
489797d9 800function scorm_simple_play($scorm,$user, $context) {
bf347041 801 global $DB;
802
9316beca 803 $result = false;
804
805 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
806 scorm_parse($scorm, false);
807 }
64f93798 808 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
809 return $result;
810 }
9316beca 811
84ab3289 812 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
9316beca 813
7325b016 814 if ($scoes) {
9316beca 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);
819 $result = true;
820 } else if ($scorm->skipview == 2) {
821 header('Location: player.php?a='.$scorm->id.'&scoid='.$sco->id);
822 $result = true;
823 }
824 }
825 }
826 return $result;
28ffbff3 827}
d8c9d8a1 828
829function scorm_get_count_users($scormid, $groupingid=null) {
bf347041 830 global $CFG, $DB;
9528568b 831
98da6021 832 if (!empty($groupingid)) {
d8c9d8a1 833 $sql = "SELECT COUNT(DISTINCT st.userid)
bf347041 834 FROM {scorm_scoes_track} st
835 INNER JOIN {groups_members} gm ON st.userid = gm.userid
9528568b 836 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
bf347041 837 WHERE st.scormid = ? AND gg.groupingid = ?
d8c9d8a1 838 ";
bf347041 839 $params = array($scormid, $groupingid);
d8c9d8a1 840 } else {
841 $sql = "SELECT COUNT(DISTINCT st.userid)
9528568b 842 FROM {scorm_scoes_track} st
bf347041 843 WHERE st.scormid = ?
d8c9d8a1 844 ";
bf347041 845 $params = array($scormid);
d8c9d8a1 846 }
9528568b 847
bf347041 848 return ($DB->count_records_sql($sql, $params));
d8c9d8a1 849}
850
527af457 851/**
852* Build up the JavaScript representation of an array element
853*
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
858* @return None
7554f671 859*/
527af457 860function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
861 // reconstitute comments_from_learner and comments_from_lms
862 $current = '';
bf34ac0f 863 $current_subelement = '';
864 $current_sub = '';
527af457 865 $count = 0;
bf34ac0f 866 $count_sub = 0;
6b635d44
DM
867 $scormseperator = '_';
868 if ($sversion == 'scorm_13') { //scorm 1.3 elements use a . instead of an _
869 $scormseperator = '.';
870 }
527af457 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;
876 }
877 }
7554f671 878
527af457 879 // sort elements in .n array order
880 uksort($element_list, "scorm_element_cmp");
7554f671 881
527af457 882 // generate JavaScript
883 foreach($element_list as $element => $value){
884 if ($sversion == 'scorm_13') {
b6293233 885 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
527af457 886 preg_match('/\.(N\d+)\./', $element, $matches);
887 } else {
b6293233 888 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
527af457 889 preg_match('/\_(\d+)\./', $element, $matches);
890 }
891 if (count($matches) > 0 && $current != $matches[1]) {
bf34ac0f 892 if ($count_sub > 0) {
6b635d44 893 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 894 }
7554f671 895 $current = $matches[1];
527af457 896 $count++;
bf34ac0f 897 $current_subelement = '';
898 $current_sub = '';
899 $count_sub = 0;
527af457 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";
907 }
908 }
7554f671 909
bf34ac0f 910 // now - flesh out the second level elements if there are any
911 if ($sversion == 'scorm_13') {
b6293233 912 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
bf34ac0f 913 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
914 } else {
b6293233 915 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
bf34ac0f 916 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
917 }
7554f671 918
bf34ac0f 919 // check the sub element type
920 if (count($matches) > 0 && $current_subelement != $matches[1]) {
921 if ($count_sub > 0) {
03e9a122 922 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 923 }
924 $current_subelement = $matches[1];
925 $current_sub = '';
926 $count_sub = 0;
927 $end = strpos($element,$matches[1])+strlen($matches[1]);
928 $subelement = substr($element,0,$end);
929 echo ' '.$subelement." = new Object();\n";
930 }
7554f671 931
bf34ac0f 932 // now check the subelement subscript
933 if (count($matches) > 0 && $current_sub != $matches[2]) {
7554f671 934 $current_sub = $matches[2];
bf34ac0f 935 $count_sub++;
936 $end = strrpos($element,$matches[2])+strlen($matches[2]);
937 $subelement = substr($element,0,$end);
938 echo ' '.$subelement." = new Object();\n";
939 }
7554f671 940
527af457 941 echo ' '.$element.' = \''.$value."';\n";
942 }
bf34ac0f 943 if ($count_sub > 0) {
6b635d44 944 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 945 }
527af457 946 if ($count > 0) {
947 echo ' '.$element_name.'._count = '.$count.";\n";
948 }
949}
950
951/**
952* Build up the JavaScript representation of an array element
953*
954* @param string $a left array element
955* @param string $b right array element
956* @return comparator - 0,1,-1
7554f671 957*/
527af457 958function scorm_element_cmp($a, $b) {
bf34ac0f 959 preg_match('/.*?(\d+)\./', $a, $matches);
527af457 960 $left = intval($matches[1]);
bf34ac0f 961 preg_match('/.?(\d+)\./', $b, $matches);
527af457 962 $right = intval($matches[1]);
963 if ($left < $right) {
964 return -1; // smaller
965 } elseif ($left > $right) {
966 return 1; // bigger
967 } else {
bf34ac0f 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) {
978 return 1; // bigger
979 } else {
980 if ($left < $right) {
981 return -1; // smaller
982 } elseif ($left > $right) {
983 return 1; // bigger
984 }
985 }
986 }
987 }
988 // fall back for no second level matches or second level matches are equal
527af457 989 return 0; // equal to
990 }
991}
6381fa56 992
993/**
994* Generate the user attempt status string
995*
996* @param object $user Current context user
997* @param object $scorm a moodle scrom object - mdl_scorm
998* @return string - Attempt status string
7554f671 999*/
6381fa56 1000function scorm_get_attempt_status($user, $scorm) {
1001 global $DB;
7554f671 1002
b1ca5d31 1003 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
6381fa56 1004 if(empty($attempts)) {
1005 $attemptcount = 0;
1006 } else {
1007 $attemptcount = count($attempts);
1008 }
7554f671 1009
6381fa56 1010 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1011 if ($scorm->maxattempt > 0) {
1012 $result .= $scorm->maxattempt . '<BR>';
1013 } else {
1014 $result .= get_string('unlimited').'<BR>';
1015 }
1016 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<BR>';
1017
b1ca5d31
DM
1018 if ($scorm->maxattempt == 1) {
1019 switch ($scorm->grademethod) {
1020 case GRADEHIGHEST:
1021 $grademethod = get_string('gradehighest', 'scorm');
1022 break;
1023 case GRADEAVERAGE:
1024 $grademethod = get_string('gradeaverage', 'scorm');
1025 break;
1026 case GRADESUM:
1027 $grademethod = get_string('gradesum', 'scorm');
1028 break;
1029 case GRADESCOES:
1030 $grademethod = get_string('gradescoes', 'scorm');
1031 break;
1032 }
1033 } else {
1034 switch ($scorm->whatgrade) {
1035 case HIGHESTATTEMPT:
1036 $grademethod = get_string('highestattempt', 'scorm');
1037 break;
1038 case AVERAGEATTEMPT:
1039 $grademethod = get_string('averageattempt', 'scorm');
1040 break;
1041 case FIRSTATTEMPT:
1042 $grademethod = get_string('firstattempt', 'scorm');
1043 break;
1044 case LASTATTEMPT:
1045 $grademethod = get_string('lastattempt', 'scorm');
1046 break;
1047 }
1048 }
7554f671 1049
6381fa56 1050 if(!empty($attempts)) {
b1ca5d31 1051 $i = 1;
6381fa56 1052 foreach($attempts as $attempt) {
1053 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
b1ca5d31
DM
1054 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'%<BR>';
1055 $i++;
6381fa56 1056 }
1057 }
b1ca5d31 1058 $calculatedgrade = scorm_grade_user($scorm, $user->id);
6381fa56 1059 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1060 if(empty($attempts)) {
1061 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . get_string('none') . '<BR>';
1062 } else {
b1ca5d31 1063 $result .= '<BR>' . get_string('gradereported','scorm') . ': ' . $calculatedgrade . ($scorm->grademethod == GRADESCOES ? '' : '%') .'<BR>';
6381fa56 1064 }
1065 $result .= '</p>';
1066 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1067 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts','scorm').'</font></p>';
1068 }
1069 return $result;
1070}
1071
1072/**
1073* Get SCORM attempt count
1074*
1075* @param object $user Current context user
1076* @param object $scorm a moodle scrom object - mdl_scorm
e24445c7 1077* @param bool $attempts return the list of attempts
6381fa56 1078* @return int - no. of attempts so far
7554f671 1079*/
b1ca5d31 1080function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
6381fa56 1081 global $DB;
1082 $attemptcount = 0;
1083 $element = 'cmi.core.score.raw';
78b203ca
DM
1084 if ($scorm->grademethod == GRADESCOES) {
1085 $element = 'cmi.core.lesson_status';
1086 }
6381fa56 1087 if ($scorm->version == 'scorm1_3') {
1088 $element = 'cmi.score.raw';
1089 }
b1ca5d31 1090 $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
1091 if ($attempts_only) {
1092 return $attempts;
1093 }
6381fa56 1094 if(!empty($attempts)) {
1095 $attemptcount = count($attempts);
1096 }
1097 return $attemptcount;
1098}
1881df27 1099
1100/**
1101* Figure out with this is a debug situation
1102*
1103* @param object $scorm a moodle scrom object - mdl_scorm
1104* @return boolean - debugging true/false
7554f671 1105*/
1881df27 1106function scorm_debugging($scorm) {
1107 global $CFG, $USER;
30fc6e2d 1108 $cfg_scorm = get_config('scorm');
7554f671 1109
30fc6e2d 1110 if (!$cfg_scorm->allowapidebug) {
1881df27 1111 return false;
1112 }
1113 $identifier = $USER->username.':'.$scorm->name;
30fc6e2d 1114 $test = $cfg_scorm->apidebugmask;
1881df27 1115 // check the regex is only a short list of safe characters
1116 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1117 return false;
1118 }
1119 $res = false;
1120 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1121 return $res;
1122}
7554f671 1123
1124/**
1125* Delete Scorm tracks for selected users
1126*
1127* @param array $attemptids list of attempts that need to be deleted
8716cc35 1128* @param int $scorm instance
7554f671 1129*
1130* return bool true deleted all responses, false failed deleting an attempt - stopped here
1131*/
8716cc35 1132function scorm_delete_responses($attemptids, $scorm) {
7554f671 1133 if(!is_array($attemptids) || empty($attemptids)) {
1134 return false;
1135 }
1136
1137 foreach($attemptids as $num => $attemptid) {
1138 if(empty($attemptid)) {
1139 unset($attemptids[$num]);
1140 }
1141 }
1142
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);
8716cc35 1148 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
7554f671 1149 return false;
1150 }
1151 } else {
1152 return false;
1153 }
1154 }
1155 return true;
1156}
1157
1158/**
1159* Delete Scorm tracks for selected users
1160*
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
1164*
1165* return bool true suceeded
1166*/
8716cc35 1167function scorm_delete_attempt($userid, $scorm, $attemptid) {
7554f671 1168 global $DB;
1169
8716cc35
DM
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);
7554f671 1173 return true;
1174}
00c1677a
DM
1175
1176/**
2700b283 1177 * Converts SCORM duration notation to human-readable format
00c1677a 1178 * The function works with both SCORM 1.2 and SCORM 2004 time formats
2700b283 1179 * @param $duration string SCORM duration
00c1677a
DM
1180 * @return string human-readable date/time
1181 */
2700b283 1182function scorm_format_duration($duration) {
00c1677a 1183 // fetch date/time strings
119d64ee 1184 $stryears = get_string('years');
00c1677a 1185 $strmonths = get_string('nummonths');
119d64ee
DM
1186 $strdays = get_string('days');
1187 $strhours = get_string('hours');
1188 $strminutes = get_string('minutes');
1189 $strseconds = get_string('seconds');
64f93798 1190
2700b283 1191 if ($duration[0] == 'P') {
00c1677a
DM
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#' );
119d64ee
DM
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, '');
00c1677a
DM
1200 } else {
1201 // else we have SCORM 1.2 format there
1202 // first convert the timestamp to some SCORM 2004-like format for conveniency
2700b283 1203 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
00c1677a
DM
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#' );
119d64ee 1206 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
00c1677a 1207 }
64f93798 1208
2700b283 1209 $result = preg_replace($pattern, $replace, $duration);
00c1677a
DM
1210
1211 return $result;
1212}