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