2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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 check what SCORM version is being used.
38 define('SCORM_12', 1);
39 define('SCORM_13', 2);
40 define('SCORM_AICC', 3);
42 // List of possible attemptstatusdisplay options.
43 define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
44 define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
45 define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
46 define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
49 * Return an array of status options
51 * Optionally with translated strings
53 * @param bool $with_strings (optional)
56 function scorm_status_options($with_strings = false) {
57 // Id's are important as they are bits
64 foreach ($options as $key => $value) {
65 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
74 * Given an object containing all the necessary data,
75 * (defined by the form in mod_form.php) this function
76 * will create a new instance and return the id number
77 * of the new instance.
81 * @uses CONTEXT_MODULE
82 * @uses SCORM_TYPE_LOCAL
83 * @uses SCORM_TYPE_LOCALSYNC
84 * @uses SCORM_TYPE_EXTERNAL
85 * @param object $scorm Form data
86 * @param object $mform
87 * @return int new instance id
89 function scorm_add_instance($scorm, $mform=null) {
92 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
94 if (empty($scorm->timeopen)) {
97 if (empty($scorm->timeclose)) {
98 $scorm->timeclose = 0;
100 $cmid = $scorm->coursemodule;
101 $cmidnumber = $scorm->cmidnumber;
102 $courseid = $scorm->course;
104 $context = context_module::instance($cmid);
106 $scorm = scorm_option2text($scorm);
107 $scorm->width = (int)str_replace('%', '', $scorm->width);
108 $scorm->height = (int)str_replace('%', '', $scorm->height);
110 if (!isset($scorm->whatgrade)) {
111 $scorm->whatgrade = 0;
114 $id = $DB->insert_record('scorm', $scorm);
116 // Update course module record - from now on this instance properly exists and all function may be used.
117 $DB->set_field('course_modules', 'instance', $id, array('id'=>$cmid));
119 // Reload scorm instance.
120 $record = $DB->get_record('scorm', array('id'=>$id));
122 // Store the package and verify.
123 if ($record->scormtype === SCORM_TYPE_LOCAL) {
124 if ($data = $mform->get_data()) {
125 $fs = get_file_storage();
126 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
127 file_save_draft_area_files($data->packagefile, $context->id, 'mod_scorm', 'package',
128 0, array('subdirs' => 0, 'maxfiles' => 1));
129 // Get filename of zip that was uploaded.
130 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
131 $file = reset($files);
132 $filename = $file->get_filename();
133 if ($filename !== false) {
134 $record->reference = $filename;
138 } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
139 $record->reference = $scorm->packageurl;
140 } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
141 $record->reference = $scorm->packageurl;
142 } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
143 $record->reference = $scorm->packageurl;
144 $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
150 $DB->update_record('scorm', $record);
152 // Extra fields required in grade related functions.
153 $record->course = $courseid;
154 $record->cmidnumber = $cmidnumber;
155 $record->cmid = $cmid;
157 scorm_parse($record, true);
159 scorm_grade_item_update($record);
165 * Given an object containing all the necessary data,
166 * (defined by the form in mod_form.php) this function
167 * will update an existing instance with new data.
171 * @uses CONTEXT_MODULE
172 * @uses SCORM_TYPE_LOCAL
173 * @uses SCORM_TYPE_LOCALSYNC
174 * @uses SCORM_TYPE_EXTERNAL
175 * @param object $scorm Form data
176 * @param object $mform
179 function scorm_update_instance($scorm, $mform=null) {
182 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
184 if (empty($scorm->timeopen)) {
185 $scorm->timeopen = 0;
187 if (empty($scorm->timeclose)) {
188 $scorm->timeclose = 0;
191 $cmid = $scorm->coursemodule;
192 $cmidnumber = $scorm->cmidnumber;
193 $courseid = $scorm->course;
195 $scorm->id = $scorm->instance;
197 $context = context_module::instance($cmid);
199 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
200 if ($data = $mform->get_data()) {
201 $fs = get_file_storage();
202 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
203 file_save_draft_area_files($data->packagefile, $context->id, 'mod_scorm', 'package',
204 0, array('subdirs' => 0, 'maxfiles' => 1));
205 // Get filename of zip that was uploaded.
206 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
207 $file = reset($files);
208 $filename = $file->get_filename();
209 if ($filename !== false) {
210 $scorm->reference = $filename;
214 } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
215 $scorm->reference = $scorm->packageurl;
216 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
217 $scorm->reference = $scorm->packageurl;
218 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
219 $scorm->reference = $scorm->packageurl;
220 $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
225 $scorm = scorm_option2text($scorm);
226 $scorm->width = (int)str_replace('%', '', $scorm->width);
227 $scorm->height = (int)str_replace('%', '', $scorm->height);
228 $scorm->timemodified = time();
230 if (!isset($scorm->whatgrade)) {
231 $scorm->whatgrade = 0;
234 $DB->update_record('scorm', $scorm);
236 $scorm = $DB->get_record('scorm', array('id'=>$scorm->id));
238 /// extra fields required in grade related functions
239 $scorm->course = $courseid;
240 $scorm->idnumber = $cmidnumber;
241 $scorm->cmid = $cmid;
243 scorm_parse($scorm, (bool)$scorm->updatefreq);
245 scorm_grade_item_update($scorm);
246 scorm_update_grades($scorm);
252 * Given an ID of an instance of this module,
253 * this function will permanently delete the instance
254 * and any data that depends on it.
258 * @param int $id Scorm instance id
261 function scorm_delete_instance($id) {
264 if (! $scorm = $DB->get_record('scorm', array('id'=>$id))) {
270 // Delete any dependent records
271 if (! $DB->delete_records('scorm_scoes_track', array('scormid'=>$scorm->id))) {
274 if ($scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
275 foreach ($scoes as $sco) {
276 if (! $DB->delete_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
280 $DB->delete_records('scorm_scoes', array('scorm'=>$scorm->id));
282 if (! $DB->delete_records('scorm', array('id'=>$scorm->id))) {
286 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
289 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
292 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
295 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
298 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
301 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
304 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
308 scorm_grade_item_delete($scorm);
314 * Return a small object with summary information about what a
315 * user has done with a given particular instance of this module
316 * Used for user activity reports.
319 * @param int $course Course id
320 * @param int $user User id
322 * @param int $scorm The scorm id
325 function scorm_user_outline($course, $user, $mod, $scorm) {
327 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
329 require_once("$CFG->libdir/gradelib.php");
330 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
331 if (!empty($grades->items[0]->grades)) {
332 $grade = reset($grades->items[0]->grades);
333 $result = new stdClass();
334 $result->info = get_string('grade') . ': '. $grade->str_long_grade;
336 //datesubmitted == time created. dategraded == time modified or time overridden
337 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
338 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
339 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
340 $result->time = $grade->dategraded;
342 $result->time = $grade->datesubmitted;
351 * Print a detailed representation of what a user has done with
352 * a given particular instance of this module, for user activity reports.
356 * @param object $course
357 * @param object $user
359 * @param object $scorm
362 function scorm_user_complete($course, $user, $mod, $scorm) {
363 global $CFG, $DB, $OUTPUT;
364 require_once("$CFG->libdir/gradelib.php");
366 $liststyle = 'structlist';
370 $sometoreport = false;
373 // First Access and Last Access dates for SCOs
374 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
375 $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
376 $firstmodify = $timetracks->start;
377 $lastmodify = $timetracks->finish;
379 $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
380 if (!empty($grades->items[0]->grades)) {
381 $grade = reset($grades->items[0]->grades);
382 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
383 if ($grade->str_feedback) {
384 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
388 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
389 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
390 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
391 array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
392 if (count($orgs) <= 1) {
395 $org = new stdClass();
396 $org->identifier = '';
399 $report .= '<div class="mod-scorm">'."\n";
400 foreach ($orgs as $org) {
401 $conditions = array();
403 if (!empty($org->identifier)) {
404 $report .= '<div class="orgtitle">'.$org->title.'</div>';
405 $currentorg = $org->identifier;
406 $conditions['organization'] = $currentorg;
408 $report .= "<ul id='0' class='$liststyle'>";
409 $conditions['scorm'] = $scorm->id;
410 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
411 // drop keys so that we can access array sequentially
412 $scoes = array_values($scoes);
415 $parents[$level]='/';
416 foreach ($scoes as $pos => $sco) {
417 if ($parents[$level]!=$sco->parent) {
418 if ($level>0 && $parents[$level-1]==$sco->parent) {
419 $report .= "\t\t</ul></li>\n";
424 while (($i > 0) && ($parents[$level] != $sco->parent)) {
425 $closelist .= "\t\t</ul></li>\n";
428 if (($i == 0) && ($sco->parent != $currentorg)) {
429 $report .= "\t\t<li><ul id='$sublist' class='$liststyle'>\n";
432 $report .= $closelist;
435 $parents[$level]=$sco->parent;
438 $report .= "\t\t<li>";
439 if (isset($scoes[$pos+1])) {
440 $nextsco = $scoes[$pos+1];
444 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) && (($level==0) || (($level>0) && ($nextsco->parent == $sco->identifier)))) {
447 $report .= '<img src="'.$OUTPUT->pix_url('spacer', 'scorm').'" alt="" />';
453 if ($usertrack=scorm_get_tracks($sco->id, $user->id)) {
454 if ($usertrack->status == '') {
455 $usertrack->status = 'notattempted';
457 $strstatus = get_string($usertrack->status, 'scorm');
458 $report .= "<img src='".$OUTPUT->pix_url($usertrack->status, 'scorm')."' alt='$strstatus' title='$strstatus' />";
460 if ($sco->scormtype == 'sco') {
461 $report .= '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
463 $report .= '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
466 $report .= " $sco->title $score$totaltime</li>\n";
467 if ($usertrack !== false) {
468 $sometoreport = true;
469 $report .= "\t\t\t<li><ul class='$liststyle'>\n";
470 foreach ($usertrack as $element => $value) {
471 if (substr($element, 0, 3) == 'cmi') {
472 $report .= '<li>'.$element.' => '.s($value).'</li>';
475 $report .= "\t\t\t</ul></li>\n";
478 $report .= " $sco->title</li>\n";
481 for ($i=0; $i<$level; $i++) {
482 $report .= "\t\t</ul></li>\n";
485 $report .= "\t</ul><br />\n";
487 $report .= "</div>\n";
490 if ($firstmodify < $now) {
491 $timeago = format_time($now - $firstmodify);
492 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")<br />\n";
494 if ($lastmodify > 0) {
495 $timeago = format_time($now - $lastmodify);
496 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")<br />\n";
498 echo get_string('report', 'scorm').":<br />\n";
501 print_string('noactivity', 'scorm');
508 * Function to be run periodically according to the moodle cron
509 * This function searches for things that need to be done, such
510 * as sending out mail, toggling flags etc ...
516 function scorm_cron () {
519 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
521 $sitetimezone = $CFG->timezone;
522 // Now see if there are any scorm updates to be done.
524 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time.
525 set_config('scorm_updatetimelast', 0);
529 $updatetime = usergetmidnight($timenow, $sitetimezone);
531 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
533 set_config('scorm_updatetimelast', $timenow);
535 mtrace('Updating scorm packages which require daily update');// We are updating.
537 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
538 foreach ($scormsupdate as $scormupdate) {
539 scorm_parse($scormupdate, true);
542 // Now clear out AICC session table with old session data.
543 $cfgscorm = get_config('scorm');
544 if (!empty($cfgscorm->allowaicchacp)) {
545 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata*24*60*60);
546 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
554 * Return grade for given user or all users.
558 * @param int $scormid id of scorm
559 * @param int $userid optional user id, 0 means all users
560 * @return array array of grades, false if none
562 function scorm_get_user_grades($scorm, $userid=0) {
564 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
567 if (empty($userid)) {
568 if ($scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid", array($scorm->id), "", "userid,null")) {
569 foreach ($scousers as $scouser) {
570 $grades[$scouser->userid] = new stdClass();
571 $grades[$scouser->userid]->id = $scouser->userid;
572 $grades[$scouser->userid]->userid = $scouser->userid;
573 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
580 if (!$DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid", array($scorm->id, $userid), "", "userid,null")) {
581 return false; //no attempt yet
583 $grades[$userid] = new stdClass();
584 $grades[$userid]->id = $userid;
585 $grades[$userid]->userid = $userid;
586 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
593 * Update grades in central gradebook
596 * @param object $scorm
597 * @param int $userid specific user only, 0 mean all
598 * @param bool $nullifnone
600 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
602 require_once($CFG->libdir.'/gradelib.php');
603 require_once($CFG->libdir.'/completionlib.php');
605 if ($grades = scorm_get_user_grades($scorm, $userid)) {
606 scorm_grade_item_update($scorm, $grades);
608 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
609 } else if ($userid and $nullifnone) {
610 $grade = new stdClass();
611 $grade->userid = $userid;
612 $grade->rawgrade = null;
613 scorm_grade_item_update($scorm, $grade);
615 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
617 scorm_grade_item_update($scorm);
622 * Update all grades in gradebook.
626 function scorm_upgrade_grades() {
629 $sql = "SELECT COUNT('x')
630 FROM {scorm} s, {course_modules} cm, {modules} m
631 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
632 $count = $DB->count_records_sql($sql);
634 $sql = "SELECT s.*, cm.idnumber AS cmidnumber, s.course AS courseid
635 FROM {scorm} s, {course_modules} cm, {modules} m
636 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
637 $rs = $DB->get_recordset_sql($sql);
639 $pbar = new progress_bar('scormupgradegrades', 500, true);
641 foreach ($rs as $scorm) {
643 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
644 scorm_update_grades($scorm, 0, false);
645 $pbar->update($i, $count, "Updating Scorm grades ($i/$count).");
652 * Update/create grade item for given scorm
655 * @uses GRADE_TYPE_VALUE
656 * @uses GRADE_TYPE_NONE
657 * @param object $scorm object with extra cmidnumber
658 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
659 * @return object grade_item
661 function scorm_grade_item_update($scorm, $grades=null) {
663 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
664 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
665 require_once($CFG->libdir.'/gradelib.php');
668 $params = array('itemname'=>$scorm->name);
669 if (isset($scorm->cmidnumber)) {
670 $params['idnumber'] = $scorm->cmidnumber;
673 if ($scorm->grademethod == GRADESCOES) {
674 if ($maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id))) {
675 $params['gradetype'] = GRADE_TYPE_VALUE;
676 $params['grademax'] = $maxgrade;
677 $params['grademin'] = 0;
679 $params['gradetype'] = GRADE_TYPE_NONE;
682 $params['gradetype'] = GRADE_TYPE_VALUE;
683 $params['grademax'] = $scorm->maxgrade;
684 $params['grademin'] = 0;
687 if ($grades === 'reset') {
688 $params['reset'] = true;
692 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
696 * Delete grade item for given scorm
699 * @param object $scorm object
700 * @return object grade_item
702 function scorm_grade_item_delete($scorm) {
704 require_once($CFG->libdir.'/gradelib.php');
706 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted'=>1));
712 function scorm_get_view_actions() {
713 return array('pre-view', 'view', 'view all', 'report');
719 function scorm_get_post_actions() {
724 * @param object $scorm
725 * @return object $scorm
727 function scorm_option2text($scorm) {
728 $scorm_popoup_options = scorm_get_popup_options_array();
730 if (isset($scorm->popup)) {
731 if ($scorm->popup == 1) {
732 $optionlist = array();
733 foreach ($scorm_popoup_options as $name => $option) {
734 if (isset($scorm->$name)) {
735 $optionlist[] = $name.'='.$scorm->$name;
737 $optionlist[] = $name.'=0';
740 $scorm->options = implode(',', $optionlist);
742 $scorm->options = '';
746 $scorm->options = '';
752 * Implementation of the function for printing the form elements that control
753 * whether the course reset functionality affects the scorm.
755 * @param object $mform form passed by reference
757 function scorm_reset_course_form_definition(&$mform) {
758 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
759 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
763 * Course reset form defaults.
767 function scorm_reset_course_form_defaults($course) {
768 return array('reset_scorm'=>1);
772 * Removes all grades from gradebook
776 * @param int $courseid
777 * @param string optional type
779 function scorm_reset_gradebook($courseid, $type='') {
782 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
783 FROM {scorm} s, {course_modules} cm, {modules} m
784 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
786 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
787 foreach ($scorms as $scorm) {
788 scorm_grade_item_update($scorm, 'reset');
794 * Actual implementation of the reset course functionality, delete all the
795 * scorm attempts for course $data->courseid.
799 * @param object $data the data submitted from the reset course.
800 * @return array status array
802 function scorm_reset_userdata($data) {
805 $componentstr = get_string('modulenameplural', 'scorm');
808 if (!empty($data->reset_scorm)) {
809 $scormssql = "SELECT s.id
813 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
815 // remove all grades from gradebook
816 if (empty($data->reset_gradebook_grades)) {
817 scorm_reset_gradebook($data->courseid);
820 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'scorm'), 'error'=>false);
823 // no dates to shift here
829 * Returns all other caps used in module
833 function scorm_get_extra_capabilities() {
834 return array('moodle/site:accessallgroups');
838 * Lists all file areas current user may browse
840 * @param object $course
842 * @param object $context
845 function scorm_get_file_areas($course, $cm, $context) {
847 $areas['content'] = get_string('areacontent', 'scorm');
848 $areas['package'] = get_string('areapackage', 'scorm');
853 * File browsing support for SCORM file areas
857 * @param file_browser $browser file browser instance
858 * @param array $areas file areas
859 * @param stdClass $course course object
860 * @param stdClass $cm course module object
861 * @param stdClass $context context object
862 * @param string $filearea file area
863 * @param int $itemid item ID
864 * @param string $filepath file path
865 * @param string $filename file name
866 * @return file_info instance or null if not found
868 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
871 if (!has_capability('moodle/course:managefiles', $context)) {
875 // no writing for now!
877 $fs = get_file_storage();
879 if ($filearea === 'content') {
881 $filepath = is_null($filepath) ? '/' : $filepath;
882 $filename = is_null($filename) ? '.' : $filename;
884 $urlbase = $CFG->wwwroot.'/pluginfile.php';
885 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
886 if ($filepath === '/' and $filename === '.') {
887 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
893 require_once("$CFG->dirroot/mod/scorm/locallib.php");
894 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
896 } else if ($filearea === 'package') {
897 $filepath = is_null($filepath) ? '/' : $filepath;
898 $filename = is_null($filename) ? '.' : $filename;
900 $urlbase = $CFG->wwwroot.'/pluginfile.php';
901 if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
902 if ($filepath === '/' and $filename === '.') {
903 $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
909 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
912 // scorm_intro handled in file_browser
918 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
922 * @param stdClass $course course object
923 * @param stdClass $cm course module object
924 * @param stdClass $context context object
925 * @param string $filearea file area
926 * @param array $args extra arguments
927 * @param bool $forcedownload whether or not force download
928 * @param array $options additional options affecting the file serving
929 * @return bool false if file not found, does not return if found - just send the file
931 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
934 if ($context->contextlevel != CONTEXT_MODULE) {
938 require_login($course, true, $cm);
940 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
942 if ($filearea === 'content') {
943 $revision = (int)array_shift($args); // prevents caching problems - ignored here
944 $relativepath = implode('/', $args);
945 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
946 // TODO: add any other access restrictions here if needed!
948 } else if ($filearea === 'package') {
949 if (!has_capability('moodle/course:manageactivities', $context)) {
952 $relativepath = implode('/', $args);
953 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
954 $lifetime = 0; // no caching here
960 $fs = get_file_storage();
961 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
962 if ($filearea === 'content') { //return file not found straight away to improve performance.
969 // finally send the file
970 send_stored_file($file, $lifetime, 0, false, $options);
974 * @uses FEATURE_GROUPS
975 * @uses FEATURE_GROUPINGS
976 * @uses FEATURE_GROUPMEMBERSONLY
977 * @uses FEATURE_MOD_INTRO
978 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
979 * @uses FEATURE_COMPLETION_HAS_RULES
980 * @uses FEATURE_GRADE_HAS_GRADE
981 * @uses FEATURE_GRADE_OUTCOMES
982 * @param string $feature FEATURE_xx constant for requested feature
983 * @return mixed True if module supports feature, false if not, null if doesn't know
985 function scorm_supports($feature) {
987 case FEATURE_GROUPS: return false;
988 case FEATURE_GROUPINGS: return false;
989 case FEATURE_GROUPMEMBERSONLY: return true;
990 case FEATURE_MOD_INTRO: return true;
991 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
992 case FEATURE_COMPLETION_HAS_RULES: return true;
993 case FEATURE_GRADE_HAS_GRADE: return true;
994 case FEATURE_GRADE_OUTCOMES: return true;
995 case FEATURE_BACKUP_MOODLE2: return true;
996 case FEATURE_SHOW_DESCRIPTION: return true;
998 default: return null;
1003 * Get the filename for a temp log file
1005 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1006 * @param integer $scoid - scoid of object this log entry is for
1007 * @return string The filename as an absolute path
1009 function scorm_debug_log_filename($type, $scoid) {
1012 $logpath = $CFG->tempdir.'/scormlogs';
1013 $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1018 * writes log output to a temp log file
1020 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1021 * @param string $text - text to be written to file.
1022 * @param integer $scoid - scoid of object this log entry is for.
1024 function scorm_debug_log_write($type, $text, $scoid) {
1027 $debugenablelog = get_config('scorm', 'allowapidebug');
1028 if (!$debugenablelog || empty($text)) {
1031 if (make_temp_directory('scormlogs/')) {
1032 $logfile = scorm_debug_log_filename($type, $scoid);
1033 @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1034 @chmod($logfile, $CFG->filepermissions);
1039 * Remove debug 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 boolean True if the file is successfully deleted, false otherwise
1045 function scorm_debug_log_remove($type, $scoid) {
1047 $debugenablelog = get_config('scorm', 'allowapidebug');
1048 $logfile = scorm_debug_log_filename($type, $scoid);
1049 if (!$debugenablelog || !file_exists($logfile)) {
1053 return @unlink($logfile);
1057 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1059 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1060 * @param array $htmlarray
1063 function scorm_print_overview($courses, &$htmlarray) {
1066 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1070 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
1074 $strscorm = get_string('modulename', 'scorm');
1075 $strduedate = get_string('duedate', 'scorm');
1077 foreach ($scorms as $scorm) {
1079 $showattemptstatus = false;
1080 if ($scorm->timeopen) {
1081 $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
1083 if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1084 $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) {
1085 $showattemptstatus = true;
1087 if ($showattemptstatus || !empty($isopen) || !empty($scorm->timeclose)) {
1088 $str = '<div class="scorm overview"><div class="name">'.$strscorm. ': '.
1089 '<a '.($scorm->visible ? '':' class="dimmed"').
1090 'title="'.$strscorm.'" href="'.$CFG->wwwroot.
1091 '/mod/scorm/view.php?id='.$scorm->coursemodule.'">'.
1092 $scorm->name.'</a></div>';
1093 if ($scorm->timeclose) {
1094 $str .= '<div class="info">'.$strduedate.': '.userdate($scorm->timeclose).'</div>';
1096 if ($showattemptstatus) {
1097 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1098 $str .= '<div class="details">'.scorm_get_attempt_status($USER, $scorm).'</div>';
1101 if (empty($htmlarray[$scorm->course]['scorm'])) {
1102 $htmlarray[$scorm->course]['scorm'] = $str;
1104 $htmlarray[$scorm->course]['scorm'] .= $str;
1111 * Return a list of page types
1112 * @param string $pagetype current page type
1113 * @param stdClass $parentcontext Block's parent context
1114 * @param stdClass $currentcontext Current context of block
1116 function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1117 $module_pagetype = array('mod-scorm-*'=>get_string('page-mod-scorm-x', 'scorm'));
1118 return $module_pagetype;
1122 * Returns the SCORM version used.
1123 * @param string $scormversion comes from $scorm->version
1124 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1125 * @return Scorm version.
1127 function scorm_version_check($scormversion, $version='') {
1128 $scormversion = trim(strtolower($scormversion));
1129 if (empty($version) || $version==SCORM_12) {
1130 if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1133 if (!empty($version)) {
1137 if (empty($version) || $version == SCORM_13) {
1138 if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1141 if (!empty($version)) {
1145 if (empty($version) || $version == SCORM_AICC) {
1146 if (strpos($scormversion, 'aicc')) {
1149 if (!empty($version)) {
1157 * Obtains the automatic completion state for this scorm based on any conditions
1158 * in scorm settings.
1160 * @param object $course Course
1161 * @param object $cm Course-module
1162 * @param int $userid User ID
1163 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1164 * @return bool True if completed, false if not. (If no conditions, then return
1165 * value depends on comparison type)
1167 function scorm_get_completion_state($course, $cm, $userid, $type) {
1173 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1174 print_error('cannotfindscorm');
1176 // Only check for existence of tracks and return false if completionstatusrequired or completionscorerequired
1177 // this means that if only view is required we don't end up with a false state.
1178 if ($scorm->completionstatusrequired !== null ||
1179 $scorm->completionscorerequired !== null) {
1180 // Get user's tracks data.
1181 $tracks = $DB->get_records_sql(
1194 'cmi.core.lesson_status',
1195 'cmi.completion_status',
1196 'cmi.success_status',
1197 'cmi.core.score.raw',
1201 array($scorm->id, $userid)
1205 return completion_info::aggregate_completion_states($type, $result, false);
1210 if ($scorm->completionstatusrequired !== null) {
1213 $statuses = array_flip(scorm_status_options());
1216 foreach ($tracks as $track) {
1217 if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1221 if (array_key_exists($track->value, $statuses)) {
1222 $nstatus |= $statuses[$track->value];
1226 if ($scorm->completionstatusrequired & $nstatus) {
1227 return completion_info::aggregate_completion_states($type, $result, true);
1229 return completion_info::aggregate_completion_states($type, $result, false);
1235 if ($scorm->completionscorerequired !== null) {
1238 foreach ($tracks as $track) {
1239 if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1243 if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1244 $maxscore = floatval($track->value);
1248 if ($scorm->completionscorerequired <= $maxscore) {
1249 return completion_info::aggregate_completion_states($type, $result, true);
1251 return completion_info::aggregate_completion_states($type, $result, false);
1259 * Register the ability to handle drag and drop file uploads
1260 * @return array containing details of the files / types the mod can handle
1262 function scorm_dndupload_register() {
1263 return array('files' => array(
1264 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1269 * Handle a file that has been uploaded
1270 * @param object $uploadinfo details of the file / content that has been uploaded
1271 * @return int instance id of the newly created mod
1273 function scorm_dndupload_handle($uploadinfo) {
1275 $context = context_module::instance($uploadinfo->coursemodule);
1276 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1277 $fs = get_file_storage();
1278 $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1279 $file = reset($files);
1281 // Validate the file, make sure it's a valid SCORM package!
1282 $errors = scorm_validate_package($file);
1283 if (!empty($errors)) {
1286 // Create a default scorm object to pass to scorm_add_instance()!
1287 $scorm = get_config('scorm');
1288 $scorm->course = $uploadinfo->course->id;
1289 $scorm->coursemodule = $uploadinfo->coursemodule;
1290 $scorm->cmidnumber = '';
1291 $scorm->name = $uploadinfo->displayname;
1292 $scorm->scormtype = SCORM_TYPE_LOCAL;
1293 $scorm->reference = $file->get_filename();
1295 $scorm->width = $scorm->framewidth;
1296 $scorm->height = $scorm->frameheight;
1298 return scorm_add_instance($scorm, null);
1302 * Sets activity completion state
1304 * @param object $scorm object
1305 * @param int $userid User ID
1306 * @param int $completionstate Completion state
1307 * @param array $grades grades array of users with grades - used when $userid = 0
1309 function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1310 $course = new stdClass();
1311 $course->id = $scorm->course;
1312 $completion = new completion_info($course);
1314 // Check if completion is enabled site-wide, or for the course
1315 if (!$completion->is_enabled()) {
1319 $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1320 if (empty($cm) || !$completion->is_enabled($cm)) {
1324 if (empty($userid)) { //we need to get all the relevant users from $grades param.
1325 foreach ($grades as $grade) {
1326 $completion->update_state($cm, $completionstate, $grade->userid);
1329 $completion->update_state($cm, $completionstate, $userid);
1334 * Check that a Zip file contains a valid SCORM package
1336 * @param $file stored_file a Zip file.
1337 * @return array empty if no issue is found. Array of error message otherwise
1339 function scorm_validate_package($file) {
1340 $packer = get_file_packer('application/zip');
1342 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1343 $file->import_external_file_contents();
1345 $filelist = $file->list_files($packer);
1347 if (!is_array($filelist)) {
1348 $errors['packagefile'] = get_string('badarchive', 'scorm');
1351 $badmanifestpresent = false;
1352 foreach ($filelist as $info) {
1353 if ($info->pathname == 'imsmanifest.xml') {
1355 } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1356 // This package has an imsmanifest file inside a folder of the package.
1357 $badmanifestpresent = true;
1359 if (preg_match('/\.cst$/', $info->pathname)) {
1364 if ($badmanifestpresent) {
1365 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1367 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1375 * Check and set the correct mode and attempt when entering a SCORM package.
1377 * @param object $scorm object
1378 * @param string $newattempt should a new attempt be generated here.
1379 * @param int $attempt the attempt number this is for.
1380 * @param int $userid the userid of the user.
1381 * @param string $mode the current mode that has been selected.
1383 function scorm_check_mode($scorm, $newattempt, &$attempt, $userid, &$mode) {
1385 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1388 } else if ($mode != 'browse') { // Check if review mode should be set.
1389 $mode = 'normal'; // Set to normal mode by default.
1391 // If all tracks == passed, failed or completed then use review mode.
1392 $tracks = $DB->get_recordset('scorm_scoes_track', array('scormid' => $scorm->id, 'userid' => $userid,
1393 'attempt' => $attempt, 'element' => 'cmi.core.lesson_status'));
1394 foreach ($tracks as $track) {
1395 if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1397 } else { // Found an incomplete sco so exit and use normal mode.
1403 } else if (($mode == 'browse') && ($scorm->hidebrowse == 1)) { // Prevent Browse mode if hidebrowse is set.