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