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