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