weekly release 2.4dev
[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
a3fc4b3a 101 $context = context_module::instance($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
c2c5c2f8 153 scorm_grade_item_update($record, null, false);
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
a3fc4b3a 192 $context = context_module::instance($cmid);
9528568b 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
c2c5c2f8 649 * @param boolean $updatecompletion set whether to update completion stuff
531fa830 650 * @return object grade_item
651 */
c2c5c2f8 652function scorm_grade_item_update($scorm, $grades=null, $updatecompletion=true) {
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
94db2749 683 // Update activity completion if applicable
c2c5c2f8
DM
684 if ($updatecompletion) {
685 // Get course info
686 $course = new stdClass();
687 $course->id = $scorm->course;
688
689 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id);
690 if (!empty($cm)) {
691 $completion = new completion_info($course);
692 $completion->update_state($cm, COMPLETION_COMPLETE);
693 }
94db2749
AB
694 }
695
0b5a80a1 696 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
531fa830 697}
698
699/**
700 * Delete grade item for given scorm
701 *
a153c9f2 702 * @category grade
531fa830 703 * @param object $scorm object
704 * @return object grade_item
705 */
706function scorm_grade_item_delete($scorm) {
707 global $CFG;
708 require_once($CFG->libdir.'/gradelib.php');
709
f7b5c6aa 710 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted'=>1));
e4aa175a 711}
712
28f672b2 713/**
714 * @return array
715 */
e4aa175a 716function scorm_get_view_actions() {
f7b5c6aa 717 return array('pre-view', 'view', 'view all', 'report');
e4aa175a 718}
719
28f672b2 720/**
721 * @return array
722 */
e4aa175a 723function scorm_get_post_actions() {
724 return array();
725}
726
28f672b2 727/**
728 * @param object $scorm
729 * @return object $scorm
730 */
e4aa175a 731function scorm_option2text($scorm) {
1adc77e6 732 $scorm_popoup_options = scorm_get_popup_options_array();
e5dd8e3b 733
e4aa175a 734 if (isset($scorm->popup)) {
76ea4fb4 735 if ($scorm->popup == 1) {
e4aa175a 736 $optionlist = array();
1adc77e6 737 foreach ($scorm_popoup_options as $name => $option) {
e4aa175a 738 if (isset($scorm->$name)) {
739 $optionlist[] = $name.'='.$scorm->$name;
740 } else {
741 $optionlist[] = $name.'=0';
742 }
9528568b 743 }
e4aa175a 744 $scorm->options = implode(',', $optionlist);
745 } else {
746 $scorm->options = '';
9528568b 747 }
e4aa175a 748 } else {
749 $scorm->popup = 0;
750 $scorm->options = '';
751 }
752 return $scorm;
753}
754
0b5a80a1 755/**
756 * Implementation of the function for printing the form elements that control
757 * whether the course reset functionality affects the scorm.
e5dd8e3b 758 *
28f672b2 759 * @param object $mform form passed by reference
0b5a80a1 760 */
761function scorm_reset_course_form_definition(&$mform) {
762 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
f7b5c6aa 763 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
0b5a80a1 764}
765
766/**
767 * Course reset form defaults.
28f672b2 768 *
769 * @return array
0b5a80a1 770 */
771function scorm_reset_course_form_defaults($course) {
772 return array('reset_scorm'=>1);
773}
774
775/**
776 * Removes all grades from gradebook
28f672b2 777 *
778 * @global stdClass
779 * @global object
0b5a80a1 780 * @param int $courseid
781 * @param string optional type
782 */
783function scorm_reset_gradebook($courseid, $type='') {
bf347041 784 global $CFG, $DB;
0b5a80a1 785
786 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
bf347041 787 FROM {scorm} s, {course_modules} cm, {modules} m
788 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
0b5a80a1 789
bf347041 790 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 791 foreach ($scorms as $scorm) {
792 scorm_grade_item_update($scorm, 'reset');
793 }
794 }
795}
796
797/**
72d2982e 798 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 799 * scorm attempts for course $data->courseid.
28f672b2 800 *
801 * @global stdClass
802 * @global object
803 * @param object $data the data submitted from the reset course.
0b5a80a1 804 * @return array status array
805 */
806function scorm_reset_userdata($data) {
bf347041 807 global $CFG, $DB;
0b5a80a1 808
809 $componentstr = get_string('modulenameplural', 'scorm');
810 $status = array();
811
812 if (!empty($data->reset_scorm)) {
813 $scormssql = "SELECT s.id
bf347041 814 FROM {scorm} s
815 WHERE s.course=?";
0b5a80a1 816
bf347041 817 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
0b5a80a1 818
819 // remove all grades from gradebook
820 if (empty($data->reset_gradebook_grades)) {
821 scorm_reset_gradebook($data->courseid);
822 }
823
824 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'scorm'), 'error'=>false);
825 }
826
827 // no dates to shift here
828
829 return $status;
830}
831
f432bebf 832/**
833 * Returns all other caps used in module
28f672b2 834 *
835 * @return array
f432bebf 836 */
837function scorm_get_extra_capabilities() {
838 return array('moodle/site:accessallgroups');
839}
840
9528568b 841/**
842 * Lists all file areas current user may browse
28f672b2 843 *
844 * @param object $course
845 * @param object $cm
846 * @param object $context
847 * @return array
9528568b 848 */
849function scorm_get_file_areas($course, $cm, $context) {
850 $areas = array();
64f93798
PS
851 $areas['content'] = get_string('areacontent', 'scorm');
852 $areas['package'] = get_string('areapackage', 'scorm');
9528568b 853 return $areas;
854}
855
856/**
9895302c 857 * File browsing support for SCORM file areas
e5dd8e3b 858 *
d2b7803e
DC
859 * @package mod_scorm
860 * @category files
861 * @param file_browser $browser file browser instance
862 * @param array $areas file areas
863 * @param stdClass $course course object
864 * @param stdClass $cm course module object
865 * @param stdClass $context context object
866 * @param string $filearea file area
867 * @param int $itemid item ID
868 * @param string $filepath file path
869 * @param string $filename file name
870 * @return file_info instance or null if not found
9528568b 871 */
872function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
873 global $CFG;
874
875 if (!has_capability('moodle/course:managefiles', $context)) {
876 return null;
877 }
878
879 // no writing for now!
880
881 $fs = get_file_storage();
882
64f93798 883 if ($filearea === 'content') {
9528568b 884
885 $filepath = is_null($filepath) ? '/' : $filepath;
886 $filename = is_null($filename) ? '.' : $filename;
e5dd8e3b 887
9528568b 888 $urlbase = $CFG->wwwroot.'/pluginfile.php';
64f93798 889 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
9528568b 890 if ($filepath === '/' and $filename === '.') {
64f93798 891 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
9528568b 892 } else {
893 // not found
894 return null;
895 }
896 }
64f93798 897 require_once("$CFG->dirroot/mod/scorm/locallib.php");
8546def3 898 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
9528568b 899
64f93798 900 } else if ($filearea === 'package') {
9528568b 901 $filepath = is_null($filepath) ? '/' : $filepath;
902 $filename = is_null($filename) ? '.' : $filename;
e5dd8e3b 903
9528568b 904 $urlbase = $CFG->wwwroot.'/pluginfile.php';
64f93798 905 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
9528568b 906 if ($filepath === '/' and $filename === '.') {
64f93798 907 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
9528568b 908 } else {
909 // not found
910 return null;
911 }
912 }
9895302c 913 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
9528568b 914 }
915
916 // scorm_intro handled in file_browser
917
918 return false;
919}
920
921/**
922 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
28f672b2 923 *
d2b7803e
DC
924 * @package mod_scorm
925 * @category files
926 * @param stdClass $course course object
927 * @param stdClass $cm course module object
928 * @param stdClass $context context object
929 * @param string $filearea file area
930 * @param array $args extra arguments
931 * @param bool $forcedownload whether or not force download
261cbbac 932 * @param array $options additional options affecting the file serving
86900a93 933 * @return bool false if file not found, does not return if found - just send the file
9528568b 934 */
261cbbac 935function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
9528568b 936 global $CFG;
937
64f93798 938 if ($context->contextlevel != CONTEXT_MODULE) {
0a8a7b6c 939 return false;
940 }
e5dd8e3b 941
0a8a7b6c 942 require_login($course, true, $cm);
943
64f93798
PS
944 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
945
946 if ($filearea === 'content') {
9528568b 947 $revision = (int)array_shift($args); // prevents caching problems - ignored here
64f93798 948 $relativepath = implode('/', $args);
4cec22dc 949 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
9528568b 950 // TODO: add any other access restrictions here if needed!
951
64f93798 952 } else if ($filearea === 'package') {
9528568b 953 if (!has_capability('moodle/course:manageactivities', $context)) {
954 return false;
955 }
64f93798
PS
956 $relativepath = implode('/', $args);
957 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
9528568b 958 $lifetime = 0; // no caching here
959
960 } else {
961 return false;
962 }
963
964 $fs = get_file_storage();
965 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
6ceef54c 966 if ($filearea === 'content') { //return file not found straight away to improve performance.
dbdc7355 967 send_header_404();
6ceef54c
DM
968 die;
969 }
9528568b 970 return false;
971 }
972
973 // finally send the file
261cbbac 974 send_stored_file($file, $lifetime, 0, false, $options);
9528568b 975}
976
42f103be 977/**
28f672b2 978 * @uses FEATURE_GROUPS
979 * @uses FEATURE_GROUPINGS
980 * @uses FEATURE_GROUPMEMBERSONLY
981 * @uses FEATURE_MOD_INTRO
982 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
94db2749 983 * @uses FEATURE_COMPLETION_HAS_RULES
28f672b2 984 * @uses FEATURE_GRADE_HAS_GRADE
985 * @uses FEATURE_GRADE_OUTCOMES
42f103be 986 * @param string $feature FEATURE_xx constant for requested feature
28f672b2 987 * @return mixed True if module supports feature, false if not, null if doesn't know
42f103be 988 */
989function scorm_supports($feature) {
990 switch($feature) {
991 case FEATURE_GROUPS: return false;
992 case FEATURE_GROUPINGS: return false;
993 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 994 case FEATURE_MOD_INTRO: return true;
42f103be 995 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
94db2749 996 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 997 case FEATURE_GRADE_HAS_GRADE: return true;
998 case FEATURE_GRADE_OUTCOMES: return true;
02488b86 999 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 1000 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 1001
1002 default: return null;
1003 }
1004}
0a1f8f8f 1005
a4c4962f
DM
1006/**
1007 * Get the filename for a temp log file
1008 *
1009 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1010 * @param integer $scoid - scoid of object this log entry is for
91421f3e 1011 * @return string The filename as an absolute path
f7b5c6aa 1012 */
a4c4962f
DM
1013function scorm_debug_log_filename($type, $scoid) {
1014 global $CFG, $USER;
1015
7aa06e6d 1016 $logpath = $CFG->tempdir.'/scormlogs';
a4c4962f
DM
1017 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1018 return $logfile;
1019}
1020
169a204c
DM
1021/**
1022 * writes log output to a temp log file
1023 *
1024 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1025 * @param string $text - text to be written to file.
1026 * @param integer $scoid - scoid of object this log entry is for.
1027 */
a4c4962f 1028function scorm_debug_log_write($type, $text, $scoid) {
169a204c 1029
3b4b776a 1030 $debugenablelog = get_config('scorm', 'allowapidebug');
169a204c 1031 if (!$debugenablelog || empty($text)) {
f7b5c6aa 1032 return;
169a204c 1033 }
af9b1444 1034 if (make_temp_directory('scormlogs/')) {
a4c4962f 1035 $logfile = scorm_debug_log_filename($type, $scoid);
169a204c
DM
1036 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1037 }
1038}
a4c4962f 1039
f7b5c6aa 1040/**
a4c4962f
DM
1041 * Remove debug log file
1042 *
1043 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1044 * @param integer $scoid - scoid of object this log entry is for
1045 * @return boolean True if the file is successfully deleted, false otherwise
1046 */
1047function scorm_debug_log_remove($type, $scoid) {
1048
3b4b776a 1049 $debugenablelog = get_config('scorm', 'allowapidebug');
a4c4962f
DM
1050 $logfile = scorm_debug_log_filename($type, $scoid);
1051 if (!$debugenablelog || !file_exists($logfile)) {
1052 return false;
1053 }
1054
1055 return @unlink($logfile);
1056}
1057
d860e4f8
DM
1058/**
1059 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1060 *
1061 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1062 * @param array $htmlarray
64f93798 1063 * @return mixed
d860e4f8
DM
1064 */
1065function scorm_print_overview($courses, &$htmlarray) {
1066 global $USER, $CFG, $DB;
1067
1068 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1069 return array();
1070 }
1071
f7b5c6aa 1072 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
d860e4f8
DM
1073 return;
1074 }
1075
1076 $scormids = array();
1077
1078 // Do scorm::isopen() here without loading the whole thing for speed
1079 foreach ($scorms as $key => $scorm) {
1080 $time = time();
1081 if ($scorm->timeopen) {
1082 $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
1083 }
1a70a647 1084 if (empty($scorm->displayattemptstatus) && (empty($isopen) || empty($scorm->timeclose))) {
d860e4f8 1085 unset($scorms[$key]);
f7b5c6aa 1086 } else {
d860e4f8
DM
1087 $scormids[] = $scorm->id;
1088 }
1089 }
1090
f7b5c6aa 1091 if (empty($scormids)) {
91421f3e 1092 // no scorms to look at - we're done
d860e4f8
DM
1093 return true;
1094 }
1095 $strscorm = get_string('modulename', 'scorm');
1096 $strduedate = get_string('duedate', 'scorm');
1097
1098 foreach ($scorms as $scorm) {
1099 $str = '<div class="scorm overview"><div class="name">'.$strscorm. ': '.
1100 '<a '.($scorm->visible ? '':' class="dimmed"').
1101 'title="'.$strscorm.'" href="'.$CFG->wwwroot.
bdea587b 1102 '/mod/scorm/view.php?id='.$scorm->coursemodule.'">'.
d860e4f8
DM
1103 $scorm->name.'</a></div>';
1104 if ($scorm->timeclose) {
1105 $str .= '<div class="info">'.$strduedate.': '.userdate($scorm->timeclose).'</div>';
1106 }
6257f664
DM
1107 if ($scorm->displayattemptstatus == 1) {
1108 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1109 $str .= '<div class="details">'.scorm_get_attempt_status($USER, $scorm).'</div>';
1110 }
d860e4f8
DM
1111 $str .= '</div>';
1112 if (empty($htmlarray[$scorm->course]['scorm'])) {
1113 $htmlarray[$scorm->course]['scorm'] = $str;
1114 } else {
1115 $htmlarray[$scorm->course]['scorm'] .= $str;
1116 }
1117 }
1118}
b1627a92
DC
1119
1120/**
1121 * Return a list of page types
1122 * @param string $pagetype current page type
1123 * @param stdClass $parentcontext Block's parent context
1124 * @param stdClass $currentcontext Current context of block
1125 */
b38e2e28 1126function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
1127 $module_pagetype = array('mod-scorm-*'=>get_string('page-mod-scorm-x', 'scorm'));
1128 return $module_pagetype;
1129}
e6402b54
DM
1130
1131/**
1132 * Returns the SCORM version used.
1133 * @param string $scormversion comes from $scorm->version
1134 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1135 * @return Scorm version.
1136 */
1137function scorm_version_check($scormversion, $version='') {
1138 $scormversion = trim(strtolower($scormversion));
1139 if (empty($version) || $version==SCORM_12) {
1140 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1141 return SCORM_12;
1142 }
1143 if (!empty($version)) {
1144 return false;
1145 }
1146 }
1147 if (empty($version) || $version == SCORM_13) {
1148 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1149 return SCORM_13;
1150 }
1151 if (!empty($version)) {
1152 return false;
1153 }
1154 }
1155 if (empty($version) || $version == SCORM_AICC) {
1156 if (strpos($scormversion, 'aicc')) {
1157 return SCORM_AICC;
1158 }
1159 if (!empty($version)) {
1160 return false;
1161 }
1162 }
1163 return false;
3e4c2435 1164}
94db2749
AB
1165
1166/**
1167 * Obtains the automatic completion state for this scorm based on any conditions
1168 * in scorm settings.
1169 *
1170 * @param object $course Course
1171 * @param object $cm Course-module
1172 * @param int $userid User ID
1173 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1174 * @return bool True if completed, false if not. (If no conditions, then return
1175 * value depends on comparison type)
1176 */
1177function scorm_get_completion_state($course, $cm, $userid, $type) {
1178 global $DB;
1179
1180 $result = $type;
1181
1182 // Get scorm
1183 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1184 print_error('cannotfindscorm');
1185 }
1186
1187 // Get user's tracks data
1188 $tracks = $DB->get_records_sql(
1189 "
1190 SELECT
1191 id,
1192 element,
1193 value
1194 FROM
1195 {scorm_scoes_track}
1196 WHERE
1197 scormid = ?
1198 AND userid = ?
1199 AND element IN
1200 (
1201 'cmi.core.lesson_status',
1202 'cmi.completion_status',
1203 'cmi.success_status',
1204 'cmi.core.score.raw',
1205 'cmi.score.raw'
1206 )
1207 ",
1208 array($scorm->id, $userid)
1209 );
1210
1211 if (!$tracks) {
1212 return completion_info::aggregate_completion_states($type, $result, false);
1213 }
1214
1215 // Check for status
1216 if ($scorm->completionstatusrequired !== null) {
1217
1218 // Get status
1219 $statuses = array_flip(scorm_status_options());
1220 $nstatus = 0;
1221
1222 foreach ($tracks as $track) {
1223 if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1224 continue;
1225 }
1226
1227 if (array_key_exists($track->value, $statuses)) {
1228 $nstatus |= $statuses[$track->value];
1229 }
1230 }
1231
1232 if ($scorm->completionstatusrequired & $nstatus) {
1233 return completion_info::aggregate_completion_states($type, $result, true);
1234 } else {
1235 return completion_info::aggregate_completion_states($type, $result, false);
1236 }
1237
1238 }
1239
1240 // Check for score
1241 if ($scorm->completionscorerequired !== null) {
1242 $maxscore = -1;
1243
1244 foreach ($tracks as $track) {
1245 if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1246 continue;
1247 }
1248
1249 if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1250 $maxscore = floatval($track->value);
1251 }
1252 }
1253
1254 if ($scorm->completionscorerequired <= $maxscore) {
1255 return completion_info::aggregate_completion_states($type, $result, true);
1256 } else {
1257 return completion_info::aggregate_completion_states($type, $result, false);
1258 }
1259 }
1260
1261 return $result;
1262}
01b5936c
CT
1263
1264/**
1265 * Register the ability to handle drag and drop file uploads
1266 * @return array containing details of the files / types the mod can handle
1267 */
1268function scorm_dndupload_register() {
1269 return array('files' => array(
1270 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1271 ));
1272}
1273
1274/**
1275 * Handle a file that has been uploaded
1276 * @param object $uploadinfo details of the file / content that has been uploaded
1277 * @return int instance id of the newly created mod
1278 */
1279function scorm_dndupload_handle($uploadinfo) {
1280
1281 $context = context_module::instance($uploadinfo->coursemodule);
1282 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1283 $fs = get_file_storage();
1284 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1285 $file = reset($files);
1286
8550d72d 1287 // Validate the file, make sure it's a valid SCORM package!
01b5936c
CT
1288 $packer = get_file_packer('application/zip');
1289 $filelist = $file->list_files($packer);
1290
1291 if (!is_array($filelist)) {
1292 return false;
1293 } else {
1294 $manifestpresent = false;
1295 $aiccfound = false;
1296
1297 foreach ($filelist as $info) {
1298 if ($info->pathname == 'imsmanifest.xml') {
1299 $manifestpresent = true;
1300 break;
1301 }
1302
1303 if (preg_match('/\.cst$/', $info->pathname)) {
1304 $aiccfound = true;
1305 break;
1306 }
1307 }
1308
1309 if (!$manifestpresent && !$aiccfound) {
1310 return false;
1311 }
1312 }
1313
8550d72d 1314 // Create a default scorm object to pass to scorm_add_instance()!
01b5936c
CT
1315 $scorm = get_config('scorm');
1316 $scorm->course = $uploadinfo->course->id;
1317 $scorm->coursemodule = $uploadinfo->coursemodule;
1318 $scorm->cmidnumber = '';
1319 $scorm->name = $uploadinfo->displayname;
1320 $scorm->scormtype = SCORM_TYPE_LOCAL;
1321 $scorm->reference = $file->get_filename();
1322 $scorm->intro = '';
1323 $scorm->width = $scorm->framewidth;
1324 $scorm->height = $scorm->frameheight;
1325
1326 return scorm_add_instance($scorm, null);
1327}