MDL-46760 mod_scorm: Fix js error when preview mode disabled
[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
02bff1ad
DM
17/**
18 * Library of internal classes and functions for module SCORM
19 *
20 * @package mod_scorm
21 * @copyright 1999 onwards Roberto Pinna
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
9528568b 25require_once("$CFG->dirroot/mod/scorm/lib.php");
64f93798 26require_once("$CFG->libdir/filelib.php");
9528568b 27
27b8872c 28// Constants and settings for module scorm.
8aba9cda
DM
29define('SCORM_UPDATE_NEVER', '0');
30define('SCORM_UPDATE_EVERYDAY', '2');
31define('SCORM_UPDATE_EVERYTIME', '3');
a679d64d 32
bb5cc0e9
DM
33define('SCORM_SKIPVIEW_NEVER', '0');
34define('SCORM_SKIPVIEW_FIRST', '1');
35define('SCORM_SKIPVIEW_ALWAYS', '2');
36
b3659259 37define('SCO_ALL', 0);
38define('SCO_DATA', 1);
39define('SCO_ONLY', 2);
a30b6819 40
41define('GRADESCOES', '0');
42define('GRADEHIGHEST', '1');
43define('GRADEAVERAGE', '2');
44define('GRADESUM', '3');
a30b6819 45
46define('HIGHESTATTEMPT', '0');
47define('AVERAGEATTEMPT', '1');
48define('FIRSTATTEMPT', '2');
49define('LASTATTEMPT', '3');
a30b6819 50
7cc7cf58
DM
51define('TOCJSLINK', 1);
52define('TOCFULLURL', 2);
53
27b8872c 54// Local Library of functions for module scorm.
a30b6819 55
64f93798 56/**
6da956e6 57 * @package mod_scorm
64f93798
PS
58 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 */
61class scorm_package_file_info extends file_info_stored {
62 public function get_parent() {
63 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
64 return $this->browser->get_file_info($this->context);
65 }
66 return parent::get_parent();
67 }
68 public function get_visible_name() {
69 if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
70 return $this->topvisiblename;
71 }
72 return parent::get_visible_name();
73 }
74}
75
30fc6e2d 76/**
77 * Returns an array of the popup options for SCORM and each options default value
7554f671 78 *
30fc6e2d 79 * @return array an array of popup options as the key and their defaults as the value
80 */
ca4eda13 81function scorm_get_popup_options_array() {
36136454 82 $cfgscorm = get_config('scorm');
7554f671 83
27b8872c
N
84 return array('scrollbars' => isset($cfgscorm->scrollbars) ? $cfgscorm->scrollbars : 0,
85 'directories' => isset($cfgscorm->directories) ? $cfgscorm->directories : 0,
86 'location' => isset($cfgscorm->location) ? $cfgscorm->location : 0,
87 'menubar' => isset($cfgscorm->menubar) ? $cfgscorm->menubar : 0,
88 'toolbar' => isset($cfgscorm->toolbar) ? $cfgscorm->toolbar : 0,
89 'status' => isset($cfgscorm->status) ? $cfgscorm->status : 0);
30fc6e2d 90}
91
92/**
93 * Returns an array of the array of what grade options
7554f671 94 *
30fc6e2d 95 * @return array an array of what grade options
96 */
ca4eda13 97function scorm_get_grade_method_array() {
30fc6e2d 98 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
99 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
100 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
7554f671 101 GRADESUM => get_string('gradesum', 'scorm'));
30fc6e2d 102}
103
104/**
105 * Returns an array of the array of what grade options
7554f671 106 *
30fc6e2d 107 * @return array an array of what grade options
108 */
ca4eda13 109function scorm_get_what_grade_array() {
30fc6e2d 110 return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
111 AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
112 FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
113 LASTATTEMPT => get_string('lastattempt', 'scorm'));
114}
115
116/**
117 * Returns an array of the array of skip view options
7554f671 118 *
30fc6e2d 119 * @return array an array of skip view options
120 */
ca4eda13 121function scorm_get_skip_view_array() {
bb5cc0e9
DM
122 return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
123 SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
124 SCORM_SKIPVIEW_ALWAYS => get_string('always'));
30fc6e2d 125}
126
127/**
128 * Returns an array of the array of hide table of contents options
7554f671 129 *
30fc6e2d 130 * @return array an array of hide table of contents options
131 */
ca4eda13 132function scorm_get_hidetoc_array() {
5f65d37c 133 return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
99da7a95
DM
134 SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
135 SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
136 SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
30fc6e2d 137}
138
139/**
140 * Returns an array of the array of update frequency options
7554f671 141 *
30fc6e2d 142 * @return array an array of update frequency options
143 */
ca4eda13 144function scorm_get_updatefreq_array() {
8aba9cda
DM
145 return array(SCORM_UPDATE_NEVER => get_string('never'),
146 SCORM_UPDATE_EVERYDAY => get_string('everyday', 'scorm'),
147 SCORM_UPDATE_EVERYTIME => get_string('everytime', 'scorm'));
30fc6e2d 148}
149
150/**
151 * Returns an array of the array of popup display options
7554f671 152 *
30fc6e2d 153 * @return array an array of popup display options
154 */
ca4eda13 155function scorm_get_popup_display_array() {
d67eb434 156 return array(0 => get_string('currentwindow', 'scorm'),
30fc6e2d 157 1 => get_string('popup', 'scorm'));
158}
159
df5c7086
MG
160/**
161 * Returns an array of the array of navigation buttons display options
162 *
163 * @return array an array of navigation buttons display options
164 */
165function scorm_get_navigation_display_array() {
166 return array(SCORM_NAV_DISABLED => get_string('no'),
167 SCORM_NAV_UNDER_CONTENT => get_string('undercontent', 'scorm'),
168 SCORM_NAV_FLOATING => get_string('floating', 'scorm'));
169}
170
30fc6e2d 171/**
172 * Returns an array of the array of attempt options
7554f671 173 *
30fc6e2d 174 * @return array an array of attempt options
175 */
ca4eda13
DM
176function scorm_get_attempts_array() {
177 $attempts = array(0 => get_string('nolimit', 'scorm'),
178 1 => get_string('attempt1', 'scorm'));
7554f671 179
27b8872c 180 for ($i = 2; $i <= 6; $i++) {
ca4eda13 181 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
30fc6e2d 182 }
7554f671 183
30fc6e2d 184 return $attempts;
185}
da92e3b0
DM
186
187/**
188 * Returns an array of the attempt status options
189 *
190 * @return array an array of attempt status options
191 */
192function scorm_get_attemptstatus_array() {
193 return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO => get_string('no'),
194 SCORM_DISPLAY_ATTEMPTSTATUS_ALL => get_string('attemptstatusall', 'scorm'),
195 SCORM_DISPLAY_ATTEMPTSTATUS_MY => get_string('attemptstatusmy', 'scorm'),
196 SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY => get_string('attemptstatusentry', 'scorm'));
197}
198
9528568b 199/**
200 * Extracts scrom package, sets up all variables.
201 * Called whenever scorm changes
202 * @param object $scorm instance - fields are updated and changes saved into database
203 * @param bool $full force full update if true
204 * @return void
205 */
206function scorm_parse($scorm, $full) {
207 global $CFG, $DB;
27b8872c 208 $cfgscorm = get_config('scorm');
8aee93f1 209
9528568b 210 if (!isset($scorm->cmid)) {
211 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
212 $scorm->cmid = $cm->id;
213 }
a3fc4b3a 214 $context = context_module::instance($scorm->cmid);
9528568b 215 $newhash = $scorm->sha1hash;
a30b6819 216
9528568b 217 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
a30b6819 218
9528568b 219 $fs = get_file_storage();
220 $packagefile = false;
361a47d4 221 $packagefileimsmanifest = false;
f69db63e 222
9528568b 223 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
64f93798 224 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
27b87c10
DM
225 if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
226 $packagefile->import_external_file_contents();
227 }
9528568b 228 $newhash = $packagefile->get_contenthash();
361a47d4
DM
229 if (strtolower($packagefile->get_filename()) == 'imsmanifest.xml') {
230 $packagefileimsmanifest = true;
231 }
9528568b 232 } else {
233 $newhash = null;
234 }
235 } else {
27b8872c
N
236 if (!$cfgscorm->allowtypelocalsync) {
237 // Sorry - localsync disabled.
9528568b 238 return;
239 }
240 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
64f93798 241 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
27b8872c
N
242 $filerecord = array('contextid' => $context->id, 'component' => 'mod_scorm', 'filearea' => 'package',
243 'itemid' => 0, 'filepath' => '/');
244 if ($packagefile = $fs->create_file_from_url($filerecord, $scorm->reference, array('calctimeout' => true))) {
9528568b 245 $newhash = sha1($scorm->reference);
5c1ac70c 246 } else {
9528568b 247 $newhash = null;
5c1ac70c 248 }
f69db63e 249 }
250 }
f69db63e 251
9528568b 252 if ($packagefile) {
253 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
254 if (strpos($scorm->version, 'SCORM') !== false) {
361a47d4
DM
255 if ($packagefileimsmanifest || $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
256 // No need to update.
9528568b 257 return;
e4aa175a 258 }
9528568b 259 } else if (strpos($scorm->version, 'AICC') !== false) {
27b8872c 260 // TODO: add more sanity checks - something really exists in scorm_content area.
9528568b 261 return;
262 }
263 }
361a47d4
DM
264 if (!$packagefileimsmanifest) {
265 // Now extract files.
266 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
9528568b 267
361a47d4
DM
268 $packer = get_file_packer('application/zip');
269 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
270 }
9528568b 271
272 } else if (!$full) {
273 return;
274 }
361a47d4
DM
275 if ($packagefileimsmanifest) {
276 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
277 // Direct link to imsmanifest.xml file.
278 if (!scorm_parse_scorm($scorm, $packagefile)) {
279 $scorm->version = 'ERROR';
280 }
9528568b 281
361a47d4 282 } else if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 283 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
27b8872c 284 // SCORM.
9528568b 285 if (!scorm_parse_scorm($scorm, $manifest)) {
286 $scorm->version = 'ERROR';
287 }
288 } else {
289 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
27b8872c 290 // AICC.
9528568b 291 if (!scorm_parse_aicc($scorm)) {
292 $scorm->version = 'ERROR';
293 }
4388bd45 294 $scorm->version = 'AICC';
9528568b 295 }
296
27b8872c 297 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfgscorm->allowtypeexternal) {
9528568b 298 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
27b8872c 299 // SCORM only, AICC can not be external.
9528568b 300 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
301 $scorm->version = 'ERROR';
302 }
303 $newhash = sha1($scorm->reference);
304
27b8872c 305 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfgscorm->allowtypeexternalaicc) {
4388bd45 306 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
27b8872c 307 // AICC.
4388bd45
DM
308 if (!scorm_parse_aicc($scorm)) {
309 $scorm->version = 'ERROR';
310 }
311 $scorm->version = 'AICC';
e4aa175a 312 } else {
27b8872c 313 // Sorry, disabled type.
9528568b 314 return;
e4aa175a 315 }
9528568b 316
317 $scorm->revision++;
318 $scorm->sha1hash = $newhash;
319 $DB->update_record('scorm', $scorm);
e4aa175a 320}
321
9528568b 322
2b3447c3 323function scorm_array_search($item, $needle, $haystacks, $strict=false) {
324 if (!empty($haystacks)) {
325 foreach ($haystacks as $key => $element) {
326 if ($strict) {
327 if ($element->{$item} === $needle) {
328 return $key;
329 }
330 } else {
331 if ($element->{$item} == $needle) {
332 return $key;
e4aa175a 333 }
334 }
e4aa175a 335 }
336 }
2b3447c3 337 return false;
e4aa175a 338}
339
2b3447c3 340function scorm_repeater($what, $times) {
341 if ($times <= 0) {
342 return null;
343 }
344 $return = '';
27b8872c 345 for ($i = 0; $i < $times; $i++) {
2b3447c3 346 $return .= $what;
347 }
348 return $return;
349}
e4aa175a 350
2b3447c3 351function scorm_external_link($link) {
27b8872c 352 // Check if a link is external.
2b3447c3 353 $result = false;
354 $link = strtolower($link);
ca4eda13 355 if (substr($link, 0, 7) == 'http://') {
2b3447c3 356 $result = true;
ca4eda13 357 } else if (substr($link, 0, 8) == 'https://') {
2b3447c3 358 $result = true;
ca4eda13 359 } else if (substr($link, 0, 4) == 'www.') {
2b3447c3 360 $result = true;
361 }
362 return $result;
e4aa175a 363}
364
b3659259 365/**
ca4eda13
DM
366 * Returns an object containing all datas relative to the given sco ID
367 *
368 * @param integer $id The sco ID
369 * @return mixed (false if sco id does not exists)
370 */
371function scorm_get_sco($id, $what=SCO_ALL) {
bf347041 372 global $DB;
373
27b8872c 374 if ($sco = $DB->get_record('scorm_scoes', array('id' => $id))) {
b3659259 375 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
27b8872c 376 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id)))) {
b3659259 377 foreach ($scodatas as $scodata) {
c31f631b 378 $sco->{$scodata->name} = $scodata->value;
b3659259 379 }
27b8872c 380 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id))))) {
9528568b 381 $sco->parameters = '';
b3659259 382 }
383 return $sco;
384 } else {
385 return false;
386 }
387}
82605bea 388
389/**
ca4eda13
DM
390 * Returns an object (array) containing all the scoes data related to the given sco ID
391 *
392 * @param integer $id The sco ID
393 * @param integer $organisation an organisation ID - defaults to false if not required
394 * @return mixed (false if there are no scoes or an array)
395 */
396function scorm_get_scoes($id, $organisation=false) {
b44c704f 397 global $DB;
398
27b8872c 399 $queryarray = array('scorm' => $id);
82605bea 400 if (!empty($organisation)) {
b44c704f 401 $queryarray['organization'] = $organisation;
82605bea 402 }
b33e4665
DM
403 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
404 // Drop keys so that it is a simple array as expected.
82605bea 405 $scoes = array_values($scoes);
406 foreach ($scoes as $sco) {
27b8872c 407 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $sco->id))) {
82605bea 408 foreach ($scodatas as $scodata) {
2fd0e9fe 409 $sco->{$scodata->name} = $scodata->value;
82605bea 410 }
411 }
412 }
413 return $scoes;
414 } else {
415 return false;
416 }
417}
418
8d17a43a 419function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false, $trackdata = null) {
86996ffe 420 global $DB, $CFG;
bf347041 421
e4aa175a 422 $id = null;
6381fa56 423
424 if ($forcecompleted) {
27b8872c 425 // TODO - this could be broadened to encompass SCORM 2004 in future.
6381fa56 426 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
27b8872c
N
427 if ($track = $DB->get_record_select('scorm_scoes_track',
428 'userid=? AND scormid=? AND scoid=? AND attempt=? AND element=\'cmi.core.score.raw\'',
429 array($userid, $scormid, $scoid, $attempt))) {
6381fa56 430 $value = 'completed';
431 }
432 }
433 if ($element == 'cmi.core.score.raw') {
27b8872c
N
434 if ($tracktest = $DB->get_record_select('scorm_scoes_track',
435 'userid=? AND scormid=? AND scoid=? AND attempt=? AND element=\'cmi.core.lesson_status\'',
436 array($userid, $scormid, $scoid, $attempt))) {
6381fa56 437 if ($tracktest->value == "incomplete") {
438 $tracktest->value = "completed";
ca4eda13 439 $DB->update_record('scorm_scoes_track', $tracktest);
6381fa56 440 }
441 }
442 }
41e205cd 443 if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
92be6fa4 444 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
dd55ec30
AB
445 $objectiveprogressstatus = true;
446 $objectivesatisfiedstatus = false;
447 if ($value == 'passed') {
448 $objectivesatisfiedstatus = true;
41e205cd
MG
449 }
450
dd55ec30 451 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
92be6fa4
DM
452 'scormid' => $scormid,
453 'scoid' => $scoid,
454 'attempt' => $attempt,
455 'element' => 'objectiveprogressstatus'))) {
41e205cd
MG
456 $track->value = $objectiveprogressstatus;
457 $track->timemodified = time();
458 $DB->update_record('scorm_scoes_track', $track);
459 $id = $track->id;
dd55ec30
AB
460 } else {
461 $track = new stdClass();
41e205cd
MG
462 $track->userid = $userid;
463 $track->scormid = $scormid;
464 $track->scoid = $scoid;
465 $track->attempt = $attempt;
466 $track->element = 'objectiveprogressstatus';
467 $track->value = $objectiveprogressstatus;
468 $track->timemodified = time();
469 $id = $DB->insert_record('scorm_scoes_track', $track);
dd55ec30
AB
470 }
471 if ($objectivesatisfiedstatus) {
92be6fa4
DM
472 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
473 'scormid' => $scormid,
474 'scoid' => $scoid,
475 'attempt' => $attempt,
476 'element' => 'objectivesatisfiedstatus'))) {
41e205cd
MG
477 $track->value = $objectivesatisfiedstatus;
478 $track->timemodified = time();
479 $DB->update_record('scorm_scoes_track', $track);
480 $id = $track->id;
481 } else {
482 $track = new stdClass();
483 $track->userid = $userid;
484 $track->scormid = $scormid;
485 $track->scoid = $scoid;
486 $track->attempt = $attempt;
487 $track->element = 'objectivesatisfiedstatus';
488 $track->value = $objectivesatisfiedstatus;
489 $track->timemodified = time();
490 $id = $DB->insert_record('scorm_scoes_track', $track);
491 ob_start();
dd55ec30
AB
492 $filepath = $CFG->dataroot."\\temp\\tempfile.txt";
493 $fh = fopen($filepath, "a+");
494 var_dump($track);
495 $string = ob_get_clean();
496 fwrite($fh, $string);
497 fclose($fh);
41e205cd
MG
498 }
499 }
500 }
501 }
502
6381fa56 503 }
504
8d17a43a
DS
505 $track = null;
506 if ($trackdata !== null) {
507 if (isset($trackdata[$element])) {
508 $track = $trackdata[$element];
509 }
510 } else {
511 $track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
92be6fa4
DM
512 'scormid' => $scormid,
513 'scoid' => $scoid,
514 'attempt' => $attempt,
8d17a43a
DS
515 'element' => $element));
516 }
517 if ($track) {
92be6fa4 518 if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
8d17a43a
DS
519 if ($track->value != $value) {
520 $track->value = $value;
521 $track->timemodified = time();
522 $DB->update_record('scorm_scoes_track', $track);
523 }
dd88de0e 524 $id = $track->id;
d1818fdc 525 }
e4aa175a 526 } else {
37ca1722 527 $track = new stdClass();
e4aa175a 528 $track->userid = $userid;
529 $track->scormid = $scormid;
530 $track->scoid = $scoid;
531 $track->attempt = $attempt;
532 $track->element = $element;
454f5aee 533 $track->value = $value;
e4aa175a 534 $track->timemodified = time();
ca4eda13 535 $id = $DB->insert_record('scorm_scoes_track', $track);
e4aa175a 536 }
9528568b 537
9528568b 538 if (strstr($element, '.score.raw') ||
94db2749
AB
539 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
540 && in_array($track->value, array('completed', 'passed')))) {
a0b36684 541 $scorm = $DB->get_record('scorm', array('id' => $scormid));
86996ffe 542 include_once($CFG->dirroot.'/mod/scorm/lib.php');
7f7946fd 543 scorm_update_grades($scorm, $userid);
d23121ab 544 }
9528568b 545
e4aa175a 546 return $id;
547}
548
410b7c9b
DM
549/**
550 * simple quick function to return true/false if this user has tracks in this scorm
551 *
552 * @param integer $scormid The scorm ID
553 * @param integer $userid the users id
554 * @return boolean (false if there are no tracks)
555 */
556function scorm_has_tracks($scormid, $userid) {
557 global $DB;
29b24454 558 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
410b7c9b
DM
559}
560
ca4eda13 561function scorm_get_tracks($scoid, $userid, $attempt='') {
b5656373
DM
562 // Gets all tracks of specified sco and user.
563 global $DB;
e4aa175a 564
565 if (empty($attempt)) {
27b8872c 566 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id' => $scoid))) {
ca4eda13 567 $attempt = scorm_get_last_attempt($scormid, $userid);
e4aa175a 568 } else {
569 $attempt = 1;
570 }
571 }
27b8872c
N
572 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid' => $userid, 'scoid' => $scoid,
573 'attempt' => $attempt), 'element ASC')) {
b5656373 574 $usertrack = scorm_format_interactions($tracks);
e4aa175a 575 $usertrack->userid = $userid;
9528568b 576 $usertrack->scoid = $scoid;
b5656373
DM
577
578 return $usertrack;
579 } else {
580 return false;
581 }
582}
583/**
584 * helper function to return a formatted list of interactions for reports.
585 *
586 * @param array $trackdata the records from scorm_scoes_track table
587 * @return object formatted list of interactions
588 */
589function scorm_format_interactions($trackdata) {
590 $usertrack = new stdClass();
591
592 // Defined in order to unify scorm1.2 and scorm2004.
593 $usertrack->score_raw = '';
594 $usertrack->status = '';
595 $usertrack->total_time = '00:00:00';
596 $usertrack->session_time = '00:00:00';
597 $usertrack->timemodified = 0;
598
599 foreach ($trackdata as $track) {
600 $element = $track->element;
601 $usertrack->{$element} = $track->value;
602 switch ($element) {
603 case 'cmi.core.lesson_status':
604 case 'cmi.completion_status':
605 if ($track->value == 'not attempted') {
606 $track->value = 'notattempted';
607 }
608 $usertrack->status = $track->value;
41e205cd 609 break;
b5656373
DM
610 case 'cmi.core.score.raw':
611 case 'cmi.score.raw':
612 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
41e205cd 613 break;
b5656373
DM
614 case 'cmi.core.session_time':
615 case 'cmi.session_time':
616 $usertrack->session_time = $track->value;
41e205cd 617 break;
b5656373
DM
618 case 'cmi.core.total_time':
619 case 'cmi.total_time':
620 $usertrack->total_time = $track->value;
41e205cd 621 break;
3505e82b 622 }
b5656373
DM
623 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
624 $usertrack->timemodified = $track->timemodified;
07b905ae 625 }
e4aa175a 626 }
51c1c4e1 627
b5656373
DM
628 return $usertrack;
629}
51c1c4e1 630/* Find the start and finsh time for a a given SCO attempt
631 *
632 * @param int $scormid SCORM Id
633 * @param int $scoid SCO Id
634 * @param int $userid User Id
635 * @param int $attemt Attempt Id
636 *
637 * @return object start and finsh time EPOC secods
638 *
639 */
640function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
4454447d 641 global $DB;
51c1c4e1 642
39790bd8 643 $timedata = new stdClass();
51c1c4e1 644 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
ca4eda13 645 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
51c1c4e1 646 if ($tracks) {
647 $tracks = array_values($tracks);
648 }
649
c86a91d5 650 if ($tracks) {
51c1c4e1 651 $timedata->start = $tracks[0]->timemodified;
ca4eda13 652 } else {
51c1c4e1 653 $timedata->start = false;
654 }
655 if ($tracks && $track = array_pop($tracks)) {
656 $timedata->finish = $track->timemodified;
ca4eda13 657 } else {
51c1c4e1 658 $timedata->finish = $timedata->start;
659 }
660 return $timedata;
661}
662
c0f6b608 663function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
bf347041 664 global $DB;
37ca1722 665 $attemptscore = new stdClass();
a30b6819 666 $attemptscore->scoes = 0;
667 $attemptscore->values = 0;
668 $attemptscore->max = 0;
669 $attemptscore->sum = 0;
670 $attemptscore->lastmodify = 0;
9528568b 671
b33e4665 672 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
ca4eda13 673 return null;
e4aa175a 674 }
e4aa175a 675
9528568b 676 foreach ($scoes as $sco) {
27b8872c 677 if ($userdata = scorm_get_tracks($sco->id, $userid, $attempt)) {
2b3447c3 678 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
a30b6819 679 $attemptscore->scoes++;
9528568b 680 }
27b8872c 681 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type == 'sco' && isset($userdata->score_raw))) {
a30b6819 682 $attemptscore->values++;
683 $attemptscore->sum += $userdata->score_raw;
27b8872c 684 $attemptscore->max = ($userdata->score_raw > $attemptscore->max) ? $userdata->score_raw : $attemptscore->max;
a30b6819 685 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
686 $attemptscore->lastmodify = $userdata->timemodified;
687 } else {
688 $attemptscore->lastmodify = 0;
689 }
9528568b 690 }
691 }
e4aa175a 692 }
03751efe 693 switch ($scorm->grademethod) {
a30b6819 694 case GRADEHIGHEST:
0d55dd4d 695 $score = (float) $attemptscore->max;
9528568b 696 break;
a30b6819 697 case GRADEAVERAGE:
698 if ($attemptscore->values > 0) {
27b8872c 699 $score = $attemptscore->sum / $attemptscore->values;
5c1ac70c 700 } else {
a30b6819 701 $score = 0;
9528568b 702 }
703 break;
a30b6819 704 case GRADESUM:
705 $score = $attemptscore->sum;
9528568b 706 break;
a30b6819 707 case GRADESCOES:
708 $score = $attemptscore->scoes;
7ef16bf9 709 break;
710 default:
27b8872c 711 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default.
5c1ac70c 712 }
a30b6819 713
c0f6b608 714 return $score;
a30b6819 715}
716
8c5516dc 717function scorm_grade_user($scorm, $userid) {
a30b6819 718
27b8872c 719 // Ensure we dont grade user beyond $scorm->maxattempt settings.
7ce6eb87 720 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
ca4eda13 721 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
7ce6eb87 722 $lastattempt = $scorm->maxattempt;
723 }
724
03751efe 725 switch ($scorm->whatgrade) {
a30b6819 726 case FIRSTATTEMPT:
8c5516dc 727 return scorm_grade_user_attempt($scorm, $userid, 1);
9528568b 728 break;
a30b6819 729 case LASTATTEMPT:
8c5516dc 730 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
a30b6819 731 break;
732 case HIGHESTATTEMPT:
a30b6819 733 $maxscore = 0;
a30b6819 734 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc 735 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
27b8872c 736 $maxscore = $attemptscore > $maxscore ? $attemptscore : $maxscore;
a30b6819 737 }
8c5516dc
DM
738 return $maxscore;
739
a30b6819 740 break;
741 case AVERAGEATTEMPT:
aafb7a5b 742 $attemptcount = scorm_get_attempt_count($userid, $scorm, true, true);
b1ca5d31
DM
743 if (empty($attemptcount)) {
744 return 0;
745 } else {
746 $attemptcount = count($attemptcount);
747 }
a30b6819 748 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
749 $sumscore = 0;
750 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
751 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
752 $sumscore += $attemptscore;
a30b6819 753 }
754
b1ca5d31 755 return round($sumscore / $attemptcount);
a30b6819 756 break;
757 }
e4aa175a 758}
759
ca4eda13 760function scorm_count_launchable($scormid, $organization='') {
bf347041 761 global $DB;
762
763 $sqlorganization = '';
764 $params = array($scormid);
8e45ba45 765 if (!empty($organization)) {
bf347041 766 $sqlorganization = " AND organization=?";
767 $params[] = $organization;
8e45ba45 768 }
ca4eda13 769 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
e4aa175a 770}
771
12287859
DM
772/**
773 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
774 *
775 * @param int $scormid the id of the scorm.
776 * @param int $userid the id of the user.
777 *
778 * @return int The attempt number to use.
779 */
2b3447c3 780function scorm_get_last_attempt($scormid, $userid) {
bf347041 781 global $DB;
782
27b8872c 783 // Find the last attempt number for the given user id and scorm id.
12287859
DM
784 $sql = "SELECT MAX(attempt)
785 FROM {scorm_scoes_track}
786 WHERE userid = ? AND scormid = ?";
787 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
788 if (empty($lastattempt)) {
789 return '1';
6381fa56 790 } else {
12287859 791 return $lastattempt;
e4aa175a 792 }
e4aa175a 793}
794
12287859
DM
795/**
796 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
797 *
798 * @param int $scormid the id of the scorm.
799 * @param int $userid the id of the user.
800 *
801 * @return int The attempt number to use.
802 */
2276208a
DM
803function scorm_get_last_completed_attempt($scormid, $userid) {
804 global $DB;
805
27b8872c 806 // Find the last completed attempt number for the given user id and scorm id.
12287859
DM
807 $sql = "SELECT MAX(attempt)
808 FROM {scorm_scoes_track}
809 WHERE userid = ? AND scormid = ?
810 AND (value='completed' OR value='passed')";
811 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
812 if (empty($lastattempt)) {
813 return '1';
2276208a 814 } else {
12287859 815 return $lastattempt;
2276208a
DM
816 }
817}
818
b5656373
DM
819/**
820 * Returns the full list of attempts a user has made.
821 *
822 * @param int $scormid the id of the scorm.
823 * @param int $userid the id of the user.
824 *
825 * @return array array of attemptids
826 */
827function scorm_get_all_attempts($scormid, $userid) {
828 global $DB;
829 $attemptids = array();
830 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
831 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
832 foreach ($attempts as $attempt) {
833 $attemptids[] = $attempt->attempt;
834 }
835 return $attemptids;
836}
837
39340358 838function scorm_view_display ($user, $scorm, $action, $cm) {
7536464d 839 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
ab3b00e1 840
8aba9cda 841 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
9528568b 842 scorm_parse($scorm, false);
ab3b00e1 843 }
844
e4aa175a 845 $organization = optional_param('organization', '', PARAM_INT);
846
ca4eda13 847 if ($scorm->displaycoursestructure == 1) {
6573b077 848 echo $OUTPUT->box_start('generalbox boxaligncenter toc', 'toc');
27b8872c 849 echo html_writer::div(get_string('contents', 'scorm'), 'structurehead');
6381fa56 850 }
e4aa175a 851 if (empty($organization)) {
852 $organization = $scorm->launch;
853 }
2e3c31bc 854 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
84ab3289
DM
855 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
856 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
b33e4665 857 array($scorm->id), 'sortorder, id', 'id,title')) {
e4aa175a 858 if (count($orgs) > 1) {
edc28287 859 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
ca4eda13 860 $select->label = get_string('organizations', 'scorm');
edc28287
PS
861 $select->class = 'scorm-center';
862 echo $OUTPUT->render($select);
e4aa175a 863 }
864 }
865 $orgidentifier = '';
b3659259 866 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
867 if (($sco->organization == '') && ($sco->launch == '')) {
868 $orgidentifier = $sco->identifier;
e4aa175a 869 } else {
b3659259 870 $orgidentifier = $sco->organization;
e4aa175a 871 }
872 }
28ffbff3 873
27b8872c 874 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe.
dbe7e6f6 875 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
876 $scorm->version = 'scorm_12';
877 }
2b3447c3 878 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
879
ca4eda13 880 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
e4aa175a 881 $incomplete = $result->incomplete;
28ffbff3 882
27b8872c 883 // Do we want the TOC to be displayed?
ca4eda13 884 if ($scorm->displaycoursestructure == 1) {
6381fa56 885 echo $result->toc;
6aff538a 886 echo $OUTPUT->box_end();
6381fa56 887 }
7554f671 888
27b8872c 889 // Is this the first attempt ?
b1ca5d31 890 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
7554f671 891
27b8872c 892 // Do not give the player launch FORM if the SCORM object is locked after the final attempt.
6381fa56 893 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
27b8872c
N
894 echo html_writer::start_div('scorm-center');
895 echo html_writer::start_tag('form', array('id' => 'scormviewform', 'method' => 'post', 'action' => $CFG->wwwroot.'/mod/scorm/player.php'));
ca4eda13
DM
896 if ($scorm->hidebrowse == 0) {
897 print_string('mode', 'scorm');
27b8872c
N
898 echo ': '.html_writer::empty_tag('input', array('type' => 'radio', 'id' => 'b', 'name' => 'mode', 'value' => 'browse')).
899 html_writer::label(get_string('browse', 'scorm'), 'b');
900 echo html_writer::empty_tag('input', array('type' => 'radio', 'id' => 'n', 'name' => 'mode', 'value' => 'normal', 'checked' => 'checked')).
901 html_writer::label(get_string('normal', 'scorm'), 'n');
902
ca4eda13 903 } else {
27b8872c 904 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'mode', 'value' => 'normal'));
ca4eda13
DM
905 }
906 if ($scorm->forcenewattempt == 1) {
907 if ($incomplete === false) {
27b8872c 908 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'newattempt', 'value' => 'on'));
ca4eda13
DM
909 }
910 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
27b8872c 911 echo html_writer::empty_tag('br');
bf4f65fb 912 echo html_writer::checkbox('newattempt', 'on', false, '', array('id' => 'a'));
27b8872c 913 echo html_writer::label(get_string('newattempt', 'scorm'), 'a');
ca4eda13 914 }
3d1808c6 915 if (!empty($scorm->popup)) {
27b8872c 916 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'display', 'value' => 'popup'));
d5159fb8 917 }
27b8872c
N
918
919 echo html_writer::empty_tag('br');
920 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scoid', 'value' => $scorm->launch));
921 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'cm', 'value' => $cm->id));
922 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'currentorg', 'value' => $orgidentifier));
923 echo html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('enter', 'scorm')));
924 echo html_writer::end_tag('form');
925 echo html_writer::end_div();
6381fa56 926 }
e4aa175a 927}
6280b17a 928
666efc14 929function scorm_simple_play($scorm, $user, $context, $cmid) {
bf347041 930 global $DB;
931
9316beca 932 $result = false;
933
27b8872c 934 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
935 return $result;
936 }
9316beca 937
db7f1ca7
DM
938 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
939 scorm_parse($scorm, false);
940 }
b33e4665
DM
941 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
942 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
9316beca 943
7325b016 944 if ($scoes) {
c5803aaa
DM
945 $orgidentifier = '';
946 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
947 if (($sco->organization == '') && ($sco->launch == '')) {
948 $orgidentifier = $sco->identifier;
949 } else {
950 $orgidentifier = $sco->organization;
951 }
952 }
234415c4 953 if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
9316beca 954 $sco = current($scoes);
aab23f98 955 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
27b8872c
N
956 'currentorg' => $orgidentifier,
957 'scoid' => $sco->id));
410b7c9b 958 if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
666efc14
DM
959 if (!empty($scorm->forcenewattempt)) {
960 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
961 if ($result->incomplete === false) {
27b8872c 962 $url->param('newattempt', 'on');
666efc14
DM
963 }
964 }
aab23f98 965 redirect($url);
9316beca 966 }
967 }
968 }
969 return $result;
28ffbff3 970}
d8c9d8a1 971
972function scorm_get_count_users($scormid, $groupingid=null) {
bf347041 973 global $CFG, $DB;
9528568b 974
98da6021 975 if (!empty($groupingid)) {
d8c9d8a1 976 $sql = "SELECT COUNT(DISTINCT st.userid)
bf347041 977 FROM {scorm_scoes_track} st
978 INNER JOIN {groups_members} gm ON st.userid = gm.userid
9528568b 979 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
bf347041 980 WHERE st.scormid = ? AND gg.groupingid = ?
d8c9d8a1 981 ";
bf347041 982 $params = array($scormid, $groupingid);
d8c9d8a1 983 } else {
984 $sql = "SELECT COUNT(DISTINCT st.userid)
9528568b 985 FROM {scorm_scoes_track} st
bf347041 986 WHERE st.scormid = ?
d8c9d8a1 987 ";
bf347041 988 $params = array($scormid);
d8c9d8a1 989 }
9528568b 990
bf347041 991 return ($DB->count_records_sql($sql, $params));
d8c9d8a1 992}
993
527af457 994/**
ca4eda13
DM
995 * Build up the JavaScript representation of an array element
996 *
997 * @param string $sversion SCORM API version
998 * @param array $userdata User track data
27b8872c 999 * @param string $elementname Name of array element to get values for
ca4eda13 1000 * @param array $children list of sub elements of this array element that also need instantiating
ad88d3ed 1001 * @return Javascript array elements
ca4eda13 1002 */
27b8872c
N
1003function scorm_reconstitute_array_element($sversion, $userdata, $elementname, $children) {
1004 // Reconstitute comments_from_learner and comments_from_lms.
527af457 1005 $current = '';
27b8872c
N
1006 $currentsubelement = '';
1007 $currentsub = '';
527af457 1008 $count = 0;
27b8872c 1009 $countsub = 0;
6b635d44 1010 $scormseperator = '_';
139f32c2 1011 $return = '';
27b8872c 1012 if (scorm_version_check($sversion, SCORM_13)) { // Scorm 1.3 elements use a . instead of an _ .
ca4eda13 1013 $scormseperator = '.';
6b635d44 1014 }
27b8872c
N
1015 // Filter out the ones we want.
1016 $elementlist = array();
ca4eda13 1017 foreach ($userdata as $element => $value) {
27b8872c
N
1018 if (substr($element, 0, strlen($elementname)) == $elementname) {
1019 $elementlist[$element] = $value;
527af457 1020 }
1021 }
7554f671 1022
27b8872c
N
1023 // Sort elements in .n array order.
1024 uksort($elementlist, "scorm_element_cmp");
7554f671 1025
27b8872c
N
1026 // Generate JavaScript.
1027 foreach ($elementlist as $element => $value) {
e6402b54 1028 if (scorm_version_check($sversion, SCORM_13)) {
b6293233 1029 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
527af457 1030 preg_match('/\.(N\d+)\./', $element, $matches);
1031 } else {
b6293233 1032 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
527af457 1033 preg_match('/\_(\d+)\./', $element, $matches);
1034 }
1035 if (count($matches) > 0 && $current != $matches[1]) {
3ad5eeed
N
1036 if ($countsub > 0) {
1037 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
bf34ac0f 1038 }
7554f671 1039 $current = $matches[1];
527af457 1040 $count++;
27b8872c
N
1041 $currentsubelement = '';
1042 $currentsub = '';
1043 $countsub = 0;
1044 $end = strpos($element, $matches[1]) + strlen($matches[1]);
ca4eda13 1045 $subelement = substr($element, 0, $end);
139f32c2 1046 $return .= ' '.$subelement." = new Object();\n";
527af457 1047 // now add the children
1048 foreach ($children as $child) {
139f32c2
N
1049 $return .= ' '.$subelement.".".$child." = new Object();\n";
1050 $return .= ' '.$subelement.".".$child."._children = ".$child."_children;\n";
527af457 1051 }
1052 }
7554f671 1053
27b8872c 1054 // Now - flesh out the second level elements if there are any.
e6402b54 1055 if (scorm_version_check($sversion, SCORM_13)) {
b6293233 1056 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
bf34ac0f 1057 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1058 } else {
b6293233 1059 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
bf34ac0f 1060 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1061 }
7554f671 1062
27b8872c 1063 // Check the sub element type.
3ad5eeed
N
1064 if (count($matches) > 0 && $currentsubelement != $matches[1]) {
1065 if ($countsub > 0) {
1066 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
bf34ac0f 1067 }
27b8872c
N
1068 $currentsubelement = $matches[1];
1069 $currentsub = '';
1070 $countsub = 0;
1071 $end = strpos($element, $matches[1]) + strlen($matches[1]);
ca4eda13 1072 $subelement = substr($element, 0, $end);
139f32c2 1073 $return .= ' '.$subelement." = new Object();\n";
bf34ac0f 1074 }
7554f671 1075
27b8872c
N
1076 // Now check the subelement subscript.
1077 if (count($matches) > 0 && $currentsub != $matches[2]) {
1078 $currentsub = $matches[2];
1079 $countsub++;
1080 $end = strrpos($element, $matches[2]) + strlen($matches[2]);
ca4eda13 1081 $subelement = substr($element, 0, $end);
139f32c2 1082 $return .= ' '.$subelement." = new Object();\n";
bf34ac0f 1083 }
7554f671 1084
139f32c2 1085 $return .= ' '.$element.' = \''.$value."';\n";
527af457 1086 }
3ad5eeed
N
1087 if ($countsub > 0) {
1088 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
bf34ac0f 1089 }
527af457 1090 if ($count > 0) {
3ad5eeed 1091 $return .= ' '.$elementname.'._count = '.$count.";\n";
527af457 1092 }
139f32c2 1093 return $return;
527af457 1094}
1095
1096/**
ca4eda13
DM
1097 * Build up the JavaScript representation of an array element
1098 *
1099 * @param string $a left array element
1100 * @param string $b right array element
1101 * @return comparator - 0,1,-1
1102 */
527af457 1103function scorm_element_cmp($a, $b) {
bf34ac0f 1104 preg_match('/.*?(\d+)\./', $a, $matches);
527af457 1105 $left = intval($matches[1]);
bf34ac0f 1106 preg_match('/.?(\d+)\./', $b, $matches);
527af457 1107 $right = intval($matches[1]);
1108 if ($left < $right) {
27b8872c 1109 return -1; // Smaller.
ca4eda13 1110 } else if ($left > $right) {
27b8872c 1111 return 1; // Bigger.
527af457 1112 } else {
27b8872c 1113 // Look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern.
bf34ac0f 1114 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1115 $leftterm = intval($matches[2]);
1116 $left = intval($matches[3]);
1117 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1118 $rightterm = intval($matches[2]);
1119 $right = intval($matches[3]);
1120 if ($leftterm < $rightterm) {
27b8872c 1121 return -1; // Smaller.
ca4eda13 1122 } else if ($leftterm > $rightterm) {
27b8872c 1123 return 1; // Bigger.
bf34ac0f 1124 } else {
1125 if ($left < $right) {
27b8872c 1126 return -1; // Smaller.
ca4eda13 1127 } else if ($left > $right) {
27b8872c 1128 return 1; // Bigger.
bf34ac0f 1129 }
1130 }
1131 }
1132 }
27b8872c
N
1133 // Fall back for no second level matches or second level matches are equal.
1134 return 0; // Equal to.
527af457 1135 }
1136}
6381fa56 1137
1138/**
ca4eda13
DM
1139 * Generate the user attempt status string
1140 *
1141 * @param object $user Current context user
1142 * @param object $scorm a moodle scrom object - mdl_scorm
1143 * @return string - Attempt status string
1144 */
d32e353e
DM
1145function scorm_get_attempt_status($user, $scorm, $cm='') {
1146 global $DB, $PAGE, $OUTPUT;
7554f671 1147
b1ca5d31 1148 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
ca4eda13 1149 if (empty($attempts)) {
6381fa56 1150 $attemptcount = 0;
1151 } else {
1152 $attemptcount = count($attempts);
1153 }
7554f671 1154
27b8872c 1155 $result = html_writer::start_tag('p').get_string('noattemptsallowed', 'scorm').': ';
6381fa56 1156 if ($scorm->maxattempt > 0) {
27b8872c 1157 $result .= $scorm->maxattempt . html_writer::empty_tag('br');
6381fa56 1158 } else {
27b8872c 1159 $result .= get_string('unlimited').html_writer::empty_tag('br');
6381fa56 1160 }
27b8872c 1161 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . html_writer::empty_tag('br');
6381fa56 1162
b1ca5d31
DM
1163 if ($scorm->maxattempt == 1) {
1164 switch ($scorm->grademethod) {
1165 case GRADEHIGHEST:
1166 $grademethod = get_string('gradehighest', 'scorm');
1167 break;
1168 case GRADEAVERAGE:
1169 $grademethod = get_string('gradeaverage', 'scorm');
1170 break;
1171 case GRADESUM:
1172 $grademethod = get_string('gradesum', 'scorm');
1173 break;
1174 case GRADESCOES:
1175 $grademethod = get_string('gradescoes', 'scorm');
1176 break;
1177 }
ca4eda13
DM
1178 } else {
1179 switch ($scorm->whatgrade) {
b1ca5d31
DM
1180 case HIGHESTATTEMPT:
1181 $grademethod = get_string('highestattempt', 'scorm');
1182 break;
1183 case AVERAGEATTEMPT:
1184 $grademethod = get_string('averageattempt', 'scorm');
1185 break;
1186 case FIRSTATTEMPT:
1187 $grademethod = get_string('firstattempt', 'scorm');
1188 break;
1189 case LASTATTEMPT:
1190 $grademethod = get_string('lastattempt', 'scorm');
1191 break;
1192 }
ca4eda13 1193 }
7554f671 1194
ca4eda13 1195 if (!empty($attempts)) {
b1ca5d31 1196 $i = 1;
ca4eda13 1197 foreach ($attempts as $attempt) {
6381fa56 1198 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
4f4a8acf 1199 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
27b8872c
N
1200 $gradereported = $gradereported / $scorm->maxgrade;
1201 $gradereported = number_format($gradereported * 100, 0) .'%';
4f4a8acf 1202 }
27b8872c 1203 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .html_writer::empty_tag('br');
b1ca5d31 1204 $i++;
6381fa56 1205 }
1206 }
b1ca5d31 1207 $calculatedgrade = scorm_grade_user($scorm, $user->id);
4f4a8acf 1208 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
27b8872c
N
1209 $calculatedgrade = $calculatedgrade / $scorm->maxgrade;
1210 $calculatedgrade = number_format($calculatedgrade * 100, 0) .'%';
4f4a8acf 1211 }
6381fa56 1212 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
ca4eda13 1213 if (empty($attempts)) {
27b8872c 1214 $result .= html_writer::empty_tag('br') . get_string('gradereported', 'scorm') . ': ' . get_string('none') . html_writer::empty_tag('br');
6381fa56 1215 } else {
27b8872c 1216 $result .= html_writer::empty_tag('br') . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . html_writer::empty_tag('br');
6381fa56 1217 }
27b8872c 1218 $result .= html_writer::end_tag('p');
6381fa56 1219 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
27b8872c 1220 $result .= html_writer::tag('p', get_string('exceededmaxattempts', 'scorm'), array('class' => 'exceededmaxattempts'));
6381fa56 1221 }
d32e353e
DM
1222 if (!empty($cm)) {
1223 $context = context_module::instance($cm->id);
a12b1d75
DM
1224 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1225 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
27b8872c
N
1226 // Check to see if any data is stored for this user.
1227 $deleteurl = new moodle_url($PAGE->url, array('action' => 'delete', 'sesskey' => sesskey()));
d32e353e
DM
1228 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1229 }
1230 }
1231
6381fa56 1232 return $result;
1233}
1234
1235/**
ca4eda13
DM
1236 * Get SCORM attempt count
1237 *
1238 * @param object $user Current context user
1239 * @param object $scorm a moodle scrom object - mdl_scorm
aafb7a5b
DM
1240 * @param bool $returnobjects if true returns a object with attempts, if false returns count of attempts.
1241 * @param bool $ignoremissingcompletion - ignores attempts that haven't reported a grade/completion.
ca4eda13
DM
1242 * @return int - no. of attempts so far
1243 */
aafb7a5b 1244function scorm_get_attempt_count($userid, $scorm, $returnobjects = false, $ignoremissingcompletion = false) {
6381fa56 1245 global $DB;
aafb7a5b
DM
1246
1247 // Historically attempts that don't report these elements haven't been included in the average attempts grading method
27b8872c 1248 // we may want to change this in future, but to avoid unexpected grade decreases we're leaving this in. MDL-43222 .
e6402b54 1249 if (scorm_version_check($scorm->version, SCORM_13)) {
6381fa56 1250 $element = 'cmi.score.raw';
aafb7a5b
DM
1251 } else if ($scorm->grademethod == GRADESCOES) {
1252 $element = 'cmi.core.lesson_status';
1253 } else {
1254 $element = 'cmi.core.score.raw';
6381fa56 1255 }
aafb7a5b
DM
1256
1257 if ($returnobjects) {
1258 $params = array('userid' => $userid, 'scormid' => $scorm->id);
1259 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1260 $params['element'] = $element;
1261 }
1262 $attempts = $DB->get_records('scorm_scoes_track', $params, 'attempt', 'DISTINCT attempt AS attemptnumber');
e24445c7 1263 return $attempts;
aafb7a5b
DM
1264 } else {
1265 $params = array($userid, $scorm->id);
1266 $sql = "SELECT COUNT(DISTINCT attempt)
1267 FROM {scorm_scoes_track}
eb07f2d8 1268 WHERE userid = ? AND scormid = ?";
aafb7a5b
DM
1269 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1270 $sql .= ' AND element = ?';
1271 $params[] = $element;
1272 }
1273
1274 $attemptscount = $DB->count_records_sql($sql, $params);
1275 return $attemptscount;
e24445c7 1276 }
6381fa56 1277}
1881df27 1278
1279/**
ca4eda13
DM
1280 * Figure out with this is a debug situation
1281 *
1282 * @param object $scorm a moodle scrom object - mdl_scorm
1283 * @return boolean - debugging true/false
1284 */
1881df27 1285function scorm_debugging($scorm) {
1286 global $CFG, $USER;
27b8872c 1287 $cfgscorm = get_config('scorm');
7554f671 1288
27b8872c 1289 if (!$cfgscorm->allowapidebug) {
1881df27 1290 return false;
1291 }
1292 $identifier = $USER->username.':'.$scorm->name;
27b8872c
N
1293 $test = $cfgscorm->apidebugmask;
1294 // Check the regex is only a short list of safe characters.
1881df27 1295 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1296 return false;
1297 }
1298 $res = false;
1299 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1300 return $res;
1301}
7554f671 1302
1303/**
ca4eda13
DM
1304 * Delete Scorm tracks for selected users
1305 *
1306 * @param array $attemptids list of attempts that need to be deleted
0a616190 1307 * @param stdClass $scorm instance
ca4eda13 1308 *
0a616190 1309 * @return bool true deleted all responses, false failed deleting an attempt - stopped here
ca4eda13 1310 */
8716cc35 1311function scorm_delete_responses($attemptids, $scorm) {
ca4eda13 1312 if (!is_array($attemptids) || empty($attemptids)) {
7554f671 1313 return false;
1314 }
1315
ca4eda13
DM
1316 foreach ($attemptids as $num => $attemptid) {
1317 if (empty($attemptid)) {
7554f671 1318 unset($attemptids[$num]);
1319 }
1320 }
1321
ca4eda13 1322 foreach ($attemptids as $attempt) {
7554f671 1323 $keys = explode(':', $attempt);
1324 if (count($keys) == 2) {
1325 $userid = clean_param($keys[0], PARAM_INT);
1326 $attemptid = clean_param($keys[1], PARAM_INT);
8716cc35 1327 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
7554f671 1328 return false;
1329 }
1330 } else {
1331 return false;
1332 }
1333 }
1334 return true;
1335}
1336
1337/**
ca4eda13
DM
1338 * Delete Scorm tracks for selected users
1339 *
1340 * @param int $userid ID of User
0a616190 1341 * @param stdClass $scorm Scorm object
ca4eda13
DM
1342 * @param int $attemptid user attempt that need to be deleted
1343 *
0a616190 1344 * @return bool true suceeded
ca4eda13 1345 */
8716cc35 1346function scorm_delete_attempt($userid, $scorm, $attemptid) {
7554f671 1347 global $DB;
1348
8716cc35 1349 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
0a616190
AA
1350 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1351
1352 // Trigger instances list viewed event.
1353 $event = \mod_scorm\event\attempt_deleted::create(array(
1354 'other' => array('attemptid' => $attemptid),
5971f626 1355 'context' => context_module::instance($cm->id),
0a616190
AA
1356 'relateduserid' => $userid
1357 ));
1358 $event->add_record_snapshot('course_modules', $cm);
1359 $event->add_record_snapshot('scorm', $scorm);
1360 $event->trigger();
1361
8716cc35
DM
1362 include_once('lib.php');
1363 scorm_update_grades($scorm, $userid, true);
7554f671 1364 return true;
1365}
00c1677a
DM
1366
1367/**
2700b283 1368 * Converts SCORM duration notation to human-readable format
00c1677a 1369 * The function works with both SCORM 1.2 and SCORM 2004 time formats
2700b283 1370 * @param $duration string SCORM duration
00c1677a
DM
1371 * @return string human-readable date/time
1372 */
2700b283 1373function scorm_format_duration($duration) {
27b8872c 1374 // Fetch date/time strings.
119d64ee 1375 $stryears = get_string('years');
00c1677a 1376 $strmonths = get_string('nummonths');
119d64ee
DM
1377 $strdays = get_string('days');
1378 $strhours = get_string('hours');
1379 $strminutes = get_string('minutes');
1380 $strseconds = get_string('seconds');
64f93798 1381
2700b283 1382 if ($duration[0] == 'P') {
27b8872c 1383 // If timestamp starts with 'P' - it's a SCORM 2004 format
00c1677a
DM
1384 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1385 // and outputs filled sections, discarding leading zeroes and any format literals
27b8872c 1386 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
00c1677a
DM
1387 $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#',
1388 '#([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
1389 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1390 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
00c1677a 1391 } else {
27b8872c
N
1392 // Else we have SCORM 1.2 format there
1393 // first convert the timestamp to some SCORM 2004-like format for conveniency.
2700b283 1394 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
27b8872c 1395 // Then convert in the same way as SCORM 2004.
00c1677a 1396 $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 1397 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
00c1677a 1398 }
64f93798 1399
2700b283 1400 $result = preg_replace($pattern, $replace, $duration);
00c1677a
DM
1401
1402 return $result;
1403}
0797000a 1404
41e205cd 1405function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
0797000a
DM
1406 global $CFG, $DB, $PAGE, $OUTPUT;
1407
c48c9bf0
DW
1408 // Always pass the mode even if empty as that is what is done elsewhere and the urls have to match.
1409 $modestr = '&mode=';
39355b46
DM
1410 if ($mode != 'normal') {
1411 $modestr = '&mode='.$mode;
0797000a
DM
1412 }
1413
41e205cd 1414 $result = array();
0797000a
DM
1415 $incomplete = false;
1416
41e205cd
MG
1417 if (!empty($organizationsco)) {
1418 $result[0] = $organizationsco;
1419 $result[0]->isvisible = true;
1420 $result[0]->statusicon = '';
1421 $result[0]->url = '';
0797000a
DM
1422 }
1423
27b8872c 1424 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)) {
41e205cd 1425 // Retrieve user tracking data for each learning object.
0797000a
DM
1426 $usertracks = array();
1427 foreach ($scoes as $sco) {
1428 if (!empty($sco->launch)) {
92be6fa4 1429 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
0797000a
DM
1430 if ($usertrack->status == '') {
1431 $usertrack->status = 'notattempted';
1432 }
1433 $usertracks[$sco->identifier] = $usertrack;
1434 }
1435 }
1436 }
41e205cd
MG
1437 foreach ($scoes as $sco) {
1438 if (!isset($sco->isvisible)) {
1439 $sco->isvisible = true;
0797000a 1440 }
41e205cd 1441
0797000a
DM
1442 if (empty($sco->title)) {
1443 $sco->title = $sco->identifier;
1444 }
41e205cd
MG
1445
1446 if (scorm_version_check($scorm->version, SCORM_13)) {
995e322e 1447 $sco->prereq = true;
41e205cd
MG
1448 } else {
1449 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1450 }
1451
1452 if ($sco->isvisible) {
b6c88d75 1453 if (!empty($sco->launch)) {
0797000a
DM
1454 if (empty($scoid) && ($mode != 'normal')) {
1455 $scoid = $sco->id;
1456 }
41e205cd 1457
0797000a
DM
1458 if (isset($usertracks[$sco->identifier])) {
1459 $usertrack = $usertracks[$sco->identifier];
27b8872c 1460 $strstatus = get_string($usertrack->status, 'scorm');
41e205cd 1461
0797000a 1462 if ($sco->scormtype == 'sco') {
27b8872c 1463 $statusicon = html_writer::img($OUTPUT->pix_url($usertrack->status, 'scorm'), $strstatus, array('title' => $strstatus));
0797000a 1464 } else {
27b8872c
N
1465 $statusicon = html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('assetlaunched', 'scorm'),
1466 array('title' => get_string('assetlaunched', 'scorm')));
0797000a
DM
1467 }
1468
1469 if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1470 $incomplete = true;
1471 if ($play && empty($scoid)) {
1472 $scoid = $sco->id;
1473 }
1474 }
41e205cd
MG
1475
1476 $strsuspended = get_string('suspended', 'scorm');
1477
0797000a 1478 $exitvar = 'cmi.core.exit';
41e205cd 1479
e6402b54 1480 if (scorm_version_check($scorm->version, SCORM_13)) {
0797000a
DM
1481 $exitvar = 'cmi.exit';
1482 }
41e205cd 1483
0797000a 1484 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
27b8872c 1485 $statusicon = html_writer::img($OUTPUT->pix_url('suspend', 'scorm'), $strstatus.' - '.$strsuspended, array('title' => $strstatus.' - '.$strsuspended));
0797000a 1486 }
41e205cd 1487
0797000a
DM
1488 } else {
1489 if ($play && empty($scoid)) {
1490 $scoid = $sco->id;
1491 }
41e205cd 1492
0797000a 1493 $incomplete = true;
41e205cd 1494
0797000a 1495 if ($sco->scormtype == 'sco') {
27b8872c
N
1496 $statusicon = html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'), get_string('notattempted', 'scorm'),
1497 array('title' => get_string('notattempted', 'scorm')));
0797000a 1498 } else {
27b8872c 1499 $statusicon = html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('asset', 'scorm'), array('title' => get_string('asset', 'scorm')));
0797000a
DM
1500 }
1501 }
41e205cd
MG
1502 }
1503 }
1504
1505 if (empty($statusicon)) {
27b8872c
N
1506 $sco->statusicon = html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'), get_string('notattempted', 'scorm'),
1507 array('title' => get_string('notattempted', 'scorm')));
41e205cd
MG
1508 } else {
1509 $sco->statusicon = $statusicon;
1510 }
1511
1512 $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
1513 $sco->incomplete = $incomplete;
1514
1515 if (!in_array($sco->id, array_keys($result))) {
1516 $result[$sco->id] = $sco;
1517 }
1518 }
1519 }
0797000a 1520
41e205cd 1521 // Get the parent scoes!
df5c7086 1522 $result = scorm_get_toc_get_parent_child($result, $currentorg);
41e205cd 1523
27b8872c 1524 // Be safe, prevent warnings from showing up while returning array.
41e205cd
MG
1525 if (!isset($scoid)) {
1526 $scoid = '';
1527 }
1528
1529 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1530}
1531
df5c7086 1532function scorm_get_toc_get_parent_child(&$result, $currentorg) {
41e205cd
MG
1533 $final = array();
1534 $level = 0;
df5c7086
MG
1535 // Organization is always the root, prevparent.
1536 if (!empty($currentorg)) {
1537 $prevparent = $currentorg;
1538 } else {
1539 $prevparent = '/';
1540 }
41e205cd
MG
1541
1542 foreach ($result as $sco) {
1543 if ($sco->parent == '/') {
1544 $final[$level][$sco->identifier] = $sco;
1545 $prevparent = $sco->identifier;
1546 unset($result[$sco->id]);
1547 } else {
1548 if ($sco->parent == $prevparent) {
1549 $final[$level][$sco->identifier] = $sco;
1550 $prevparent = $sco->identifier;
1551 unset($result[$sco->id]);
1552 } else {
1553 if (!empty($final[$level])) {
1554 $found = false;
1555 foreach ($final[$level] as $fin) {
1556 if ($sco->parent == $fin->identifier) {
1557 $found = true;
0797000a
DM
1558 }
1559 }
41e205cd
MG
1560
1561 if ($found) {
1562 $final[$level][$sco->identifier] = $sco;
1563 unset($result[$sco->id]);
1564 $found = false;
0797000a 1565 } else {
41e205cd
MG
1566 $level++;
1567 $final[$level][$sco->identifier] = $sco;
1568 unset($result[$sco->id]);
0797000a 1569 }
41e205cd
MG
1570 }
1571 }
1572 }
1573 }
1574
1575 for ($i = 0; $i <= $level; $i++) {
1576 $prevparent = '';
1577 foreach ($final[$i] as $ident => $sco) {
1578 if (empty($prevparent)) {
1579 $prevparent = $ident;
1580 }
d8356656
DM
1581 if (!isset($final[$i][$prevparent]->children)) {
1582 $final[$i][$prevparent]->children = array();
1583 }
41e205cd 1584 if ($sco->parent == $prevparent) {
41e205cd
MG
1585 $final[$i][$prevparent]->children[] = $sco;
1586 $prevparent = $ident;
1587 } else {
1588 $parent = false;
1589 foreach ($final[$i] as $identifier => $scoobj) {
1590 if ($identifier == $sco->parent) {
1591 $parent = $identifier;
1592 }
1593 }
1594
1595 if ($parent !== false) {
1596 $final[$i][$parent]->children[] = $sco;
1597 }
1598 }
1599 }
1600 }
1601
1602 $results = array();
1603 for ($i = 0; $i <= $level; $i++) {
1604 $keys = array_keys($final[$i]);
1605 $results[] = $final[$i][$keys[0]];
1606 }
d8356656 1607
41e205cd
MG
1608 return $results;
1609}
1610
27b8872c
N
1611function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='',
1612 $attempt='', $play=false, $organizationsco=null, $children=false) {
41e205cd
MG
1613 global $CFG;
1614
1615 $result = new stdClass();
1616 $result->prerequisites = true;
d8356656 1617 $result->incomplete = true;
957566eb 1618 $result->toc = '';
41e205cd
MG
1619
1620 if (!$children) {
220e5b52
DM
1621 $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1622 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
41e205cd
MG
1623 }
1624
1625 if (!$children) {
27b8872c 1626 $result->toc = html_writer::start_tag('ul');
41e205cd 1627
27b8872c
N
1628 if (!$play && !empty($organizationsco)) {
1629 $result->toc .= html_writer::start_tag('li').$organizationsco->title.html_writer::end_tag('li');
41e205cd
MG
1630 }
1631 }
1632
1633 $prevsco = '';
1634 if (!empty($scoes)) {
1635 foreach ($scoes as $sco) {
27b8872c 1636 $result->toc .= html_writer::start_tag('li');
41e205cd
MG
1637 $scoid = $sco->id;
1638
1639 $sco->isvisible = true;
1640
1641 if ($sco->isvisible) {
1642 $score = '';
1643
1644 if (isset($usertracks[$sco->identifier])) {
92be6fa4 1645 $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
41e205cd
MG
1646 if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1647 if ($usertracks[$sco->identifier]->score_raw != '') {
27b8872c 1648 $score = '('.get_string('score', 'scorm').':&nbsp;'.$usertracks[$sco->identifier]->score_raw.')';
0797000a 1649 }
41e205cd
MG
1650 }
1651 }
1652
1653 if (!empty($sco->prereq)) {
1654 if ($sco->id == $scoid) {
1655 $result->prerequisites = true;
1656 }
1657
1658 if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1659 if ($sco->scormtype == 'sco') {
27b8872c 1660 $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
41e205cd 1661 } else {
27b8872c 1662 $result->toc .= html_writer::span('&nbsp;'.format_string($sco->title));
41e205cd
MG
1663 }
1664 } else if ($toclink == TOCFULLURL) {
1665 $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
724dc929
MS
1666 if (!empty($sco->launch)) {
1667 if ($sco->scormtype == 'sco') {
27b8872c 1668 $result->toc .= $sco->statusicon.'&nbsp;'.html_writer::link($url, format_string($sco->title)).$score;
724dc929 1669 } else {
27b8872c 1670 $result->toc .= '&nbsp;'.html_writer::link($url, format_string($sco->title), array('data-scoid' => $sco->id)).$score;
724dc929 1671 }
41e205cd 1672 } else {
724dc929 1673 if ($sco->scormtype == 'sco') {
27b8872c 1674 $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title).$score;
724dc929 1675 } else {
27b8872c 1676 $result->toc .= '&nbsp;'.format_string($sco->title).$score;
724dc929 1677 }
41e205cd
MG
1678 }
1679 } else {
724dc929 1680 if (!empty($sco->launch)) {
41e205cd 1681 if ($sco->scormtype == 'sco') {
27b8872c
N
1682 $result->toc .= html_writer::tag('a', $sco->statusicon.'&nbsp;'.format_string($sco->title).'&nbsp;'.$score,
1683 array('data-scoid' => $sco->id, 'title' => $sco->url));
41e205cd 1684 } else {
27b8872c 1685 $result->toc .= html_writer::tag('a', '&nbsp;'.format_string($sco->title).'&nbsp;'.$score, array('data-scoid' => $sco->id, 'title' => $sco->url));
41e205cd
MG
1686 }
1687 } else {
1688 if ($sco->scormtype == 'sco') {
27b8872c 1689 $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
0797000a 1690 } else {
27b8872c 1691 $result->toc .= html_writer::span('&nbsp;'.format_string($sco->title));
0797000a
DM
1692 }
1693 }
41e205cd
MG
1694 }
1695
1696 } else {
1697 if ($play) {
1698 if ($sco->scormtype == 'sco') {
27b8872c 1699 $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
41e205cd 1700 } else {
27b8872c 1701 $result->toc .= '&nbsp;'.format_string($sco->title).html_writer::end_span();
0797000a 1702 }
41e205cd
MG
1703 } else {
1704 if ($sco->scormtype == 'sco') {
27b8872c 1705 $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title);
0797000a 1706 } else {
27b8872c 1707 $result->toc .= '&nbsp;'.format_string($sco->title);
0797000a
DM
1708 }
1709 }
0797000a 1710 }
41e205cd
MG
1711
1712 } else {
27b8872c 1713 $result->toc .= "&nbsp;".format_string($sco->title);
0797000a 1714 }
41e205cd
MG
1715
1716 if (!empty($sco->children)) {
27b8872c 1717 $result->toc .= html_writer::start_tag('ul');
41e205cd
MG
1718 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1719 $result->toc .= $childresult->toc;
27b8872c
N
1720 $result->toc .= html_writer::end_tag('ul');
1721 $result->toc .= html_writer::end_tag('li');
41e205cd 1722 } else {
27b8872c 1723 $result->toc .= html_writer::end_tag('li');
0797000a 1724 }
6917eee8 1725 $prevsco = $sco;
0797000a 1726 }
41e205cd
MG
1727 $result->incomplete = $sco->incomplete;
1728 }
1729
1730 if (!$children) {
27b8872c 1731 $result->toc .= html_writer::end_tag('ul');
41e205cd
MG
1732 }
1733
1734 return $result;
1735}
1736
1737function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1738 if (!empty($scoes)) {
1739 if (!empty($organizationsco) && !$children) {
1740 $tocmenus[$organizationsco->id] = $organizationsco->title;
0797000a
DM
1741 }
1742
27b8872c 1743 $parents[$level] = '/';
41e205cd
MG
1744 foreach ($scoes as $sco) {
1745 if ($parents[$level] != $sco->parent) {
1746 if ($newlevel = array_search($sco->parent, $parents)) {
1747 $level = $newlevel;
1748 } else {
1749 $i = $level;
1750 while (($i > 0) && ($parents[$level] != $sco->parent)) {
1751 $i--;
1752 }
1753
1754 if (($i == 0) && ($sco->parent != $currentorg)) {
1755 $level++;
1756 } else {
1757 $level = $i;
1758 }
1759
1760 $parents[$level] = $sco->parent;
1761 }
1762 }
1763
1764 if ($sco->prereq) {
1765 if ($sco->scormtype == 'sco') {
1766 $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
1767 }
1768 } else {
1769 if ($sco->scormtype == 'sco') {
1770 $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
1771 }
1772 }
1773
1774 if (!empty($sco->children)) {
1775 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
8a4561ac 1776 }
0797000a
DM
1777 }
1778 }
0797000a 1779
41e205cd
MG
1780 return $tocmenus;
1781}
1782
27b8872c
N
1783function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal',
1784 $attempt='', $play=false, $tocheader=false) {
41e205cd
MG
1785 global $CFG, $DB, $OUTPUT;
1786
1787 if (empty($attempt)) {
aafb7a5b 1788 $attempt = scorm_get_last_attempt($scorm->id, $user->id);
41e205cd
MG
1789 }
1790
1791 $result = new stdClass();
1792 $organizationsco = null;
1793
0797000a 1794 if ($tocheader) {
27b8872c
N
1795 $result->toc = html_writer::start_div('yui3-g-r', array('id' => 'scorm_layout'));
1796 $result->toc .= html_writer::start_div('yui3-u-1-5', array('id' => 'scorm_toc'));
1797 $result->toc .= html_writer::div('', '', array('id' => 'scorm_toc_title'));
1798 $result->toc .= html_writer::start_div('', array('id' => 'scorm_tree'));
41e205cd
MG
1799 }
1800
1801 if (!empty($currentorg)) {
27b8872c 1802 $organizationsco = $DB->get_record('scorm_scoes', array('scorm' => $scorm->id, 'identifier' => $currentorg));
41e205cd
MG
1803 if (!empty($organizationsco->title)) {
1804 if ($play) {
1805 $result->toctitle = $organizationsco->title;
1806 }
1807 }
1808 }
1809
1810 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1811
27b8872c
N
1812 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid,
1813 $toclink, $currentorg, $attempt, $play, $organizationsco, false);
41e205cd
MG
1814
1815 if ($tocheader) {
1816 $result->toc .= $treeview->toc;
1817 } else {
1818 $result->toc = $treeview->toc;
1819 }
1820
1821 if (!empty($scoes['scoid'])) {
1822 $scoid = $scoes['scoid'];
1823 }
1824
1825 if (empty($scoid)) {
3c443042 1826 $result->sco = $scoes['scoes'][0]->children[0];
41e205cd
MG
1827 } else {
1828 $result->sco = scorm_get_sco($scoid);
1829 }
1830
1831 if ($scorm->hidetoc == SCORM_TOC_POPUP) {
1832 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $currentorg, $organizationsco);
1833
1834 $modestr = '';
39355b46
DM
1835 if ($mode != 'normal') {
1836 $modestr = '&mode='.$mode;
41e205cd
MG
1837 }
1838
1839 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
dd55ec30 1840 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
0797000a
DM
1841 }
1842
41e205cd
MG
1843 $result->prerequisites = $treeview->prerequisites;
1844 $result->incomplete = $treeview->incomplete;
1845 $result->attemptleft = $treeview->attemptleft;
1846
1847 if ($tocheader) {
27b8872c
N
1848 $result->toc .= html_writer::end_div().html_writer::end_div();
1849 $result->toc .= html_writer::start_div('', array('id' => 'scorm_toc_toggle'));
1850 $result->toc .= html_writer::tag('button', '', array('id' => 'scorm_toc_toggle_btn')).html_writer::end_div();
1851 $result->toc .= html_writer::start_div('', array('id' => 'scorm_content'));
1852 $result->toc .= html_writer::div('', '', array('id' => 'scorm_navpanel'));
1853 $result->toc .= html_writer::end_div().html_writer::end_div();
41e205cd 1854 }
0797000a
DM
1855
1856 return $result;
701570b5 1857}
41e205cd
MG
1858
1859function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1860 if (is_object($scoes)) {
1861 $sco = $scoes;
1862 if (isset($sco->url)) {
1863 $adlnav[$sco->id]['identifier'] = $sco->identifier;
1864 $adlnav[$sco->id]['launch'] = $sco->launch;
1865 $adlnav[$sco->id]['title'] = $sco->title;
1866 $adlnav[$sco->id]['url'] = $sco->url;
1867 $adlnav[$sco->id]['parent'] = $sco->parent;
1868 if (isset($sco->choice)) {
1869 $adlnav[$sco->id]['choice'] = $sco->choice;
1870 }
1871 if (isset($sco->flow)) {
1872 $adlnav[$sco->id]['flow'] = $sco->flow;
1873 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1874 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1875 }
1876 if (isset($sco->isvisible)) {
1877 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1878 }
1879 if (isset($sco->parameters)) {
1880 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1881 }
1882 if (isset($sco->hidecontinue)) {
1883 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1884 }
1885 if (isset($sco->hideprevious)) {
1886 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1887 }
1888 if (isset($sco->hidesuspendall)) {
1889 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1890 }
1891 if (!empty($parentscoid)) {
1892 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1893 }
1894 if (isset($adlnav['prevscoid'])) {
1895 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1896 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1897 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1898 $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1899 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1900 }
1901 }
1902 $adlnav['prevscoid'] = $sco->id;
1903 $adlnav['prevparent'] = $sco->parent;
1904 }
1905 if (isset($sco->children)) {
1906 foreach ($sco->children as $children) {
1907 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1908 }
1909 }
1910 } else {
1911 foreach ($scoes as $sco) {
1912 scorm_get_adlnav_json ($sco, $adlnav);
1913 }
1914 unset($adlnav['prevscoid']);
1915 unset($adlnav['prevparent']);
1916 }
1917 return json_encode($adlnav);
1918}
f833171f
MS
1919
1920/**
1921 * Check for the availability of a resource by URL.
1922 *
1923 * Check is performed using an HTTP HEAD call.
1924 *
1925 * @param $url string A valid URL
1926 * @return bool|string True if no issue is found. The error string message, otherwise
1927 */
1928function scorm_check_url($url) {
1929 $curl = new curl;
90627d9d
1930 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1931 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
f833171f
MS
1932 $cmsg = $curl->head($url);
1933 $info = $curl->get_info();
1934 if (empty($info['http_code']) || $info['http_code'] != 200) {
1935 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
1936 }
1937
1938 return true;
1939}
139f32c2 1940
ad88d3ed
N
1941/**
1942 * Check for a parameter in userdata and return it if it's set
1943 * or return the value from $ifempty if its empty
1944 *
1945 * @param stdClass $userdata Contains user's data
1946 * @param string $param parameter that should be checked
1947 * @param string $ifempty value to be replaced with if $param is not set
1948 * @return string value from $userdata->$param if its not empty, or $ifempty
1949 */
139f32c2
N
1950function scorm_isset($userdata, $param, $ifempty = '') {
1951 if (isset($userdata->$param)) {
1952 return $userdata->$param;
1953 } else {
1954 return $ifempty;
1955 }
1956}
1957
ad88d3ed
N
1958/**
1959 * Check for a parameter in userdata and return it with or without slashes it it's not empty
1960 * or return the value from $ifempty if its empty
1961 *
1962 * @param stdClass $userdata Contains user's data
1963 * @param string $param parameter that should be checked
1964 * @param string $ifempty value to be replaced with if $param is not set
1965 * @param bool $addslash if True - add slashes, if False - Don't add slash
1966 * @return string value from $userdata->$param with or without if its not empty, or $ifempty
1967 */
139f32c2
N
1968function scorm_empty($userdata, $param, $ifempty = '', $addslash = false) {
1969 if (!empty($userdata->$param)) {
1970 return $addslash ? '\''.$userdata->$param.'\'' : $userdata->$param;
1971 } else {
1972 return $ifempty;
1973 }
1974}