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