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