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