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