Merge branch 'wip-MDL-56788-master' of git://github.com/abgreeve/moodle
[moodle.git] / mod / scorm / lib.php
blob2f740e529909693d23a96dd8bfa57ea5090ac1fb
1 <?php
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.
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/>.
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
23 /** SCORM_TYPE_LOCAL = local */
24 define('SCORM_TYPE_LOCAL', 'local');
25 /** SCORM_TYPE_LOCALSYNC = localsync */
26 define('SCORM_TYPE_LOCALSYNC', 'localsync');
27 /** SCORM_TYPE_EXTERNAL = external */
28 define('SCORM_TYPE_EXTERNAL', 'external');
29 /** SCORM_TYPE_AICCURL = external AICC url */
30 define('SCORM_TYPE_AICCURL', 'aiccurl');
32 define('SCORM_TOC_SIDE', 0);
33 define('SCORM_TOC_HIDDEN', 1);
34 define('SCORM_TOC_POPUP', 2);
35 define('SCORM_TOC_DISABLED', 3);
37 // Used to show/hide navigation buttons and set their position.
38 define('SCORM_NAV_DISABLED', 0);
39 define('SCORM_NAV_UNDER_CONTENT', 1);
40 define('SCORM_NAV_FLOATING', 2);
42 // Used to check what SCORM version is being used.
43 define('SCORM_12', 1);
44 define('SCORM_13', 2);
45 define('SCORM_AICC', 3);
47 // List of possible attemptstatusdisplay options.
48 define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
49 define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
50 define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
51 define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
53 /**
54 * Return an array of status options
56 * Optionally with translated strings
58 * @param bool $with_strings (optional)
59 * @return array
61 function scorm_status_options($withstrings = false) {
62 // Id's are important as they are bits.
63 $options = array(
64 2 => 'passed',
65 4 => 'completed'
68 if ($withstrings) {
69 foreach ($options as $key => $value) {
70 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
74 return $options;
78 /**
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.
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
90 * @param object $scorm Form data
91 * @param object $mform
92 * @return int new instance id
94 function scorm_add_instance($scorm, $mform=null) {
95 global $CFG, $DB;
97 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
99 if (empty($scorm->timeopen)) {
100 $scorm->timeopen = 0;
102 if (empty($scorm->timeclose)) {
103 $scorm->timeclose = 0;
105 if (empty($scorm->completionstatusallscos)) {
106 $scorm->completionstatusallscos = 0;
108 $cmid = $scorm->coursemodule;
109 $cmidnumber = $scorm->cmidnumber;
110 $courseid = $scorm->course;
112 $context = context_module::instance($cmid);
114 $scorm = scorm_option2text($scorm);
115 $scorm->width = (int)str_replace('%', '', $scorm->width);
116 $scorm->height = (int)str_replace('%', '', $scorm->height);
118 if (!isset($scorm->whatgrade)) {
119 $scorm->whatgrade = 0;
122 $id = $DB->insert_record('scorm', $scorm);
124 // Update course module record - from now on this instance properly exists and all function may be used.
125 $DB->set_field('course_modules', 'instance', $id, array('id' => $cmid));
127 // Reload scorm instance.
128 $record = $DB->get_record('scorm', array('id' => $id));
130 // Store the package and verify.
131 if ($record->scormtype === SCORM_TYPE_LOCAL) {
132 if (!empty($scorm->packagefile)) {
133 $fs = get_file_storage();
134 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
135 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
136 0, array('subdirs' => 0, 'maxfiles' => 1));
137 // Get filename of zip that was uploaded.
138 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
139 $file = reset($files);
140 $filename = $file->get_filename();
141 if ($filename !== false) {
142 $record->reference = $filename;
146 } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
147 $record->reference = $scorm->packageurl;
148 } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
149 $record->reference = $scorm->packageurl;
150 } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
151 $record->reference = $scorm->packageurl;
152 $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
153 } else {
154 return false;
157 // Save reference.
158 $DB->update_record('scorm', $record);
160 // Extra fields required in grade related functions.
161 $record->course = $courseid;
162 $record->cmidnumber = $cmidnumber;
163 $record->cmid = $cmid;
165 scorm_parse($record, true);
167 scorm_grade_item_update($record);
169 return $record->id;
173 * Given an object containing all the necessary data,
174 * (defined by the form in mod_form.php) this function
175 * will update an existing instance with new data.
177 * @global stdClass
178 * @global object
179 * @uses CONTEXT_MODULE
180 * @uses SCORM_TYPE_LOCAL
181 * @uses SCORM_TYPE_LOCALSYNC
182 * @uses SCORM_TYPE_EXTERNAL
183 * @param object $scorm Form data
184 * @param object $mform
185 * @return bool
187 function scorm_update_instance($scorm, $mform=null) {
188 global $CFG, $DB;
190 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
192 if (empty($scorm->timeopen)) {
193 $scorm->timeopen = 0;
195 if (empty($scorm->timeclose)) {
196 $scorm->timeclose = 0;
198 if (empty($scorm->completionstatusallscos)) {
199 $scorm->completionstatusallscos = 0;
202 $cmid = $scorm->coursemodule;
203 $cmidnumber = $scorm->cmidnumber;
204 $courseid = $scorm->course;
206 $scorm->id = $scorm->instance;
208 $context = context_module::instance($cmid);
210 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
211 if (!empty($scorm->packagefile)) {
212 $fs = get_file_storage();
213 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
214 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
215 0, array('subdirs' => 0, 'maxfiles' => 1));
216 // Get filename of zip that was uploaded.
217 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
218 $file = reset($files);
219 $filename = $file->get_filename();
220 if ($filename !== false) {
221 $scorm->reference = $filename;
225 } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
226 $scorm->reference = $scorm->packageurl;
227 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
228 $scorm->reference = $scorm->packageurl;
229 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
230 $scorm->reference = $scorm->packageurl;
231 $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
232 } else {
233 return false;
236 $scorm = scorm_option2text($scorm);
237 $scorm->width = (int)str_replace('%', '', $scorm->width);
238 $scorm->height = (int)str_replace('%', '', $scorm->height);
239 $scorm->timemodified = time();
241 if (!isset($scorm->whatgrade)) {
242 $scorm->whatgrade = 0;
245 $DB->update_record('scorm', $scorm);
247 $scorm = $DB->get_record('scorm', array('id' => $scorm->id));
249 // Extra fields required in grade related functions.
250 $scorm->course = $courseid;
251 $scorm->idnumber = $cmidnumber;
252 $scorm->cmid = $cmid;
254 scorm_parse($scorm, (bool)$scorm->updatefreq);
256 scorm_grade_item_update($scorm);
257 scorm_update_grades($scorm);
259 return true;
263 * Given an ID of an instance of this module,
264 * this function will permanently delete the instance
265 * and any data that depends on it.
267 * @global stdClass
268 * @global object
269 * @param int $id Scorm instance id
270 * @return boolean
272 function scorm_delete_instance($id) {
273 global $CFG, $DB;
275 if (! $scorm = $DB->get_record('scorm', array('id' => $id))) {
276 return false;
279 $result = true;
281 // Delete any dependent records.
282 if (! $DB->delete_records('scorm_scoes_track', array('scormid' => $scorm->id))) {
283 $result = false;
285 if ($scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id))) {
286 foreach ($scoes as $sco) {
287 if (! $DB->delete_records('scorm_scoes_data', array('scoid' => $sco->id))) {
288 $result = false;
291 $DB->delete_records('scorm_scoes', array('scorm' => $scorm->id));
293 if (! $DB->delete_records('scorm', array('id' => $scorm->id))) {
294 $result = false;
297 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
298 $result = false;
300 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
301 $result = false;
303 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
304 $result = false;
306 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
307 $result = false;
309 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
310 $result = false;
312 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
313 $result = false;
315 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
316 $result = false;
319 scorm_grade_item_delete($scorm);
321 return $result;
325 * Return a small object with summary information about what a
326 * user has done with a given particular instance of this module
327 * Used for user activity reports.
329 * @global stdClass
330 * @param int $course Course id
331 * @param int $user User id
332 * @param int $mod
333 * @param int $scorm The scorm id
334 * @return mixed
336 function scorm_user_outline($course, $user, $mod, $scorm) {
337 global $CFG;
338 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
340 require_once("$CFG->libdir/gradelib.php");
341 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
342 if (!empty($grades->items[0]->grades)) {
343 $grade = reset($grades->items[0]->grades);
344 $result = new stdClass();
345 $result->info = get_string('grade') . ': '. $grade->str_long_grade;
347 // Datesubmitted == time created. dategraded == time modified or time overridden
348 // if grade was last modified by the user themselves use date graded. Otherwise use date submitted.
349 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
350 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
351 $result->time = $grade->dategraded;
352 } else {
353 $result->time = $grade->datesubmitted;
356 return $result;
358 return null;
362 * Print a detailed representation of what a user has done with
363 * a given particular instance of this module, for user activity reports.
365 * @global stdClass
366 * @global object
367 * @param object $course
368 * @param object $user
369 * @param object $mod
370 * @param object $scorm
371 * @return boolean
373 function scorm_user_complete($course, $user, $mod, $scorm) {
374 global $CFG, $DB, $OUTPUT;
375 require_once("$CFG->libdir/gradelib.php");
377 $liststyle = 'structlist';
378 $now = time();
379 $firstmodify = $now;
380 $lastmodify = 0;
381 $sometoreport = false;
382 $report = '';
384 // First Access and Last Access dates for SCOs.
385 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
386 $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
387 $firstmodify = $timetracks->start;
388 $lastmodify = $timetracks->finish;
390 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
391 if (!empty($grades->items[0]->grades)) {
392 $grade = reset($grades->items[0]->grades);
393 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
394 if ($grade->str_feedback) {
395 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
399 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
400 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
401 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
402 array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
403 if (count($orgs) <= 1) {
404 unset($orgs);
405 $orgs = array();
406 $org = new stdClass();
407 $org->identifier = '';
408 $orgs[] = $org;
410 $report .= html_writer::start_div('mod-scorm');
411 foreach ($orgs as $org) {
412 $conditions = array();
413 $currentorg = '';
414 if (!empty($org->identifier)) {
415 $report .= html_writer::div($org->title, 'orgtitle');
416 $currentorg = $org->identifier;
417 $conditions['organization'] = $currentorg;
419 $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
420 $conditions['scorm'] = $scorm->id;
421 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
422 // Drop keys so that we can access array sequentially.
423 $scoes = array_values($scoes);
424 $level = 0;
425 $sublist = 1;
426 $parents[$level] = '/';
427 foreach ($scoes as $pos => $sco) {
428 if ($parents[$level] != $sco->parent) {
429 if ($level > 0 && $parents[$level - 1] == $sco->parent) {
430 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
431 $level--;
432 } else {
433 $i = $level;
434 $closelist = '';
435 while (($i > 0) && ($parents[$level] != $sco->parent)) {
436 $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
437 $i--;
439 if (($i == 0) && ($sco->parent != $currentorg)) {
440 $report .= html_writer::start_tag('li');
441 $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
442 $level++;
443 } else {
444 $report .= $closelist;
445 $level = $i;
447 $parents[$level] = $sco->parent;
450 $report .= html_writer::start_tag('li');
451 if (isset($scoes[$pos + 1])) {
452 $nextsco = $scoes[$pos + 1];
453 } else {
454 $nextsco = false;
456 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
457 (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
458 $sublist++;
459 } else {
460 $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
463 if ($sco->launch) {
464 $score = '';
465 $totaltime = '';
466 if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
467 if ($usertrack->status == '') {
468 $usertrack->status = 'notattempted';
470 $strstatus = get_string($usertrack->status, 'scorm');
471 $report .= html_writer::img($OUTPUT->pix_url($usertrack->status, 'scorm'),
472 $strstatus, array('title' => $strstatus));
473 } else {
474 if ($sco->scormtype == 'sco') {
475 $report .= html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'),
476 get_string('notattempted', 'scorm'),
477 array('title' => get_string('notattempted', 'scorm')));
478 } else {
479 $report .= html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('asset', 'scorm'),
480 array('title' => get_string('asset', 'scorm')));
483 $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
484 if ($usertrack !== false) {
485 $sometoreport = true;
486 $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
487 foreach ($usertrack as $element => $value) {
488 if (substr($element, 0, 3) == 'cmi') {
489 $report .= html_writer::tag('li', $element.' => '.s($value));
492 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
494 } else {
495 $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
498 for ($i = 0; $i < $level; $i++) {
499 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
502 $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
504 $report .= html_writer::end_div();
506 if ($sometoreport) {
507 if ($firstmodify < $now) {
508 $timeago = format_time($now - $firstmodify);
509 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
511 if ($lastmodify > 0) {
512 $timeago = format_time($now - $lastmodify);
513 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
515 echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
516 echo $report;
517 } else {
518 print_string('noactivity', 'scorm');
521 return true;
525 * Function to be run periodically according to the moodle cron
526 * This function searches for things that need to be done, such
527 * as sending out mail, toggling flags etc ...
529 * @global stdClass
530 * @global object
531 * @return boolean
533 function scorm_cron () {
534 global $CFG, $DB;
536 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
538 $sitetimezone = core_date::get_server_timezone();
539 // Now see if there are any scorm updates to be done.
541 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time.
542 set_config('scorm_updatetimelast', 0);
545 $timenow = time();
546 $updatetime = usergetmidnight($timenow, $sitetimezone);
548 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
550 set_config('scorm_updatetimelast', $timenow);
552 mtrace('Updating scorm packages which require daily update');// We are updating.
554 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
555 foreach ($scormsupdate as $scormupdate) {
556 scorm_parse($scormupdate, true);
559 // Now clear out AICC session table with old session data.
560 $cfgscorm = get_config('scorm');
561 if (!empty($cfgscorm->allowaicchacp)) {
562 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata * 24 * 60 * 60);
563 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
567 return true;
571 * Return grade for given user or all users.
573 * @global stdClass
574 * @global object
575 * @param int $scormid id of scorm
576 * @param int $userid optional user id, 0 means all users
577 * @return array array of grades, false if none
579 function scorm_get_user_grades($scorm, $userid=0) {
580 global $CFG, $DB;
581 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
583 $grades = array();
584 if (empty($userid)) {
585 $scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid",
586 array($scorm->id), "", "userid,null");
587 if ($scousers) {
588 foreach ($scousers as $scouser) {
589 $grades[$scouser->userid] = new stdClass();
590 $grades[$scouser->userid]->id = $scouser->userid;
591 $grades[$scouser->userid]->userid = $scouser->userid;
592 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
594 } else {
595 return false;
598 } else {
599 $preattempt = $DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid",
600 array($scorm->id, $userid), "", "userid,null");
601 if (!$preattempt) {
602 return false; // No attempt yet.
604 $grades[$userid] = new stdClass();
605 $grades[$userid]->id = $userid;
606 $grades[$userid]->userid = $userid;
607 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
610 return $grades;
614 * Update grades in central gradebook
616 * @category grade
617 * @param object $scorm
618 * @param int $userid specific user only, 0 mean all
619 * @param bool $nullifnone
621 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
622 global $CFG;
623 require_once($CFG->libdir.'/gradelib.php');
624 require_once($CFG->libdir.'/completionlib.php');
626 if ($grades = scorm_get_user_grades($scorm, $userid)) {
627 scorm_grade_item_update($scorm, $grades);
628 // Set complete.
629 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
630 } else if ($userid and $nullifnone) {
631 $grade = new stdClass();
632 $grade->userid = $userid;
633 $grade->rawgrade = null;
634 scorm_grade_item_update($scorm, $grade);
635 // Set incomplete.
636 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
637 } else {
638 scorm_grade_item_update($scorm);
643 * Update/create grade item for given scorm
645 * @category grade
646 * @uses GRADE_TYPE_VALUE
647 * @uses GRADE_TYPE_NONE
648 * @param object $scorm object with extra cmidnumber
649 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
650 * @return object grade_item
652 function scorm_grade_item_update($scorm, $grades=null) {
653 global $CFG, $DB;
654 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
655 if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
656 require_once($CFG->libdir.'/gradelib.php');
659 $params = array('itemname' => $scorm->name);
660 if (isset($scorm->cmidnumber)) {
661 $params['idnumber'] = $scorm->cmidnumber;
664 if ($scorm->grademethod == GRADESCOES) {
665 $maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.
666 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id));
667 if ($maxgrade) {
668 $params['gradetype'] = GRADE_TYPE_VALUE;
669 $params['grademax'] = $maxgrade;
670 $params['grademin'] = 0;
671 } else {
672 $params['gradetype'] = GRADE_TYPE_NONE;
674 } else {
675 $params['gradetype'] = GRADE_TYPE_VALUE;
676 $params['grademax'] = $scorm->maxgrade;
677 $params['grademin'] = 0;
680 if ($grades === 'reset') {
681 $params['reset'] = true;
682 $grades = null;
685 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
689 * Delete grade item for given scorm
691 * @category grade
692 * @param object $scorm object
693 * @return object grade_item
695 function scorm_grade_item_delete($scorm) {
696 global $CFG;
697 require_once($CFG->libdir.'/gradelib.php');
699 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted' => 1));
703 * List the actions that correspond to a view of this module.
704 * This is used by the participation report.
706 * Note: This is not used by new logging system. Event with
707 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
708 * be considered as view action.
710 * @return array
712 function scorm_get_view_actions() {
713 return array('pre-view', 'view', 'view all', 'report');
717 * List the actions that correspond to a post of this module.
718 * This is used by the participation report.
720 * Note: This is not used by new logging system. Event with
721 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
722 * will be considered as post action.
724 * @return array
726 function scorm_get_post_actions() {
727 return array();
731 * @param object $scorm
732 * @return object $scorm
734 function scorm_option2text($scorm) {
735 $scormpopoupoptions = scorm_get_popup_options_array();
737 if (isset($scorm->popup)) {
738 if ($scorm->popup == 1) {
739 $optionlist = array();
740 foreach ($scormpopoupoptions as $name => $option) {
741 if (isset($scorm->$name)) {
742 $optionlist[] = $name.'='.$scorm->$name;
743 } else {
744 $optionlist[] = $name.'=0';
747 $scorm->options = implode(',', $optionlist);
748 } else {
749 $scorm->options = '';
751 } else {
752 $scorm->popup = 0;
753 $scorm->options = '';
755 return $scorm;
759 * Implementation of the function for printing the form elements that control
760 * whether the course reset functionality affects the scorm.
762 * @param object $mform form passed by reference
764 function scorm_reset_course_form_definition(&$mform) {
765 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
766 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
770 * Course reset form defaults.
772 * @return array
774 function scorm_reset_course_form_defaults($course) {
775 return array('reset_scorm' => 1);
779 * Removes all grades from gradebook
781 * @global stdClass
782 * @global object
783 * @param int $courseid
784 * @param string optional type
786 function scorm_reset_gradebook($courseid, $type='') {
787 global $CFG, $DB;
789 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
790 FROM {scorm} s, {course_modules} cm, {modules} m
791 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
793 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
794 foreach ($scorms as $scorm) {
795 scorm_grade_item_update($scorm, 'reset');
801 * Actual implementation of the reset course functionality, delete all the
802 * scorm attempts for course $data->courseid.
804 * @global stdClass
805 * @global object
806 * @param object $data the data submitted from the reset course.
807 * @return array status array
809 function scorm_reset_userdata($data) {
810 global $CFG, $DB;
812 $componentstr = get_string('modulenameplural', 'scorm');
813 $status = array();
815 if (!empty($data->reset_scorm)) {
816 $scormssql = "SELECT s.id
817 FROM {scorm} s
818 WHERE s.course=?";
820 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
822 // Remove all grades from gradebook.
823 if (empty($data->reset_gradebook_grades)) {
824 scorm_reset_gradebook($data->courseid);
827 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallattempts', 'scorm'), 'error' => false);
830 // No dates to shift here.
832 return $status;
836 * Returns all other caps used in module
838 * @return array
840 function scorm_get_extra_capabilities() {
841 return array('moodle/site:accessallgroups');
845 * Lists all file areas current user may browse
847 * @param object $course
848 * @param object $cm
849 * @param object $context
850 * @return array
852 function scorm_get_file_areas($course, $cm, $context) {
853 $areas = array();
854 $areas['content'] = get_string('areacontent', 'scorm');
855 $areas['package'] = get_string('areapackage', 'scorm');
856 return $areas;
860 * File browsing support for SCORM file areas
862 * @package mod_scorm
863 * @category files
864 * @param file_browser $browser file browser instance
865 * @param array $areas file areas
866 * @param stdClass $course course object
867 * @param stdClass $cm course module object
868 * @param stdClass $context context object
869 * @param string $filearea file area
870 * @param int $itemid item ID
871 * @param string $filepath file path
872 * @param string $filename file name
873 * @return file_info instance or null if not found
875 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
876 global $CFG;
878 if (!has_capability('moodle/course:managefiles', $context)) {
879 return null;
882 // No writing for now!
884 $fs = get_file_storage();
886 if ($filearea === 'content') {
888 $filepath = is_null($filepath) ? '/' : $filepath;
889 $filename = is_null($filename) ? '.' : $filename;
891 $urlbase = $CFG->wwwroot.'/pluginfile.php';
892 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
893 if ($filepath === '/' and $filename === '.') {
894 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
895 } else {
896 // Not found.
897 return null;
900 require_once("$CFG->dirroot/mod/scorm/locallib.php");
901 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
903 } else if ($filearea === 'package') {
904 $filepath = is_null($filepath) ? '/' : $filepath;
905 $filename = is_null($filename) ? '.' : $filename;
907 $urlbase = $CFG->wwwroot.'/pluginfile.php';
908 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
909 if ($filepath === '/' and $filename === '.') {
910 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
911 } else {
912 // Not found.
913 return null;
916 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
919 // Scorm_intro handled in file_browser.
921 return false;
925 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
927 * @package mod_scorm
928 * @category files
929 * @param stdClass $course course object
930 * @param stdClass $cm course module object
931 * @param stdClass $context context object
932 * @param string $filearea file area
933 * @param array $args extra arguments
934 * @param bool $forcedownload whether or not force download
935 * @param array $options additional options affecting the file serving
936 * @return bool false if file not found, does not return if found - just send the file
938 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
939 global $CFG, $DB;
941 if ($context->contextlevel != CONTEXT_MODULE) {
942 return false;
945 require_login($course, true, $cm);
947 $canmanageactivity = has_capability('moodle/course:manageactivities', $context);
948 $lifetime = null;
950 // Check SCORM availability.
951 if (!$canmanageactivity) {
952 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
954 $scorm = $DB->get_record('scorm', array('id' => $cm->instance), 'id, timeopen, timeclose', MUST_EXIST);
955 list($available, $warnings) = scorm_get_availability_status($scorm);
956 if (!$available) {
957 return false;
961 if ($filearea === 'content') {
962 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
963 $relativepath = implode('/', $args);
964 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
965 // TODO: add any other access restrictions here if needed!
967 } else if ($filearea === 'package') {
968 // Check if the global setting for disabling package downloads is enabled.
969 $protectpackagedownloads = get_config('scorm', 'protectpackagedownloads');
970 if ($protectpackagedownloads and !$canmanageactivity) {
971 return false;
973 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
974 $relativepath = implode('/', $args);
975 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
976 $lifetime = 0; // No caching here.
978 } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
979 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
980 $relativepath = implode('/', $args);
982 // Get imsmanifest file.
983 $fs = get_file_storage();
984 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
985 $file = reset($files);
987 // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
988 $packagefilename = $file->get_filename();
989 if (strtolower($packagefilename) !== 'imsmanifest.xml') {
990 return false;
993 $file->send_relative_file($relativepath);
994 } else {
995 return false;
998 $fs = get_file_storage();
999 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1000 if ($filearea === 'content') { // Return file not found straight away to improve performance.
1001 send_header_404();
1002 die;
1004 return false;
1007 // Finally send the file.
1008 send_stored_file($file, $lifetime, 0, false, $options);
1012 * @uses FEATURE_GROUPS
1013 * @uses FEATURE_GROUPINGS
1014 * @uses FEATURE_MOD_INTRO
1015 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1016 * @uses FEATURE_COMPLETION_HAS_RULES
1017 * @uses FEATURE_GRADE_HAS_GRADE
1018 * @uses FEATURE_GRADE_OUTCOMES
1019 * @param string $feature FEATURE_xx constant for requested feature
1020 * @return mixed True if module supports feature, false if not, null if doesn't know
1022 function scorm_supports($feature) {
1023 switch($feature) {
1024 case FEATURE_GROUPS: return true;
1025 case FEATURE_GROUPINGS: return true;
1026 case FEATURE_MOD_INTRO: return true;
1027 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1028 case FEATURE_COMPLETION_HAS_RULES: return true;
1029 case FEATURE_GRADE_HAS_GRADE: return true;
1030 case FEATURE_GRADE_OUTCOMES: return true;
1031 case FEATURE_BACKUP_MOODLE2: return true;
1032 case FEATURE_SHOW_DESCRIPTION: return true;
1034 default: return null;
1039 * Get the filename for a temp log file
1041 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1042 * @param integer $scoid - scoid of object this log entry is for
1043 * @return string The filename as an absolute path
1045 function scorm_debug_log_filename($type, $scoid) {
1046 global $CFG, $USER;
1048 $logpath = $CFG->tempdir.'/scormlogs';
1049 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1050 return $logfile;
1054 * writes log output to a temp log file
1056 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1057 * @param string $text - text to be written to file.
1058 * @param integer $scoid - scoid of object this log entry is for.
1060 function scorm_debug_log_write($type, $text, $scoid) {
1061 global $CFG;
1063 $debugenablelog = get_config('scorm', 'allowapidebug');
1064 if (!$debugenablelog || empty($text)) {
1065 return;
1067 if (make_temp_directory('scormlogs/')) {
1068 $logfile = scorm_debug_log_filename($type, $scoid);
1069 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1070 @chmod($logfile, $CFG->filepermissions);
1075 * Remove debug log file
1077 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1078 * @param integer $scoid - scoid of object this log entry is for
1079 * @return boolean True if the file is successfully deleted, false otherwise
1081 function scorm_debug_log_remove($type, $scoid) {
1083 $debugenablelog = get_config('scorm', 'allowapidebug');
1084 $logfile = scorm_debug_log_filename($type, $scoid);
1085 if (!$debugenablelog || !file_exists($logfile)) {
1086 return false;
1089 return @unlink($logfile);
1093 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1095 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1096 * @param array $htmlarray
1097 * @return mixed
1099 function scorm_print_overview($courses, &$htmlarray) {
1100 global $USER, $CFG;
1102 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1103 return array();
1106 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
1107 return;
1110 $strscorm = get_string('modulename', 'scorm');
1111 $strduedate = get_string('duedate', 'scorm');
1113 foreach ($scorms as $scorm) {
1114 $time = time();
1115 $showattemptstatus = false;
1116 if ($scorm->timeopen) {
1117 $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
1119 if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1120 $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) {
1121 $showattemptstatus = true;
1123 if ($showattemptstatus || !empty($isopen) || !empty($scorm->timeclose)) {
1124 $str = html_writer::start_div('scorm overview').html_writer::div($strscorm. ': '.
1125 html_writer::link($CFG->wwwroot.'/mod/scorm/view.php?id='.$scorm->coursemodule, $scorm->name,
1126 array('title' => $strscorm, 'class' => $scorm->visible ? '' : 'dimmed')), 'name');
1127 if ($scorm->timeclose) {
1128 $str .= html_writer::div($strduedate.': '.userdate($scorm->timeclose), 'info');
1130 if ($showattemptstatus) {
1131 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1132 $str .= html_writer::div(scorm_get_attempt_status($USER, $scorm), 'details');
1134 $str .= html_writer::end_div();
1135 if (empty($htmlarray[$scorm->course]['scorm'])) {
1136 $htmlarray[$scorm->course]['scorm'] = $str;
1137 } else {
1138 $htmlarray[$scorm->course]['scorm'] .= $str;
1145 * Return a list of page types
1146 * @param string $pagetype current page type
1147 * @param stdClass $parentcontext Block's parent context
1148 * @param stdClass $currentcontext Current context of block
1150 function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1151 $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1152 return $modulepagetype;
1156 * Returns the SCORM version used.
1157 * @param string $scormversion comes from $scorm->version
1158 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1159 * @return Scorm version.
1161 function scorm_version_check($scormversion, $version='') {
1162 $scormversion = trim(strtolower($scormversion));
1163 if (empty($version) || $version == SCORM_12) {
1164 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1165 return SCORM_12;
1167 if (!empty($version)) {
1168 return false;
1171 if (empty($version) || $version == SCORM_13) {
1172 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1173 return SCORM_13;
1175 if (!empty($version)) {
1176 return false;
1179 if (empty($version) || $version == SCORM_AICC) {
1180 if (strpos($scormversion, 'aicc')) {
1181 return SCORM_AICC;
1183 if (!empty($version)) {
1184 return false;
1187 return false;
1191 * Obtains the automatic completion state for this scorm based on any conditions
1192 * in scorm settings.
1194 * @param object $course Course
1195 * @param object $cm Course-module
1196 * @param int $userid User ID
1197 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1198 * @return bool True if completed, false if not. (If no conditions, then return
1199 * value depends on comparison type)
1201 function scorm_get_completion_state($course, $cm, $userid, $type) {
1202 global $DB;
1204 $result = $type;
1206 // Get scorm.
1207 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1208 print_error('cannotfindscorm');
1210 // Only check for existence of tracks and return false if completionstatusrequired or completionscorerequired
1211 // this means that if only view is required we don't end up with a false state.
1212 if ($scorm->completionstatusrequired !== null ||
1213 $scorm->completionscorerequired !== null) {
1214 // Get user's tracks data.
1215 $tracks = $DB->get_records_sql(
1217 SELECT
1219 scoid,
1220 element,
1221 value
1222 FROM
1223 {scorm_scoes_track}
1224 WHERE
1225 scormid = ?
1226 AND userid = ?
1227 AND element IN
1229 'cmi.core.lesson_status',
1230 'cmi.completion_status',
1231 'cmi.success_status',
1232 'cmi.core.score.raw',
1233 'cmi.score.raw'
1236 array($scorm->id, $userid)
1239 if (!$tracks) {
1240 return completion_info::aggregate_completion_states($type, $result, false);
1244 // Check for status.
1245 if ($scorm->completionstatusrequired !== null) {
1247 // Get status.
1248 $statuses = array_flip(scorm_status_options());
1249 $nstatus = 0;
1250 // Check any track for these values.
1251 $scostatus = array();
1252 foreach ($tracks as $track) {
1253 if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1254 continue;
1256 if (array_key_exists($track->value, $statuses)) {
1257 $scostatus[$track->scoid] = true;
1258 $nstatus |= $statuses[$track->value];
1262 if (!empty($scorm->completionstatusallscos)) {
1263 // Iterate over all scos and make sure each has a lesson_status.
1264 $scos = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id, 'scormtype' => 'sco'));
1265 foreach ($scos as $sco) {
1266 if (empty($scostatus[$sco->id])) {
1267 return completion_info::aggregate_completion_states($type, $result, false);
1270 return completion_info::aggregate_completion_states($type, $result, true);
1271 } else if ($scorm->completionstatusrequired & $nstatus) {
1272 return completion_info::aggregate_completion_states($type, $result, true);
1273 } else {
1274 return completion_info::aggregate_completion_states($type, $result, false);
1278 // Check for score.
1279 if ($scorm->completionscorerequired !== null) {
1280 $maxscore = -1;
1282 foreach ($tracks as $track) {
1283 if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1284 continue;
1287 if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1288 $maxscore = floatval($track->value);
1292 if ($scorm->completionscorerequired <= $maxscore) {
1293 return completion_info::aggregate_completion_states($type, $result, true);
1294 } else {
1295 return completion_info::aggregate_completion_states($type, $result, false);
1299 return $result;
1303 * Register the ability to handle drag and drop file uploads
1304 * @return array containing details of the files / types the mod can handle
1306 function scorm_dndupload_register() {
1307 return array('files' => array(
1308 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1313 * Handle a file that has been uploaded
1314 * @param object $uploadinfo details of the file / content that has been uploaded
1315 * @return int instance id of the newly created mod
1317 function scorm_dndupload_handle($uploadinfo) {
1319 $context = context_module::instance($uploadinfo->coursemodule);
1320 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1321 $fs = get_file_storage();
1322 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1323 $file = reset($files);
1325 // Validate the file, make sure it's a valid SCORM package!
1326 $errors = scorm_validate_package($file);
1327 if (!empty($errors)) {
1328 return false;
1330 // Create a default scorm object to pass to scorm_add_instance()!
1331 $scorm = get_config('scorm');
1332 $scorm->course = $uploadinfo->course->id;
1333 $scorm->coursemodule = $uploadinfo->coursemodule;
1334 $scorm->cmidnumber = '';
1335 $scorm->name = $uploadinfo->displayname;
1336 $scorm->scormtype = SCORM_TYPE_LOCAL;
1337 $scorm->reference = $file->get_filename();
1338 $scorm->intro = '';
1339 $scorm->width = $scorm->framewidth;
1340 $scorm->height = $scorm->frameheight;
1342 return scorm_add_instance($scorm, null);
1346 * Sets activity completion state
1348 * @param object $scorm object
1349 * @param int $userid User ID
1350 * @param int $completionstate Completion state
1351 * @param array $grades grades array of users with grades - used when $userid = 0
1353 function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1354 $course = new stdClass();
1355 $course->id = $scorm->course;
1356 $completion = new completion_info($course);
1358 // Check if completion is enabled site-wide, or for the course.
1359 if (!$completion->is_enabled()) {
1360 return;
1363 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1364 if (empty($cm) || !$completion->is_enabled($cm)) {
1365 return;
1368 if (empty($userid)) { // We need to get all the relevant users from $grades param.
1369 foreach ($grades as $grade) {
1370 $completion->update_state($cm, $completionstate, $grade->userid);
1372 } else {
1373 $completion->update_state($cm, $completionstate, $userid);
1378 * Check that a Zip file contains a valid SCORM package
1380 * @param $file stored_file a Zip file.
1381 * @return array empty if no issue is found. Array of error message otherwise
1383 function scorm_validate_package($file) {
1384 $packer = get_file_packer('application/zip');
1385 $errors = array();
1386 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1387 $file->import_external_file_contents();
1389 $filelist = $file->list_files($packer);
1391 if (!is_array($filelist)) {
1392 $errors['packagefile'] = get_string('badarchive', 'scorm');
1393 } else {
1394 $aiccfound = false;
1395 $badmanifestpresent = false;
1396 foreach ($filelist as $info) {
1397 if ($info->pathname == 'imsmanifest.xml') {
1398 return array();
1399 } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1400 // This package has an imsmanifest file inside a folder of the package.
1401 $badmanifestpresent = true;
1403 if (preg_match('/\.cst$/', $info->pathname)) {
1404 return array();
1407 if (!$aiccfound) {
1408 if ($badmanifestpresent) {
1409 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1410 } else {
1411 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1415 return $errors;
1419 * Check and set the correct mode and attempt when entering a SCORM package.
1421 * @param object $scorm object
1422 * @param string $newattempt should a new attempt be generated here.
1423 * @param int $attempt the attempt number this is for.
1424 * @param int $userid the userid of the user.
1425 * @param string $mode the current mode that has been selected.
1427 function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1428 global $DB;
1430 if (($mode == 'browse')) {
1431 if ($scorm->hidebrowse == 1) {
1432 // Prevent Browse mode if hidebrowse is set.
1433 $mode = 'normal';
1434 } else {
1435 // We don't need to check attempts as browse mode is set.
1436 return;
1439 // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1440 $incomplete = true;
1441 $tracks = $DB->get_recordset('scorm_scoes_track', array('scormid' => $scorm->id, 'userid' => $userid,
1442 'attempt' => $attempt, 'element' => 'cmi.core.lesson_status'));
1443 foreach ($tracks as $track) {
1444 if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1445 $incomplete = false;
1446 } else {
1447 $incomplete = true;
1448 break; // Found an incomplete sco, so the result as a whole is incomplete.
1451 $tracks->close();
1453 // Validate user request to start a new attempt.
1454 if ($incomplete === true) {
1455 // The option to start a new attempt should never have been presented. Force false.
1456 $newattempt = 'off';
1457 } else if (!empty($scorm->forcenewattempt)) {
1458 // A new attempt should be forced for already completed attempts.
1459 $newattempt = 'on';
1462 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1463 $attempt++;
1464 $mode = 'normal';
1465 } else { // Check if review mode should be set.
1466 if ($incomplete === true) {
1467 $mode = 'normal';
1468 } else {
1469 $mode = 'review';
1475 * Trigger the course_module_viewed event.
1477 * @param stdClass $scorm scorm object
1478 * @param stdClass $course course object
1479 * @param stdClass $cm course module object
1480 * @param stdClass $context context object
1481 * @since Moodle 3.0
1483 function scorm_view($scorm, $course, $cm, $context) {
1485 // Trigger course_module_viewed event.
1486 $params = array(
1487 'context' => $context,
1488 'objectid' => $scorm->id
1491 $event = \mod_scorm\event\course_module_viewed::create($params);
1492 $event->add_record_snapshot('course_modules', $cm);
1493 $event->add_record_snapshot('course', $course);
1494 $event->add_record_snapshot('scorm', $scorm);
1495 $event->trigger();
1499 * Check if the module has any update that affects the current user since a given time.
1501 * @param cm_info $cm course module data
1502 * @param int $from the time to check updates from
1503 * @param array $filter if we need to check only specific updates
1504 * @return stdClass an object with the different type of areas indicating if they were updated or not
1505 * @since Moodle 3.2
1507 function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1508 global $DB, $USER, $CFG;
1509 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1511 $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1512 $updates = new stdClass();
1513 list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1514 if (!$available) {
1515 return $updates;
1517 $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1519 $updates->tracks = (object) array('updated' => false);
1520 $select = 'scormid = ? AND userid = ? AND timemodified > ?';
1521 $params = array($scorm->id, $USER->id, $from);
1522 $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1523 if (!empty($tracks)) {
1524 $updates->tracks->updated = true;
1525 $updates->tracks->itemids = array_keys($tracks);
1527 return $updates;