MDL-28649 SCORM fix force new attempt when skipview is used
[moodle.git] / mod / scorm / locallib.php
CommitLineData
e5dd8e3b 1<?php
f7b5c6aa
DM
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
f69db63e 16
9528568b 17require_once("$CFG->dirroot/mod/scorm/lib.php");
64f93798 18require_once("$CFG->libdir/filelib.php");
9528568b 19
a30b6819 20/// Constants and settings for module scorm
a679d64d 21define('UPDATE_NEVER', '0');
22define('UPDATE_ONCHANGE', '1');
23define('UPDATE_EVERYDAY', '2');
24define('UPDATE_EVERYTIME', '3');
25
b3659259 26define('SCO_ALL', 0);
27define('SCO_DATA', 1);
28define('SCO_ONLY', 2);
a30b6819 29
30define('GRADESCOES', '0');
31define('GRADEHIGHEST', '1');
32define('GRADEAVERAGE', '2');
33define('GRADESUM', '3');
a30b6819 34
35define('HIGHESTATTEMPT', '0');
36define('AVERAGEATTEMPT', '1');
37define('FIRSTATTEMPT', '2');
38define('LASTATTEMPT', '3');
a30b6819 39
7cc7cf58
DM
40define('TOCJSLINK', 1);
41define('TOCFULLURL', 2);
42
9528568b 43/// Local Library of functions for module scorm
a30b6819 44
64f93798
PS
45/**
46 * @package mod-scorm
47 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 */
50class scorm_package_file_info extends file_info_stored {
51 public function get_parent() {
52 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
53 return $this->browser->get_file_info($this->context);
54 }
55 return parent::get_parent();
56 }
57 public function get_visible_name() {
58 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
59 return $this->topvisiblename;
60 }
61 return parent::get_visible_name();
62 }
63}
64
30fc6e2d 65/**
66 * Returns an array of the popup options for SCORM and each options default value
7554f671 67 *
30fc6e2d 68 * @return array an array of popup options as the key and their defaults as the value
69 */
ca4eda13 70function scorm_get_popup_options_array() {
30fc6e2d 71 global $CFG;
72 $cfg_scorm = get_config('scorm');
7554f671 73
74 return array('resizable'=> isset($cfg_scorm->resizable) ? $cfg_scorm->resizable : 0,
75 'scrollbars'=> isset($cfg_scorm->scrollbars) ? $cfg_scorm->scrollbars : 0,
76 'directories'=> isset($cfg_scorm->directories) ? $cfg_scorm->directories : 0,
1adc77e6 77 'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
7554f671 78 'menubar'=> isset($cfg_scorm->menubar) ? $cfg_scorm->menubar : 0,
79 'toolbar'=> isset($cfg_scorm->toolbar) ? $cfg_scorm->toolbar : 0,
80 'status'=> isset($cfg_scorm->status) ? $cfg_scorm->status : 0);
30fc6e2d 81}
82
83/**
84 * Returns an array of the array of what grade options
7554f671 85 *
30fc6e2d 86 * @return array an array of what grade options
87 */
ca4eda13 88function scorm_get_grade_method_array() {
30fc6e2d 89 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
90 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
91 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
7554f671 92 GRADESUM => get_string('gradesum', 'scorm'));
30fc6e2d 93}
94
95/**
96 * Returns an array of the array of what grade options
7554f671 97 *
30fc6e2d 98 * @return array an array of what grade options
99 */
ca4eda13 100function scorm_get_what_grade_array() {
30fc6e2d 101 return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
102 AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
103 FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
104 LASTATTEMPT => get_string('lastattempt', 'scorm'));
105}
106
107/**
108 * Returns an array of the array of skip view options
7554f671 109 *
30fc6e2d 110 * @return array an array of skip view options
111 */
ca4eda13
DM
112function scorm_get_skip_view_array() {
113 return array(0 => get_string('never'),
114 1 => get_string('firstaccess', 'scorm'),
30fc6e2d 115 2 => get_string('always'));
116}
117
118/**
119 * Returns an array of the array of hide table of contents options
7554f671 120 *
30fc6e2d 121 * @return array an array of hide table of contents options
122 */
ca4eda13 123function scorm_get_hidetoc_array() {
5f65d37c 124 return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
99da7a95
DM
125 SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
126 SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
127 SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
30fc6e2d 128}
129
130/**
131 * Returns an array of the array of update frequency options
7554f671 132 *
30fc6e2d 133 * @return array an array of update frequency options
134 */
ca4eda13 135function scorm_get_updatefreq_array() {
30fc6e2d 136 return array(0 => get_string('never'),
ca4eda13
DM
137 1 => get_string('onchanges', 'scorm'),
138 2 => get_string('everyday', 'scorm'),
139 3 => get_string('everytime', 'scorm'));
30fc6e2d 140}
141
142/**
143 * Returns an array of the array of popup display options
7554f671 144 *
30fc6e2d 145 * @return array an array of popup display options
146 */
ca4eda13 147function scorm_get_popup_display_array() {
d67eb434 148 return array(0 => get_string('currentwindow', 'scorm'),
30fc6e2d 149 1 => get_string('popup', 'scorm'));
150}
151
152/**
153 * Returns an array of the array of attempt options
7554f671 154 *
30fc6e2d 155 * @return array an array of attempt options
156 */
ca4eda13
DM
157function scorm_get_attempts_array() {
158 $attempts = array(0 => get_string('nolimit', 'scorm'),
159 1 => get_string('attempt1', 'scorm'));
7554f671 160
30fc6e2d 161 for ($i=2; $i<=6; $i++) {
ca4eda13 162 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
30fc6e2d 163 }
7554f671 164
30fc6e2d 165 return $attempts;
166}
9528568b 167/**
168 * Extracts scrom package, sets up all variables.
169 * Called whenever scorm changes
170 * @param object $scorm instance - fields are updated and changes saved into database
171 * @param bool $full force full update if true
172 * @return void
173 */
174function scorm_parse($scorm, $full) {
175 global $CFG, $DB;
30fc6e2d 176 $cfg_scorm = get_config('scorm');
8aee93f1 177
9528568b 178 if (!isset($scorm->cmid)) {
179 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
180 $scorm->cmid = $cm->id;
181 }
182 $context = get_context_instance(CONTEXT_MODULE, $scorm->cmid);
183 $newhash = $scorm->sha1hash;
a30b6819 184
9528568b 185 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
a30b6819 186
9528568b 187 $fs = get_file_storage();
188 $packagefile = false;
f69db63e 189
9528568b 190 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
64f93798 191 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
9528568b 192 $newhash = $packagefile->get_contenthash();
193 } else {
194 $newhash = null;
195 }
196 } else {
30fc6e2d 197 if (!$cfg_scorm->allowtypelocalsync) {
9528568b 198 // sorry - localsync disabled
199 return;
200 }
201 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
64f93798
PS
202 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
203 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
60b5a2fe 204 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
9528568b 205 $newhash = sha1($scorm->reference);
5c1ac70c 206 } else {
9528568b 207 $newhash = null;
5c1ac70c 208 }
f69db63e 209 }
210 }
f69db63e 211
9528568b 212 if ($packagefile) {
213 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
214 if (strpos($scorm->version, 'SCORM') !== false) {
64f93798 215 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 216 // no need to update
217 return;
e4aa175a 218 }
9528568b 219 } else if (strpos($scorm->version, 'AICC') !== false) {
220 // TODO: add more sanity checks - something really exists in scorm_content area
221 return;
222 }
223 }
224
225 // now extract files
64f93798 226 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
9528568b 227
228 $packer = get_file_packer('application/zip');
64f93798 229 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
9528568b 230
231 } else if (!$full) {
232 return;
233 }
234
64f93798 235 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 236 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
237 // SCORM
238 if (!scorm_parse_scorm($scorm, $manifest)) {
239 $scorm->version = 'ERROR';
240 }
241 } else {
242 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
243 // AICC
244 if (!scorm_parse_aicc($scorm)) {
245 $scorm->version = 'ERROR';
246 }
247 }
248
30fc6e2d 249 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
9528568b 250 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
251 return;
252 }
253 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
254 // SCORM only, AICC can not be external
255 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
256 $scorm->version = 'ERROR';
257 }
258 $newhash = sha1($scorm->reference);
259
30fc6e2d 260 } else if ($scorm->scormtype === SCORM_TYPE_IMSREPOSITORY and !empty($CFG->repositoryactivate) and $cfg_scorm->allowtypeimsrepository) {
9528568b 261 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
262 return;
263 }
264 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
ca4eda13 265 if (!scorm_parse_scorm($scorm, $CFG->repository.substr($scorm->reference, 1).'/imsmanifest.xml')) {
9528568b 266 $scorm->version = 'ERROR';
267 }
268 $newhash = sha1($scorm->reference);
269
e4aa175a 270 } else {
9528568b 271 // sorry, disabled type
272 return;
e4aa175a 273 }
9528568b 274
275 $scorm->revision++;
276 $scorm->sha1hash = $newhash;
277 $DB->update_record('scorm', $scorm);
e4aa175a 278}
279
9528568b 280
2b3447c3 281function scorm_array_search($item, $needle, $haystacks, $strict=false) {
282 if (!empty($haystacks)) {
283 foreach ($haystacks as $key => $element) {
284 if ($strict) {
285 if ($element->{$item} === $needle) {
286 return $key;
287 }
288 } else {
289 if ($element->{$item} == $needle) {
290 return $key;
e4aa175a 291 }
292 }
e4aa175a 293 }
294 }
2b3447c3 295 return false;
e4aa175a 296}
297
2b3447c3 298function scorm_repeater($what, $times) {
299 if ($times <= 0) {
300 return null;
301 }
302 $return = '';
ca4eda13 303 for ($i=0; $i<$times; $i++) {
2b3447c3 304 $return .= $what;
305 }
306 return $return;
307}
e4aa175a 308
2b3447c3 309function scorm_external_link($link) {
ca4eda13 310 // check if a link is external
2b3447c3 311 $result = false;
312 $link = strtolower($link);
ca4eda13 313 if (substr($link, 0, 7) == 'http://') {
2b3447c3 314 $result = true;
ca4eda13 315 } else if (substr($link, 0, 8) == 'https://') {
2b3447c3 316 $result = true;
ca4eda13 317 } else if (substr($link, 0, 4) == 'www.') {
2b3447c3 318 $result = true;
319 }
320 return $result;
e4aa175a 321}
322
b3659259 323/**
ca4eda13
DM
324 * Returns an object containing all datas relative to the given sco ID
325 *
326 * @param integer $id The sco ID
327 * @return mixed (false if sco id does not exists)
328 */
329function scorm_get_sco($id, $what=SCO_ALL) {
bf347041 330 global $DB;
331
332 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
b3659259 333 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
bf347041 334 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
b3659259 335 foreach ($scodatas as $scodata) {
c31f631b 336 $sco->{$scodata->name} = $scodata->value;
b3659259 337 }
bf347041 338 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
9528568b 339 $sco->parameters = '';
b3659259 340 }
341 return $sco;
342 } else {
343 return false;
344 }
345}
82605bea 346
347/**
ca4eda13
DM
348 * Returns an object (array) containing all the scoes data related to the given sco ID
349 *
350 * @param integer $id The sco ID
351 * @param integer $organisation an organisation ID - defaults to false if not required
352 * @return mixed (false if there are no scoes or an array)
353 */
354function scorm_get_scoes($id, $organisation=false) {
b44c704f 355 global $DB;
356
82605bea 357 $organizationsql = '';
b44c704f 358 $queryarray = array('scorm'=>$id);
82605bea 359 if (!empty($organisation)) {
b44c704f 360 $queryarray['organization'] = $organisation;
82605bea 361 }
b44c704f 362 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
82605bea 363 // drop keys so that it is a simple array as expected
364 $scoes = array_values($scoes);
365 foreach ($scoes as $sco) {
ca4eda13 366 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
82605bea 367 foreach ($scodatas as $scodata) {
2fd0e9fe 368 $sco->{$scodata->name} = $scodata->value;
82605bea 369 }
370 }
371 }
372 return $scoes;
373 } else {
374 return false;
375 }
376}
377
ca4eda13 378function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
86996ffe 379 global $DB, $CFG;
bf347041 380
e4aa175a 381 $id = null;
6381fa56 382
383 if ($forcecompleted) {
384 //TODO - this could be broadened to encompass SCORM 2004 in future
385 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
ca4eda13 386 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))) {
6381fa56 387 $value = 'completed';
388 }
389 }
390 if ($element == 'cmi.core.score.raw') {
ca4eda13 391 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))) {
6381fa56 392 if ($tracktest->value == "incomplete") {
393 $tracktest->value = "completed";
ca4eda13 394 $DB->update_record('scorm_scoes_track', $tracktest);
6381fa56 395 }
396 }
397 }
398 }
399
ca4eda13 400 if ($track = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid, 'scoid'=>$scoid, 'attempt'=>$attempt, 'element'=>$element))) {
d1818fdc 401 if ($element != 'x.start.time' ) { //don't update x.start.time - keep the original value.
454f5aee 402 $track->value = $value;
d1818fdc 403 $track->timemodified = time();
ca4eda13 404 $DB->update_record('scorm_scoes_track', $track);
dd88de0e 405 $id = $track->id;
d1818fdc 406 }
e4aa175a 407 } else {
408 $track->userid = $userid;
409 $track->scormid = $scormid;
410 $track->scoid = $scoid;
411 $track->attempt = $attempt;
412 $track->element = $element;
454f5aee 413 $track->value = $value;
e4aa175a 414 $track->timemodified = time();
ca4eda13 415 $id = $DB->insert_record('scorm_scoes_track', $track);
e4aa175a 416 }
9528568b 417
9528568b 418 if (strstr($element, '.score.raw') ||
a0b36684 419 (($element == 'cmi.core.lesson_status' || $element == 'cmi.completion_status') && ($track->value == 'completed' || $track->value == 'passed'))) {
420 $scorm = $DB->get_record('scorm', array('id' => $scormid));
86996ffe 421 include_once($CFG->dirroot.'/mod/scorm/lib.php');
7f7946fd 422 scorm_update_grades($scorm, $userid);
d23121ab 423 }
9528568b 424
e4aa175a 425 return $id;
426}
427
ca4eda13
DM
428function scorm_get_tracks($scoid, $userid, $attempt='') {
429 /// Gets all tracks of specified sco and user
bf347041 430 global $CFG, $DB;
e4aa175a 431
432 if (empty($attempt)) {
ca4eda13
DM
433 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
434 $attempt = scorm_get_last_attempt($scormid, $userid);
e4aa175a 435 } else {
436 $attempt = 1;
437 }
438 }
ca4eda13 439 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid, 'attempt'=>$attempt), 'element ASC')) {
39790bd8 440 $usertrack = new stdClass();
e4aa175a 441 $usertrack->userid = $userid;
9528568b 442 $usertrack->scoid = $scoid;
a30b6819 443 // Defined in order to unify scorm1.2 and scorm2004
e4aa175a 444 $usertrack->score_raw = '';
e4aa175a 445 $usertrack->status = '';
e4aa175a 446 $usertrack->total_time = '00:00:00';
447 $usertrack->session_time = '00:00:00';
448 $usertrack->timemodified = 0;
449 foreach ($tracks as $track) {
450 $element = $track->element;
451 $usertrack->{$element} = $track->value;
452 switch ($element) {
f69db63e 453 case 'cmi.core.lesson_status':
454 case 'cmi.completion_status':
455 if ($track->value == 'not attempted') {
456 $track->value = 'notattempted';
9528568b 457 }
f69db63e 458 $usertrack->status = $track->value;
9528568b 459 break;
e4aa175a 460 case 'cmi.core.score.raw':
461 case 'cmi.score.raw':
0d55dd4d 462 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
9528568b 463 break;
e4aa175a 464 case 'cmi.core.session_time':
465 case 'cmi.session_time':
466 $usertrack->session_time = $track->value;
9528568b 467 break;
e4aa175a 468 case 'cmi.core.total_time':
469 case 'cmi.total_time':
470 $usertrack->total_time = $track->value;
9528568b 471 break;
472 }
e4aa175a 473 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
474 $usertrack->timemodified = $track->timemodified;
9528568b 475 }
3505e82b 476 }
9528568b 477 if (is_array($usertrack)) {
07b905ae 478 ksort($usertrack);
479 }
e4aa175a 480 return $usertrack;
481 } else {
482 return false;
483 }
484}
485
51c1c4e1 486
487/* Find the start and finsh time for a a given SCO attempt
488 *
489 * @param int $scormid SCORM Id
490 * @param int $scoid SCO Id
491 * @param int $userid User Id
492 * @param int $attemt Attempt Id
493 *
494 * @return object start and finsh time EPOC secods
495 *
496 */
497function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
4454447d 498 global $DB;
51c1c4e1 499
39790bd8 500 $timedata = new stdClass();
51c1c4e1 501 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
ca4eda13 502 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
51c1c4e1 503 if ($tracks) {
504 $tracks = array_values($tracks);
505 }
506
c86a91d5 507 if ($tracks) {
51c1c4e1 508 $timedata->start = $tracks[0]->timemodified;
ca4eda13 509 } else {
51c1c4e1 510 $timedata->start = false;
511 }
512 if ($tracks && $track = array_pop($tracks)) {
513 $timedata->finish = $track->timemodified;
ca4eda13 514 } else {
51c1c4e1 515 $timedata->finish = $timedata->start;
516 }
517 return $timedata;
518}
519
520
2b3447c3 521function scorm_get_user_data($userid) {
bf347041 522 global $DB;
ca4eda13
DM
523 /// Gets user info required to display the table of scorm results
524 /// for report.php
e4aa175a 525
629f5021 526 return $DB->get_record('user', array('id'=>$userid), user_picture::fields());
2b3447c3 527}
e4aa175a 528
c0f6b608 529function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
bf347041 530 global $DB;
ca4eda13 531 $attemptscore = null;
a30b6819 532 $attemptscore->scoes = 0;
533 $attemptscore->values = 0;
534 $attemptscore->max = 0;
535 $attemptscore->sum = 0;
536 $attemptscore->lastmodify = 0;
9528568b 537
bf347041 538 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
ca4eda13 539 return null;
e4aa175a 540 }
e4aa175a 541
9528568b 542 foreach ($scoes as $sco) {
ca4eda13 543 if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
2b3447c3 544 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
a30b6819 545 $attemptscore->scoes++;
9528568b 546 }
5c2aa157 547 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
a30b6819 548 $attemptscore->values++;
549 $attemptscore->sum += $userdata->score_raw;
550 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
551 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
552 $attemptscore->lastmodify = $userdata->timemodified;
553 } else {
554 $attemptscore->lastmodify = 0;
555 }
9528568b 556 }
557 }
e4aa175a 558 }
03751efe 559 switch ($scorm->grademethod) {
a30b6819 560 case GRADEHIGHEST:
0d55dd4d 561 $score = (float) $attemptscore->max;
9528568b 562 break;
a30b6819 563 case GRADEAVERAGE:
564 if ($attemptscore->values > 0) {
565 $score = $attemptscore->sum/$attemptscore->values;
5c1ac70c 566 } else {
a30b6819 567 $score = 0;
9528568b 568 }
569 break;
a30b6819 570 case GRADESUM:
571 $score = $attemptscore->sum;
9528568b 572 break;
a30b6819 573 case GRADESCOES:
574 $score = $attemptscore->scoes;
7ef16bf9 575 break;
576 default:
577 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
5c1ac70c 578 }
a30b6819 579
c0f6b608 580 return $score;
a30b6819 581}
582
8c5516dc 583function scorm_grade_user($scorm, $userid) {
a30b6819 584
03751efe 585 // ensure we dont grade user beyond $scorm->maxattempt settings
7ce6eb87 586 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
ca4eda13 587 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
7ce6eb87 588 $lastattempt = $scorm->maxattempt;
589 }
590
03751efe 591 switch ($scorm->whatgrade) {
a30b6819 592 case FIRSTATTEMPT:
8c5516dc 593 return scorm_grade_user_attempt($scorm, $userid, 1);
9528568b 594 break;
a30b6819 595 case LASTATTEMPT:
8c5516dc 596 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
a30b6819 597 break;
598 case HIGHESTATTEMPT:
a30b6819 599 $maxscore = 0;
a30b6819 600 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
601 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
602 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
a30b6819 603 }
8c5516dc
DM
604 return $maxscore;
605
a30b6819 606 break;
607 case AVERAGEATTEMPT:
b1ca5d31 608 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
b1ca5d31
DM
609 if (empty($attemptcount)) {
610 return 0;
611 } else {
612 $attemptcount = count($attemptcount);
613 }
a30b6819 614 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
615 $sumscore = 0;
616 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
617 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
618 $sumscore += $attemptscore;
a30b6819 619 }
620
b1ca5d31 621 return round($sumscore / $attemptcount);
a30b6819 622 break;
623 }
e4aa175a 624}
625
ca4eda13 626function scorm_count_launchable($scormid, $organization='') {
bf347041 627 global $DB;
628
629 $sqlorganization = '';
630 $params = array($scormid);
8e45ba45 631 if (!empty($organization)) {
bf347041 632 $sqlorganization = " AND organization=?";
633 $params[] = $organization;
8e45ba45 634 }
ca4eda13 635 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
e4aa175a 636}
637
2b3447c3 638function scorm_get_last_attempt($scormid, $userid) {
bf347041 639 global $DB;
640
ca4eda13 641 /// Find the last attempt number for the given user id and scorm id
bf347041 642 if ($lastattempt = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid), 'max(attempt) as a')) {
2b3447c3 643 if (empty($lastattempt->a)) {
644 return '1';
645 } else {
646 return $lastattempt->a;
e4aa175a 647 }
6381fa56 648 } else {
649 return false;
e4aa175a 650 }
e4aa175a 651}
652
2276208a
DM
653function scorm_get_last_completed_attempt($scormid, $userid) {
654 global $DB;
655
ca4eda13 656 /// Find the last attempt number for the given user id and scorm id
ed98c4e9 657 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
658 if (empty($lastattempt->a)) {
659 return '1';
660 } else {
661 return $lastattempt->a;
662 }
663 } else {
664 return false;
665 }
666}
667
ca4eda13 668function scorm_course_format_display($user, $course) {
f2a1963c 669 global $CFG, $DB, $PAGE, $OUTPUT;
e4aa175a 670
671 $strupdate = get_string('update');
ca4eda13 672 $context = get_context_instance(CONTEXT_COURSE, $course->id);
e4aa175a 673
674 echo '<div class="mod-scorm">';
675 if ($scorms = get_all_instances_in_course('scorm', $course)) {
9528568b 676 // The module SCORM activity with the least id is the course
e4aa175a 677 $scorm = current($scorms);
678 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
08b56f93 679 print_error('invalidcoursemodule');
e4aa175a 680 }
aab23f98 681 $contextmodule = get_context_instance(CONTEXT_MODULE, $cm->id);
4201a746 682 if ((has_capability('mod/scorm:skipview', $contextmodule))) {
666efc14 683 scorm_simple_play($scorm, $user, $contextmodule, $cm->id);
aab23f98 684 }
e4aa175a 685 $colspan = '';
686 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
2b3447c3 687 if (has_capability('moodle/course:manageactivities', $context)) {
830dd6e9 688 if ($PAGE->user_is_editing()) {
e4aa175a 689 // Display update icon
690 $path = $CFG->wwwroot.'/course';
691 $headertext .= '<span class="commands">'.
692 '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&amp;sesskey='.sesskey().'">'.
b5d0cafc 693 '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
e4aa175a 694 }
695 $headertext .= '</td>';
696 // Display report link
bf347041 697 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
e4aa175a 698 if ($trackedusers->c > 0) {
699 $headertext .= '<td class="reportlink">'.
4aea3cc7 700 '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
ca4eda13 701 get_string('viewallreports', 'scorm', $trackedusers->c).'</a>';
e4aa175a 702 } else {
ca4eda13 703 $headertext .= '<td class="reportlink">'.get_string('noreports', 'scorm');
e4aa175a 704 }
705 $colspan = ' colspan="2"';
9528568b 706 }
ac3668bf 707 $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
ca4eda13 708 echo $OUTPUT->box($headertext, 'generalbox boxwidthwide');
39340358 709 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm);
e4aa175a 710 } else {
0d699c24 711 if (has_capability('moodle/course:update', $context)) {
e4aa175a 712 // Create a new activity
444ff001
DM
713 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'section'=>'0', 'sesskey'=>sesskey(),'add'=>'scorm'));
714 redirect($url);
e4aa175a 715 } else {
6aff538a 716 echo $OUTPUT->notification('Could not find a scorm course here');
e4aa175a 717 }
718 }
719 echo '</div>';
720}
721
39340358 722function scorm_view_display ($user, $scorm, $action, $cm) {
4eeec9ac 723 global $CFG, $DB, $PAGE, $OUTPUT;
ab3b00e1 724
9528568b 725 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
726 scorm_parse($scorm, false);
ab3b00e1 727 }
728
e4aa175a 729 $organization = optional_param('organization', '', PARAM_INT);
730
ca4eda13 731 if ($scorm->displaycoursestructure == 1) {
30bce58e 732 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
ca4eda13
DM
733 ?>
734 <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
735 <?php
6381fa56 736 }
e4aa175a 737 if (empty($organization)) {
738 $organization = $scorm->launch;
739 }
2e3c31bc 740 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
84ab3289
DM
741 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
742 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
ca4eda13 743 array($scorm->id), 'id', 'id,title')) {
e4aa175a 744 if (count($orgs) > 1) {
edc28287 745 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
ca4eda13 746 $select->label = get_string('organizations', 'scorm');
edc28287
PS
747 $select->class = 'scorm-center';
748 echo $OUTPUT->render($select);
e4aa175a 749 }
750 }
751 $orgidentifier = '';
b3659259 752 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
753 if (($sco->organization == '') && ($sco->launch == '')) {
754 $orgidentifier = $sco->identifier;
e4aa175a 755 } else {
b3659259 756 $orgidentifier = $sco->organization;
e4aa175a 757 }
758 }
28ffbff3 759
2b3447c3 760 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
dbe7e6f6 761 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
762 $scorm->version = 'scorm_12';
763 }
2b3447c3 764 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
765
ca4eda13 766 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
e4aa175a 767 $incomplete = $result->incomplete;
28ffbff3 768
6381fa56 769 // do we want the TOC to be displayed?
ca4eda13 770 if ($scorm->displaycoursestructure == 1) {
6381fa56 771 echo $result->toc;
6aff538a 772 echo $OUTPUT->box_end();
6381fa56 773 }
7554f671 774
6381fa56 775 // is this the first attempt ?
b1ca5d31 776 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
7554f671 777
6381fa56 778 // do not give the player launch FORM if the SCORM object is locked after the final attempt
779 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
ca4eda13 780 ?>
52a9a9b5 781 <div class="scorm-center">
4675994a 782 <form id="theform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
ca4eda13
DM
783 <?php
784 if ($scorm->hidebrowse == 0) {
785 print_string('mode', 'scorm');
786 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
787 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
788 } else {
789 echo '<input type="hidden" name="mode" value="normal" />'."\n";
790 }
791 if ($scorm->forcenewattempt == 1) {
792 if ($incomplete === false) {
793 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
794 }
795 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
796 ?>
6381fa56 797 <br />
798 <input type="checkbox" id="a" name="newattempt" />
ca4eda13
DM
799 <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
800 <?php
801 }
802 ?>
e4aa175a 803 <br />
4675994a 804 <input type="hidden" name="scoid"/>
3d00d6ab 805 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
e4aa175a 806 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
ca4eda13 807 <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
e4aa175a 808 </form>
809 </div>
ca4eda13 810 <?php
6381fa56 811 }
e4aa175a 812}
6280b17a 813
666efc14 814function scorm_simple_play($scorm, $user, $context, $cmid) {
bf347041 815 global $DB;
816
9316beca 817 $result = false;
818
819 if ($scorm->updatefreq == UPDATE_EVERYTIME) {
820 scorm_parse($scorm, false);
821 }
64f93798 822 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
823 return $result;
824 }
9316beca 825
84ab3289 826 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
9316beca 827
7325b016 828 if ($scoes) {
c5803aaa
DM
829 $orgidentifier = '';
830 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
831 if (($sco->organization == '') && ($sco->launch == '')) {
832 $orgidentifier = $sco->identifier;
833 } else {
834 $orgidentifier = $sco->organization;
835 }
836 }
9316beca 837 if ($scorm->skipview >= 1) {
838 $sco = current($scoes);
aab23f98
DM
839 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
840 'currentorg'=>$orgidentifier,
841 'scoid'=>$sco->id));
842 if ($scorm->skipview == 2 || scorm_get_tracks($sco->id, $user->id) === false) {
666efc14
DM
843 if (!empty($scorm->forcenewattempt)) {
844 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
845 if ($result->incomplete === false) {
846 $url->param('newattempt','on');
847 }
848 }
aab23f98 849 redirect($url);
9316beca 850 }
851 }
852 }
853 return $result;
28ffbff3 854}
d8c9d8a1 855
856function scorm_get_count_users($scormid, $groupingid=null) {
bf347041 857 global $CFG, $DB;
9528568b 858
98da6021 859 if (!empty($groupingid)) {
d8c9d8a1 860 $sql = "SELECT COUNT(DISTINCT st.userid)
bf347041 861 FROM {scorm_scoes_track} st
862 INNER JOIN {groups_members} gm ON st.userid = gm.userid
9528568b 863 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
bf347041 864 WHERE st.scormid = ? AND gg.groupingid = ?
d8c9d8a1 865 ";
bf347041 866 $params = array($scormid, $groupingid);
d8c9d8a1 867 } else {
868 $sql = "SELECT COUNT(DISTINCT st.userid)
9528568b 869 FROM {scorm_scoes_track} st
bf347041 870 WHERE st.scormid = ?
d8c9d8a1 871 ";
bf347041 872 $params = array($scormid);
d8c9d8a1 873 }
9528568b 874
bf347041 875 return ($DB->count_records_sql($sql, $params));
d8c9d8a1 876}
877
527af457 878/**
ca4eda13
DM
879 * Build up the JavaScript representation of an array element
880 *
881 * @param string $sversion SCORM API version
882 * @param array $userdata User track data
883 * @param string $element_name Name of array element to get values for
884 * @param array $children list of sub elements of this array element that also need instantiating
885 * @return None
886 */
527af457 887function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
888 // reconstitute comments_from_learner and comments_from_lms
889 $current = '';
bf34ac0f 890 $current_subelement = '';
891 $current_sub = '';
527af457 892 $count = 0;
bf34ac0f 893 $count_sub = 0;
6b635d44
DM
894 $scormseperator = '_';
895 if ($sversion == 'scorm_13') { //scorm 1.3 elements use a . instead of an _
ca4eda13 896 $scormseperator = '.';
6b635d44 897 }
527af457 898 // filter out the ones we want
899 $element_list = array();
ca4eda13
DM
900 foreach ($userdata as $element => $value) {
901 if (substr($element, 0, strlen($element_name)) == $element_name) {
527af457 902 $element_list[$element] = $value;
903 }
904 }
7554f671 905
527af457 906 // sort elements in .n array order
907 uksort($element_list, "scorm_element_cmp");
7554f671 908
527af457 909 // generate JavaScript
ca4eda13 910 foreach ($element_list as $element => $value) {
527af457 911 if ($sversion == 'scorm_13') {
b6293233 912 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
527af457 913 preg_match('/\.(N\d+)\./', $element, $matches);
914 } else {
b6293233 915 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
527af457 916 preg_match('/\_(\d+)\./', $element, $matches);
917 }
918 if (count($matches) > 0 && $current != $matches[1]) {
bf34ac0f 919 if ($count_sub > 0) {
6b635d44 920 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 921 }
7554f671 922 $current = $matches[1];
527af457 923 $count++;
bf34ac0f 924 $current_subelement = '';
925 $current_sub = '';
926 $count_sub = 0;
ca4eda13
DM
927 $end = strpos($element, $matches[1])+strlen($matches[1]);
928 $subelement = substr($element, 0, $end);
527af457 929 echo ' '.$subelement." = new Object();\n";
930 // now add the children
931 foreach ($children as $child) {
932 echo ' '.$subelement.".".$child." = new Object();\n";
933 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
934 }
935 }
7554f671 936
bf34ac0f 937 // now - flesh out the second level elements if there are any
938 if ($sversion == 'scorm_13') {
b6293233 939 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
bf34ac0f 940 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
941 } else {
b6293233 942 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
bf34ac0f 943 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
944 }
7554f671 945
bf34ac0f 946 // check the sub element type
947 if (count($matches) > 0 && $current_subelement != $matches[1]) {
948 if ($count_sub > 0) {
03e9a122 949 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 950 }
951 $current_subelement = $matches[1];
952 $current_sub = '';
953 $count_sub = 0;
ca4eda13
DM
954 $end = strpos($element, $matches[1])+strlen($matches[1]);
955 $subelement = substr($element, 0, $end);
bf34ac0f 956 echo ' '.$subelement." = new Object();\n";
957 }
7554f671 958
bf34ac0f 959 // now check the subelement subscript
960 if (count($matches) > 0 && $current_sub != $matches[2]) {
7554f671 961 $current_sub = $matches[2];
bf34ac0f 962 $count_sub++;
ca4eda13
DM
963 $end = strrpos($element, $matches[2])+strlen($matches[2]);
964 $subelement = substr($element, 0, $end);
bf34ac0f 965 echo ' '.$subelement." = new Object();\n";
966 }
7554f671 967
527af457 968 echo ' '.$element.' = \''.$value."';\n";
969 }
bf34ac0f 970 if ($count_sub > 0) {
6b635d44 971 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 972 }
527af457 973 if ($count > 0) {
974 echo ' '.$element_name.'._count = '.$count.";\n";
975 }
976}
977
978/**
ca4eda13
DM
979 * Build up the JavaScript representation of an array element
980 *
981 * @param string $a left array element
982 * @param string $b right array element
983 * @return comparator - 0,1,-1
984 */
527af457 985function scorm_element_cmp($a, $b) {
bf34ac0f 986 preg_match('/.*?(\d+)\./', $a, $matches);
527af457 987 $left = intval($matches[1]);
bf34ac0f 988 preg_match('/.?(\d+)\./', $b, $matches);
527af457 989 $right = intval($matches[1]);
990 if ($left < $right) {
991 return -1; // smaller
ca4eda13 992 } else if ($left > $right) {
527af457 993 return 1; // bigger
994 } else {
bf34ac0f 995 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
996 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
997 $leftterm = intval($matches[2]);
998 $left = intval($matches[3]);
999 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1000 $rightterm = intval($matches[2]);
1001 $right = intval($matches[3]);
1002 if ($leftterm < $rightterm) {
1003 return -1; // smaller
ca4eda13 1004 } else if ($leftterm > $rightterm) {
bf34ac0f 1005 return 1; // bigger
1006 } else {
1007 if ($left < $right) {
1008 return -1; // smaller
ca4eda13 1009 } else if ($left > $right) {
bf34ac0f 1010 return 1; // bigger
1011 }
1012 }
1013 }
1014 }
1015 // fall back for no second level matches or second level matches are equal
527af457 1016 return 0; // equal to
1017 }
1018}
6381fa56 1019
1020/**
ca4eda13
DM
1021 * Generate the user attempt status string
1022 *
1023 * @param object $user Current context user
1024 * @param object $scorm a moodle scrom object - mdl_scorm
1025 * @return string - Attempt status string
1026 */
6381fa56 1027function scorm_get_attempt_status($user, $scorm) {
1028 global $DB;
7554f671 1029
b1ca5d31 1030 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
ca4eda13 1031 if (empty($attempts)) {
6381fa56 1032 $attemptcount = 0;
1033 } else {
1034 $attemptcount = count($attempts);
1035 }
7554f671 1036
6381fa56 1037 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1038 if ($scorm->maxattempt > 0) {
4f4a8acf 1039 $result .= $scorm->maxattempt . '<br />';
6381fa56 1040 } else {
4f4a8acf 1041 $result .= get_string('unlimited').'<br />';
6381fa56 1042 }
4f4a8acf 1043 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
6381fa56 1044
b1ca5d31
DM
1045 if ($scorm->maxattempt == 1) {
1046 switch ($scorm->grademethod) {
1047 case GRADEHIGHEST:
1048 $grademethod = get_string('gradehighest', 'scorm');
1049 break;
1050 case GRADEAVERAGE:
1051 $grademethod = get_string('gradeaverage', 'scorm');
1052 break;
1053 case GRADESUM:
1054 $grademethod = get_string('gradesum', 'scorm');
1055 break;
1056 case GRADESCOES:
1057 $grademethod = get_string('gradescoes', 'scorm');
1058 break;
1059 }
ca4eda13
DM
1060 } else {
1061 switch ($scorm->whatgrade) {
b1ca5d31
DM
1062 case HIGHESTATTEMPT:
1063 $grademethod = get_string('highestattempt', 'scorm');
1064 break;
1065 case AVERAGEATTEMPT:
1066 $grademethod = get_string('averageattempt', 'scorm');
1067 break;
1068 case FIRSTATTEMPT:
1069 $grademethod = get_string('firstattempt', 'scorm');
1070 break;
1071 case LASTATTEMPT:
1072 $grademethod = get_string('lastattempt', 'scorm');
1073 break;
1074 }
ca4eda13 1075 }
7554f671 1076
ca4eda13 1077 if (!empty($attempts)) {
b1ca5d31 1078 $i = 1;
ca4eda13 1079 foreach ($attempts as $attempt) {
6381fa56 1080 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
4f4a8acf
DM
1081 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1082 $gradereported = $gradereported/$scorm->maxgrade;
1083 $gradereported = number_format($gradereported*100, 0) .'%';
1084 }
1085 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
b1ca5d31 1086 $i++;
6381fa56 1087 }
1088 }
b1ca5d31 1089 $calculatedgrade = scorm_grade_user($scorm, $user->id);
4f4a8acf
DM
1090 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1091 $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1092 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1093 }
6381fa56 1094 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
ca4eda13
DM
1095 if (empty($attempts)) {
1096 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
6381fa56 1097 } else {
ca4eda13 1098 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
6381fa56 1099 }
1100 $result .= '</p>';
1101 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
ca4eda13 1102 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
6381fa56 1103 }
1104 return $result;
1105}
1106
1107/**
ca4eda13
DM
1108 * Get SCORM attempt count
1109 *
1110 * @param object $user Current context user
1111 * @param object $scorm a moodle scrom object - mdl_scorm
1112 * @param bool $attempts return the list of attempts
1113 * @return int - no. of attempts so far
1114 */
b1ca5d31 1115function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
6381fa56 1116 global $DB;
1117 $attemptcount = 0;
1118 $element = 'cmi.core.score.raw';
78b203ca
DM
1119 if ($scorm->grademethod == GRADESCOES) {
1120 $element = 'cmi.core.lesson_status';
1121 }
7b6f5c8d 1122 if ($scorm->version == 'scorm_13' || $scorm->version == 'SCORM_1.3') {
6381fa56 1123 $element = 'cmi.score.raw';
1124 }
ca4eda13 1125 $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
1126 if ($attempts_only) {
1127 return $attempts;
1128 }
ca4eda13 1129 if (!empty($attempts)) {
6381fa56 1130 $attemptcount = count($attempts);
1131 }
1132 return $attemptcount;
1133}
1881df27 1134
1135/**
ca4eda13
DM
1136 * Figure out with this is a debug situation
1137 *
1138 * @param object $scorm a moodle scrom object - mdl_scorm
1139 * @return boolean - debugging true/false
1140 */
1881df27 1141function scorm_debugging($scorm) {
1142 global $CFG, $USER;
30fc6e2d 1143 $cfg_scorm = get_config('scorm');
7554f671 1144
30fc6e2d 1145 if (!$cfg_scorm->allowapidebug) {
1881df27 1146 return false;
1147 }
1148 $identifier = $USER->username.':'.$scorm->name;
30fc6e2d 1149 $test = $cfg_scorm->apidebugmask;
1881df27 1150 // check the regex is only a short list of safe characters
1151 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1152 return false;
1153 }
1154 $res = false;
1155 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1156 return $res;
1157}
7554f671 1158
1159/**
ca4eda13
DM
1160 * Delete Scorm tracks for selected users
1161 *
1162 * @param array $attemptids list of attempts that need to be deleted
1163 * @param int $scorm instance
1164 *
1165 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1166 */
8716cc35 1167function scorm_delete_responses($attemptids, $scorm) {
ca4eda13 1168 if (!is_array($attemptids) || empty($attemptids)) {
7554f671 1169 return false;
1170 }
1171
ca4eda13
DM
1172 foreach ($attemptids as $num => $attemptid) {
1173 if (empty($attemptid)) {
7554f671 1174 unset($attemptids[$num]);
1175 }
1176 }
1177
ca4eda13 1178 foreach ($attemptids as $attempt) {
7554f671 1179 $keys = explode(':', $attempt);
1180 if (count($keys) == 2) {
1181 $userid = clean_param($keys[0], PARAM_INT);
1182 $attemptid = clean_param($keys[1], PARAM_INT);
8716cc35 1183 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
7554f671 1184 return false;
1185 }
1186 } else {
1187 return false;
1188 }
1189 }
1190 return true;
1191}
1192
1193/**
ca4eda13
DM
1194 * Delete Scorm tracks for selected users
1195 *
1196 * @param int $userid ID of User
1197 * @param int $scormid ID of Scorm
1198 * @param int $attemptid user attempt that need to be deleted
1199 *
1200 * return bool true suceeded
1201 */
8716cc35 1202function scorm_delete_attempt($userid, $scorm, $attemptid) {
7554f671 1203 global $DB;
1204
8716cc35
DM
1205 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1206 include_once('lib.php');
1207 scorm_update_grades($scorm, $userid, true);
7554f671 1208 return true;
1209}
00c1677a
DM
1210
1211/**
2700b283 1212 * Converts SCORM duration notation to human-readable format
00c1677a 1213 * The function works with both SCORM 1.2 and SCORM 2004 time formats
2700b283 1214 * @param $duration string SCORM duration
00c1677a
DM
1215 * @return string human-readable date/time
1216 */
2700b283 1217function scorm_format_duration($duration) {
00c1677a 1218 // fetch date/time strings
119d64ee 1219 $stryears = get_string('years');
00c1677a 1220 $strmonths = get_string('nummonths');
119d64ee
DM
1221 $strdays = get_string('days');
1222 $strhours = get_string('hours');
1223 $strminutes = get_string('minutes');
1224 $strseconds = get_string('seconds');
64f93798 1225
2700b283 1226 if ($duration[0] == 'P') {
00c1677a
DM
1227 // if timestamp starts with 'P' - it's a SCORM 2004 format
1228 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1229 // and outputs filled sections, discarding leading zeroes and any format literals
1230 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1231 $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#',
1232 '#([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
1233 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1234 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
00c1677a
DM
1235 } else {
1236 // else we have SCORM 1.2 format there
1237 // first convert the timestamp to some SCORM 2004-like format for conveniency
2700b283 1238 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
00c1677a
DM
1239 // then convert in the same way as SCORM 2004
1240 $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 1241 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
00c1677a 1242 }
64f93798 1243
2700b283 1244 $result = preg_replace($pattern, $replace, $duration);
00c1677a
DM
1245
1246 return $result;
1247}
0797000a
DM
1248
1249function scorm_get_toc($user,$scorm,$cmid,$toclink=TOCJSLINK,$currentorg='',$scoid='',$mode='normal',$attempt='',$play=false, $tocheader=false) {
1250 global $CFG, $DB, $PAGE, $OUTPUT;
1251
1252 $modestr = '';
1253 if ($mode == 'browse') {
1254 $modestr = '&amp;mode='.$mode;
1255 }
1256
1257 $result = new stdClass();
1258 if ($tocheader) {
1259 $result->toc = '<div id="scorm_layout">';
1260 $result->toc .= '<div id="scorm_toc">';
1261 $result->toc .= '<div id="scorm_tree">';
1262 }
1263 $result->toc .= '<ul>';
1264 $tocmenus = array();
1265 $result->prerequisites = true;
1266 $incomplete = false;
1267
1268 //
1269 // Get the current organization infos
1270 //
1271 if (!empty($currentorg)) {
1272 if (($organizationtitle = $DB->get_field('scorm_scoes','title', array('scorm'=>$scorm->id,'identifier'=>$currentorg))) != '') {
1273 if ($play) {
1274 $result->toctitle = "$organizationtitle";
1275 }
1276 else {
1277 $result->toc .= "\t<li>$organizationtitle</li>\n";
1278 }
1279 $tocmenus[] = $organizationtitle;
1280 }
1281 }
1282
1283 //
1284 // If not specified retrieve the last attempt number
1285 //
1286 if (empty($attempt)) {
1287 $attempt = scorm_get_attempt_count($user->id, $scorm);
1288 }
1289 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attempt;
1290 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1291 //
1292 // Retrieve user tracking data for each learning object
1293 //
1294 $usertracks = array();
1295 foreach ($scoes as $sco) {
1296 if (!empty($sco->launch)) {
1297 if (empty($scoid)) {
1298 $scoid = $sco->id;
1299 }
1300 if ($usertrack = scorm_get_tracks($sco->id,$user->id,$attempt)) {
1301 if ($usertrack->status == '') {
1302 $usertrack->status = 'notattempted';
1303 }
1304 $usertracks[$sco->identifier] = $usertrack;
1305 }
1306 }
1307 }
1308
1309 $level=0;
1310 $sublist=1;
1311 $previd = 0;
1312 $nextid = 0;
1313 $findnext = false;
1314 $parents[$level]='/';
0797000a
DM
1315 foreach ($scoes as $pos => $sco) {
1316 $isvisible = false;
1317 $sco->title = $sco->title;
1318 if (!isset($sco->isvisible) || (isset($sco->isvisible) && ($sco->isvisible == 'true'))) {
1319 $isvisible = true;
1320 }
1321 if ($parents[$level] != $sco->parent) {
1322 if ($newlevel = array_search($sco->parent,$parents)) {
1323 for ($i=0; $i<($level-$newlevel); $i++) {
1324 $result->toc .= "\t\t</li></ul></li>\n";
1325 }
1326 $level = $newlevel;
1327 } else {
1328 $i = $level;
1329 $closelist = '';
1330 while (($i > 0) && ($parents[$level] != $sco->parent)) {
8cb7096b 1331 if ($i === 1 && $level > 1) {
b6c88d75
DM
1332 $closelist .= "\t\t</ul></li>\n";
1333 } else {
1334 $closelist .= "\t</li></ul></li>\n";
1335 }
0797000a
DM
1336 $i--;
1337 }
1338 if (($i == 0) && ($sco->parent != $currentorg)) {
b6c88d75 1339 $result->toc .= "\n\t<ul>\n";
0797000a
DM
1340 $level++;
1341 } else {
1342 $result->toc .= $closelist;
1343 $level = $i;
1344 }
1345 $parents[$level] = $sco->parent;
1346 }
1347 }
1348 if ($isvisible) {
1349 $result->toc .= "<li>";
1350 }
1351 if (isset($scoes[$pos+1])) {
1352 $nextsco = $scoes[$pos+1];
1353 } else {
1354 $nextsco = false;
1355 }
1356 $nextisvisible = false;
1357 if (($nextsco !== false) && (!isset($nextsco->isvisible) || (isset($nextsco->isvisible) && ($nextsco->isvisible == 'true')))) {
1358 $nextisvisible = true;
1359 }
1360 if ($nextisvisible && ($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
1361 (($level==0) || (($level>0) && ($nextsco->parent == $sco->identifier)))) {
1362 $sublist++;
1363 }
1364 if (empty($sco->title)) {
1365 $sco->title = $sco->identifier;
1366 }
b6c88d75
DM
1367 if ($isvisible) {
1368 if (!empty($sco->launch)) {
0797000a
DM
1369 $score = '';
1370 if (empty($scoid) && ($mode != 'normal')) {
1371 $scoid = $sco->id;
1372 }
1373 if (isset($usertracks[$sco->identifier])) {
1374 $usertrack = $usertracks[$sco->identifier];
1375 $strstatus = get_string($usertrack->status,'scorm');
1376 if ($sco->scormtype == 'sco') {
1377 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1378 } else {
1379 $statusicon = '<img src="'.$OUTPUT->pix_url('assetc', 'scorm').'" alt="'.get_string('assetlaunched','scorm').'" title="'.get_string('assetlaunched','scorm').'" />';
1380 }
1381
1382 if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1383 $incomplete = true;
1384 if ($play && empty($scoid)) {
1385 $scoid = $sco->id;
1386 }
1387 }
1388 if ($usertrack->score_raw != '' && has_capability('mod/scorm:viewscores', get_context_instance(CONTEXT_MODULE,$cmid))) {
1389 $score = '('.get_string('score','scorm').':&nbsp;'.$usertrack->score_raw.')';
1390 }
1391 $strsuspended = get_string('suspended','scorm');
1392 $exitvar = 'cmi.core.exit';
1393 if ($scorm->version == 'SCORM_1.3') {
1394 $exitvar = 'cmi.exit';
1395 }
1396 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1397 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1398 }
1399 } else {
1400 if ($play && empty($scoid)) {
1401 $scoid = $sco->id;
1402 }
1403 $incomplete = true;
1404 if ($sco->scormtype == 'sco') {
1405 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted','scorm').'" title="'.get_string('notattempted','scorm').'" />';
1406 } else {
1407 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset','scorm').'" title="'.get_string('asset','scorm').'" />';
1408 }
1409 }
1410 if ($sco->id == $scoid) {
1411 $findnext = true;
1412 }
1413
1414 if (($nextid == 0) && (scorm_count_launchable($scorm->id,$currentorg) > 1) && ($nextsco!==false) && (!$findnext)) {
1415 if (!empty($sco->launch)) {
1416 $previd = $sco->id;
1417 }
1418 }
1419
1420 if ($scorm->version == 'SCORM_1.3') {
1421 require_once($CFG->dirroot.'/mod/scorm/datamodels/sequencinglib.php');
1422 $prereq = scorm_seq_evaluate($sco->id,$usertracks);
1423 } else {
1424 //TODO: split check for sco->prerequisites only for AICC as I think that's the only case it's set.
1425 $prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites,$usertracks);
1426 }
1427 if ($prereq) {
1428 if ($sco->id == $scoid) {
1429 $result->prerequisites = true;
1430 }
1431
1432 if ($toclink == TOCFULLURL) { //display toc with urls for structure page
1433 $url = $CFG->wwwroot.'/mod/scorm/player.php?a='.$scorm->id.'&amp;currentorg='.$currentorg.$modestr.'&amp;scoid='.$sco->id;
1434 $result->toc .= $statusicon.'&nbsp;<a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1435 } else { //display toc for inside scorm player
1436 if ($sco->launch) {
1437 $link = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
1438 $result->toc .= '<a title="'.$link.'">'.$statusicon.'&nbsp;'.format_string($sco->title).'&nbsp;'.$score.'</a>';
1439 } else {
1440 $result->toc .= '<span>'.$statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1441 }
1442 }
1443 $tocmenus[$sco->id] = scorm_repeater('&minus;',$level) . '&gt;' . format_string($sco->title);
1444 } else {
1445 if ($sco->id == $scoid) {
1446 $result->prerequisites = false;
1447 }
1448 if ($play) {
1449 // should be disabled
1450 $result->toc .= '<span>'.$statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1451 } else {
1452 $result->toc .= $statusicon.'&nbsp;'.format_string($sco->title)."\n";
1453 }
1454 }
b6c88d75
DM
1455 } else {
1456 $result->toc .= '&nbsp;'.format_string($sco->title);
1457 }
1458 if (($nextsco === false) || $nextsco->parent == $sco->parent) {
1459 $result->toc .= "</li>\n";
0797000a 1460 }
0797000a
DM
1461 }
1462 if (($nextsco !== false) && ($nextid == 0) && ($findnext)) {
1463 if (!empty($nextsco->launch)) {
1464 $nextid = $nextsco->id;
1465 }
1466 }
1467 }
1468 for ($i=0;$i<$level;$i++) {
1469 $result->toc .= "\t\t</ul></li>\n";
1470 }
1471
1472 if ($play) {
8a4561ac
DM
1473 if (empty($scoid)) {
1474 $scoid = reset($scoes)->id;
1475 }
0797000a
DM
1476 $sco = scorm_get_sco($scoid);
1477 $sco->previd = $previd;
1478 $sco->nextid = $nextid;
1479 $result->sco = $sco;
1480 $result->incomplete = $incomplete;
1481 } else {
1482 $result->incomplete = $incomplete;
1483 }
1484 }
1485 $result->toc .= '</ul>';
1486
1487 // NEW IMS TOC
1488 if ($tocheader) {
1489 $result->toc .= '</div></div></div>';
1490 $result->toc .= '<div id="scorm_navpanel"></div>';
1491 }
1492
1493
1494 if ($scorm->hidetoc == 0) {
1495 $PAGE->requires->data_for_js('scormdata', array(
1496 'plusicon' => $OUTPUT->pix_url('plus', 'scorm'),
1497 'minusicon' => $OUTPUT->pix_url('minus', 'scorm')));
1498 $PAGE->requires->js('/lib/cookies.js');
1499 $PAGE->requires->js('/mod/scorm/datamodels/scorm_datamodels.js');
1500 }
1501
1502 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
1503 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenus, $sco->id, null, "tocmenu");
1504
1505 return $result;
701570b5 1506}