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