MDL-57324 scorm: exclude objective raw.score from grade update
[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 }
7f062ebe 240 if ($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' => '/');
7f062ebe
JL
244 if ($packagefile = $fs->create_file_from_url($filerecord, $scorm->reference, array('calctimeout' => true), true)) {
245 $newhash = $packagefile->get_contenthash();
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.
d92c406a
DM
291 $result = scorm_parse_aicc($scorm);
292 if (!$result) {
9528568b 293 $scorm->version = 'ERROR';
d92c406a
DM
294 } else {
295 $scorm->version = 'AICC';
9528568b 296 }
297 }
298
27b8872c 299 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfgscorm->allowtypeexternal) {
9528568b 300 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
27b8872c 301 // SCORM only, AICC can not be external.
9528568b 302 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
303 $scorm->version = 'ERROR';
304 }
305 $newhash = sha1($scorm->reference);
306
27b8872c 307 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfgscorm->allowtypeexternalaicc) {
4388bd45 308 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
27b8872c 309 // AICC.
d92c406a
DM
310 $result = scorm_parse_aicc($scorm);
311 if (!$result) {
4388bd45 312 $scorm->version = 'ERROR';
d92c406a
DM
313 } else {
314 $scorm->version = 'AICC';
4388bd45 315 }
d92c406a 316
e4aa175a 317 } else {
27b8872c 318 // Sorry, disabled type.
9528568b 319 return;
e4aa175a 320 }
9528568b 321
322 $scorm->revision++;
323 $scorm->sha1hash = $newhash;
324 $DB->update_record('scorm', $scorm);
e4aa175a 325}
326
9528568b 327
2b3447c3 328function scorm_array_search($item, $needle, $haystacks, $strict=false) {
329 if (!empty($haystacks)) {
330 foreach ($haystacks as $key => $element) {
331 if ($strict) {
332 if ($element->{$item} === $needle) {
333 return $key;
334 }
335 } else {
336 if ($element->{$item} == $needle) {
337 return $key;
e4aa175a 338 }
339 }
e4aa175a 340 }
341 }
2b3447c3 342 return false;
e4aa175a 343}
344
2b3447c3 345function scorm_repeater($what, $times) {
346 if ($times <= 0) {
347 return null;
348 }
349 $return = '';
27b8872c 350 for ($i = 0; $i < $times; $i++) {
2b3447c3 351 $return .= $what;
352 }
353 return $return;
354}
e4aa175a 355
2b3447c3 356function scorm_external_link($link) {
27b8872c 357 // Check if a link is external.
2b3447c3 358 $result = false;
359 $link = strtolower($link);
ca4eda13 360 if (substr($link, 0, 7) == 'http://') {
2b3447c3 361 $result = true;
ca4eda13 362 } else if (substr($link, 0, 8) == 'https://') {
2b3447c3 363 $result = true;
ca4eda13 364 } else if (substr($link, 0, 4) == 'www.') {
2b3447c3 365 $result = true;
366 }
367 return $result;
e4aa175a 368}
369
b3659259 370/**
ca4eda13
DM
371 * Returns an object containing all datas relative to the given sco ID
372 *
373 * @param integer $id The sco ID
374 * @return mixed (false if sco id does not exists)
375 */
376function scorm_get_sco($id, $what=SCO_ALL) {
bf347041 377 global $DB;
378
27b8872c 379 if ($sco = $DB->get_record('scorm_scoes', array('id' => $id))) {
b3659259 380 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
27b8872c 381 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id)))) {
b3659259 382 foreach ($scodatas as $scodata) {
c31f631b 383 $sco->{$scodata->name} = $scodata->value;
b3659259 384 }
27b8872c 385 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id))))) {
9528568b 386 $sco->parameters = '';
b3659259 387 }
388 return $sco;
389 } else {
390 return false;
391 }
392}
82605bea 393
394/**
ca4eda13
DM
395 * Returns an object (array) containing all the scoes data related to the given sco ID
396 *
397 * @param integer $id The sco ID
398 * @param integer $organisation an organisation ID - defaults to false if not required
399 * @return mixed (false if there are no scoes or an array)
400 */
401function scorm_get_scoes($id, $organisation=false) {
b44c704f 402 global $DB;
403
27b8872c 404 $queryarray = array('scorm' => $id);
82605bea 405 if (!empty($organisation)) {
b44c704f 406 $queryarray['organization'] = $organisation;
82605bea 407 }
b33e4665
DM
408 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
409 // Drop keys so that it is a simple array as expected.
82605bea 410 $scoes = array_values($scoes);
411 foreach ($scoes as $sco) {
27b8872c 412 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $sco->id))) {
82605bea 413 foreach ($scodatas as $scodata) {
2fd0e9fe 414 $sco->{$scodata->name} = $scodata->value;
82605bea 415 }
416 }
417 }
418 return $scoes;
419 } else {
420 return false;
421 }
422}
423
8d17a43a 424function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false, $trackdata = null) {
86996ffe 425 global $DB, $CFG;
bf347041 426
e4aa175a 427 $id = null;
6381fa56 428
429 if ($forcecompleted) {
27b8872c 430 // TODO - this could be broadened to encompass SCORM 2004 in future.
6381fa56 431 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
27b8872c 432 if ($track = $DB->get_record_select('scorm_scoes_track',
4cb25b36 433 'userid=? AND scormid=? AND scoid=? AND attempt=? '.
434 'AND element=\'cmi.core.score.raw\'',
27b8872c 435 array($userid, $scormid, $scoid, $attempt))) {
6381fa56 436 $value = 'completed';
437 }
438 }
439 if ($element == 'cmi.core.score.raw') {
27b8872c 440 if ($tracktest = $DB->get_record_select('scorm_scoes_track',
4cb25b36 441 'userid=? AND scormid=? AND scoid=? AND attempt=? '.
442 'AND element=\'cmi.core.lesson_status\'',
27b8872c 443 array($userid, $scormid, $scoid, $attempt))) {
6381fa56 444 if ($tracktest->value == "incomplete") {
445 $tracktest->value = "completed";
ca4eda13 446 $DB->update_record('scorm_scoes_track', $tracktest);
6381fa56 447 }
448 }
449 }
41e205cd 450 if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
92be6fa4 451 if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
dd55ec30
AB
452 $objectiveprogressstatus = true;
453 $objectivesatisfiedstatus = false;
454 if ($value == 'passed') {
455 $objectivesatisfiedstatus = true;
41e205cd
MG
456 }
457
dd55ec30 458 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
92be6fa4
DM
459 'scormid' => $scormid,
460 'scoid' => $scoid,
461 'attempt' => $attempt,
462 'element' => 'objectiveprogressstatus'))) {
41e205cd
MG
463 $track->value = $objectiveprogressstatus;
464 $track->timemodified = time();
465 $DB->update_record('scorm_scoes_track', $track);
466 $id = $track->id;
dd55ec30
AB
467 } else {
468 $track = new stdClass();
41e205cd
MG
469 $track->userid = $userid;
470 $track->scormid = $scormid;
471 $track->scoid = $scoid;
472 $track->attempt = $attempt;
473 $track->element = 'objectiveprogressstatus';
474 $track->value = $objectiveprogressstatus;
475 $track->timemodified = time();
476 $id = $DB->insert_record('scorm_scoes_track', $track);
dd55ec30
AB
477 }
478 if ($objectivesatisfiedstatus) {
92be6fa4
DM
479 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
480 'scormid' => $scormid,
481 'scoid' => $scoid,
482 'attempt' => $attempt,
483 'element' => 'objectivesatisfiedstatus'))) {
41e205cd
MG
484 $track->value = $objectivesatisfiedstatus;
485 $track->timemodified = time();
486 $DB->update_record('scorm_scoes_track', $track);
487 $id = $track->id;
488 } else {
489 $track = new stdClass();
490 $track->userid = $userid;
491 $track->scormid = $scormid;
492 $track->scoid = $scoid;
493 $track->attempt = $attempt;
494 $track->element = 'objectivesatisfiedstatus';
495 $track->value = $objectivesatisfiedstatus;
496 $track->timemodified = time();
497 $id = $DB->insert_record('scorm_scoes_track', $track);
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);
f5bc19c8 536 $track->id = $id;
e4aa175a 537 }
9528568b 538
f5bc19c8
MS
539 // Trigger updating grades based on a given set of SCORM CMI elements.
540 $scorm = false;
936030d9 541 if (in_array($element, array('cmi.core.score.raw', 'cmi.score.raw')) ||
94db2749
AB
542 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
543 && in_array($track->value, array('completed', 'passed')))) {
a0b36684 544 $scorm = $DB->get_record('scorm', array('id' => $scormid));
86996ffe 545 include_once($CFG->dirroot.'/mod/scorm/lib.php');
7f7946fd 546 scorm_update_grades($scorm, $userid);
d23121ab 547 }
9528568b 548
f5bc19c8 549 // Trigger CMI element events.
936030d9 550 if (in_array($element, array('cmi.core.score.raw', 'cmi.score.raw')) ||
f5bc19c8
MS
551 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
552 && in_array($track->value, array('completed', 'failed', 'passed')))) {
553 if (!$scorm) {
554 $scorm = $DB->get_record('scorm', array('id' => $scormid));
555 }
556 $cm = get_coursemodule_from_instance('scorm', $scormid);
557 $data = array(
558 'other' => array('attemptid' => $attempt, 'cmielement' => $element, 'cmivalue' => $track->value),
559 'objectid' => $scorm->id,
560 'context' => context_module::instance($cm->id),
561 'relateduserid' => $userid
562 );
936030d9 563 if (in_array($element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
f5bc19c8
MS
564 // Create score submitted event.
565 $event = \mod_scorm\event\scoreraw_submitted::create($data);
566 } else {
567 // Create status submitted event.
568 $event = \mod_scorm\event\status_submitted::create($data);
569 }
beafa1c3
MS
570 // Fix the missing track keys when the SCORM track record already exists, see $trackdata in datamodel.php.
571 // There, for performances reasons, columns are limited to: element, id, value, timemodified.
572 // Missing fields are: userid, scormid, scoid, attempt.
573 $track->userid = $userid;
574 $track->scormid = $scormid;
575 $track->scoid = $scoid;
576 $track->attempt = $attempt;
f5bc19c8
MS
577 // Trigger submitted event.
578 $event->add_record_snapshot('scorm_scoes_track', $track);
579 $event->add_record_snapshot('course_modules', $cm);
580 $event->add_record_snapshot('scorm', $scorm);
581 $event->trigger();
582 }
583
e4aa175a 584 return $id;
585}
586
410b7c9b
DM
587/**
588 * simple quick function to return true/false if this user has tracks in this scorm
589 *
590 * @param integer $scormid The scorm ID
591 * @param integer $userid the users id
592 * @return boolean (false if there are no tracks)
593 */
594function scorm_has_tracks($scormid, $userid) {
595 global $DB;
29b24454 596 return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
410b7c9b
DM
597}
598
ca4eda13 599function scorm_get_tracks($scoid, $userid, $attempt='') {
b5656373
DM
600 // Gets all tracks of specified sco and user.
601 global $DB;
e4aa175a 602
603 if (empty($attempt)) {
27b8872c 604 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id' => $scoid))) {
ca4eda13 605 $attempt = scorm_get_last_attempt($scormid, $userid);
e4aa175a 606 } else {
607 $attempt = 1;
608 }
609 }
27b8872c
N
610 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid' => $userid, 'scoid' => $scoid,
611 'attempt' => $attempt), 'element ASC')) {
b5656373 612 $usertrack = scorm_format_interactions($tracks);
e4aa175a 613 $usertrack->userid = $userid;
9528568b 614 $usertrack->scoid = $scoid;
b5656373
DM
615
616 return $usertrack;
617 } else {
618 return false;
619 }
620}
621/**
622 * helper function to return a formatted list of interactions for reports.
623 *
624 * @param array $trackdata the records from scorm_scoes_track table
625 * @return object formatted list of interactions
626 */
627function scorm_format_interactions($trackdata) {
628 $usertrack = new stdClass();
629
630 // Defined in order to unify scorm1.2 and scorm2004.
631 $usertrack->score_raw = '';
632 $usertrack->status = '';
633 $usertrack->total_time = '00:00:00';
634 $usertrack->session_time = '00:00:00';
635 $usertrack->timemodified = 0;
636
637 foreach ($trackdata as $track) {
638 $element = $track->element;
639 $usertrack->{$element} = $track->value;
640 switch ($element) {
641 case 'cmi.core.lesson_status':
642 case 'cmi.completion_status':
643 if ($track->value == 'not attempted') {
644 $track->value = 'notattempted';
645 }
646 $usertrack->status = $track->value;
41e205cd 647 break;
b5656373
DM
648 case 'cmi.core.score.raw':
649 case 'cmi.score.raw':
650 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
41e205cd 651 break;
b5656373
DM
652 case 'cmi.core.session_time':
653 case 'cmi.session_time':
654 $usertrack->session_time = $track->value;
41e205cd 655 break;
b5656373
DM
656 case 'cmi.core.total_time':
657 case 'cmi.total_time':
658 $usertrack->total_time = $track->value;
41e205cd 659 break;
3505e82b 660 }
b5656373
DM
661 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
662 $usertrack->timemodified = $track->timemodified;
07b905ae 663 }
e4aa175a 664 }
51c1c4e1 665
b5656373
DM
666 return $usertrack;
667}
51c1c4e1 668/* Find the start and finsh time for a a given SCO attempt
669 *
670 * @param int $scormid SCORM Id
671 * @param int $scoid SCO Id
672 * @param int $userid User Id
673 * @param int $attemt Attempt Id
674 *
675 * @return object start and finsh time EPOC secods
676 *
677 */
678function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
4454447d 679 global $DB;
51c1c4e1 680
39790bd8 681 $timedata = new stdClass();
7383195c
DM
682 $params = array('userid' => $userid, 'scormid' => $scormid, 'attempt' => $attempt);
683 if (!empty($scoid)) {
684 $params['scoid'] = $scoid;
685 }
686 $tracks = $DB->get_records('scorm_scoes_track', $params, "timemodified ASC");
51c1c4e1 687 if ($tracks) {
688 $tracks = array_values($tracks);
689 }
690
c86a91d5 691 if ($tracks) {
51c1c4e1 692 $timedata->start = $tracks[0]->timemodified;
ca4eda13 693 } else {
51c1c4e1 694 $timedata->start = false;
695 }
696 if ($tracks && $track = array_pop($tracks)) {
697 $timedata->finish = $track->timemodified;
ca4eda13 698 } else {
51c1c4e1 699 $timedata->finish = $timedata->start;
700 }
701 return $timedata;
702}
703
c0f6b608 704function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
bf347041 705 global $DB;
37ca1722 706 $attemptscore = new stdClass();
a30b6819 707 $attemptscore->scoes = 0;
708 $attemptscore->values = 0;
709 $attemptscore->max = 0;
710 $attemptscore->sum = 0;
711 $attemptscore->lastmodify = 0;
9528568b 712
b33e4665 713 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
ca4eda13 714 return null;
e4aa175a 715 }
e4aa175a 716
9528568b 717 foreach ($scoes as $sco) {
27b8872c 718 if ($userdata = scorm_get_tracks($sco->id, $userid, $attempt)) {
2b3447c3 719 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
a30b6819 720 $attemptscore->scoes++;
9528568b 721 }
27b8872c 722 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type == 'sco' && isset($userdata->score_raw))) {
a30b6819 723 $attemptscore->values++;
724 $attemptscore->sum += $userdata->score_raw;
27b8872c 725 $attemptscore->max = ($userdata->score_raw > $attemptscore->max) ? $userdata->score_raw : $attemptscore->max;
a30b6819 726 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
727 $attemptscore->lastmodify = $userdata->timemodified;
728 } else {
729 $attemptscore->lastmodify = 0;
730 }
9528568b 731 }
732 }
e4aa175a 733 }
03751efe 734 switch ($scorm->grademethod) {
a30b6819 735 case GRADEHIGHEST:
0d55dd4d 736 $score = (float) $attemptscore->max;
9528568b 737 break;
a30b6819 738 case GRADEAVERAGE:
739 if ($attemptscore->values > 0) {
27b8872c 740 $score = $attemptscore->sum / $attemptscore->values;
5c1ac70c 741 } else {
a30b6819 742 $score = 0;
9528568b 743 }
744 break;
a30b6819 745 case GRADESUM:
746 $score = $attemptscore->sum;
9528568b 747 break;
a30b6819 748 case GRADESCOES:
749 $score = $attemptscore->scoes;
7ef16bf9 750 break;
751 default:
27b8872c 752 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default.
5c1ac70c 753 }
a30b6819 754
c0f6b608 755 return $score;
a30b6819 756}
757
8c5516dc 758function scorm_grade_user($scorm, $userid) {
a30b6819 759
27b8872c 760 // Ensure we dont grade user beyond $scorm->maxattempt settings.
7ce6eb87 761 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
ca4eda13 762 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
7ce6eb87 763 $lastattempt = $scorm->maxattempt;
764 }
765
03751efe 766 switch ($scorm->whatgrade) {
a30b6819 767 case FIRSTATTEMPT:
8c5516dc 768 return scorm_grade_user_attempt($scorm, $userid, 1);
9528568b 769 break;
a30b6819 770 case LASTATTEMPT:
8c5516dc 771 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
a30b6819 772 break;
773 case HIGHESTATTEMPT:
a30b6819 774 $maxscore = 0;
a30b6819 775 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc 776 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
27b8872c 777 $maxscore = $attemptscore > $maxscore ? $attemptscore : $maxscore;
a30b6819 778 }
8c5516dc
DM
779 return $maxscore;
780
a30b6819 781 break;
782 case AVERAGEATTEMPT:
aafb7a5b 783 $attemptcount = scorm_get_attempt_count($userid, $scorm, true, true);
b1ca5d31
DM
784 if (empty($attemptcount)) {
785 return 0;
786 } else {
787 $attemptcount = count($attemptcount);
788 }
a30b6819 789 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
790 $sumscore = 0;
791 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
792 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
793 $sumscore += $attemptscore;
a30b6819 794 }
795
b1ca5d31 796 return round($sumscore / $attemptcount);
a30b6819 797 break;
798 }
e4aa175a 799}
800
ca4eda13 801function scorm_count_launchable($scormid, $organization='') {
bf347041 802 global $DB;
803
804 $sqlorganization = '';
805 $params = array($scormid);
8e45ba45 806 if (!empty($organization)) {
bf347041 807 $sqlorganization = " AND organization=?";
808 $params[] = $organization;
8e45ba45 809 }
4cb25b36 810 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".
811 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
812 $params);
e4aa175a 813}
814
12287859
DM
815/**
816 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
817 *
818 * @param int $scormid the id of the scorm.
819 * @param int $userid the id of the user.
820 *
821 * @return int The attempt number to use.
822 */
2b3447c3 823function scorm_get_last_attempt($scormid, $userid) {
bf347041 824 global $DB;
825
27b8872c 826 // Find the last attempt number for the given user id and scorm id.
12287859
DM
827 $sql = "SELECT MAX(attempt)
828 FROM {scorm_scoes_track}
829 WHERE userid = ? AND scormid = ?";
830 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
831 if (empty($lastattempt)) {
832 return '1';
6381fa56 833 } else {
12287859 834 return $lastattempt;
e4aa175a 835 }
e4aa175a 836}
837
12287859
DM
838/**
839 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
840 *
841 * @param int $scormid the id of the scorm.
842 * @param int $userid the id of the user.
843 *
844 * @return int The attempt number to use.
845 */
2276208a
DM
846function scorm_get_last_completed_attempt($scormid, $userid) {
847 global $DB;
848
27b8872c 849 // Find the last completed attempt number for the given user id and scorm id.
12287859
DM
850 $sql = "SELECT MAX(attempt)
851 FROM {scorm_scoes_track}
852 WHERE userid = ? AND scormid = ?
ee8a2e2e
SC
853 AND (".$DB->sql_compare_text('value')." = ".$DB->sql_compare_text('?')." OR ".
854 $DB->sql_compare_text('value')." = ".$DB->sql_compare_text('?').")";
855 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid, 'completed', 'passed'));
12287859
DM
856 if (empty($lastattempt)) {
857 return '1';
2276208a 858 } else {
12287859 859 return $lastattempt;
2276208a
DM
860 }
861}
862
b5656373
DM
863/**
864 * Returns the full list of attempts a user has made.
865 *
866 * @param int $scormid the id of the scorm.
867 * @param int $userid the id of the user.
868 *
869 * @return array array of attemptids
870 */
871function scorm_get_all_attempts($scormid, $userid) {
872 global $DB;
873 $attemptids = array();
874 $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
875 $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
876 foreach ($attempts as $attempt) {
877 $attemptids[] = $attempt->attempt;
878 }
879 return $attemptids;
880}
881
0b9fc18b
JL
882/**
883 * Displays the entry form and toc if required.
884 *
885 * @param stdClass $user user object
886 * @param stdClass $scorm scorm object
887 * @param string $action base URL for the organizations select box
888 * @param stdClass $cm course module object
889 */
890function scorm_print_launch ($user, $scorm, $action, $cm) {
e435f174 891 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
ab3b00e1 892
9e733da7 893 if ($scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
9528568b 894 scorm_parse($scorm, false);
ab3b00e1 895 }
896
e4aa175a 897 $organization = optional_param('organization', '', PARAM_INT);
898
ca4eda13 899 if ($scorm->displaycoursestructure == 1) {
f25185d7 900 echo $OUTPUT->box_start('generalbox boxaligncenter toc container', 'toc');
27b8872c 901 echo html_writer::div(get_string('contents', 'scorm'), 'structurehead');
6381fa56 902 }
e4aa175a 903 if (empty($organization)) {
904 $organization = $scorm->launch;
905 }
2e3c31bc 906 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
84ab3289
DM
907 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
908 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
b33e4665 909 array($scorm->id), 'sortorder, id', 'id,title')) {
e4aa175a 910 if (count($orgs) > 1) {
edc28287 911 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
ca4eda13 912 $select->label = get_string('organizations', 'scorm');
edc28287
PS
913 $select->class = 'scorm-center';
914 echo $OUTPUT->render($select);
e4aa175a 915 }
916 }
917 $orgidentifier = '';
b3659259 918 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
919 if (($sco->organization == '') && ($sco->launch == '')) {
920 $orgidentifier = $sco->identifier;
e4aa175a 921 } else {
b3659259 922 $orgidentifier = $sco->organization;
e4aa175a 923 }
924 }
28ffbff3 925
27b8872c 926 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe.
dbe7e6f6 927 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
928 $scorm->version = 'scorm_12';
929 }
2b3447c3 930 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
931
ca4eda13 932 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
e4aa175a 933 $incomplete = $result->incomplete;
28ffbff3 934
27b8872c 935 // Do we want the TOC to be displayed?
ca4eda13 936 if ($scorm->displaycoursestructure == 1) {
6381fa56 937 echo $result->toc;
6aff538a 938 echo $OUTPUT->box_end();
6381fa56 939 }
7554f671 940
27b8872c 941 // Is this the first attempt ?
b1ca5d31 942 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
7554f671 943
27b8872c 944 // Do not give the player launch FORM if the SCORM object is locked after the final attempt.
6381fa56 945 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
27b8872c 946 echo html_writer::start_div('scorm-center');
4cb25b36 947 echo html_writer::start_tag('form', array('id' => 'scormviewform',
948 'method' => 'post',
f25185d7
DW
949 'action' => $CFG->wwwroot.'/mod/scorm/player.php',
950 'class' => 'container'));
ca4eda13
DM
951 if ($scorm->hidebrowse == 0) {
952 print_string('mode', 'scorm');
1d9356d7
SL
953 echo ': '.html_writer::empty_tag('input', array('type' => 'radio', 'id' => 'b', 'name' => 'mode',
954 'value' => 'browse', 'class' => 'm-r-1')).
27b8872c 955 html_writer::label(get_string('browse', 'scorm'), 'b');
4cb25b36 956 echo html_writer::empty_tag('input', array('type' => 'radio',
957 'id' => 'n', 'name' => 'mode',
1d9356d7
SL
958 'value' => 'normal', 'checked' => 'checked',
959 'class' => 'm-x-1')).
4cb25b36 960 html_writer::label(get_string('normal', 'scorm'), 'n');
27b8872c 961
ca4eda13 962 } else {
27b8872c 963 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'mode', 'value' => 'normal'));
ca4eda13
DM
964 }
965 if ($scorm->forcenewattempt == 1) {
966 if ($incomplete === false) {
27b8872c 967 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'newattempt', 'value' => 'on'));
ca4eda13
DM
968 }
969 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
27b8872c 970 echo html_writer::empty_tag('br');
bf4f65fb 971 echo html_writer::checkbox('newattempt', 'on', false, '', array('id' => 'a'));
27b8872c 972 echo html_writer::label(get_string('newattempt', 'scorm'), 'a');
ca4eda13 973 }
3d1808c6 974 if (!empty($scorm->popup)) {
27b8872c 975 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'display', 'value' => 'popup'));
d5159fb8 976 }
27b8872c
N
977
978 echo html_writer::empty_tag('br');
979 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scoid', 'value' => $scorm->launch));
980 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'cm', 'value' => $cm->id));
981 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'currentorg', 'value' => $orgidentifier));
1d9356d7
SL
982 echo html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('enter', 'scorm'),
983 'class' => 'btn btn-primary'));
27b8872c
N
984 echo html_writer::end_tag('form');
985 echo html_writer::end_div();
6381fa56 986 }
e4aa175a 987}
6280b17a 988
666efc14 989function scorm_simple_play($scorm, $user, $context, $cmid) {
bf347041 990 global $DB;
991
9316beca 992 $result = false;
993
4cb25b36 994 if (has_capability('mod/scorm:viewreport', $context)) {
995 // If this user can view reports, don't skipview so they can see links to reports.
489797d9
DM
996 return $result;
997 }
9316beca 998
9e733da7 999 if ($scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
db7f1ca7
DM
1000 scorm_parse($scorm, false);
1001 }
b33e4665
DM
1002 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
1003 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
9316beca 1004
7325b016 1005 if ($scoes) {
c5803aaa
DM
1006 $orgidentifier = '';
1007 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
1008 if (($sco->organization == '') && ($sco->launch == '')) {
1009 $orgidentifier = $sco->identifier;
1010 } else {
1011 $orgidentifier = $sco->organization;
1012 }
1013 }
234415c4 1014 if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
9316beca 1015 $sco = current($scoes);
aab23f98 1016 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
27b8872c
N
1017 'currentorg' => $orgidentifier,
1018 'scoid' => $sco->id));
410b7c9b 1019 if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
666efc14
DM
1020 if (!empty($scorm->forcenewattempt)) {
1021 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
1022 if ($result->incomplete === false) {
27b8872c 1023 $url->param('newattempt', 'on');
666efc14
DM
1024 }
1025 }
aab23f98 1026 redirect($url);
9316beca 1027 }
1028 }
1029 }
1030 return $result;
28ffbff3 1031}
d8c9d8a1 1032
1033function scorm_get_count_users($scormid, $groupingid=null) {
bf347041 1034 global $CFG, $DB;
9528568b 1035
98da6021 1036 if (!empty($groupingid)) {
d8c9d8a1 1037 $sql = "SELECT COUNT(DISTINCT st.userid)
bf347041 1038 FROM {scorm_scoes_track} st
1039 INNER JOIN {groups_members} gm ON st.userid = gm.userid
9528568b 1040 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
bf347041 1041 WHERE st.scormid = ? AND gg.groupingid = ?
d8c9d8a1 1042 ";
bf347041 1043 $params = array($scormid, $groupingid);
d8c9d8a1 1044 } else {
1045 $sql = "SELECT COUNT(DISTINCT st.userid)
9528568b 1046 FROM {scorm_scoes_track} st
bf347041 1047 WHERE st.scormid = ?
d8c9d8a1 1048 ";
bf347041 1049 $params = array($scormid);
d8c9d8a1 1050 }
9528568b 1051
bf347041 1052 return ($DB->count_records_sql($sql, $params));
d8c9d8a1 1053}
1054
527af457 1055/**
ca4eda13
DM
1056 * Build up the JavaScript representation of an array element
1057 *
1058 * @param string $sversion SCORM API version
1059 * @param array $userdata User track data
27b8872c 1060 * @param string $elementname Name of array element to get values for
ca4eda13 1061 * @param array $children list of sub elements of this array element that also need instantiating
ad88d3ed 1062 * @return Javascript array elements
ca4eda13 1063 */
27b8872c
N
1064function scorm_reconstitute_array_element($sversion, $userdata, $elementname, $children) {
1065 // Reconstitute comments_from_learner and comments_from_lms.
527af457 1066 $current = '';
27b8872c
N
1067 $currentsubelement = '';
1068 $currentsub = '';
527af457 1069 $count = 0;
27b8872c 1070 $countsub = 0;
6b635d44 1071 $scormseperator = '_';
139f32c2 1072 $return = '';
27b8872c 1073 if (scorm_version_check($sversion, SCORM_13)) { // Scorm 1.3 elements use a . instead of an _ .
ca4eda13 1074 $scormseperator = '.';
6b635d44 1075 }
27b8872c
N
1076 // Filter out the ones we want.
1077 $elementlist = array();
ca4eda13 1078 foreach ($userdata as $element => $value) {
27b8872c
N
1079 if (substr($element, 0, strlen($elementname)) == $elementname) {
1080 $elementlist[$element] = $value;
527af457 1081 }
1082 }
7554f671 1083
27b8872c
N
1084 // Sort elements in .n array order.
1085 uksort($elementlist, "scorm_element_cmp");
7554f671 1086
27b8872c
N
1087 // Generate JavaScript.
1088 foreach ($elementlist as $element => $value) {
e6402b54 1089 if (scorm_version_check($sversion, SCORM_13)) {
b6293233 1090 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
527af457 1091 preg_match('/\.(N\d+)\./', $element, $matches);
1092 } else {
b6293233 1093 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
527af457 1094 preg_match('/\_(\d+)\./', $element, $matches);
1095 }
1096 if (count($matches) > 0 && $current != $matches[1]) {
3ad5eeed
N
1097 if ($countsub > 0) {
1098 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
bf34ac0f 1099 }
7554f671 1100 $current = $matches[1];
527af457 1101 $count++;
27b8872c
N
1102 $currentsubelement = '';
1103 $currentsub = '';
1104 $countsub = 0;
1105 $end = strpos($element, $matches[1]) + strlen($matches[1]);
ca4eda13 1106 $subelement = substr($element, 0, $end);
139f32c2 1107 $return .= ' '.$subelement." = new Object();\n";
4cb25b36 1108 // Now add the children.
527af457 1109 foreach ($children as $child) {
139f32c2
N
1110 $return .= ' '.$subelement.".".$child." = new Object();\n";
1111 $return .= ' '.$subelement.".".$child."._children = ".$child."_children;\n";
527af457 1112 }
1113 }
7554f671 1114
27b8872c 1115 // Now - flesh out the second level elements if there are any.
e6402b54 1116 if (scorm_version_check($sversion, SCORM_13)) {
b6293233 1117 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
bf34ac0f 1118 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1119 } else {
b6293233 1120 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
bf34ac0f 1121 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1122 }
7554f671 1123
27b8872c 1124 // Check the sub element type.
3ad5eeed
N
1125 if (count($matches) > 0 && $currentsubelement != $matches[1]) {
1126 if ($countsub > 0) {
1127 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
bf34ac0f 1128 }
27b8872c
N
1129 $currentsubelement = $matches[1];
1130 $currentsub = '';
1131 $countsub = 0;
1132 $end = strpos($element, $matches[1]) + strlen($matches[1]);
ca4eda13 1133 $subelement = substr($element, 0, $end);
139f32c2 1134 $return .= ' '.$subelement." = new Object();\n";
bf34ac0f 1135 }
7554f671 1136
27b8872c
N
1137 // Now check the subelement subscript.
1138 if (count($matches) > 0 && $currentsub != $matches[2]) {
1139 $currentsub = $matches[2];
1140 $countsub++;
1141 $end = strrpos($element, $matches[2]) + strlen($matches[2]);
ca4eda13 1142 $subelement = substr($element, 0, $end);
139f32c2 1143 $return .= ' '.$subelement." = new Object();\n";
bf34ac0f 1144 }
7554f671 1145
d1673b8f 1146 $return .= ' '.$element.' = '.json_encode($value).";\n";
527af457 1147 }
3ad5eeed
N
1148 if ($countsub > 0) {
1149 $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
bf34ac0f 1150 }
527af457 1151 if ($count > 0) {
3ad5eeed 1152 $return .= ' '.$elementname.'._count = '.$count.";\n";
527af457 1153 }
139f32c2 1154 return $return;
527af457 1155}
1156
1157/**
ca4eda13
DM
1158 * Build up the JavaScript representation of an array element
1159 *
1160 * @param string $a left array element
1161 * @param string $b right array element
1162 * @return comparator - 0,1,-1
1163 */
527af457 1164function scorm_element_cmp($a, $b) {
bf34ac0f 1165 preg_match('/.*?(\d+)\./', $a, $matches);
527af457 1166 $left = intval($matches[1]);
bf34ac0f 1167 preg_match('/.?(\d+)\./', $b, $matches);
527af457 1168 $right = intval($matches[1]);
1169 if ($left < $right) {
27b8872c 1170 return -1; // Smaller.
ca4eda13 1171 } else if ($left > $right) {
27b8872c 1172 return 1; // Bigger.
527af457 1173 } else {
27b8872c 1174 // Look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern.
bf34ac0f 1175 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1176 $leftterm = intval($matches[2]);
1177 $left = intval($matches[3]);
1178 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1179 $rightterm = intval($matches[2]);
1180 $right = intval($matches[3]);
1181 if ($leftterm < $rightterm) {
27b8872c 1182 return -1; // Smaller.
ca4eda13 1183 } else if ($leftterm > $rightterm) {
27b8872c 1184 return 1; // Bigger.
bf34ac0f 1185 } else {
1186 if ($left < $right) {
27b8872c 1187 return -1; // Smaller.
ca4eda13 1188 } else if ($left > $right) {
27b8872c 1189 return 1; // Bigger.
bf34ac0f 1190 }
1191 }
1192 }
1193 }
27b8872c
N
1194 // Fall back for no second level matches or second level matches are equal.
1195 return 0; // Equal to.
527af457 1196 }
1197}
6381fa56 1198
1199/**
ca4eda13
DM
1200 * Generate the user attempt status string
1201 *
1202 * @param object $user Current context user
1203 * @param object $scorm a moodle scrom object - mdl_scorm
1204 * @return string - Attempt status string
1205 */
d32e353e
DM
1206function scorm_get_attempt_status($user, $scorm, $cm='') {
1207 global $DB, $PAGE, $OUTPUT;
7554f671 1208
b1ca5d31 1209 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
ca4eda13 1210 if (empty($attempts)) {
6381fa56 1211 $attemptcount = 0;
1212 } else {
1213 $attemptcount = count($attempts);
1214 }
7554f671 1215
27b8872c 1216 $result = html_writer::start_tag('p').get_string('noattemptsallowed', 'scorm').': ';
6381fa56 1217 if ($scorm->maxattempt > 0) {
27b8872c 1218 $result .= $scorm->maxattempt . html_writer::empty_tag('br');
6381fa56 1219 } else {
27b8872c 1220 $result .= get_string('unlimited').html_writer::empty_tag('br');
6381fa56 1221 }
27b8872c 1222 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . html_writer::empty_tag('br');
6381fa56 1223
b1ca5d31
DM
1224 if ($scorm->maxattempt == 1) {
1225 switch ($scorm->grademethod) {
1226 case GRADEHIGHEST:
1227 $grademethod = get_string('gradehighest', 'scorm');
1228 break;
1229 case GRADEAVERAGE:
1230 $grademethod = get_string('gradeaverage', 'scorm');
1231 break;
1232 case GRADESUM:
1233 $grademethod = get_string('gradesum', 'scorm');
1234 break;
1235 case GRADESCOES:
1236 $grademethod = get_string('gradescoes', 'scorm');
1237 break;
1238 }
ca4eda13
DM
1239 } else {
1240 switch ($scorm->whatgrade) {
b1ca5d31
DM
1241 case HIGHESTATTEMPT:
1242 $grademethod = get_string('highestattempt', 'scorm');
1243 break;
1244 case AVERAGEATTEMPT:
1245 $grademethod = get_string('averageattempt', 'scorm');
1246 break;
1247 case FIRSTATTEMPT:
1248 $grademethod = get_string('firstattempt', 'scorm');
1249 break;
1250 case LASTATTEMPT:
1251 $grademethod = get_string('lastattempt', 'scorm');
1252 break;
1253 }
ca4eda13 1254 }
7554f671 1255
ca4eda13 1256 if (!empty($attempts)) {
b1ca5d31 1257 $i = 1;
ca4eda13 1258 foreach ($attempts as $attempt) {
6381fa56 1259 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
4f4a8acf 1260 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
27b8872c
N
1261 $gradereported = $gradereported / $scorm->maxgrade;
1262 $gradereported = number_format($gradereported * 100, 0) .'%';
4f4a8acf 1263 }
27b8872c 1264 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .html_writer::empty_tag('br');
b1ca5d31 1265 $i++;
6381fa56 1266 }
1267 }
b1ca5d31 1268 $calculatedgrade = scorm_grade_user($scorm, $user->id);
4f4a8acf 1269 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
27b8872c
N
1270 $calculatedgrade = $calculatedgrade / $scorm->maxgrade;
1271 $calculatedgrade = number_format($calculatedgrade * 100, 0) .'%';
4f4a8acf 1272 }
6381fa56 1273 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
ca4eda13 1274 if (empty($attempts)) {
4cb25b36 1275 $result .= html_writer::empty_tag('br').get_string('gradereported', 'scorm').
1276 ': '.get_string('none').html_writer::empty_tag('br');
6381fa56 1277 } else {
4cb25b36 1278 $result .= html_writer::empty_tag('br').get_string('gradereported', 'scorm').
1279 ': '.$calculatedgrade.html_writer::empty_tag('br');
6381fa56 1280 }
27b8872c 1281 $result .= html_writer::end_tag('p');
6381fa56 1282 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
27b8872c 1283 $result .= html_writer::tag('p', get_string('exceededmaxattempts', 'scorm'), array('class' => 'exceededmaxattempts'));
6381fa56 1284 }
d32e353e
DM
1285 if (!empty($cm)) {
1286 $context = context_module::instance($cm->id);
a12b1d75
DM
1287 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1288 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
27b8872c
N
1289 // Check to see if any data is stored for this user.
1290 $deleteurl = new moodle_url($PAGE->url, array('action' => 'delete', 'sesskey' => sesskey()));
d32e353e
DM
1291 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1292 }
1293 }
1294
6381fa56 1295 return $result;
1296}
1297
1298/**
ca4eda13
DM
1299 * Get SCORM attempt count
1300 *
1301 * @param object $user Current context user
1302 * @param object $scorm a moodle scrom object - mdl_scorm
aafb7a5b
DM
1303 * @param bool $returnobjects if true returns a object with attempts, if false returns count of attempts.
1304 * @param bool $ignoremissingcompletion - ignores attempts that haven't reported a grade/completion.
ca4eda13
DM
1305 * @return int - no. of attempts so far
1306 */
aafb7a5b 1307function scorm_get_attempt_count($userid, $scorm, $returnobjects = false, $ignoremissingcompletion = false) {
6381fa56 1308 global $DB;
aafb7a5b
DM
1309
1310 // Historically attempts that don't report these elements haven't been included in the average attempts grading method
27b8872c 1311 // we may want to change this in future, but to avoid unexpected grade decreases we're leaving this in. MDL-43222 .
e6402b54 1312 if (scorm_version_check($scorm->version, SCORM_13)) {
6381fa56 1313 $element = 'cmi.score.raw';
aafb7a5b
DM
1314 } else if ($scorm->grademethod == GRADESCOES) {
1315 $element = 'cmi.core.lesson_status';
1316 } else {
1317 $element = 'cmi.core.score.raw';
6381fa56 1318 }
aafb7a5b
DM
1319
1320 if ($returnobjects) {
1321 $params = array('userid' => $userid, 'scormid' => $scorm->id);
1322 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1323 $params['element'] = $element;
1324 }
1325 $attempts = $DB->get_records('scorm_scoes_track', $params, 'attempt', 'DISTINCT attempt AS attemptnumber');
e24445c7 1326 return $attempts;
aafb7a5b
DM
1327 } else {
1328 $params = array($userid, $scorm->id);
1329 $sql = "SELECT COUNT(DISTINCT attempt)
1330 FROM {scorm_scoes_track}
eb07f2d8 1331 WHERE userid = ? AND scormid = ?";
aafb7a5b
DM
1332 if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
1333 $sql .= ' AND element = ?';
1334 $params[] = $element;
1335 }
1336
1337 $attemptscount = $DB->count_records_sql($sql, $params);
1338 return $attemptscount;
e24445c7 1339 }
6381fa56 1340}
1881df27 1341
1342/**
ca4eda13
DM
1343 * Figure out with this is a debug situation
1344 *
1345 * @param object $scorm a moodle scrom object - mdl_scorm
1346 * @return boolean - debugging true/false
1347 */
1881df27 1348function scorm_debugging($scorm) {
524aaa17 1349 global $USER;
27b8872c 1350 $cfgscorm = get_config('scorm');
7554f671 1351
27b8872c 1352 if (!$cfgscorm->allowapidebug) {
1881df27 1353 return false;
1354 }
1355 $identifier = $USER->username.':'.$scorm->name;
27b8872c
N
1356 $test = $cfgscorm->apidebugmask;
1357 // Check the regex is only a short list of safe characters.
1881df27 1358 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1359 return false;
1360 }
524aaa17
DM
1361
1362 if (preg_match('/^'.$test.'/', $identifier)) {
1363 return true;
1364 }
1365 return false;
1881df27 1366}
7554f671 1367
1368/**
ca4eda13
DM
1369 * Delete Scorm tracks for selected users
1370 *
1371 * @param array $attemptids list of attempts that need to be deleted
0a616190 1372 * @param stdClass $scorm instance
ca4eda13 1373 *
0a616190 1374 * @return bool true deleted all responses, false failed deleting an attempt - stopped here
ca4eda13 1375 */
8716cc35 1376function scorm_delete_responses($attemptids, $scorm) {
ca4eda13 1377 if (!is_array($attemptids) || empty($attemptids)) {
7554f671 1378 return false;
1379 }
1380
ca4eda13
DM
1381 foreach ($attemptids as $num => $attemptid) {
1382 if (empty($attemptid)) {
7554f671 1383 unset($attemptids[$num]);
1384 }
1385 }
1386
ca4eda13 1387 foreach ($attemptids as $attempt) {
7554f671 1388 $keys = explode(':', $attempt);
1389 if (count($keys) == 2) {
1390 $userid = clean_param($keys[0], PARAM_INT);
1391 $attemptid = clean_param($keys[1], PARAM_INT);
8716cc35 1392 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
7554f671 1393 return false;
1394 }
1395 } else {
1396 return false;
1397 }
1398 }
1399 return true;
1400}
1401
1402/**
ca4eda13
DM
1403 * Delete Scorm tracks for selected users
1404 *
1405 * @param int $userid ID of User
0a616190 1406 * @param stdClass $scorm Scorm object
ca4eda13
DM
1407 * @param int $attemptid user attempt that need to be deleted
1408 *
0a616190 1409 * @return bool true suceeded
ca4eda13 1410 */
8716cc35 1411function scorm_delete_attempt($userid, $scorm, $attemptid) {
7554f671 1412 global $DB;
1413
8716cc35 1414 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
0a616190
AA
1415 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1416
1417 // Trigger instances list viewed event.
1418 $event = \mod_scorm\event\attempt_deleted::create(array(
1419 'other' => array('attemptid' => $attemptid),
5971f626 1420 'context' => context_module::instance($cm->id),
0a616190
AA
1421 'relateduserid' => $userid
1422 ));
1423 $event->add_record_snapshot('course_modules', $cm);
1424 $event->add_record_snapshot('scorm', $scorm);
1425 $event->trigger();
1426
8716cc35
DM
1427 include_once('lib.php');
1428 scorm_update_grades($scorm, $userid, true);
7554f671 1429 return true;
1430}
00c1677a
DM
1431
1432/**
2700b283 1433 * Converts SCORM duration notation to human-readable format
00c1677a 1434 * The function works with both SCORM 1.2 and SCORM 2004 time formats
2700b283 1435 * @param $duration string SCORM duration
00c1677a
DM
1436 * @return string human-readable date/time
1437 */
2700b283 1438function scorm_format_duration($duration) {
27b8872c 1439 // Fetch date/time strings.
119d64ee 1440 $stryears = get_string('years');
00c1677a 1441 $strmonths = get_string('nummonths');
119d64ee
DM
1442 $strdays = get_string('days');
1443 $strhours = get_string('hours');
1444 $strminutes = get_string('minutes');
1445 $strseconds = get_string('seconds');
64f93798 1446
2700b283 1447 if ($duration[0] == 'P') {
27b8872c 1448 // If timestamp starts with 'P' - it's a SCORM 2004 format
00c1677a
DM
1449 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1450 // and outputs filled sections, discarding leading zeroes and any format literals
27b8872c 1451 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
4cb25b36 1452 $pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#',
1453 '#0*(\d+)Y#', '#0*(\d+)D#', '#P#', '#([A-Z])0+H#', '#([A-Z])[0.]+S#',
1454 '#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#',
1455 '#0*([\d.]+)S#', '#T#' );
1456 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ',
1457 '', '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ',
1458 '0.$1 '.$strseconds, '$1 '.$strseconds, '');
00c1677a 1459 } else {
27b8872c
N
1460 // Else we have SCORM 1.2 format there
1461 // first convert the timestamp to some SCORM 2004-like format for conveniency.
2700b283 1462 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
27b8872c 1463 // Then convert in the same way as SCORM 2004.
4cb25b36 1464 $pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#',
1465 '#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
1466 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ',
1467 '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
00c1677a 1468 }
64f93798 1469
2700b283 1470 $result = preg_replace($pattern, $replace, $duration);
00c1677a
DM
1471
1472 return $result;
1473}
0797000a 1474
4cb25b36 1475function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='',
1476 $play=false, $organizationsco=null) {
0797000a
DM
1477 global $CFG, $DB, $PAGE, $OUTPUT;
1478
c48c9bf0
DW
1479 // Always pass the mode even if empty as that is what is done elsewhere and the urls have to match.
1480 $modestr = '&mode=';
39355b46
DM
1481 if ($mode != 'normal') {
1482 $modestr = '&mode='.$mode;
0797000a
DM
1483 }
1484
41e205cd 1485 $result = array();
0797000a
DM
1486 $incomplete = false;
1487
41e205cd
MG
1488 if (!empty($organizationsco)) {
1489 $result[0] = $organizationsco;
7f28e8a5 1490 $result[0]->isvisible = 'true';
41e205cd
MG
1491 $result[0]->statusicon = '';
1492 $result[0]->url = '';
0797000a
DM
1493 }
1494
27b8872c 1495 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)) {
41e205cd 1496 // Retrieve user tracking data for each learning object.
0797000a
DM
1497 $usertracks = array();
1498 foreach ($scoes as $sco) {
1499 if (!empty($sco->launch)) {
92be6fa4 1500 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
0797000a
DM
1501 if ($usertrack->status == '') {
1502 $usertrack->status = 'notattempted';
1503 }
1504 $usertracks[$sco->identifier] = $usertrack;
1505 }
1506 }
1507 }
41e205cd
MG
1508 foreach ($scoes as $sco) {
1509 if (!isset($sco->isvisible)) {
7f28e8a5 1510 $sco->isvisible = 'true';
0797000a 1511 }
41e205cd 1512
0797000a
DM
1513 if (empty($sco->title)) {
1514 $sco->title = $sco->identifier;
1515 }
41e205cd
MG
1516
1517 if (scorm_version_check($scorm->version, SCORM_13)) {
995e322e 1518 $sco->prereq = true;
41e205cd
MG
1519 } else {
1520 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1521 }
1522
7f28e8a5 1523 if ($sco->isvisible === 'true') {
b6c88d75 1524 if (!empty($sco->launch)) {
0797000a
DM
1525 if (empty($scoid) && ($mode != 'normal')) {
1526 $scoid = $sco->id;
1527 }
41e205cd 1528
0797000a
DM
1529 if (isset($usertracks[$sco->identifier])) {
1530 $usertrack = $usertracks[$sco->identifier];
27b8872c 1531 $strstatus = get_string($usertrack->status, 'scorm');
41e205cd 1532
0797000a 1533 if ($sco->scormtype == 'sco') {
4cb25b36 1534 $statusicon = html_writer::img($OUTPUT->pix_url($usertrack->status, 'scorm'), $strstatus,
1535 array('title' => $strstatus));
0797000a 1536 } else {
27b8872c
N
1537 $statusicon = html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('assetlaunched', 'scorm'),
1538 array('title' => get_string('assetlaunched', 'scorm')));
0797000a
DM
1539 }
1540
4cb25b36 1541 if (($usertrack->status == 'notattempted') ||
1542 ($usertrack->status == 'incomplete') ||
1543 ($usertrack->status == 'browsed')) {
0797000a
DM
1544 $incomplete = true;
1545 if ($play && empty($scoid)) {
1546 $scoid = $sco->id;
1547 }
1548 }
41e205cd
MG
1549
1550 $strsuspended = get_string('suspended', 'scorm');
1551
0797000a 1552 $exitvar = 'cmi.core.exit';
41e205cd 1553
e6402b54 1554 if (scorm_version_check($scorm->version, SCORM_13)) {
0797000a
DM
1555 $exitvar = 'cmi.exit';
1556 }
41e205cd 1557
0797000a 1558 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
4cb25b36 1559 $statusicon = html_writer::img($OUTPUT->pix_url('suspend', 'scorm'), $strstatus.' - '.$strsuspended,
1560 array('title' => $strstatus.' - '.$strsuspended));
0797000a 1561 }
41e205cd 1562
0797000a
DM
1563 } else {
1564 if ($play && empty($scoid)) {
1565 $scoid = $sco->id;
1566 }
41e205cd 1567
0797000a 1568 $incomplete = true;
41e205cd 1569
0797000a 1570 if ($sco->scormtype == 'sco') {
4cb25b36 1571 $statusicon = html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'),
1572 get_string('notattempted', 'scorm'),
27b8872c 1573 array('title' => get_string('notattempted', 'scorm')));
0797000a 1574 } else {
4cb25b36 1575 $statusicon = html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('asset', 'scorm'),
1576 array('title' => get_string('asset', 'scorm')));
0797000a
DM
1577 }
1578 }
41e205cd
MG
1579 }
1580 }
1581
1582 if (empty($statusicon)) {
27b8872c
N
1583 $sco->statusicon = html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'), get_string('notattempted', 'scorm'),
1584 array('title' => get_string('notattempted', 'scorm')));
41e205cd
MG
1585 } else {
1586 $sco->statusicon = $statusicon;
1587 }
1588
1589 $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
1590 $sco->incomplete = $incomplete;
1591
1592 if (!in_array($sco->id, array_keys($result))) {
1593 $result[$sco->id] = $sco;
1594 }
1595 }
1596 }
0797000a 1597
41e205cd 1598 // Get the parent scoes!
df5c7086 1599 $result = scorm_get_toc_get_parent_child($result, $currentorg);
41e205cd 1600
27b8872c 1601 // Be safe, prevent warnings from showing up while returning array.
41e205cd
MG
1602 if (!isset($scoid)) {
1603 $scoid = '';
1604 }
1605
1606 return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1607}
1608
df5c7086 1609function scorm_get_toc_get_parent_child(&$result, $currentorg) {
41e205cd
MG
1610 $final = array();
1611 $level = 0;
df5c7086
MG
1612 // Organization is always the root, prevparent.
1613 if (!empty($currentorg)) {
1614 $prevparent = $currentorg;
1615 } else {
1616 $prevparent = '/';
1617 }
41e205cd
MG
1618
1619 foreach ($result as $sco) {
1620 if ($sco->parent == '/') {
1621 $final[$level][$sco->identifier] = $sco;
1622 $prevparent = $sco->identifier;
1623 unset($result[$sco->id]);
1624 } else {
1625 if ($sco->parent == $prevparent) {
1626 $final[$level][$sco->identifier] = $sco;
1627 $prevparent = $sco->identifier;
1628 unset($result[$sco->id]);
1629 } else {
1630 if (!empty($final[$level])) {
1631 $found = false;
1632 foreach ($final[$level] as $fin) {
1633 if ($sco->parent == $fin->identifier) {
1634 $found = true;
0797000a
DM
1635 }
1636 }
41e205cd
MG
1637
1638 if ($found) {
1639 $final[$level][$sco->identifier] = $sco;
1640 unset($result[$sco->id]);
1641 $found = false;
0797000a 1642 } else {
41e205cd
MG
1643 $level++;
1644 $final[$level][$sco->identifier] = $sco;
1645 unset($result[$sco->id]);
0797000a 1646 }
41e205cd
MG
1647 }
1648 }
1649 }
1650 }
1651
1652 for ($i = 0; $i <= $level; $i++) {
1653 $prevparent = '';
1654 foreach ($final[$i] as $ident => $sco) {
1655 if (empty($prevparent)) {
1656 $prevparent = $ident;
1657 }
d8356656
DM
1658 if (!isset($final[$i][$prevparent]->children)) {
1659 $final[$i][$prevparent]->children = array();
1660 }
41e205cd 1661 if ($sco->parent == $prevparent) {
41e205cd
MG
1662 $final[$i][$prevparent]->children[] = $sco;
1663 $prevparent = $ident;
1664 } else {
1665 $parent = false;
1666 foreach ($final[$i] as $identifier => $scoobj) {
1667 if ($identifier == $sco->parent) {
1668 $parent = $identifier;
1669 }
1670 }
1671
1672 if ($parent !== false) {
1673 $final[$i][$parent]->children[] = $sco;
1674 }
1675 }
1676 }
1677 }
1678
1679 $results = array();
1680 for ($i = 0; $i <= $level; $i++) {
1681 $keys = array_keys($final[$i]);
1682 $results[] = $final[$i][$keys[0]];
1683 }
d8356656 1684
41e205cd
MG
1685 return $results;
1686}
1687
27b8872c
N
1688function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='',
1689 $attempt='', $play=false, $organizationsco=null, $children=false) {
41e205cd
MG
1690 global $CFG;
1691
1692 $result = new stdClass();
1693 $result->prerequisites = true;
d8356656 1694 $result->incomplete = true;
957566eb 1695 $result->toc = '';
41e205cd
MG
1696
1697 if (!$children) {
220e5b52
DM
1698 $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1699 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
41e205cd
MG
1700 }
1701
1702 if (!$children) {
27b8872c 1703 $result->toc = html_writer::start_tag('ul');
41e205cd 1704
27b8872c
N
1705 if (!$play && !empty($organizationsco)) {
1706 $result->toc .= html_writer::start_tag('li').$organizationsco->title.html_writer::end_tag('li');
41e205cd
MG
1707 }
1708 }
1709
1710 $prevsco = '';
1711 if (!empty($scoes)) {
1712 foreach ($scoes as $sco) {
7f28e8a5
JL
1713
1714 if ($sco->isvisible === 'false') {
1715 continue;
1716 }
1717
27b8872c 1718 $result->toc .= html_writer::start_tag('li');
41e205cd
MG
1719 $scoid = $sco->id;
1720
7f28e8a5 1721 $score = '';
41e205cd 1722
7f28e8a5
JL
1723 if (isset($usertracks[$sco->identifier])) {
1724 $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
1725 if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1726 if ($usertracks[$sco->identifier]->score_raw != '') {
1727 $score = '('.get_string('score', 'scorm').':&nbsp;'.$usertracks[$sco->identifier]->score_raw.')';
41e205cd
MG
1728 }
1729 }
7f28e8a5 1730 }
41e205cd 1731
7f28e8a5
JL
1732 if (!empty($sco->prereq)) {
1733 if ($sco->id == $scoid) {
1734 $result->prerequisites = true;
1735 }
41e205cd 1736
7f28e8a5
JL
1737 if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1738 if ($sco->scormtype == 'sco') {
1739 $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
1740 } else {
1741 $result->toc .= html_writer::span('&nbsp;'.format_string($sco->title));
1742 }
1743 } else if ($toclink == TOCFULLURL) {
1744 $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
1745 if (!empty($sco->launch)) {
41e205cd 1746 if ($sco->scormtype == 'sco') {
7f28e8a5
JL
1747 $result->toc .= $sco->statusicon.'&nbsp;';
1748 $result->toc .= html_writer::link($url, format_string($sco->title)).$score;
41e205cd 1749 } else {
7f28e8a5
JL
1750 $result->toc .= '&nbsp;'.html_writer::link($url, format_string($sco->title),
1751 array('data-scoid' => $sco->id)).$score;
41e205cd
MG
1752 }
1753 } else {
7f28e8a5
JL
1754 if ($sco->scormtype == 'sco') {
1755 $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title).$score;
41e205cd 1756 } else {
7f28e8a5 1757 $result->toc .= '&nbsp;'.format_string($sco->title).$score;
0797000a 1758 }
41e205cd 1759 }
41e205cd 1760 } else {
7f28e8a5 1761 if (!empty($sco->launch)) {
41e205cd 1762 if ($sco->scormtype == 'sco') {
7f28e8a5
JL
1763 $result->toc .= html_writer::tag('a', $sco->statusicon.'&nbsp;'.
1764 format_string($sco->title).'&nbsp;'.$score,
1765 array('data-scoid' => $sco->id, 'title' => $sco->url));
41e205cd 1766 } else {
7f28e8a5
JL
1767 $result->toc .= html_writer::tag('a', '&nbsp;'.format_string($sco->title).'&nbsp;'.$score,
1768 array('data-scoid' => $sco->id, 'title' => $sco->url));
0797000a 1769 }
41e205cd
MG
1770 } else {
1771 if ($sco->scormtype == 'sco') {
7f28e8a5 1772 $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
0797000a 1773 } else {
7f28e8a5 1774 $result->toc .= html_writer::span('&nbsp;'.format_string($sco->title));
0797000a
DM
1775 }
1776 }
0797000a 1777 }
41e205cd
MG
1778
1779 } else {
7f28e8a5
JL
1780 if ($play) {
1781 if ($sco->scormtype == 'sco') {
1782 $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
1783 } else {
1784 $result->toc .= '&nbsp;'.format_string($sco->title).html_writer::end_span();
1785 }
1786 } else {
1787 if ($sco->scormtype == 'sco') {
1788 $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title);
1789 } else {
1790 $result->toc .= '&nbsp;'.format_string($sco->title);
1791 }
1792 }
0797000a 1793 }
41e205cd
MG
1794
1795 if (!empty($sco->children)) {
27b8872c 1796 $result->toc .= html_writer::start_tag('ul');
4cb25b36 1797 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid,
1798 $toclink, $currentorg, $attempt, $play, $organizationsco, true);
a6c11677
JL
1799
1800 // Is any of the children incomplete?
1801 $sco->incomplete = $childresult->incomplete;
41e205cd 1802 $result->toc .= $childresult->toc;
27b8872c
N
1803 $result->toc .= html_writer::end_tag('ul');
1804 $result->toc .= html_writer::end_tag('li');
41e205cd 1805 } else {
27b8872c 1806 $result->toc .= html_writer::end_tag('li');
0797000a 1807 }
6917eee8 1808 $prevsco = $sco;
0797000a 1809 }
41e205cd
MG
1810 $result->incomplete = $sco->incomplete;
1811 }
1812
1813 if (!$children) {
27b8872c 1814 $result->toc .= html_writer::end_tag('ul');
41e205cd
MG
1815 }
1816
1817 return $result;
1818}
1819
4cb25b36 1820function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null,
1821 $children=false, $level=0, $tocmenus=array()) {
41e205cd
MG
1822 if (!empty($scoes)) {
1823 if (!empty($organizationsco) && !$children) {
1824 $tocmenus[$organizationsco->id] = $organizationsco->title;
0797000a
DM
1825 }
1826
27b8872c 1827 $parents[$level] = '/';
41e205cd
MG
1828 foreach ($scoes as $sco) {
1829 if ($parents[$level] != $sco->parent) {
1830 if ($newlevel = array_search($sco->parent, $parents)) {
1831 $level = $newlevel;
1832 } else {
1833 $i = $level;
1834 while (($i > 0) && ($parents[$level] != $sco->parent)) {
1835 $i--;
1836 }
1837
1838 if (($i == 0) && ($sco->parent != $currentorg)) {
1839 $level++;
1840 } else {
1841 $level = $i;
1842 }
1843
1844 $parents[$level] = $sco->parent;
1845 }
1846 }
1847
f47a8a6f
DM
1848 if ($sco->scormtype == 'sco') {
1849 $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
41e205cd
MG
1850 }
1851
1852 if (!empty($sco->children)) {
4cb25b36 1853 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg,
1854 $organizationsco, true, $level, $tocmenus);
8a4561ac 1855 }
0797000a
DM
1856 }
1857 }
0797000a 1858
41e205cd
MG
1859 return $tocmenus;
1860}
1861
27b8872c
N
1862function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal',
1863 $attempt='', $play=false, $tocheader=false) {
41e205cd
MG
1864 global $CFG, $DB, $OUTPUT;
1865
1866 if (empty($attempt)) {
aafb7a5b 1867 $attempt = scorm_get_last_attempt($scorm->id, $user->id);
41e205cd
MG
1868 }
1869
1870 $result = new stdClass();
1871 $organizationsco = null;
1872
0797000a 1873 if ($tocheader) {
27b8872c
N
1874 $result->toc = html_writer::start_div('yui3-g-r', array('id' => 'scorm_layout'));
1875 $result->toc .= html_writer::start_div('yui3-u-1-5', array('id' => 'scorm_toc'));
1876 $result->toc .= html_writer::div('', '', array('id' => 'scorm_toc_title'));
1877 $result->toc .= html_writer::start_div('', array('id' => 'scorm_tree'));
41e205cd
MG
1878 }
1879
1880 if (!empty($currentorg)) {
27b8872c 1881 $organizationsco = $DB->get_record('scorm_scoes', array('scorm' => $scorm->id, 'identifier' => $currentorg));
41e205cd
MG
1882 if (!empty($organizationsco->title)) {
1883 if ($play) {
1884 $result->toctitle = $organizationsco->title;
1885 }
1886 }
1887 }
1888
1889 $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1890
27b8872c
N
1891 $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid,
1892 $toclink, $currentorg, $attempt, $play, $organizationsco, false);
41e205cd
MG
1893
1894 if ($tocheader) {
1895 $result->toc .= $treeview->toc;
1896 } else {
1897 $result->toc = $treeview->toc;
1898 }
1899
1900 if (!empty($scoes['scoid'])) {
1901 $scoid = $scoes['scoid'];
1902 }
1903
1904 if (empty($scoid)) {
d92c406a
DM
1905 // If this is a normal package with an org sco and child scos get the first child.
1906 if (!empty($scoes['scoes'][0]->children)) {
1907 $result->sco = $scoes['scoes'][0]->children[0];
1908 } else { // This package only has one sco - it may be a simple external AICC package.
1909 $result->sco = $scoes['scoes'][0];
1910 }
1911
41e205cd
MG
1912 } else {
1913 $result->sco = scorm_get_sco($scoid);
1914 }
1915
1916 if ($scorm->hidetoc == SCORM_TOC_POPUP) {
4cb25b36 1917 $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'],
1918 $currentorg, $organizationsco);
41e205cd
MG
1919
1920 $modestr = '';
39355b46
DM
1921 if ($mode != 'normal') {
1922 $modestr = '&mode='.$mode;
41e205cd
MG
1923 }
1924
1925 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
dd55ec30 1926 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
0797000a
DM
1927 }
1928
41e205cd
MG
1929 $result->prerequisites = $treeview->prerequisites;
1930 $result->incomplete = $treeview->incomplete;
1931 $result->attemptleft = $treeview->attemptleft;
1932
1933 if ($tocheader) {
27b8872c
N
1934 $result->toc .= html_writer::end_div().html_writer::end_div();
1935 $result->toc .= html_writer::start_div('', array('id' => 'scorm_toc_toggle'));
1936 $result->toc .= html_writer::tag('button', '', array('id' => 'scorm_toc_toggle_btn')).html_writer::end_div();
1937 $result->toc .= html_writer::start_div('', array('id' => 'scorm_content'));
1938 $result->toc .= html_writer::div('', '', array('id' => 'scorm_navpanel'));
1939 $result->toc .= html_writer::end_div().html_writer::end_div();
41e205cd 1940 }
0797000a
DM
1941
1942 return $result;
701570b5 1943}
41e205cd
MG
1944
1945function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1946 if (is_object($scoes)) {
1947 $sco = $scoes;
1948 if (isset($sco->url)) {
1949 $adlnav[$sco->id]['identifier'] = $sco->identifier;
1950 $adlnav[$sco->id]['launch'] = $sco->launch;
1951 $adlnav[$sco->id]['title'] = $sco->title;
1952 $adlnav[$sco->id]['url'] = $sco->url;
1953 $adlnav[$sco->id]['parent'] = $sco->parent;
1954 if (isset($sco->choice)) {
1955 $adlnav[$sco->id]['choice'] = $sco->choice;
1956 }
1957 if (isset($sco->flow)) {
1958 $adlnav[$sco->id]['flow'] = $sco->flow;
1959 } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1960 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1961 }
1962 if (isset($sco->isvisible)) {
1963 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1964 }
1965 if (isset($sco->parameters)) {
1966 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1967 }
1968 if (isset($sco->hidecontinue)) {
1969 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1970 }
1971 if (isset($sco->hideprevious)) {
1972 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1973 }
1974 if (isset($sco->hidesuspendall)) {
1975 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1976 }
1977 if (!empty($parentscoid)) {
1978 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1979 }
1980 if (isset($adlnav['prevscoid'])) {
1981 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1982 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1983 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1984 $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1985 $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1986 }
1987 }
1988 $adlnav['prevscoid'] = $sco->id;
1989 $adlnav['prevparent'] = $sco->parent;
1990 }
1991 if (isset($sco->children)) {
1992 foreach ($sco->children as $children) {
1993 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1994 }
1995 }
1996 } else {
1997 foreach ($scoes as $sco) {
1998 scorm_get_adlnav_json ($sco, $adlnav);
1999 }
2000 unset($adlnav['prevscoid']);
2001 unset($adlnav['prevparent']);
2002 }
2003 return json_encode($adlnav);
2004}
f833171f
MS
2005
2006/**
2007 * Check for the availability of a resource by URL.
2008 *
2009 * Check is performed using an HTTP HEAD call.
2010 *
2011 * @param $url string A valid URL
2012 * @return bool|string True if no issue is found. The error string message, otherwise
2013 */
2014function scorm_check_url($url) {
2015 $curl = new curl;
90627d9d
2016 // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
2017 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
f833171f
MS
2018 $cmsg = $curl->head($url);
2019 $info = $curl->get_info();
2020 if (empty($info['http_code']) || $info['http_code'] != 200) {
2021 return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
2022 }
2023
2024 return true;
2025}
139f32c2 2026
ad88d3ed
N
2027/**
2028 * Check for a parameter in userdata and return it if it's set
2029 * or return the value from $ifempty if its empty
2030 *
2031 * @param stdClass $userdata Contains user's data
2032 * @param string $param parameter that should be checked
2033 * @param string $ifempty value to be replaced with if $param is not set
2034 * @return string value from $userdata->$param if its not empty, or $ifempty
2035 */
139f32c2
N
2036function scorm_isset($userdata, $param, $ifempty = '') {
2037 if (isset($userdata->$param)) {
2038 return $userdata->$param;
4cb25b36 2039 } else {
139f32c2
N
2040 return $ifempty;
2041 }
2042}
f47a8a6f
DM
2043
2044/**
2045 * Check if the current sco is launchable
2046 * If not, find the next launchable sco
2047 *
2048 * @param stdClass $scorm Scorm object
2049 * @param integer $scoid id of scorm_scoes record.
2050 * @return integer scoid of correct sco to launch or empty if one cannot be found, which will trigger first sco.
2051 */
2052function scorm_check_launchable_sco($scorm, $scoid) {
2053 global $DB;
2054 if ($sco = scorm_get_sco($scoid, SCO_ONLY)) {
2055 if ($sco->launch == '') {
2056 // This scoid might be a top level org that can't be launched, find the first launchable sco after this sco.
2057 $scoes = $DB->get_records_select('scorm_scoes',
2058 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).
2059 ' AND id > ?', array($scorm->id, $sco->id), 'sortorder, id', 'id', 0, 1);
2060 if (!empty($scoes)) {
2061 $sco = reset($scoes); // Get first item from the list.
2062 return $sco->id;
2063 }
2064 } else {
2065 return $sco->id;
2066 }
2067 }
2068 // Returning 0 will cause default behaviour which will find the first launchable sco in the package.
2069 return 0;
22de67f4
JL
2070}
2071
2072/**
2073 * Check if a SCORM is available for the current user.
2074 *
2075 * @param stdClass $scorm SCORM record
2076 * @param boolean $checkviewreportcap Check the scorm:viewreport cap
2077 * @param stdClass $context Module context, required if $checkviewreportcap is set to true
2078 * @return array status (available or not and possible warnings)
2079 * @since Moodle 3.0
2080 */
2081function scorm_get_availability_status($scorm, $checkviewreportcap = false, $context = null) {
2082 $open = true;
2083 $closed = false;
2084 $warnings = array();
2085
2086 $timenow = time();
2087 if (!empty($scorm->timeopen) and $scorm->timeopen > $timenow) {
2088 $open = false;
2089 }
2090 if (!empty($scorm->timeclose) and $timenow > $scorm->timeclose) {
2091 $closed = true;
2092 }
2093
2094 if (!$open or $closed) {
2095 if ($checkviewreportcap and !empty($context) and has_capability('mod/scorm:viewreport', $context)) {
2096 return array(true, $warnings);
2097 }
2098
2099 if (!$open) {
2100 $warnings['notopenyet'] = userdate($scorm->timeopen);
2101 }
2102 if ($closed) {
2103 $warnings['expired'] = userdate($scorm->timeclose);
2104 }
2105 return array(false, $warnings);
2106 }
2107
2108 // Scorm is available.
2109 return array(true, $warnings);
2110}
2111
2112/**
2113 * Requires a SCORM package to be available for the current user.
2114 *
2115 * @param stdClass $scorm SCORM record
2116 * @param boolean $checkviewreportcap Check the scorm:viewreport cap
2117 * @param stdClass $context Module context, required if $checkviewreportcap is set to true
2118 * @throws moodle_exception
2119 * @since Moodle 3.0
2120 */
2121function scorm_require_available($scorm, $checkviewreportcap = false, $context = null) {
2122
2123 list($available, $warnings) = scorm_get_availability_status($scorm, $checkviewreportcap, $context);
2124
2125 if (!$available) {
2126 $reason = current(array_keys($warnings));
2127 throw new moodle_exception($reason, 'scorm', '', $warnings[$reason]);
2128 }
2129
2130}
e9b1e1cc
JL
2131
2132/**
2133 * Return a SCO object and the SCO launch URL
2134 *
2135 * @param stdClass $scorm SCORM object
2136 * @param int $scoid The SCO id in database
2137 * @param stdClass $context context object
2138 * @return array the SCO object and URL
2139 * @since Moodle 3.1
2140 */
2141function scorm_get_sco_and_launch_url($scorm, $scoid, $context) {
2142 global $CFG, $DB;
2143
2144 if (!empty($scoid)) {
2145 // Direct SCO request.
2146 if ($sco = scorm_get_sco($scoid)) {
2147 if ($sco->launch == '') {
2148 // Search for the next launchable sco.
2149 if ($scoes = $DB->get_records_select(
2150 'scorm_scoes',
2151 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).' AND id > ?',
2152 array($scorm->id, $sco->id),
2153 'sortorder, id')) {
2154 $sco = current($scoes);
2155 }
2156 }
2157 }
2158 }
2159
2160 // If no sco was found get the first of SCORM package.
2161 if (!isset($sco)) {
2162 $scoes = $DB->get_records_select(
2163 'scorm_scoes',
2164 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
2165 array($scorm->id),
2166 'sortorder, id'
2167 );
2168 $sco = current($scoes);
2169 }
2170
2171 $connector = '';
2172 $version = substr($scorm->version, 0, 4);
2173 if ((isset($sco->parameters) && (!empty($sco->parameters))) || ($version == 'AICC')) {
2174 if (stripos($sco->launch, '?') !== false) {
2175 $connector = '&';
2176 } else {
2177 $connector = '?';
2178 }
2179 if ((isset($sco->parameters) && (!empty($sco->parameters))) && ($sco->parameters[0] == '?')) {
2180 $sco->parameters = substr($sco->parameters, 1);
2181 }
2182 }
2183
2184 if ($version == 'AICC') {
2185 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
2186 $aiccsid = scorm_aicc_get_hacp_session($scorm->id);
2187 if (empty($aiccsid)) {
2188 $aiccsid = sesskey();
2189 }
2190 $scoparams = '';
2191 if (isset($sco->parameters) && (!empty($sco->parameters))) {
2192 $scoparams = '&'. $sco->parameters;
2193 }
2194 $launcher = $sco->launch.$connector.'aicc_sid='.$aiccsid.'&aicc_url='.$CFG->wwwroot.'/mod/scorm/aicc.php'.$scoparams;
2195 } else {
2196 if (isset($sco->parameters) && (!empty($sco->parameters))) {
2197 $launcher = $sco->launch.$connector.$sco->parameters;
2198 } else {
2199 $launcher = $sco->launch;
2200 }
2201 }
2202
2203 if (scorm_external_link($sco->launch)) {
2204 // TODO: does this happen?
2205 $scolaunchurl = $launcher;
2206 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
2207 // Remote learning activity.
2208 $scolaunchurl = dirname($scorm->reference).'/'.$launcher;
2209 } else if ($scorm->scormtype === SCORM_TYPE_LOCAL && strtolower($scorm->reference) == 'imsmanifest.xml') {
2210 // This SCORM content sits in a repository that allows relative links.
2211 $scolaunchurl = "$CFG->wwwroot/pluginfile.php/$context->id/mod_scorm/imsmanifest/$scorm->revision/$launcher";
2212 } else if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
11d4bea2 2213 // Note: do not convert this to use moodle_url().
e9b1e1cc
JL
2214 // SCORM does not work without slasharguments and moodle_url() encodes querystring vars.
2215 $scolaunchurl = "$CFG->wwwroot/pluginfile.php/$context->id/mod_scorm/content/$scorm->revision/$launcher";
2216 }
2217 return array($sco, $scolaunchurl);
2218}
2219
2220/**
2221 * Trigger the scorm_launched event.
2222 *
2223 * @param stdClass $scorm scorm object
2224 * @param stdClass $sco sco object
2225 * @param stdClass $cm course module object
2226 * @param stdClass $context context object
2227 * @param string $scourl SCO URL
2228 * @since Moodle 3.1
2229 */
2230function scorm_launch_sco($scorm, $sco, $cm, $context, $scourl) {
2231
2232 $event = \mod_scorm\event\sco_launched::create(array(
2233 'objectid' => $sco->id,
2234 'context' => $context,
2235 'other' => array('instanceid' => $scorm->id, 'loadedcontent' => $scourl)
2236 ));
2237 $event->add_record_snapshot('course_modules', $cm);
2238 $event->add_record_snapshot('scorm', $scorm);
2239 $event->add_record_snapshot('scorm_scoes', $sco);
2240 $event->trigger();
2241}