MDL-41580 SCORM: allow imsmanifest.xml to be used in file system repos
[moodle.git] / mod / scorm / lib.php
CommitLineData
28f672b2 1<?php
28f672b2 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/>.
e4aa175a 16
28f672b2 17/**
18 * @package mod-scorm
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21 */
22
23/** SCORM_TYPE_LOCAL = local */
9528568b 24define('SCORM_TYPE_LOCAL', 'local');
28f672b2 25/** SCORM_TYPE_LOCALSYNC = localsync */
9528568b 26define('SCORM_TYPE_LOCALSYNC', 'localsync');
28f672b2 27/** SCORM_TYPE_EXTERNAL = external */
9528568b 28define('SCORM_TYPE_EXTERNAL', 'external');
4388bd45
DM
29/** SCORM_TYPE_AICCURL = external AICC url */
30define('SCORM_TYPE_AICCURL', 'aiccurl');
9528568b 31
99da7a95
DM
32define('SCORM_TOC_SIDE', 0);
33define('SCORM_TOC_HIDDEN', 1);
34define('SCORM_TOC_POPUP', 2);
35define('SCORM_TOC_DISABLED', 3);
9528568b 36
e6402b54
DM
37//used to check what SCORM version is being used.
38define('SCORM_12', 1);
39define('SCORM_13', 2);
40define('SCORM_AICC', 3);
41
da92e3b0
DM
42// List of possible attemptstatusdisplay options.
43define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
44define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
45define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
46define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
47
94db2749
AB
48/**
49 * Return an array of status options
50 *
51 * Optionally with translated strings
52 *
53 * @param bool $with_strings (optional)
54 * @return array
55 */
56function scorm_status_options($with_strings = false) {
57 // Id's are important as they are bits
58 $options = array(
59 2 => 'passed',
60 4 => 'completed'
61 );
62
63 if ($with_strings) {
64 foreach ($options as $key => $value) {
65 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
66 }
67 }
68
69 return $options;
70}
71
72
e4aa175a 73/**
28f672b2 74 * Given an object containing all the necessary data,
75 * (defined by the form in mod_form.php) this function
76 * will create a new instance and return the id number
77 * of the new instance.
78 *
79 * @global stdClass
80 * @global object
81 * @uses CONTEXT_MODULE
82 * @uses SCORM_TYPE_LOCAL
83 * @uses SCORM_TYPE_LOCALSYNC
84 * @uses SCORM_TYPE_EXTERNAL
28f672b2 85 * @param object $scorm Form data
86 * @param object $mform
87 * @return int new instance id
88 */
9528568b 89function scorm_add_instance($scorm, $mform=null) {
c18269c7 90 global $CFG, $DB;
a679d64d 91
86996ffe 92 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
a679d64d 93
413900b4 94 if (empty($scorm->timeopen)) {
d54e2145 95 $scorm->timeopen = 0;
413900b4
DM
96 }
97 if (empty($scorm->timeclose)) {
d54e2145 98 $scorm->timeclose = 0;
99 }
9528568b 100 $cmid = $scorm->coursemodule;
101 $cmidnumber = $scorm->cmidnumber;
102 $courseid = $scorm->course;
76ea4fb4 103
a3fc4b3a 104 $context = context_module::instance($cmid);
a679d64d 105
9528568b 106 $scorm = scorm_option2text($scorm);
107 $scorm->width = (int)str_replace('%', '', $scorm->width);
108 $scorm->height = (int)str_replace('%', '', $scorm->height);
e4aa175a 109
9528568b 110 if (!isset($scorm->whatgrade)) {
111 $scorm->whatgrade = 0;
112 }
b3659259 113
a8f3a651 114 $id = $DB->insert_record('scorm', $scorm);
e4aa175a 115
27b87c10 116 // Update course module record - from now on this instance properly exists and all function may be used.
bf8e93d7 117 $DB->set_field('course_modules', 'instance', $id, array('id'=>$cmid));
e4aa175a 118
27b87c10 119 // Reload scorm instance.
783f1486 120 $record = $DB->get_record('scorm', array('id'=>$id));
9528568b 121
27b87c10 122 // Store the package and verify.
783f1486 123 if ($record->scormtype === SCORM_TYPE_LOCAL) {
27b87c10
DM
124 if ($data = $mform->get_data()) {
125 $fs = get_file_storage();
126 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
127 file_save_draft_area_files($data->packagefile, $context->id, 'mod_scorm', 'package',
128 0, array('subdirs' => 0, 'maxfiles' => 1));
129 // Get filename of zip that was uploaded.
130 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
131 $file = reset($files);
132 $filename = $file->get_filename();
9528568b 133 if ($filename !== false) {
783f1486 134 $record->reference = $filename;
8ba4f1e0 135 }
e4aa175a 136 }
137
783f1486
DC
138 } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
139 $record->reference = $scorm->packageurl;
783f1486
DC
140 } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
141 $record->reference = $scorm->packageurl;
4388bd45
DM
142 } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
143 $record->reference = $scorm->packageurl;
f2b3e82b 144 $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
a679d64d 145 } else {
9528568b 146 return false;
e4aa175a 147 }
9528568b 148
27b87c10 149 // Save reference.
783f1486 150 $DB->update_record('scorm', $record);
9528568b 151
27b87c10 152 // Extra fields required in grade related functions.
783f1486
DC
153 $record->course = $courseid;
154 $record->cmidnumber = $cmidnumber;
155 $record->cmid = $cmid;
9528568b 156
783f1486 157 scorm_parse($record, true);
9528568b 158
3270869a 159 scorm_grade_item_update($record);
9528568b 160
783f1486 161 return $record->id;
e4aa175a 162}
163
164/**
28f672b2 165 * Given an object containing all the necessary data,
166 * (defined by the form in mod_form.php) this function
167 * will update an existing instance with new data.
168 *
169 * @global stdClass
170 * @global object
171 * @uses CONTEXT_MODULE
172 * @uses SCORM_TYPE_LOCAL
173 * @uses SCORM_TYPE_LOCALSYNC
174 * @uses SCORM_TYPE_EXTERNAL
28f672b2 175 * @param object $scorm Form data
176 * @param object $mform
177 * @return bool
178 */
9528568b 179function scorm_update_instance($scorm, $mform=null) {
c18269c7 180 global $CFG, $DB;
e4aa175a 181
86996ffe 182 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
76ea4fb4 183
413900b4 184 if (empty($scorm->timeopen)) {
d54e2145 185 $scorm->timeopen = 0;
413900b4
DM
186 }
187 if (empty($scorm->timeclose)) {
d54e2145 188 $scorm->timeclose = 0;
189 }
190
9528568b 191 $cmid = $scorm->coursemodule;
192 $cmidnumber = $scorm->cmidnumber;
193 $courseid = $scorm->course;
194
195 $scorm->id = $scorm->instance;
196
a3fc4b3a 197 $context = context_module::instance($cmid);
9528568b 198
199 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
27b87c10
DM
200 if ($data = $mform->get_data()) {
201 $fs = get_file_storage();
202 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
203 file_save_draft_area_files($data->packagefile, $context->id, 'mod_scorm', 'package',
204 0, array('subdirs' => 0, 'maxfiles' => 1));
205 // Get filename of zip that was uploaded.
206 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
207 $file = reset($files);
208 $filename = $file->get_filename();
9528568b 209 if ($filename !== false) {
210 $scorm->reference = $filename;
a679d64d 211 }
76ea4fb4 212 }
76ea4fb4 213
9528568b 214 } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
215 $scorm->reference = $scorm->packageurl;
9528568b 216 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
217 $scorm->reference = $scorm->packageurl;
047b4e83
DM
218 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
219 $scorm->reference = $scorm->packageurl;
f2b3e82b 220 $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
9528568b 221 } else {
222 return false;
223 }
bfe8c2f0 224
e4aa175a 225 $scorm = scorm_option2text($scorm);
f7b5c6aa
DM
226 $scorm->width = (int)str_replace('%', '', $scorm->width);
227 $scorm->height = (int)str_replace('%', '', $scorm->height);
9528568b 228 $scorm->timemodified = time();
e4aa175a 229
b3659259 230 if (!isset($scorm->whatgrade)) {
231 $scorm->whatgrade = 0;
232 }
a30b6819 233
a8c31db2 234 $DB->update_record('scorm', $scorm);
531fa830 235
9528568b 236 $scorm = $DB->get_record('scorm', array('id'=>$scorm->id));
237
f7b5c6aa 238 /// extra fields required in grade related functions
9528568b 239 $scorm->course = $courseid;
240 $scorm->idnumber = $cmidnumber;
241 $scorm->cmid = $cmid;
242
243 scorm_parse($scorm, (bool)$scorm->updatefreq);
244
245 scorm_grade_item_update($scorm);
50412dc1 246 scorm_update_grades($scorm);
9528568b 247
248 return true;
e4aa175a 249}
250
251/**
28f672b2 252 * Given an ID of an instance of this module,
253 * this function will permanently delete the instance
254 * and any data that depends on it.
255 *
256 * @global stdClass
257 * @global object
258 * @param int $id Scorm instance id
259 * @return boolean
260 */
e4aa175a 261function scorm_delete_instance($id) {
c18269c7 262 global $CFG, $DB;
e4aa175a 263
c18269c7 264 if (! $scorm = $DB->get_record('scorm', array('id'=>$id))) {
e4aa175a 265 return false;
266 }
267
268 $result = true;
269
e4aa175a 270 // Delete any dependent records
c18269c7 271 if (! $DB->delete_records('scorm_scoes_track', array('scormid'=>$scorm->id))) {
e4aa175a 272 $result = false;
273 }
c18269c7 274 if ($scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
b3659259 275 foreach ($scoes as $sco) {
c18269c7 276 if (! $DB->delete_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
b3659259 277 $result = false;
278 }
9528568b 279 }
c18269c7 280 $DB->delete_records('scorm_scoes', array('scorm'=>$scorm->id));
e4aa175a 281 }
c18269c7 282 if (! $DB->delete_records('scorm', array('id'=>$scorm->id))) {
e4aa175a 283 $result = false;
284 }
a30b6819 285
c18269c7 286 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
e4aa175a 287 $result = false;
288 }
c18269c7 289 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
e4aa175a 290 $result = false;
291 }
c18269c7 292 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
e4aa175a 293 $result = false;
294 }
c18269c7 295 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
e4aa175a 296 $result = false;
297 }
c18269c7 298 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
e4aa175a 299 $result = false;
300 }
c18269c7 301 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
e4aa175a 302 $result = false;
303 }
c18269c7 304 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
e4aa175a 305 $result = false;
9528568b 306 }*/
531fa830 307
c18269c7 308 scorm_grade_item_delete($scorm);
9528568b 309
e4aa175a 310 return $result;
311}
312
313/**
28f672b2 314 * Return a small object with summary information about what a
315 * user has done with a given particular instance of this module
316 * Used for user activity reports.
317 *
318 * @global stdClass
319 * @param int $course Course id
320 * @param int $user User id
321 * @param int $mod
322 * @param int $scorm The scorm id
323 * @return mixed
324 */
9528568b 325function scorm_user_outline($course, $user, $mod, $scorm) {
531fa830 326 global $CFG;
86996ffe 327 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
a30b6819 328
1a96363a
NC
329 require_once("$CFG->libdir/gradelib.php");
330 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
331 if (!empty($grades->items[0]->grades)) {
332 $grade = reset($grades->items[0]->grades);
39790bd8 333 $result = new stdClass();
1a96363a 334 $result->info = get_string('grade') . ': '. $grade->str_long_grade;
4433f871
AD
335
336 //datesubmitted == time created. dategraded == time modified or time overridden
337 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
94a74f54 338 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
4433f871
AD
339 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
340 $result->time = $grade->dategraded;
341 } else {
342 $result->time = $grade->datesubmitted;
343 }
344
1a96363a
NC
345 return $result;
346 }
347 return null;
e4aa175a 348}
349
350/**
28f672b2 351 * Print a detailed representation of what a user has done with
352 * a given particular instance of this module, for user activity reports.
353 *
354 * @global stdClass
355 * @global object
356 * @param object $course
357 * @param object $user
358 * @param object $mod
359 * @param object $scorm
360 * @return boolean
361 */
e4aa175a 362function scorm_user_complete($course, $user, $mod, $scorm) {
d436d197 363 global $CFG, $DB, $OUTPUT;
1a96363a 364 require_once("$CFG->libdir/gradelib.php");
e4aa175a 365
366 $liststyle = 'structlist';
e4aa175a 367 $now = time();
368 $firstmodify = $now;
369 $lastmodify = 0;
370 $sometoreport = false;
371 $report = '';
9895302c 372
c86a91d5 373 // First Access and Last Access dates for SCOs
86996ffe 374 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
c86a91d5
PH
375 $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
376 $firstmodify = $timetracks->start;
377 $lastmodify = $timetracks->finish;
9895302c 378
1a96363a
NC
379 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
380 if (!empty($grades->items[0]->grades)) {
381 $grade = reset($grades->items[0]->grades);
382 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
383 if ($grade->str_feedback) {
384 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
385 }
386 }
387
84ab3289
DM
388 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
389 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
390 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
b33e4665 391 array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
e4aa175a 392 if (count($orgs) <= 1) {
393 unset($orgs);
6e9d3c19
AA
394 $orgs = array();
395 $org = new stdClass();
396 $org->identifier = '';
397 $orgs[] = $org;
e4aa175a 398 }
399 $report .= '<div class="mod-scorm">'."\n";
400 foreach ($orgs as $org) {
bf347041 401 $conditions = array();
e4aa175a 402 $currentorg = '';
403 if (!empty($org->identifier)) {
404 $report .= '<div class="orgtitle">'.$org->title.'</div>';
405 $currentorg = $org->identifier;
bf347041 406 $conditions['organization'] = $currentorg;
e4aa175a 407 }
408 $report .= "<ul id='0' class='$liststyle'>";
bf347041 409 $conditions['scorm'] = $scorm->id;
b33e4665 410 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
9fb2de4e 411 // drop keys so that we can access array sequentially
9528568b 412 $scoes = array_values($scoes);
e4aa175a 413 $level=0;
414 $sublist=1;
415 $parents[$level]='/';
f7b5c6aa 416 foreach ($scoes as $pos => $sco) {
e4aa175a 417 if ($parents[$level]!=$sco->parent) {
418 if ($level>0 && $parents[$level-1]==$sco->parent) {
419 $report .= "\t\t</ul></li>\n";
420 $level--;
421 } else {
422 $i = $level;
423 $closelist = '';
424 while (($i > 0) && ($parents[$level] != $sco->parent)) {
425 $closelist .= "\t\t</ul></li>\n";
426 $i--;
427 }
428 if (($i == 0) && ($sco->parent != $currentorg)) {
429 $report .= "\t\t<li><ul id='$sublist' class='$liststyle'>\n";
430 $level++;
431 } else {
432 $report .= $closelist;
433 $level = $i;
434 }
435 $parents[$level]=$sco->parent;
436 }
437 }
438 $report .= "\t\t<li>";
9fb2de4e 439 if (isset($scoes[$pos+1])) {
440 $nextsco = $scoes[$pos+1];
441 } else {
442 $nextsco = false;
443 }
e4aa175a 444 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) && (($level==0) || (($level>0) && ($nextsco->parent == $sco->identifier)))) {
445 $sublist++;
446 } else {
485f4ce6 447 $report .= '<img src="'.$OUTPUT->pix_url('spacer', 'scorm').'" alt="" />';
e4aa175a 448 }
449
450 if ($sco->launch) {
e4aa175a 451 $score = '';
452 $totaltime = '';
f7b5c6aa 453 if ($usertrack=scorm_get_tracks($sco->id, $user->id)) {
e4aa175a 454 if ($usertrack->status == '') {
455 $usertrack->status = 'notattempted';
456 }
f7b5c6aa 457 $strstatus = get_string($usertrack->status, 'scorm');
485f4ce6 458 $report .= "<img src='".$OUTPUT->pix_url($usertrack->status, 'scorm')."' alt='$strstatus' title='$strstatus' />";
e4aa175a 459 } else {
460 if ($sco->scormtype == 'sco') {
f7b5c6aa 461 $report .= '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
e4aa175a 462 } else {
f7b5c6aa 463 $report .= '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
e4aa175a 464 }
465 }
466 $report .= "&nbsp;$sco->title $score$totaltime</li>\n";
467 if ($usertrack !== false) {
468 $sometoreport = true;
469 $report .= "\t\t\t<li><ul class='$liststyle'>\n";
f7b5c6aa
DM
470 foreach ($usertrack as $element => $value) {
471 if (substr($element, 0, 3) == 'cmi') {
a7ab614d 472 $report .= '<li>'.$element.' => '.s($value).'</li>';
e4aa175a 473 }
474 }
475 $report .= "\t\t\t</ul></li>\n";
9528568b 476 }
e4aa175a 477 } else {
478 $report .= "&nbsp;$sco->title</li>\n";
479 }
480 }
f7b5c6aa 481 for ($i=0; $i<$level; $i++) {
e4aa175a 482 $report .= "\t\t</ul></li>\n";
483 }
484 }
485 $report .= "\t</ul><br />\n";
486 }
487 $report .= "</div>\n";
488 }
489 if ($sometoreport) {
490 if ($firstmodify < $now) {
491 $timeago = format_time($now - $firstmodify);
f7b5c6aa 492 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")<br />\n";
e4aa175a 493 }
494 if ($lastmodify > 0) {
495 $timeago = format_time($now - $lastmodify);
f7b5c6aa 496 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")<br />\n";
e4aa175a 497 }
f7b5c6aa 498 echo get_string('report', 'scorm').":<br />\n";
e4aa175a 499 echo $report;
500 } else {
f7b5c6aa 501 print_string('noactivity', 'scorm');
e4aa175a 502 }
503
504 return true;
505}
506
e4aa175a 507/**
28f672b2 508 * Function to be run periodically according to the moodle cron
509 * This function searches for things that need to be done, such
510 * as sending out mail, toggling flags etc ...
511 *
512 * @global stdClass
513 * @global object
514 * @return boolean
515 */
e4aa175a 516function scorm_cron () {
bf347041 517 global $CFG, $DB;
a679d64d 518
86996ffe 519 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
a679d64d 520
521 $sitetimezone = $CFG->timezone;
27b87c10 522 // Now see if there are any scorm updates to be done.
9528568b 523
27b87c10 524 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time.
bfe8c2f0 525 set_config('scorm_updatetimelast', 0);
526 }
527
a679d64d 528 $timenow = time();
c5b3ba6a 529 $updatetime = usergetmidnight($timenow, $sitetimezone);
a679d64d 530
531 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
532
bfe8c2f0 533 set_config('scorm_updatetimelast', $timenow);
e4aa175a 534
27b87c10 535 mtrace('Updating scorm packages which require daily update');// We are updating.
bfe8c2f0 536
27b87c10 537 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
f7b5c6aa 538 foreach ($scormsupdate as $scormupdate) {
9528568b 539 scorm_parse($scormupdate, true);
a679d64d 540 }
ba0e91a2 541
27b87c10
DM
542 // Now clear out AICC session table with old session data.
543 $cfgscorm = get_config('scorm');
544 if (!empty($cfgscorm->allowaicchacp)) {
545 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata*24*60*60);
63a1625d 546 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
ba0e91a2 547 }
a679d64d 548 }
549
e4aa175a 550 return true;
551}
552
553/**
531fa830 554 * Return grade for given user or all users.
555 *
28f672b2 556 * @global stdClass
557 * @global object
531fa830 558 * @param int $scormid id of scorm
559 * @param int $userid optional user id, 0 means all users
560 * @return array array of grades, false if none
561 */
562function scorm_get_user_grades($scorm, $userid=0) {
bf347041 563 global $CFG, $DB;
86996ffe 564 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
531fa830 565
566 $grades = array();
567 if (empty($userid)) {
bf347041 568 if ($scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid", array($scorm->id), "", "userid,null")) {
531fa830 569 foreach ($scousers as $scouser) {
39790bd8 570 $grades[$scouser->userid] = new stdClass();
531fa830 571 $grades[$scouser->userid]->id = $scouser->userid;
572 $grades[$scouser->userid]->userid = $scouser->userid;
573 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
574 }
575 } else {
576 return false;
577 }
e4aa175a 578
531fa830 579 } else {
bf347041 580 if (!$DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid", array($scorm->id, $userid), "", "userid,null")) {
531fa830 581 return false; //no attempt yet
582 }
39790bd8 583 $grades[$userid] = new stdClass();
531fa830 584 $grades[$userid]->id = $userid;
585 $grades[$userid]->userid = $userid;
586 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
e4aa175a 587 }
e4aa175a 588
531fa830 589 return $grades;
590}
591
592/**
593 * Update grades in central gradebook
594 *
a153c9f2 595 * @category grade
775f811a 596 * @param object $scorm
531fa830 597 * @param int $userid specific user only, 0 mean all
28f672b2 598 * @param bool $nullifnone
531fa830 599 */
775f811a 600function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
3270869a 601 global $CFG;
775f811a 602 require_once($CFG->libdir.'/gradelib.php');
3270869a 603 require_once($CFG->libdir.'/completionlib.php');
531fa830 604
775f811a 605 if ($grades = scorm_get_user_grades($scorm, $userid)) {
606 scorm_grade_item_update($scorm, $grades);
3270869a
DM
607 //set complete
608 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
775f811a 609 } else if ($userid and $nullifnone) {
39790bd8 610 $grade = new stdClass();
775f811a 611 $grade->userid = $userid;
f7b5c6aa 612 $grade->rawgrade = null;
775f811a 613 scorm_grade_item_update($scorm, $grade);
3270869a
DM
614 //set incomplete.
615 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
e4aa175a 616 } else {
775f811a 617 scorm_grade_item_update($scorm);
618 }
619}
620
621/**
622 * Update all grades in gradebook.
28f672b2 623 *
624 * @global object
775f811a 625 */
626function scorm_upgrade_grades() {
627 global $DB;
628
629 $sql = "SELECT COUNT('x')
630 FROM {scorm} s, {course_modules} cm, {modules} m
631 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
632 $count = $DB->count_records_sql($sql);
633
634 $sql = "SELECT s.*, cm.idnumber AS cmidnumber, s.course AS courseid
635 FROM {scorm} s, {course_modules} cm, {modules} m
636 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
676874df
EL
637 $rs = $DB->get_recordset_sql($sql);
638 if ($rs->valid()) {
775f811a 639 $pbar = new progress_bar('scormupgradegrades', 500, true);
640 $i=0;
641 foreach ($rs as $scorm) {
642 $i++;
643 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
644 scorm_update_grades($scorm, 0, false);
645 $pbar->update($i, $count, "Updating Scorm grades ($i/$count).");
531fa830 646 }
e4aa175a 647 }
676874df 648 $rs->close();
531fa830 649}
e4aa175a 650
531fa830 651/**
652 * Update/create grade item for given scorm
653 *
a153c9f2 654 * @category grade
28f672b2 655 * @uses GRADE_TYPE_VALUE
656 * @uses GRADE_TYPE_NONE
531fa830 657 * @param object $scorm object with extra cmidnumber
28f672b2 658 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
531fa830 659 * @return object grade_item
660 */
3270869a 661function scorm_grade_item_update($scorm, $grades=null) {
bf347041 662 global $CFG, $DB;
0b9e4fdc 663 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
531fa830 664 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
665 require_once($CFG->libdir.'/gradelib.php');
666 }
667
7ef16bf9 668 $params = array('itemname'=>$scorm->name);
669 if (isset($scorm->cmidnumber)) {
670 $params['idnumber'] = $scorm->cmidnumber;
671 }
9528568b 672
50412dc1 673 if ($scorm->grademethod == GRADESCOES) {
84ab3289 674 if ($maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id))) {
531fa830 675 $params['gradetype'] = GRADE_TYPE_VALUE;
676 $params['grademax'] = $maxgrade;
677 $params['grademin'] = 0;
678 } else {
679 $params['gradetype'] = GRADE_TYPE_NONE;
e4aa175a 680 }
531fa830 681 } else {
682 $params['gradetype'] = GRADE_TYPE_VALUE;
683 $params['grademax'] = $scorm->maxgrade;
684 $params['grademin'] = 0;
e4aa175a 685 }
531fa830 686
0b5a80a1 687 if ($grades === 'reset') {
688 $params['reset'] = true;
f7b5c6aa 689 $grades = null;
0b5a80a1 690 }
691
692 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
531fa830 693}
694
695/**
696 * Delete grade item for given scorm
697 *
a153c9f2 698 * @category grade
531fa830 699 * @param object $scorm object
700 * @return object grade_item
701 */
702function scorm_grade_item_delete($scorm) {
703 global $CFG;
704 require_once($CFG->libdir.'/gradelib.php');
705
f7b5c6aa 706 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted'=>1));
e4aa175a 707}
708
28f672b2 709/**
710 * @return array
711 */
e4aa175a 712function scorm_get_view_actions() {
f7b5c6aa 713 return array('pre-view', 'view', 'view all', 'report');
e4aa175a 714}
715
28f672b2 716/**
717 * @return array
718 */
e4aa175a 719function scorm_get_post_actions() {
720 return array();
721}
722
28f672b2 723/**
724 * @param object $scorm
725 * @return object $scorm
726 */
e4aa175a 727function scorm_option2text($scorm) {
1adc77e6 728 $scorm_popoup_options = scorm_get_popup_options_array();
e5dd8e3b 729
e4aa175a 730 if (isset($scorm->popup)) {
76ea4fb4 731 if ($scorm->popup == 1) {
e4aa175a 732 $optionlist = array();
1adc77e6 733 foreach ($scorm_popoup_options as $name => $option) {
e4aa175a 734 if (isset($scorm->$name)) {
735 $optionlist[] = $name.'='.$scorm->$name;
736 } else {
737 $optionlist[] = $name.'=0';
738 }
9528568b 739 }
e4aa175a 740 $scorm->options = implode(',', $optionlist);
741 } else {
742 $scorm->options = '';
9528568b 743 }
e4aa175a 744 } else {
745 $scorm->popup = 0;
746 $scorm->options = '';
747 }
748 return $scorm;
749}
750
0b5a80a1 751/**
752 * Implementation of the function for printing the form elements that control
753 * whether the course reset functionality affects the scorm.
e5dd8e3b 754 *
28f672b2 755 * @param object $mform form passed by reference
0b5a80a1 756 */
757function scorm_reset_course_form_definition(&$mform) {
758 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
f7b5c6aa 759 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
0b5a80a1 760}
761
762/**
763 * Course reset form defaults.
28f672b2 764 *
765 * @return array
0b5a80a1 766 */
767function scorm_reset_course_form_defaults($course) {
768 return array('reset_scorm'=>1);
769}
770
771/**
772 * Removes all grades from gradebook
28f672b2 773 *
774 * @global stdClass
775 * @global object
0b5a80a1 776 * @param int $courseid
777 * @param string optional type
778 */
779function scorm_reset_gradebook($courseid, $type='') {
bf347041 780 global $CFG, $DB;
0b5a80a1 781
782 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
bf347041 783 FROM {scorm} s, {course_modules} cm, {modules} m
784 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
0b5a80a1 785
bf347041 786 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 787 foreach ($scorms as $scorm) {
788 scorm_grade_item_update($scorm, 'reset');
789 }
790 }
791}
792
793/**
72d2982e 794 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 795 * scorm attempts for course $data->courseid.
28f672b2 796 *
797 * @global stdClass
798 * @global object
799 * @param object $data the data submitted from the reset course.
0b5a80a1 800 * @return array status array
801 */
802function scorm_reset_userdata($data) {
bf347041 803 global $CFG, $DB;
0b5a80a1 804
805 $componentstr = get_string('modulenameplural', 'scorm');
806 $status = array();
807
808 if (!empty($data->reset_scorm)) {
809 $scormssql = "SELECT s.id
bf347041 810 FROM {scorm} s
811 WHERE s.course=?";
0b5a80a1 812
bf347041 813 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
0b5a80a1 814
815 // remove all grades from gradebook
816 if (empty($data->reset_gradebook_grades)) {
817 scorm_reset_gradebook($data->courseid);
818 }
819
820 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'scorm'), 'error'=>false);
821 }
822
823 // no dates to shift here
824
825 return $status;
826}
827
f432bebf 828/**
829 * Returns all other caps used in module
28f672b2 830 *
831 * @return array
f432bebf 832 */
833function scorm_get_extra_capabilities() {
834 return array('moodle/site:accessallgroups');
835}
836
9528568b 837/**
838 * Lists all file areas current user may browse
28f672b2 839 *
840 * @param object $course
841 * @param object $cm
842 * @param object $context
843 * @return array
9528568b 844 */
845function scorm_get_file_areas($course, $cm, $context) {
846 $areas = array();
64f93798
PS
847 $areas['content'] = get_string('areacontent', 'scorm');
848 $areas['package'] = get_string('areapackage', 'scorm');
9528568b 849 return $areas;
850}
851
852/**
9895302c 853 * File browsing support for SCORM file areas
e5dd8e3b 854 *
d2b7803e
DC
855 * @package mod_scorm
856 * @category files
857 * @param file_browser $browser file browser instance
858 * @param array $areas file areas
859 * @param stdClass $course course object
860 * @param stdClass $cm course module object
861 * @param stdClass $context context object
862 * @param string $filearea file area
863 * @param int $itemid item ID
864 * @param string $filepath file path
865 * @param string $filename file name
866 * @return file_info instance or null if not found
9528568b 867 */
868function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
869 global $CFG;
870
871 if (!has_capability('moodle/course:managefiles', $context)) {
872 return null;
873 }
874
875 // no writing for now!
876
877 $fs = get_file_storage();
878
64f93798 879 if ($filearea === 'content') {
9528568b 880
881 $filepath = is_null($filepath) ? '/' : $filepath;
882 $filename = is_null($filename) ? '.' : $filename;
e5dd8e3b 883
9528568b 884 $urlbase = $CFG->wwwroot.'/pluginfile.php';
64f93798 885 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
9528568b 886 if ($filepath === '/' and $filename === '.') {
64f93798 887 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
9528568b 888 } else {
889 // not found
890 return null;
891 }
892 }
64f93798 893 require_once("$CFG->dirroot/mod/scorm/locallib.php");
8546def3 894 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
9528568b 895
64f93798 896 } else if ($filearea === 'package') {
9528568b 897 $filepath = is_null($filepath) ? '/' : $filepath;
898 $filename = is_null($filename) ? '.' : $filename;
e5dd8e3b 899
9528568b 900 $urlbase = $CFG->wwwroot.'/pluginfile.php';
64f93798 901 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
9528568b 902 if ($filepath === '/' and $filename === '.') {
64f93798 903 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
9528568b 904 } else {
905 // not found
906 return null;
907 }
908 }
9895302c 909 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
9528568b 910 }
911
912 // scorm_intro handled in file_browser
913
914 return false;
915}
916
917/**
918 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
28f672b2 919 *
d2b7803e
DC
920 * @package mod_scorm
921 * @category files
922 * @param stdClass $course course object
923 * @param stdClass $cm course module object
924 * @param stdClass $context context object
925 * @param string $filearea file area
926 * @param array $args extra arguments
927 * @param bool $forcedownload whether or not force download
261cbbac 928 * @param array $options additional options affecting the file serving
86900a93 929 * @return bool false if file not found, does not return if found - just send the file
9528568b 930 */
261cbbac 931function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
9528568b 932 global $CFG;
933
64f93798 934 if ($context->contextlevel != CONTEXT_MODULE) {
0a8a7b6c 935 return false;
936 }
e5dd8e3b 937
0a8a7b6c 938 require_login($course, true, $cm);
939
64f93798
PS
940 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
941
942 if ($filearea === 'content') {
9528568b 943 $revision = (int)array_shift($args); // prevents caching problems - ignored here
64f93798 944 $relativepath = implode('/', $args);
4cec22dc 945 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
9528568b 946 // TODO: add any other access restrictions here if needed!
947
64f93798 948 } else if ($filearea === 'package') {
9528568b 949 if (!has_capability('moodle/course:manageactivities', $context)) {
950 return false;
951 }
64f93798
PS
952 $relativepath = implode('/', $args);
953 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
9528568b 954 $lifetime = 0; // no caching here
955
361a47d4
DM
956 } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
957 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
958 $relativepath = implode('/', $args);
959
960 // Get imsmanifest file.
961 $fs = get_file_storage();
962 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
963 $file = reset($files);
964
965 // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
966 $packagefilename = $file->get_filename();
967 if (strtolower($packagefilename) !== 'imsmanifest.xml') {
968 return false;
969 }
970
971 $file->send_relative_file($relativepath);
9528568b 972 } else {
973 return false;
974 }
975
976 $fs = get_file_storage();
977 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
6ceef54c 978 if ($filearea === 'content') { //return file not found straight away to improve performance.
dbdc7355 979 send_header_404();
6ceef54c
DM
980 die;
981 }
9528568b 982 return false;
983 }
984
985 // finally send the file
261cbbac 986 send_stored_file($file, $lifetime, 0, false, $options);
9528568b 987}
988
42f103be 989/**
28f672b2 990 * @uses FEATURE_GROUPS
991 * @uses FEATURE_GROUPINGS
992 * @uses FEATURE_GROUPMEMBERSONLY
993 * @uses FEATURE_MOD_INTRO
994 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
94db2749 995 * @uses FEATURE_COMPLETION_HAS_RULES
28f672b2 996 * @uses FEATURE_GRADE_HAS_GRADE
997 * @uses FEATURE_GRADE_OUTCOMES
42f103be 998 * @param string $feature FEATURE_xx constant for requested feature
28f672b2 999 * @return mixed True if module supports feature, false if not, null if doesn't know
42f103be 1000 */
1001function scorm_supports($feature) {
1002 switch($feature) {
1003 case FEATURE_GROUPS: return false;
1004 case FEATURE_GROUPINGS: return false;
1005 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 1006 case FEATURE_MOD_INTRO: return true;
42f103be 1007 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
94db2749 1008 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 1009 case FEATURE_GRADE_HAS_GRADE: return true;
1010 case FEATURE_GRADE_OUTCOMES: return true;
02488b86 1011 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 1012 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 1013
1014 default: return null;
1015 }
1016}
0a1f8f8f 1017
a4c4962f
DM
1018/**
1019 * Get the filename for a temp log file
1020 *
1021 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1022 * @param integer $scoid - scoid of object this log entry is for
91421f3e 1023 * @return string The filename as an absolute path
f7b5c6aa 1024 */
a4c4962f
DM
1025function scorm_debug_log_filename($type, $scoid) {
1026 global $CFG, $USER;
1027
7aa06e6d 1028 $logpath = $CFG->tempdir.'/scormlogs';
a4c4962f
DM
1029 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1030 return $logfile;
1031}
1032
169a204c
DM
1033/**
1034 * writes log output to a temp log file
1035 *
1036 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1037 * @param string $text - text to be written to file.
1038 * @param integer $scoid - scoid of object this log entry is for.
1039 */
a4c4962f 1040function scorm_debug_log_write($type, $text, $scoid) {
eb459f71 1041 global $CFG;
169a204c 1042
3b4b776a 1043 $debugenablelog = get_config('scorm', 'allowapidebug');
169a204c 1044 if (!$debugenablelog || empty($text)) {
f7b5c6aa 1045 return;
169a204c 1046 }
af9b1444 1047 if (make_temp_directory('scormlogs/')) {
a4c4962f 1048 $logfile = scorm_debug_log_filename($type, $scoid);
169a204c 1049 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
eb459f71 1050 @chmod($logfile, $CFG->filepermissions);
169a204c
DM
1051 }
1052}
a4c4962f 1053
f7b5c6aa 1054/**
a4c4962f
DM
1055 * Remove debug log file
1056 *
1057 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1058 * @param integer $scoid - scoid of object this log entry is for
1059 * @return boolean True if the file is successfully deleted, false otherwise
1060 */
1061function scorm_debug_log_remove($type, $scoid) {
1062
3b4b776a 1063 $debugenablelog = get_config('scorm', 'allowapidebug');
a4c4962f
DM
1064 $logfile = scorm_debug_log_filename($type, $scoid);
1065 if (!$debugenablelog || !file_exists($logfile)) {
1066 return false;
1067 }
1068
1069 return @unlink($logfile);
1070}
1071
d860e4f8
DM
1072/**
1073 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1074 *
1075 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1076 * @param array $htmlarray
64f93798 1077 * @return mixed
d860e4f8
DM
1078 */
1079function scorm_print_overview($courses, &$htmlarray) {
828b6925 1080 global $USER, $CFG;
d860e4f8
DM
1081
1082 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1083 return array();
1084 }
1085
f7b5c6aa 1086 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
d860e4f8
DM
1087 return;
1088 }
1089
d860e4f8
DM
1090 $strscorm = get_string('modulename', 'scorm');
1091 $strduedate = get_string('duedate', 'scorm');
1092
1093 foreach ($scorms as $scorm) {
828b6925
DM
1094 $time = time();
1095 $showattemptstatus = false;
1096 if ($scorm->timeopen) {
1097 $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
d860e4f8 1098 }
da92e3b0
DM
1099 if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1100 $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) {
828b6925 1101 $showattemptstatus = true;
6257f664 1102 }
828b6925
DM
1103 if ($showattemptstatus || !empty($isopen) || !empty($scorm->timeclose)) {
1104 $str = '<div class="scorm overview"><div class="name">'.$strscorm. ': '.
1105 '<a '.($scorm->visible ? '':' class="dimmed"').
1106 'title="'.$strscorm.'" href="'.$CFG->wwwroot.
1107 '/mod/scorm/view.php?id='.$scorm->coursemodule.'">'.
1108 $scorm->name.'</a></div>';
1109 if ($scorm->timeclose) {
1110 $str .= '<div class="info">'.$strduedate.': '.userdate($scorm->timeclose).'</div>';
1111 }
1112 if ($showattemptstatus) {
1113 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1114 $str .= '<div class="details">'.scorm_get_attempt_status($USER, $scorm).'</div>';
1115 }
1116 $str .= '</div>';
1117 if (empty($htmlarray[$scorm->course]['scorm'])) {
1118 $htmlarray[$scorm->course]['scorm'] = $str;
1119 } else {
1120 $htmlarray[$scorm->course]['scorm'] .= $str;
1121 }
d860e4f8
DM
1122 }
1123 }
1124}
b1627a92
DC
1125
1126/**
1127 * Return a list of page types
1128 * @param string $pagetype current page type
1129 * @param stdClass $parentcontext Block's parent context
1130 * @param stdClass $currentcontext Current context of block
1131 */
b38e2e28 1132function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
1133 $module_pagetype = array('mod-scorm-*'=>get_string('page-mod-scorm-x', 'scorm'));
1134 return $module_pagetype;
1135}
e6402b54
DM
1136
1137/**
1138 * Returns the SCORM version used.
1139 * @param string $scormversion comes from $scorm->version
1140 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1141 * @return Scorm version.
1142 */
1143function scorm_version_check($scormversion, $version='') {
1144 $scormversion = trim(strtolower($scormversion));
1145 if (empty($version) || $version==SCORM_12) {
1146 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1147 return SCORM_12;
1148 }
1149 if (!empty($version)) {
1150 return false;
1151 }
1152 }
1153 if (empty($version) || $version == SCORM_13) {
1154 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1155 return SCORM_13;
1156 }
1157 if (!empty($version)) {
1158 return false;
1159 }
1160 }
1161 if (empty($version) || $version == SCORM_AICC) {
1162 if (strpos($scormversion, 'aicc')) {
1163 return SCORM_AICC;
1164 }
1165 if (!empty($version)) {
1166 return false;
1167 }
1168 }
1169 return false;
3e4c2435 1170}
94db2749
AB
1171
1172/**
1173 * Obtains the automatic completion state for this scorm based on any conditions
1174 * in scorm settings.
1175 *
1176 * @param object $course Course
1177 * @param object $cm Course-module
1178 * @param int $userid User ID
1179 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1180 * @return bool True if completed, false if not. (If no conditions, then return
1181 * value depends on comparison type)
1182 */
1183function scorm_get_completion_state($course, $cm, $userid, $type) {
1184 global $DB;
1185
1186 $result = $type;
1187
1188 // Get scorm
1189 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1190 print_error('cannotfindscorm');
1191 }
cf0387ff
SC
1192 // Only check for existence of tracks and return false if completionstatusrequired or completionscorerequired
1193 // this means that if only view is required we don't end up with a false state.
1194 if ($scorm->completionstatusrequired !== null ||
1195 $scorm->completionscorerequired !== null) {
1196 // Get user's tracks data.
1197 $tracks = $DB->get_records_sql(
1198 "
1199 SELECT
1200 id,
1201 element,
1202 value
1203 FROM
1204 {scorm_scoes_track}
1205 WHERE
1206 scormid = ?
1207 AND userid = ?
1208 AND element IN
1209 (
1210 'cmi.core.lesson_status',
1211 'cmi.completion_status',
1212 'cmi.success_status',
1213 'cmi.core.score.raw',
1214 'cmi.score.raw'
1215 )
1216 ",
1217 array($scorm->id, $userid)
1218 );
1219
1220 if (!$tracks) {
1221 return completion_info::aggregate_completion_states($type, $result, false);
1222 }
94db2749
AB
1223 }
1224
1225 // Check for status
1226 if ($scorm->completionstatusrequired !== null) {
1227
1228 // Get status
1229 $statuses = array_flip(scorm_status_options());
1230 $nstatus = 0;
1231
1232 foreach ($tracks as $track) {
1233 if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1234 continue;
1235 }
1236
1237 if (array_key_exists($track->value, $statuses)) {
1238 $nstatus |= $statuses[$track->value];
1239 }
1240 }
1241
1242 if ($scorm->completionstatusrequired & $nstatus) {
1243 return completion_info::aggregate_completion_states($type, $result, true);
1244 } else {
1245 return completion_info::aggregate_completion_states($type, $result, false);
1246 }
1247
1248 }
1249
1250 // Check for score
1251 if ($scorm->completionscorerequired !== null) {
1252 $maxscore = -1;
1253
1254 foreach ($tracks as $track) {
1255 if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1256 continue;
1257 }
1258
1259 if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1260 $maxscore = floatval($track->value);
1261 }
1262 }
1263
1264 if ($scorm->completionscorerequired <= $maxscore) {
1265 return completion_info::aggregate_completion_states($type, $result, true);
1266 } else {
1267 return completion_info::aggregate_completion_states($type, $result, false);
1268 }
1269 }
1270
1271 return $result;
1272}
01b5936c
CT
1273
1274/**
1275 * Register the ability to handle drag and drop file uploads
1276 * @return array containing details of the files / types the mod can handle
1277 */
1278function scorm_dndupload_register() {
1279 return array('files' => array(
1280 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1281 ));
1282}
1283
1284/**
1285 * Handle a file that has been uploaded
1286 * @param object $uploadinfo details of the file / content that has been uploaded
1287 * @return int instance id of the newly created mod
1288 */
1289function scorm_dndupload_handle($uploadinfo) {
1290
1291 $context = context_module::instance($uploadinfo->coursemodule);
1292 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1293 $fs = get_file_storage();
1294 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1295 $file = reset($files);
1296
8550d72d 1297 // Validate the file, make sure it's a valid SCORM package!
c7e6fb6c
DM
1298 $errors = scorm_validate_package($file);
1299 if (!empty($errors)) {
01b5936c 1300 return false;
01b5936c 1301 }
8550d72d 1302 // Create a default scorm object to pass to scorm_add_instance()!
01b5936c
CT
1303 $scorm = get_config('scorm');
1304 $scorm->course = $uploadinfo->course->id;
1305 $scorm->coursemodule = $uploadinfo->coursemodule;
1306 $scorm->cmidnumber = '';
1307 $scorm->name = $uploadinfo->displayname;
1308 $scorm->scormtype = SCORM_TYPE_LOCAL;
1309 $scorm->reference = $file->get_filename();
1310 $scorm->intro = '';
1311 $scorm->width = $scorm->framewidth;
1312 $scorm->height = $scorm->frameheight;
1313
1314 return scorm_add_instance($scorm, null);
1315}
3270869a
DM
1316
1317/**
1318 * Sets activity completion state
1319 *
1320 * @param object $scorm object
1321 * @param int $userid User ID
1322 * @param int $completionstate Completion state
1323 * @param array $grades grades array of users with grades - used when $userid = 0
1324 */
1325function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
3270869a
DM
1326 $course = new stdClass();
1327 $course->id = $scorm->course;
01259692
AB
1328 $completion = new completion_info($course);
1329
1330 // Check if completion is enabled site-wide, or for the course
1331 if (!$completion->is_enabled()) {
1332 return;
1333 }
3270869a
DM
1334
1335 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
01259692
AB
1336 if (empty($cm) || !$completion->is_enabled($cm)) {
1337 return;
1338 }
1339
1340 if (empty($userid)) { //we need to get all the relevant users from $grades param.
1341 foreach ($grades as $grade) {
1342 $completion->update_state($cm, $completionstate, $grade->userid);
3270869a 1343 }
01259692
AB
1344 } else {
1345 $completion->update_state($cm, $completionstate, $userid);
3270869a 1346 }
5d3559f7 1347}
c7e6fb6c
DM
1348
1349/**
1350 * Check that a Zip file contains a valid SCORM package
1351 *
1352 * @param $file stored_file a Zip file.
1353 * @return array empty if no issue is found. Array of error message otherwise
1354 */
1355function scorm_validate_package($file) {
1356 $packer = get_file_packer('application/zip');
1357 $errors = array();
27b87c10
DM
1358 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1359 $file->import_external_file_contents();
1360 }
c7e6fb6c
DM
1361 $filelist = $file->list_files($packer);
1362
1363 if (!is_array($filelist)) {
1364 $errors['packagefile'] = get_string('badarchive', 'scorm');
1365 } else {
1366 $aiccfound = false;
1367 $badmanifestpresent = false;
1368 foreach ($filelist as $info) {
1369 if ($info->pathname == 'imsmanifest.xml') {
1370 return array();
1371 } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1372 // This package has an imsmanifest file inside a folder of the package.
1373 $badmanifestpresent = true;
1374 }
1375 if (preg_match('/\.cst$/', $info->pathname)) {
1376 return array();
1377 }
1378 }
1379 if (!$aiccfound) {
1380 if ($badmanifestpresent) {
1381 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1382 } else {
1383 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1384 }
1385 }
1386 }
1387 return $errors;
27b87c10 1388}
39355b46
DM
1389
1390/**
1391 * Check and set the correct mode and attempt when entering a SCORM package.
1392 *
1393 * @param object $scorm object
1394 * @param string $newattempt should a new attempt be generated here.
1395 * @param int $attempt the attempt number this is for.
1396 * @param int $userid the userid of the user.
1397 * @param string $mode the current mode that has been selected.
1398 */
1399function scorm_check_mode($scorm, $newattempt, &$attempt, $userid, &$mode) {
1400 global $DB;
1401 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1402 $attempt++;
1403 $mode = 'normal';
1404 } else if ($mode != 'browse') { // Check if review mode should be set.
1405 $mode = 'normal'; // Set to normal mode by default.
1406
1407 // If all tracks == passed, failed or completed then use review mode.
1408 $tracks = $DB->get_recordset('scorm_scoes_track', array('scormid' => $scorm->id, 'userid' => $userid,
1409 'attempt' => $attempt, 'element' => 'cmi.core.lesson_status'));
1410 foreach ($tracks as $track) {
1411 if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1412 $mode = 'review';
1413 } else { // Found an incomplete sco so exit and use normal mode.
1414 $mode = 'normal';
1415 break;
1416 }
1417 }
1418 $tracks->close();
1419 } else if (($mode == 'browse') && ($scorm->hidebrowse == 1)) { // Prevent Browse mode if hidebrowse is set.
1420 $mode = 'normal';
1421 }
31dea4fe 1422}