MDL-63953 mod_scorm: Use correct value for first attempt.
[moodle.git] / mod / scorm / lib.php
blobad07348d740f0c1e0bdf6f52fcc218ee56216cfb
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 define('SCORM_EVENT_TYPE_OPEN', 'open');
54 define('SCORM_EVENT_TYPE_CLOSE', 'close');
56 /**
57 * Return an array of status options
59 * Optionally with translated strings
61 * @param bool $with_strings (optional)
62 * @return array
64 function scorm_status_options($withstrings = false) {
65 // Id's are important as they are bits.
66 $options = array(
67 2 => 'passed',
68 4 => 'completed'
71 if ($withstrings) {
72 foreach ($options as $key => $value) {
73 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
77 return $options;
81 /**
82 * Given an object containing all the necessary data,
83 * (defined by the form in mod_form.php) this function
84 * will create a new instance and return the id number
85 * of the new instance.
87 * @global stdClass
88 * @global object
89 * @uses CONTEXT_MODULE
90 * @uses SCORM_TYPE_LOCAL
91 * @uses SCORM_TYPE_LOCALSYNC
92 * @uses SCORM_TYPE_EXTERNAL
93 * @param object $scorm Form data
94 * @param object $mform
95 * @return int new instance id
97 function scorm_add_instance($scorm, $mform=null) {
98 global $CFG, $DB;
100 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
102 if (empty($scorm->timeopen)) {
103 $scorm->timeopen = 0;
105 if (empty($scorm->timeclose)) {
106 $scorm->timeclose = 0;
108 if (empty($scorm->completionstatusallscos)) {
109 $scorm->completionstatusallscos = 0;
111 $cmid = $scorm->coursemodule;
112 $cmidnumber = $scorm->cmidnumber;
113 $courseid = $scorm->course;
115 $context = context_module::instance($cmid);
117 $scorm = scorm_option2text($scorm);
118 $scorm->width = (int)str_replace('%', '', $scorm->width);
119 $scorm->height = (int)str_replace('%', '', $scorm->height);
121 if (!isset($scorm->whatgrade)) {
122 $scorm->whatgrade = 0;
125 $id = $DB->insert_record('scorm', $scorm);
127 // Update course module record - from now on this instance properly exists and all function may be used.
128 $DB->set_field('course_modules', 'instance', $id, array('id' => $cmid));
130 // Reload scorm instance.
131 $record = $DB->get_record('scorm', array('id' => $id));
133 // Store the package and verify.
134 if ($record->scormtype === SCORM_TYPE_LOCAL) {
135 if (!empty($scorm->packagefile)) {
136 $fs = get_file_storage();
137 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
138 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
139 0, array('subdirs' => 0, 'maxfiles' => 1));
140 // Get filename of zip that was uploaded.
141 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
142 $file = reset($files);
143 $filename = $file->get_filename();
144 if ($filename !== false) {
145 $record->reference = $filename;
149 } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
150 $record->reference = $scorm->packageurl;
151 } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
152 $record->reference = $scorm->packageurl;
153 } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
154 $record->reference = $scorm->packageurl;
155 $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
156 } else {
157 return false;
160 // Save reference.
161 $DB->update_record('scorm', $record);
163 // Extra fields required in grade related functions.
164 $record->course = $courseid;
165 $record->cmidnumber = $cmidnumber;
166 $record->cmid = $cmid;
168 scorm_parse($record, true);
170 scorm_grade_item_update($record);
171 scorm_update_calendar($record, $cmid);
172 if (!empty($scorm->completionexpected)) {
173 \core_completion\api::update_completion_date_event($cmid, 'scorm', $record, $scorm->completionexpected);
176 return $record->id;
180 * Given an object containing all the necessary data,
181 * (defined by the form in mod_form.php) this function
182 * will update an existing instance with new data.
184 * @global stdClass
185 * @global object
186 * @uses CONTEXT_MODULE
187 * @uses SCORM_TYPE_LOCAL
188 * @uses SCORM_TYPE_LOCALSYNC
189 * @uses SCORM_TYPE_EXTERNAL
190 * @param object $scorm Form data
191 * @param object $mform
192 * @return bool
194 function scorm_update_instance($scorm, $mform=null) {
195 global $CFG, $DB;
197 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
199 if (empty($scorm->timeopen)) {
200 $scorm->timeopen = 0;
202 if (empty($scorm->timeclose)) {
203 $scorm->timeclose = 0;
205 if (empty($scorm->completionstatusallscos)) {
206 $scorm->completionstatusallscos = 0;
209 $cmid = $scorm->coursemodule;
210 $cmidnumber = $scorm->cmidnumber;
211 $courseid = $scorm->course;
213 $scorm->id = $scorm->instance;
215 $context = context_module::instance($cmid);
217 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
218 if (!empty($scorm->packagefile)) {
219 $fs = get_file_storage();
220 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
221 file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
222 0, array('subdirs' => 0, 'maxfiles' => 1));
223 // Get filename of zip that was uploaded.
224 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
225 $file = reset($files);
226 $filename = $file->get_filename();
227 if ($filename !== false) {
228 $scorm->reference = $filename;
232 } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
233 $scorm->reference = $scorm->packageurl;
234 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
235 $scorm->reference = $scorm->packageurl;
236 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
237 $scorm->reference = $scorm->packageurl;
238 $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
239 } else {
240 return false;
243 $scorm = scorm_option2text($scorm);
244 $scorm->width = (int)str_replace('%', '', $scorm->width);
245 $scorm->height = (int)str_replace('%', '', $scorm->height);
246 $scorm->timemodified = time();
248 if (!isset($scorm->whatgrade)) {
249 $scorm->whatgrade = 0;
252 $DB->update_record('scorm', $scorm);
253 // We need to find this out before we blow away the form data.
254 $completionexpected = (!empty($scorm->completionexpected)) ? $scorm->completionexpected : null;
256 $scorm = $DB->get_record('scorm', array('id' => $scorm->id));
258 // Extra fields required in grade related functions.
259 $scorm->course = $courseid;
260 $scorm->idnumber = $cmidnumber;
261 $scorm->cmid = $cmid;
263 scorm_parse($scorm, (bool)$scorm->updatefreq);
265 scorm_grade_item_update($scorm);
266 scorm_update_grades($scorm);
267 scorm_update_calendar($scorm, $cmid);
268 \core_completion\api::update_completion_date_event($cmid, 'scorm', $scorm, $completionexpected);
270 return true;
274 * Given an ID of an instance of this module,
275 * this function will permanently delete the instance
276 * and any data that depends on it.
278 * @global stdClass
279 * @global object
280 * @param int $id Scorm instance id
281 * @return boolean
283 function scorm_delete_instance($id) {
284 global $CFG, $DB;
286 if (! $scorm = $DB->get_record('scorm', array('id' => $id))) {
287 return false;
290 $result = true;
292 // Delete any dependent records.
293 if (! $DB->delete_records('scorm_scoes_track', array('scormid' => $scorm->id))) {
294 $result = false;
296 if ($scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id))) {
297 foreach ($scoes as $sco) {
298 if (! $DB->delete_records('scorm_scoes_data', array('scoid' => $sco->id))) {
299 $result = false;
302 $DB->delete_records('scorm_scoes', array('scorm' => $scorm->id));
304 if (! $DB->delete_records('scorm', array('id' => $scorm->id))) {
305 $result = false;
308 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
309 $result = false;
311 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
312 $result = false;
314 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
315 $result = false;
317 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
318 $result = false;
320 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
321 $result = false;
323 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
324 $result = false;
326 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
327 $result = false;
330 scorm_grade_item_delete($scorm);
332 return $result;
336 * Return a small object with summary information about what a
337 * user has done with a given particular instance of this module
338 * Used for user activity reports.
340 * @global stdClass
341 * @param int $course Course id
342 * @param int $user User id
343 * @param int $mod
344 * @param int $scorm The scorm id
345 * @return mixed
347 function scorm_user_outline($course, $user, $mod, $scorm) {
348 global $CFG;
349 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
351 require_once("$CFG->libdir/gradelib.php");
352 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
353 if (!empty($grades->items[0]->grades)) {
354 $grade = reset($grades->items[0]->grades);
355 $result = new stdClass();
356 $result->info = get_string('grade') . ': '. $grade->str_long_grade;
358 // Datesubmitted == time created. dategraded == time modified or time overridden
359 // if grade was last modified by the user themselves use date graded. Otherwise use date submitted.
360 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
361 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
362 $result->time = $grade->dategraded;
363 } else {
364 $result->time = $grade->datesubmitted;
367 return $result;
369 return null;
373 * Print a detailed representation of what a user has done with
374 * a given particular instance of this module, for user activity reports.
376 * @global stdClass
377 * @global object
378 * @param object $course
379 * @param object $user
380 * @param object $mod
381 * @param object $scorm
382 * @return boolean
384 function scorm_user_complete($course, $user, $mod, $scorm) {
385 global $CFG, $DB, $OUTPUT;
386 require_once("$CFG->libdir/gradelib.php");
388 $liststyle = 'structlist';
389 $now = time();
390 $firstmodify = $now;
391 $lastmodify = 0;
392 $sometoreport = false;
393 $report = '';
395 // First Access and Last Access dates for SCOs.
396 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
397 $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
398 $firstmodify = $timetracks->start;
399 $lastmodify = $timetracks->finish;
401 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
402 if (!empty($grades->items[0]->grades)) {
403 $grade = reset($grades->items[0]->grades);
404 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
405 if ($grade->str_feedback) {
406 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
410 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
411 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
412 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
413 array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
414 if (count($orgs) <= 1) {
415 unset($orgs);
416 $orgs = array();
417 $org = new stdClass();
418 $org->identifier = '';
419 $orgs[] = $org;
421 $report .= html_writer::start_div('mod-scorm');
422 foreach ($orgs as $org) {
423 $conditions = array();
424 $currentorg = '';
425 if (!empty($org->identifier)) {
426 $report .= html_writer::div($org->title, 'orgtitle');
427 $currentorg = $org->identifier;
428 $conditions['organization'] = $currentorg;
430 $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
431 $conditions['scorm'] = $scorm->id;
432 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
433 // Drop keys so that we can access array sequentially.
434 $scoes = array_values($scoes);
435 $level = 0;
436 $sublist = 1;
437 $parents[$level] = '/';
438 foreach ($scoes as $pos => $sco) {
439 if ($parents[$level] != $sco->parent) {
440 if ($level > 0 && $parents[$level - 1] == $sco->parent) {
441 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
442 $level--;
443 } else {
444 $i = $level;
445 $closelist = '';
446 while (($i > 0) && ($parents[$level] != $sco->parent)) {
447 $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
448 $i--;
450 if (($i == 0) && ($sco->parent != $currentorg)) {
451 $report .= html_writer::start_tag('li');
452 $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
453 $level++;
454 } else {
455 $report .= $closelist;
456 $level = $i;
458 $parents[$level] = $sco->parent;
461 $report .= html_writer::start_tag('li');
462 if (isset($scoes[$pos + 1])) {
463 $nextsco = $scoes[$pos + 1];
464 } else {
465 $nextsco = false;
467 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
468 (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
469 $sublist++;
470 } else {
471 $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
474 if ($sco->launch) {
475 $score = '';
476 $totaltime = '';
477 if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
478 if ($usertrack->status == '') {
479 $usertrack->status = 'notattempted';
481 $strstatus = get_string($usertrack->status, 'scorm');
482 $report .= $OUTPUT->pix_icon($usertrack->status, $strstatus, 'scorm');
483 } else {
484 if ($sco->scormtype == 'sco') {
485 $report .= $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
486 } else {
487 $report .= $OUTPUT->pix_icon('asset', get_string('asset', 'scorm'), 'scorm');
490 $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
491 if ($usertrack !== false) {
492 $sometoreport = true;
493 $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
494 foreach ($usertrack as $element => $value) {
495 if (substr($element, 0, 3) == 'cmi') {
496 $report .= html_writer::tag('li', $element.' => '.s($value));
499 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
501 } else {
502 $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
505 for ($i = 0; $i < $level; $i++) {
506 $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
509 $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
511 $report .= html_writer::end_div();
513 if ($sometoreport) {
514 if ($firstmodify < $now) {
515 $timeago = format_time($now - $firstmodify);
516 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
518 if ($lastmodify > 0) {
519 $timeago = format_time($now - $lastmodify);
520 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
522 echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
523 echo $report;
524 } else {
525 print_string('noactivity', 'scorm');
528 return true;
532 * Function to be run periodically according to the moodle Tasks API
533 * This function searches for things that need to be done, such
534 * as sending out mail, toggling flags etc ...
536 * @global stdClass
537 * @global object
538 * @return boolean
540 function scorm_cron_scheduled_task () {
541 global $CFG, $DB;
543 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
545 $sitetimezone = core_date::get_server_timezone();
546 // Now see if there are any scorm updates to be done.
548 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time.
549 set_config('scorm_updatetimelast', 0);
552 $timenow = time();
553 $updatetime = usergetmidnight($timenow, $sitetimezone);
555 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
557 set_config('scorm_updatetimelast', $timenow);
559 mtrace('Updating scorm packages which require daily update');// We are updating.
561 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
562 foreach ($scormsupdate as $scormupdate) {
563 scorm_parse($scormupdate, true);
566 // Now clear out AICC session table with old session data.
567 $cfgscorm = get_config('scorm');
568 if (!empty($cfgscorm->allowaicchacp)) {
569 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata * 24 * 60 * 60);
570 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
574 return true;
578 * Return grade for given user or all users.
580 * @global stdClass
581 * @global object
582 * @param int $scormid id of scorm
583 * @param int $userid optional user id, 0 means all users
584 * @return array array of grades, false if none
586 function scorm_get_user_grades($scorm, $userid=0) {
587 global $CFG, $DB;
588 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
590 $grades = array();
591 if (empty($userid)) {
592 $scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid",
593 array($scorm->id), "", "userid,null");
594 if ($scousers) {
595 foreach ($scousers as $scouser) {
596 $grades[$scouser->userid] = new stdClass();
597 $grades[$scouser->userid]->id = $scouser->userid;
598 $grades[$scouser->userid]->userid = $scouser->userid;
599 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
601 } else {
602 return false;
605 } else {
606 $preattempt = $DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid",
607 array($scorm->id, $userid), "", "userid,null");
608 if (!$preattempt) {
609 return false; // No attempt yet.
611 $grades[$userid] = new stdClass();
612 $grades[$userid]->id = $userid;
613 $grades[$userid]->userid = $userid;
614 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
617 return $grades;
621 * Update grades in central gradebook
623 * @category grade
624 * @param object $scorm
625 * @param int $userid specific user only, 0 mean all
626 * @param bool $nullifnone
628 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
629 global $CFG;
630 require_once($CFG->libdir.'/gradelib.php');
631 require_once($CFG->libdir.'/completionlib.php');
633 if ($grades = scorm_get_user_grades($scorm, $userid)) {
634 scorm_grade_item_update($scorm, $grades);
635 // Set complete.
636 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
637 } else if ($userid and $nullifnone) {
638 $grade = new stdClass();
639 $grade->userid = $userid;
640 $grade->rawgrade = null;
641 scorm_grade_item_update($scorm, $grade);
642 // Set incomplete.
643 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
644 } else {
645 scorm_grade_item_update($scorm);
650 * Update/create grade item for given scorm
652 * @category grade
653 * @uses GRADE_TYPE_VALUE
654 * @uses GRADE_TYPE_NONE
655 * @param object $scorm object with extra cmidnumber
656 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
657 * @return object grade_item
659 function scorm_grade_item_update($scorm, $grades=null) {
660 global $CFG, $DB;
661 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
662 if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
663 require_once($CFG->libdir.'/gradelib.php');
666 $params = array('itemname' => $scorm->name);
667 if (isset($scorm->cmidnumber)) {
668 $params['idnumber'] = $scorm->cmidnumber;
671 if ($scorm->grademethod == GRADESCOES) {
672 $maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.
673 $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id));
674 if ($maxgrade) {
675 $params['gradetype'] = GRADE_TYPE_VALUE;
676 $params['grademax'] = $maxgrade;
677 $params['grademin'] = 0;
678 } else {
679 $params['gradetype'] = GRADE_TYPE_NONE;
681 } else {
682 $params['gradetype'] = GRADE_TYPE_VALUE;
683 $params['grademax'] = $scorm->maxgrade;
684 $params['grademin'] = 0;
687 if ($grades === 'reset') {
688 $params['reset'] = true;
689 $grades = null;
692 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
696 * Delete grade item for given scorm
698 * @category grade
699 * @param object $scorm object
700 * @return object grade_item
702 function scorm_grade_item_delete($scorm) {
703 global $CFG;
704 require_once($CFG->libdir.'/gradelib.php');
706 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted' => 1));
710 * List the actions that correspond to a view of this module.
711 * This is used by the participation report.
713 * Note: This is not used by new logging system. Event with
714 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
715 * be considered as view action.
717 * @return array
719 function scorm_get_view_actions() {
720 return array('pre-view', 'view', 'view all', 'report');
724 * List the actions that correspond to a post of this module.
725 * This is used by the participation report.
727 * Note: This is not used by new logging system. Event with
728 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
729 * will be considered as post action.
731 * @return array
733 function scorm_get_post_actions() {
734 return array();
738 * @param object $scorm
739 * @return object $scorm
741 function scorm_option2text($scorm) {
742 $scormpopoupoptions = scorm_get_popup_options_array();
744 if (isset($scorm->popup)) {
745 if ($scorm->popup == 1) {
746 $optionlist = array();
747 foreach ($scormpopoupoptions as $name => $option) {
748 if (isset($scorm->$name)) {
749 $optionlist[] = $name.'='.$scorm->$name;
750 } else {
751 $optionlist[] = $name.'=0';
754 $scorm->options = implode(',', $optionlist);
755 } else {
756 $scorm->options = '';
758 } else {
759 $scorm->popup = 0;
760 $scorm->options = '';
762 return $scorm;
766 * Implementation of the function for printing the form elements that control
767 * whether the course reset functionality affects the scorm.
769 * @param object $mform form passed by reference
771 function scorm_reset_course_form_definition(&$mform) {
772 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
773 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
777 * Course reset form defaults.
779 * @return array
781 function scorm_reset_course_form_defaults($course) {
782 return array('reset_scorm' => 1);
786 * Removes all grades from gradebook
788 * @global stdClass
789 * @global object
790 * @param int $courseid
791 * @param string optional type
793 function scorm_reset_gradebook($courseid, $type='') {
794 global $CFG, $DB;
796 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
797 FROM {scorm} s, {course_modules} cm, {modules} m
798 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
800 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
801 foreach ($scorms as $scorm) {
802 scorm_grade_item_update($scorm, 'reset');
808 * Actual implementation of the reset course functionality, delete all the
809 * scorm attempts for course $data->courseid.
811 * @global stdClass
812 * @global object
813 * @param object $data the data submitted from the reset course.
814 * @return array status array
816 function scorm_reset_userdata($data) {
817 global $CFG, $DB;
819 $componentstr = get_string('modulenameplural', 'scorm');
820 $status = array();
822 if (!empty($data->reset_scorm)) {
823 $scormssql = "SELECT s.id
824 FROM {scorm} s
825 WHERE s.course=?";
827 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
829 // Remove all grades from gradebook.
830 if (empty($data->reset_gradebook_grades)) {
831 scorm_reset_gradebook($data->courseid);
834 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallattempts', 'scorm'), 'error' => false);
837 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
838 // See MDL-9367.
839 shift_course_mod_dates('scorm', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
840 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
842 return $status;
846 * Returns all other caps used in module
848 * @return array
850 function scorm_get_extra_capabilities() {
851 return array('moodle/site:accessallgroups');
855 * Lists all file areas current user may browse
857 * @param object $course
858 * @param object $cm
859 * @param object $context
860 * @return array
862 function scorm_get_file_areas($course, $cm, $context) {
863 $areas = array();
864 $areas['content'] = get_string('areacontent', 'scorm');
865 $areas['package'] = get_string('areapackage', 'scorm');
866 return $areas;
870 * File browsing support for SCORM file areas
872 * @package mod_scorm
873 * @category files
874 * @param file_browser $browser file browser instance
875 * @param array $areas file areas
876 * @param stdClass $course course object
877 * @param stdClass $cm course module object
878 * @param stdClass $context context object
879 * @param string $filearea file area
880 * @param int $itemid item ID
881 * @param string $filepath file path
882 * @param string $filename file name
883 * @return file_info instance or null if not found
885 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
886 global $CFG;
888 if (!has_capability('moodle/course:managefiles', $context)) {
889 return null;
892 // No writing for now!
894 $fs = get_file_storage();
896 if ($filearea === 'content') {
898 $filepath = is_null($filepath) ? '/' : $filepath;
899 $filename = is_null($filename) ? '.' : $filename;
901 $urlbase = $CFG->wwwroot.'/pluginfile.php';
902 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
903 if ($filepath === '/' and $filename === '.') {
904 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
905 } else {
906 // Not found.
907 return null;
910 require_once("$CFG->dirroot/mod/scorm/locallib.php");
911 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
913 } else if ($filearea === 'package') {
914 $filepath = is_null($filepath) ? '/' : $filepath;
915 $filename = is_null($filename) ? '.' : $filename;
917 $urlbase = $CFG->wwwroot.'/pluginfile.php';
918 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
919 if ($filepath === '/' and $filename === '.') {
920 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
921 } else {
922 // Not found.
923 return null;
926 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
929 // Scorm_intro handled in file_browser.
931 return false;
935 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
937 * @package mod_scorm
938 * @category files
939 * @param stdClass $course course object
940 * @param stdClass $cm course module object
941 * @param stdClass $context context object
942 * @param string $filearea file area
943 * @param array $args extra arguments
944 * @param bool $forcedownload whether or not force download
945 * @param array $options additional options affecting the file serving
946 * @return bool false if file not found, does not return if found - just send the file
948 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
949 global $CFG, $DB;
951 if ($context->contextlevel != CONTEXT_MODULE) {
952 return false;
955 require_login($course, true, $cm);
957 $canmanageactivity = has_capability('moodle/course:manageactivities', $context);
958 $lifetime = null;
960 // Check SCORM availability.
961 if (!$canmanageactivity) {
962 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
964 $scorm = $DB->get_record('scorm', array('id' => $cm->instance), 'id, timeopen, timeclose', MUST_EXIST);
965 list($available, $warnings) = scorm_get_availability_status($scorm);
966 if (!$available) {
967 return false;
971 if ($filearea === 'content') {
972 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
973 $relativepath = implode('/', $args);
974 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
975 $options['immutable'] = true; // Add immutable option, $relativepath changes on file update.
977 } else if ($filearea === 'package') {
978 // Check if the global setting for disabling package downloads is enabled.
979 $protectpackagedownloads = get_config('scorm', 'protectpackagedownloads');
980 if ($protectpackagedownloads and !$canmanageactivity) {
981 return false;
983 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
984 $relativepath = implode('/', $args);
985 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
986 $lifetime = 0; // No caching here.
988 } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
989 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
990 $relativepath = implode('/', $args);
992 // Get imsmanifest file.
993 $fs = get_file_storage();
994 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
995 $file = reset($files);
997 // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
998 $packagefilename = $file->get_filename();
999 if (strtolower($packagefilename) !== 'imsmanifest.xml') {
1000 return false;
1003 $file->send_relative_file($relativepath);
1004 } else {
1005 return false;
1008 $fs = get_file_storage();
1009 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1010 if ($filearea === 'content') { // Return file not found straight away to improve performance.
1011 send_header_404();
1012 die;
1014 return false;
1017 // Finally send the file.
1018 send_stored_file($file, $lifetime, 0, false, $options);
1022 * @uses FEATURE_GROUPS
1023 * @uses FEATURE_GROUPINGS
1024 * @uses FEATURE_MOD_INTRO
1025 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1026 * @uses FEATURE_COMPLETION_HAS_RULES
1027 * @uses FEATURE_GRADE_HAS_GRADE
1028 * @uses FEATURE_GRADE_OUTCOMES
1029 * @param string $feature FEATURE_xx constant for requested feature
1030 * @return mixed True if module supports feature, false if not, null if doesn't know
1032 function scorm_supports($feature) {
1033 switch($feature) {
1034 case FEATURE_GROUPS: return true;
1035 case FEATURE_GROUPINGS: return true;
1036 case FEATURE_MOD_INTRO: return true;
1037 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1038 case FEATURE_COMPLETION_HAS_RULES: return true;
1039 case FEATURE_GRADE_HAS_GRADE: return true;
1040 case FEATURE_GRADE_OUTCOMES: return true;
1041 case FEATURE_BACKUP_MOODLE2: return true;
1042 case FEATURE_SHOW_DESCRIPTION: return true;
1044 default: return null;
1049 * Get the filename for a temp log file
1051 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1052 * @param integer $scoid - scoid of object this log entry is for
1053 * @return string The filename as an absolute path
1055 function scorm_debug_log_filename($type, $scoid) {
1056 global $CFG, $USER;
1058 $logpath = $CFG->tempdir.'/scormlogs';
1059 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1060 return $logfile;
1064 * writes log output to a temp log file
1066 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1067 * @param string $text - text to be written to file.
1068 * @param integer $scoid - scoid of object this log entry is for.
1070 function scorm_debug_log_write($type, $text, $scoid) {
1071 global $CFG;
1073 $debugenablelog = get_config('scorm', 'allowapidebug');
1074 if (!$debugenablelog || empty($text)) {
1075 return;
1077 if (make_temp_directory('scormlogs/')) {
1078 $logfile = scorm_debug_log_filename($type, $scoid);
1079 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1080 @chmod($logfile, $CFG->filepermissions);
1085 * Remove debug log file
1087 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1088 * @param integer $scoid - scoid of object this log entry is for
1089 * @return boolean True if the file is successfully deleted, false otherwise
1091 function scorm_debug_log_remove($type, $scoid) {
1093 $debugenablelog = get_config('scorm', 'allowapidebug');
1094 $logfile = scorm_debug_log_filename($type, $scoid);
1095 if (!$debugenablelog || !file_exists($logfile)) {
1096 return false;
1099 return @unlink($logfile);
1103 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1105 * @deprecated since 3.3
1106 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1107 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1108 * @param array $htmlarray
1109 * @return mixed
1111 function scorm_print_overview($courses, &$htmlarray) {
1112 global $USER, $CFG;
1114 debugging('The function scorm_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1116 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1117 return array();
1120 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
1121 return;
1124 $strscorm = get_string('modulename', 'scorm');
1125 $strduedate = get_string('duedate', 'scorm');
1127 foreach ($scorms as $scorm) {
1128 $time = time();
1129 $showattemptstatus = false;
1130 if ($scorm->timeopen) {
1131 $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
1133 if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1134 $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) {
1135 $showattemptstatus = true;
1137 if ($showattemptstatus || !empty($isopen) || !empty($scorm->timeclose)) {
1138 $str = html_writer::start_div('scorm overview').html_writer::div($strscorm. ': '.
1139 html_writer::link($CFG->wwwroot.'/mod/scorm/view.php?id='.$scorm->coursemodule, $scorm->name,
1140 array('title' => $strscorm, 'class' => $scorm->visible ? '' : 'dimmed')), 'name');
1141 if ($scorm->timeclose) {
1142 $str .= html_writer::div($strduedate.': '.userdate($scorm->timeclose), 'info');
1144 if ($showattemptstatus) {
1145 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1146 $str .= html_writer::div(scorm_get_attempt_status($USER, $scorm), 'details');
1148 $str .= html_writer::end_div();
1149 if (empty($htmlarray[$scorm->course]['scorm'])) {
1150 $htmlarray[$scorm->course]['scorm'] = $str;
1151 } else {
1152 $htmlarray[$scorm->course]['scorm'] .= $str;
1159 * Return a list of page types
1160 * @param string $pagetype current page type
1161 * @param stdClass $parentcontext Block's parent context
1162 * @param stdClass $currentcontext Current context of block
1164 function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1165 $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1166 return $modulepagetype;
1170 * Returns the SCORM version used.
1171 * @param string $scormversion comes from $scorm->version
1172 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1173 * @return Scorm version.
1175 function scorm_version_check($scormversion, $version='') {
1176 $scormversion = trim(strtolower($scormversion));
1177 if (empty($version) || $version == SCORM_12) {
1178 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1179 return SCORM_12;
1181 if (!empty($version)) {
1182 return false;
1185 if (empty($version) || $version == SCORM_13) {
1186 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1187 return SCORM_13;
1189 if (!empty($version)) {
1190 return false;
1193 if (empty($version) || $version == SCORM_AICC) {
1194 if (strpos($scormversion, 'aicc')) {
1195 return SCORM_AICC;
1197 if (!empty($version)) {
1198 return false;
1201 return false;
1205 * Obtains the automatic completion state for this scorm based on any conditions
1206 * in scorm settings.
1208 * @param object $course Course
1209 * @param object $cm Course-module
1210 * @param int $userid User ID
1211 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1212 * @return bool True if completed, false if not. (If no conditions, then return
1213 * value depends on comparison type)
1215 function scorm_get_completion_state($course, $cm, $userid, $type) {
1216 global $DB;
1218 $result = $type;
1220 // Get scorm.
1221 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1222 print_error('cannotfindscorm');
1224 // Only check for existence of tracks and return false if completionstatusrequired or completionscorerequired
1225 // this means that if only view is required we don't end up with a false state.
1226 if ($scorm->completionstatusrequired !== null ||
1227 $scorm->completionscorerequired !== null) {
1228 // Get user's tracks data.
1229 $tracks = $DB->get_records_sql(
1231 SELECT
1233 scoid,
1234 element,
1235 value
1236 FROM
1237 {scorm_scoes_track}
1238 WHERE
1239 scormid = ?
1240 AND userid = ?
1241 AND element IN
1243 'cmi.core.lesson_status',
1244 'cmi.completion_status',
1245 'cmi.success_status',
1246 'cmi.core.score.raw',
1247 'cmi.score.raw'
1250 array($scorm->id, $userid)
1253 if (!$tracks) {
1254 return completion_info::aggregate_completion_states($type, $result, false);
1258 // Check for status.
1259 if ($scorm->completionstatusrequired !== null) {
1261 // Get status.
1262 $statuses = array_flip(scorm_status_options());
1263 $nstatus = 0;
1264 // Check any track for these values.
1265 $scostatus = array();
1266 foreach ($tracks as $track) {
1267 if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1268 continue;
1270 if (array_key_exists($track->value, $statuses)) {
1271 $scostatus[$track->scoid] = true;
1272 $nstatus |= $statuses[$track->value];
1276 if (!empty($scorm->completionstatusallscos)) {
1277 // Iterate over all scos and make sure each has a lesson_status.
1278 $scos = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id, 'scormtype' => 'sco'));
1279 foreach ($scos as $sco) {
1280 if (empty($scostatus[$sco->id])) {
1281 return completion_info::aggregate_completion_states($type, $result, false);
1284 return completion_info::aggregate_completion_states($type, $result, true);
1285 } else if ($scorm->completionstatusrequired & $nstatus) {
1286 return completion_info::aggregate_completion_states($type, $result, true);
1287 } else {
1288 return completion_info::aggregate_completion_states($type, $result, false);
1292 // Check for score.
1293 if ($scorm->completionscorerequired !== null) {
1294 $maxscore = -1;
1296 foreach ($tracks as $track) {
1297 if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1298 continue;
1301 if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1302 $maxscore = floatval($track->value);
1306 if ($scorm->completionscorerequired <= $maxscore) {
1307 return completion_info::aggregate_completion_states($type, $result, true);
1308 } else {
1309 return completion_info::aggregate_completion_states($type, $result, false);
1313 return $result;
1317 * Register the ability to handle drag and drop file uploads
1318 * @return array containing details of the files / types the mod can handle
1320 function scorm_dndupload_register() {
1321 return array('files' => array(
1322 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1327 * Handle a file that has been uploaded
1328 * @param object $uploadinfo details of the file / content that has been uploaded
1329 * @return int instance id of the newly created mod
1331 function scorm_dndupload_handle($uploadinfo) {
1333 $context = context_module::instance($uploadinfo->coursemodule);
1334 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1335 $fs = get_file_storage();
1336 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1337 $file = reset($files);
1339 // Validate the file, make sure it's a valid SCORM package!
1340 $errors = scorm_validate_package($file);
1341 if (!empty($errors)) {
1342 return false;
1344 // Create a default scorm object to pass to scorm_add_instance()!
1345 $scorm = get_config('scorm');
1346 $scorm->course = $uploadinfo->course->id;
1347 $scorm->coursemodule = $uploadinfo->coursemodule;
1348 $scorm->cmidnumber = '';
1349 $scorm->name = $uploadinfo->displayname;
1350 $scorm->scormtype = SCORM_TYPE_LOCAL;
1351 $scorm->reference = $file->get_filename();
1352 $scorm->intro = '';
1353 $scorm->width = $scorm->framewidth;
1354 $scorm->height = $scorm->frameheight;
1356 return scorm_add_instance($scorm, null);
1360 * Sets activity completion state
1362 * @param object $scorm object
1363 * @param int $userid User ID
1364 * @param int $completionstate Completion state
1365 * @param array $grades grades array of users with grades - used when $userid = 0
1367 function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1368 $course = new stdClass();
1369 $course->id = $scorm->course;
1370 $completion = new completion_info($course);
1372 // Check if completion is enabled site-wide, or for the course.
1373 if (!$completion->is_enabled()) {
1374 return;
1377 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1378 if (empty($cm) || !$completion->is_enabled($cm)) {
1379 return;
1382 if (empty($userid)) { // We need to get all the relevant users from $grades param.
1383 foreach ($grades as $grade) {
1384 $completion->update_state($cm, $completionstate, $grade->userid);
1386 } else {
1387 $completion->update_state($cm, $completionstate, $userid);
1392 * Check that a Zip file contains a valid SCORM package
1394 * @param $file stored_file a Zip file.
1395 * @return array empty if no issue is found. Array of error message otherwise
1397 function scorm_validate_package($file) {
1398 $packer = get_file_packer('application/zip');
1399 $errors = array();
1400 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1401 $file->import_external_file_contents();
1403 $filelist = $file->list_files($packer);
1405 if (!is_array($filelist)) {
1406 $errors['packagefile'] = get_string('badarchive', 'scorm');
1407 } else {
1408 $aiccfound = false;
1409 $badmanifestpresent = false;
1410 foreach ($filelist as $info) {
1411 if ($info->pathname == 'imsmanifest.xml') {
1412 return array();
1413 } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1414 // This package has an imsmanifest file inside a folder of the package.
1415 $badmanifestpresent = true;
1417 if (preg_match('/\.cst$/', $info->pathname)) {
1418 return array();
1421 if (!$aiccfound) {
1422 if ($badmanifestpresent) {
1423 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1424 } else {
1425 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1429 return $errors;
1433 * Check and set the correct mode and attempt when entering a SCORM package.
1435 * @param object $scorm object
1436 * @param string $newattempt should a new attempt be generated here.
1437 * @param int $attempt the attempt number this is for.
1438 * @param int $userid the userid of the user.
1439 * @param string $mode the current mode that has been selected.
1441 function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1442 global $DB;
1444 if (($mode == 'browse')) {
1445 if ($scorm->hidebrowse == 1) {
1446 // Prevent Browse mode if hidebrowse is set.
1447 $mode = 'normal';
1448 } else {
1449 // We don't need to check attempts as browse mode is set.
1450 return;
1454 if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS) {
1455 // This SCORM is configured to force a new attempt on every re-entry.
1456 $newattempt = 'on';
1457 $mode = 'normal';
1458 if ($attempt == 1) {
1459 // Check if the user has any existing data or if this is really the first attempt.
1460 $exists = $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id));
1461 if (!$exists) {
1462 // No records yet - Attempt should == 1.
1463 return;
1466 $attempt++;
1468 return;
1470 // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1471 $incomplete = true;
1473 // Note - in SCORM_13 the cmi-core.lesson_status field was split into
1474 // 'cmi.completion_status' and 'cmi.success_status'.
1475 // 'cmi.completion_status' can only contain values 'completed', 'incomplete', 'not attempted' or 'unknown'.
1476 // This means the values 'passed' or 'failed' will never be reported for a track in SCORM_13 and
1477 // the only status that will be treated as complete is 'completed'.
1479 $completionelements = array(
1480 SCORM_12 => 'cmi.core.lesson_status',
1481 SCORM_13 => 'cmi.completion_status',
1482 SCORM_AICC => 'cmi.core.lesson_status'
1484 $scormversion = scorm_version_check($scorm->version);
1485 if($scormversion===false) {
1486 $scormversion = SCORM_12;
1488 $completionelement = $completionelements[$scormversion];
1490 $sql = "SELECT sc.id, t.value
1491 FROM {scorm_scoes} sc
1492 LEFT JOIN {scorm_scoes_track} t ON sc.scorm = t.scormid AND sc.id = t.scoid
1493 AND t.element = ? AND t.userid = ? AND t.attempt = ?
1494 WHERE sc.scormtype = 'sco' AND sc.scorm = ?";
1495 $tracks = $DB->get_recordset_sql($sql, array($completionelement, $userid, $attempt, $scorm->id));
1497 foreach ($tracks as $track) {
1498 if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1499 $incomplete = false;
1500 } else {
1501 $incomplete = true;
1502 break; // Found an incomplete sco, so the result as a whole is incomplete.
1505 $tracks->close();
1507 // Validate user request to start a new attempt.
1508 if ($incomplete === true) {
1509 // The option to start a new attempt should never have been presented. Force false.
1510 $newattempt = 'off';
1511 } else if (!empty($scorm->forcenewattempt)) {
1512 // A new attempt should be forced for already completed attempts.
1513 $newattempt = 'on';
1516 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1517 $attempt++;
1518 $mode = 'normal';
1519 } else { // Check if review mode should be set.
1520 if ($incomplete === true) {
1521 $mode = 'normal';
1522 } else {
1523 $mode = 'review';
1529 * Trigger the course_module_viewed event.
1531 * @param stdClass $scorm scorm object
1532 * @param stdClass $course course object
1533 * @param stdClass $cm course module object
1534 * @param stdClass $context context object
1535 * @since Moodle 3.0
1537 function scorm_view($scorm, $course, $cm, $context) {
1539 // Trigger course_module_viewed event.
1540 $params = array(
1541 'context' => $context,
1542 'objectid' => $scorm->id
1545 $event = \mod_scorm\event\course_module_viewed::create($params);
1546 $event->add_record_snapshot('course_modules', $cm);
1547 $event->add_record_snapshot('course', $course);
1548 $event->add_record_snapshot('scorm', $scorm);
1549 $event->trigger();
1553 * Check if the module has any update that affects the current user since a given time.
1555 * @param cm_info $cm course module data
1556 * @param int $from the time to check updates from
1557 * @param array $filter if we need to check only specific updates
1558 * @return stdClass an object with the different type of areas indicating if they were updated or not
1559 * @since Moodle 3.2
1561 function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1562 global $DB, $USER, $CFG;
1563 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1565 $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1566 $updates = new stdClass();
1567 list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1568 if (!$available) {
1569 return $updates;
1571 $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1573 $updates->tracks = (object) array('updated' => false);
1574 $select = 'scormid = ? AND userid = ? AND timemodified > ?';
1575 $params = array($scorm->id, $USER->id, $from);
1576 $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1577 if (!empty($tracks)) {
1578 $updates->tracks->updated = true;
1579 $updates->tracks->itemids = array_keys($tracks);
1582 // Now, teachers should see other students updates.
1583 if (has_capability('mod/scorm:viewreport', $cm->context)) {
1584 $select = 'scormid = ? AND timemodified > ?';
1585 $params = array($scorm->id, $from);
1587 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1588 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1589 if (empty($groupusers)) {
1590 return $updates;
1592 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1593 $select .= ' AND userid ' . $insql;
1594 $params = array_merge($params, $inparams);
1597 $updates->usertracks = (object) array('updated' => false);
1598 $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1599 if (!empty($tracks)) {
1600 $updates->usertracks->updated = true;
1601 $updates->usertracks->itemids = array_keys($tracks);
1604 return $updates;
1608 * Get icon mapping for font-awesome.
1610 function mod_scorm_get_fontawesome_icon_map() {
1611 return [
1612 'mod_scorm:assetc' => 'fa-file-archive-o',
1613 'mod_scorm:asset' => 'fa-file-archive-o',
1614 'mod_scorm:browsed' => 'fa-book',
1615 'mod_scorm:completed' => 'fa-check-square-o',
1616 'mod_scorm:failed' => 'fa-times',
1617 'mod_scorm:incomplete' => 'fa-pencil-square-o',
1618 'mod_scorm:minus' => 'fa-minus',
1619 'mod_scorm:notattempted' => 'fa-square-o',
1620 'mod_scorm:passed' => 'fa-check',
1621 'mod_scorm:plus' => 'fa-plus',
1622 'mod_scorm:popdown' => 'fa-window-close-o',
1623 'mod_scorm:popup' => 'fa-window-restore',
1624 'mod_scorm:suspend' => 'fa-pause',
1625 'mod_scorm:wait' => 'fa-clock-o',
1630 * This standard function will check all instances of this module
1631 * and make sure there are up-to-date events created for each of them.
1632 * If courseid = 0, then every scorm event in the site is checked, else
1633 * only scorm events belonging to the course specified are checked.
1635 * @param int $courseid
1636 * @param int|stdClass $instance scorm module instance or ID.
1637 * @param int|stdClass $cm Course module object or ID.
1638 * @return bool
1640 function scorm_refresh_events($courseid = 0, $instance = null, $cm = null) {
1641 global $CFG, $DB;
1643 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1645 // If we have instance information then we can just update the one event instead of updating all events.
1646 if (isset($instance)) {
1647 if (!is_object($instance)) {
1648 $instance = $DB->get_record('scorm', array('id' => $instance), '*', MUST_EXIST);
1650 if (isset($cm)) {
1651 if (!is_object($cm)) {
1652 $cm = (object)array('id' => $cm);
1654 } else {
1655 $cm = get_coursemodule_from_instance('scorm', $instance->id);
1657 scorm_update_calendar($instance, $cm->id);
1658 return true;
1661 if ($courseid) {
1662 // Make sure that the course id is numeric.
1663 if (!is_numeric($courseid)) {
1664 return false;
1666 if (!$scorms = $DB->get_records('scorm', array('course' => $courseid))) {
1667 return false;
1669 } else {
1670 if (!$scorms = $DB->get_records('scorm')) {
1671 return false;
1675 foreach ($scorms as $scorm) {
1676 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1677 scorm_update_calendar($scorm, $cm->id);
1680 return true;
1684 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1686 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1687 * is not displayed on the block.
1689 * @param calendar_event $event
1690 * @param \core_calendar\action_factory $factory
1691 * @return \core_calendar\local\event\entities\action_interface|null
1693 function mod_scorm_core_calendar_provide_event_action(calendar_event $event,
1694 \core_calendar\action_factory $factory) {
1695 global $CFG;
1697 require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1699 $cm = get_fast_modinfo($event->courseid)->instances['scorm'][$event->instance];
1701 if (has_capability('mod/scorm:viewreport', $cm->context)) {
1702 // Teachers do not need to be reminded to complete a scorm.
1703 return null;
1706 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
1707 // The scorm has closed so the user can no longer submit anything.
1708 return null;
1711 // Restore scorm object from cached values in $cm, we only need id, timeclose and timeopen.
1712 $customdata = $cm->customdata ?: [];
1713 $customdata['id'] = $cm->instance;
1714 $scorm = (object)($customdata + ['timeclose' => 0, 'timeopen' => 0]);
1716 // Check that the SCORM activity is open.
1717 list($actionable, $warnings) = scorm_get_availability_status($scorm);
1719 return $factory->create_instance(
1720 get_string('enter', 'scorm'),
1721 new \moodle_url('/mod/scorm/view.php', array('id' => $cm->id)),
1723 $actionable
1728 * Add a get_coursemodule_info function in case any SCORM type wants to add 'extra' information
1729 * for the course (see resource).
1731 * Given a course_module object, this function returns any "extra" information that may be needed
1732 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1734 * @param stdClass $coursemodule The coursemodule object (record).
1735 * @return cached_cm_info An object on information that the courses
1736 * will know about (most noticeably, an icon).
1738 function scorm_get_coursemodule_info($coursemodule) {
1739 global $DB;
1741 $dbparams = ['id' => $coursemodule->instance];
1742 $fields = 'id, name, intro, introformat, completionstatusrequired, completionscorerequired, completionstatusallscos, '.
1743 'timeopen, timeclose';
1744 if (!$scorm = $DB->get_record('scorm', $dbparams, $fields)) {
1745 return false;
1748 $result = new cached_cm_info();
1749 $result->name = $scorm->name;
1751 if ($coursemodule->showdescription) {
1752 // Convert intro to html. Do not filter cached version, filters run at display time.
1753 $result->content = format_module_intro('scorm', $scorm, $coursemodule->id, false);
1756 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1757 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1758 $result->customdata['customcompletionrules']['completionstatusrequired'] = $scorm->completionstatusrequired;
1759 $result->customdata['customcompletionrules']['completionscorerequired'] = $scorm->completionscorerequired;
1760 $result->customdata['customcompletionrules']['completionstatusallscos'] = $scorm->completionstatusallscos;
1762 // Populate some other values that can be used in calendar or on dashboard.
1763 if ($scorm->timeopen) {
1764 $result->customdata['timeopen'] = $scorm->timeopen;
1766 if ($scorm->timeclose) {
1767 $result->customdata['timeclose'] = $scorm->timeclose;
1770 return $result;
1774 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1776 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1777 * @return array $descriptions the array of descriptions for the custom rules.
1779 function mod_scorm_get_completion_active_rule_descriptions($cm) {
1780 // Values will be present in cm_info, and we assume these are up to date.
1781 if (empty($cm->customdata['customcompletionrules'])
1782 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1783 return [];
1786 $descriptions = [];
1787 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1788 switch ($key) {
1789 case 'completionstatusrequired':
1790 if (is_null($val)) {
1791 continue;
1793 // Determine the selected statuses using a bitwise operation.
1794 $cvalues = array();
1795 foreach (scorm_status_options(true) as $bit => $string) {
1796 if (($val & $bit) == $bit) {
1797 $cvalues[] = $string;
1800 $statusstring = implode(', ', $cvalues);
1801 $descriptions[] = get_string('completionstatusrequireddesc', 'scorm', $statusstring);
1802 break;
1803 case 'completionscorerequired':
1804 if (is_null($val)) {
1805 continue;
1807 $descriptions[] = get_string('completionscorerequireddesc', 'scorm', $val);
1808 break;
1809 case 'completionstatusallscos':
1810 if (empty($val)) {
1811 continue;
1813 $descriptions[] = get_string('completionstatusallscos', 'scorm');
1814 break;
1815 default:
1816 break;
1819 return $descriptions;
1823 * This function will update the scorm module according to the
1824 * event that has been modified.
1826 * It will set the timeopen or timeclose value of the scorm instance
1827 * according to the type of event provided.
1829 * @throws \moodle_exception
1830 * @param \calendar_event $event
1831 * @param stdClass $scorm The module instance to get the range from
1833 function mod_scorm_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $scorm) {
1834 global $DB;
1836 if (empty($event->instance) || $event->modulename != 'scorm') {
1837 return;
1840 if ($event->instance != $scorm->id) {
1841 return;
1844 if (!in_array($event->eventtype, [SCORM_EVENT_TYPE_OPEN, SCORM_EVENT_TYPE_CLOSE])) {
1845 return;
1848 $courseid = $event->courseid;
1849 $modulename = $event->modulename;
1850 $instanceid = $event->instance;
1851 $modified = false;
1853 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1854 $context = context_module::instance($coursemodule->id);
1856 // The user does not have the capability to modify this activity.
1857 if (!has_capability('moodle/course:manageactivities', $context)) {
1858 return;
1861 if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1862 // If the event is for the scorm activity opening then we should
1863 // set the start time of the scorm activity to be the new start
1864 // time of the event.
1865 if ($scorm->timeopen != $event->timestart) {
1866 $scorm->timeopen = $event->timestart;
1867 $scorm->timemodified = time();
1868 $modified = true;
1870 } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1871 // If the event is for the scorm activity closing then we should
1872 // set the end time of the scorm activity to be the new start
1873 // time of the event.
1874 if ($scorm->timeclose != $event->timestart) {
1875 $scorm->timeclose = $event->timestart;
1876 $modified = true;
1880 if ($modified) {
1881 $scorm->timemodified = time();
1882 $DB->update_record('scorm', $scorm);
1883 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1884 $event->trigger();
1889 * This function calculates the minimum and maximum cutoff values for the timestart of
1890 * the given event.
1892 * It will return an array with two values, the first being the minimum cutoff value and
1893 * the second being the maximum cutoff value. Either or both values can be null, which
1894 * indicates there is no minimum or maximum, respectively.
1896 * If a cutoff is required then the function must return an array containing the cutoff
1897 * timestamp and error string to display to the user if the cutoff value is violated.
1899 * A minimum and maximum cutoff return value will look like:
1901 * [1505704373, 'The date must be after this date'],
1902 * [1506741172, 'The date must be before this date']
1905 * @param \calendar_event $event The calendar event to get the time range for
1906 * @param \stdClass $instance The module instance to get the range from
1907 * @return array Returns an array with min and max date.
1909 function mod_scorm_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1910 $mindate = null;
1911 $maxdate = null;
1913 if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1914 // The start time of the open event can't be equal to or after the
1915 // close time of the scorm activity.
1916 if (!empty($instance->timeclose)) {
1917 $maxdate = [
1918 $instance->timeclose,
1919 get_string('openafterclose', 'scorm')
1922 } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1923 // The start time of the close event can't be equal to or earlier than the
1924 // open time of the scorm activity.
1925 if (!empty($instance->timeopen)) {
1926 $mindate = [
1927 $instance->timeopen,
1928 get_string('closebeforeopen', 'scorm')
1933 return [$mindate, $maxdate];