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 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);
54 * Return an array of status options
56 * Optionally with translated strings
58 * @param bool $with_strings (optional)
61 function scorm_status_options($with_strings = false) {
62 // Id's are important as they are bits
69 foreach ($options as $key => $value) {
70 $options[$key] = get_string('completionstatus_'.$value, 'scorm');
79 * Given an object containing all the necessary data,
80 * (defined by the form in mod_form.php) this function
81 * will create a new instance and return the id number
82 * of the new instance.
86 * @uses CONTEXT_MODULE
87 * @uses SCORM_TYPE_LOCAL
88 * @uses SCORM_TYPE_LOCALSYNC
89 * @uses SCORM_TYPE_EXTERNAL
90 * @param object $scorm Form data
91 * @param object $mform
92 * @return int new instance id
94 function scorm_add_instance($scorm, $mform=null) {
97 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
99 if (empty($scorm->timeopen
)) {
100 $scorm->timeopen
= 0;
102 if (empty($scorm->timeclose
)) {
103 $scorm->timeclose
= 0;
105 $cmid = $scorm->coursemodule
;
106 $cmidnumber = $scorm->cmidnumber
;
107 $courseid = $scorm->course
;
109 $context = context_module
::instance($cmid);
111 $scorm = scorm_option2text($scorm);
112 $scorm->width
= (int)str_replace('%', '', $scorm->width
);
113 $scorm->height
= (int)str_replace('%', '', $scorm->height
);
115 if (!isset($scorm->whatgrade
)) {
116 $scorm->whatgrade
= 0;
119 $id = $DB->insert_record('scorm', $scorm);
121 // Update course module record - from now on this instance properly exists and all function may be used.
122 $DB->set_field('course_modules', 'instance', $id, array('id'=>$cmid));
124 // Reload scorm instance.
125 $record = $DB->get_record('scorm', array('id'=>$id));
127 // Store the package and verify.
128 if ($record->scormtype
=== SCORM_TYPE_LOCAL
) {
129 if (!empty($scorm->packagefile
)) {
130 $fs = get_file_storage();
131 $fs->delete_area_files($context->id
, 'mod_scorm', 'package');
132 file_save_draft_area_files($scorm->packagefile
, $context->id
, 'mod_scorm', 'package',
133 0, array('subdirs' => 0, 'maxfiles' => 1));
134 // Get filename of zip that was uploaded.
135 $files = $fs->get_area_files($context->id
, 'mod_scorm', 'package', 0, '', false);
136 $file = reset($files);
137 $filename = $file->get_filename();
138 if ($filename !== false) {
139 $record->reference
= $filename;
143 } else if ($record->scormtype
=== SCORM_TYPE_LOCALSYNC
) {
144 $record->reference
= $scorm->packageurl
;
145 } else if ($record->scormtype
=== SCORM_TYPE_EXTERNAL
) {
146 $record->reference
= $scorm->packageurl
;
147 } else if ($record->scormtype
=== SCORM_TYPE_AICCURL
) {
148 $record->reference
= $scorm->packageurl
;
149 $record->hidetoc
= SCORM_TOC_DISABLED
; // TOC is useless for direct AICCURL so disable it.
155 $DB->update_record('scorm', $record);
157 // Extra fields required in grade related functions.
158 $record->course
= $courseid;
159 $record->cmidnumber
= $cmidnumber;
160 $record->cmid
= $cmid;
162 scorm_parse($record, true);
164 scorm_grade_item_update($record);
170 * Given an object containing all the necessary data,
171 * (defined by the form in mod_form.php) this function
172 * will update an existing instance with new data.
176 * @uses CONTEXT_MODULE
177 * @uses SCORM_TYPE_LOCAL
178 * @uses SCORM_TYPE_LOCALSYNC
179 * @uses SCORM_TYPE_EXTERNAL
180 * @param object $scorm Form data
181 * @param object $mform
184 function scorm_update_instance($scorm, $mform=null) {
187 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
189 if (empty($scorm->timeopen
)) {
190 $scorm->timeopen
= 0;
192 if (empty($scorm->timeclose
)) {
193 $scorm->timeclose
= 0;
196 $cmid = $scorm->coursemodule
;
197 $cmidnumber = $scorm->cmidnumber
;
198 $courseid = $scorm->course
;
200 $scorm->id
= $scorm->instance
;
202 $context = context_module
::instance($cmid);
204 if ($scorm->scormtype
=== SCORM_TYPE_LOCAL
) {
205 if (!empty($scorm->packagefile
)) {
206 $fs = get_file_storage();
207 $fs->delete_area_files($context->id
, 'mod_scorm', 'package');
208 file_save_draft_area_files($scorm->packagefile
, $context->id
, 'mod_scorm', 'package',
209 0, array('subdirs' => 0, 'maxfiles' => 1));
210 // Get filename of zip that was uploaded.
211 $files = $fs->get_area_files($context->id
, 'mod_scorm', 'package', 0, '', false);
212 $file = reset($files);
213 $filename = $file->get_filename();
214 if ($filename !== false) {
215 $scorm->reference
= $filename;
219 } else if ($scorm->scormtype
=== SCORM_TYPE_LOCALSYNC
) {
220 $scorm->reference
= $scorm->packageurl
;
221 } else if ($scorm->scormtype
=== SCORM_TYPE_EXTERNAL
) {
222 $scorm->reference
= $scorm->packageurl
;
223 } else if ($scorm->scormtype
=== SCORM_TYPE_AICCURL
) {
224 $scorm->reference
= $scorm->packageurl
;
225 $scorm->hidetoc
= SCORM_TOC_DISABLED
; // TOC is useless for direct AICCURL so disable it.
230 $scorm = scorm_option2text($scorm);
231 $scorm->width
= (int)str_replace('%', '', $scorm->width
);
232 $scorm->height
= (int)str_replace('%', '', $scorm->height
);
233 $scorm->timemodified
= time();
235 if (!isset($scorm->whatgrade
)) {
236 $scorm->whatgrade
= 0;
239 $DB->update_record('scorm', $scorm);
241 $scorm = $DB->get_record('scorm', array('id'=>$scorm->id
));
243 /// extra fields required in grade related functions
244 $scorm->course
= $courseid;
245 $scorm->idnumber
= $cmidnumber;
246 $scorm->cmid
= $cmid;
248 scorm_parse($scorm, (bool)$scorm->updatefreq
);
250 scorm_grade_item_update($scorm);
251 scorm_update_grades($scorm);
257 * Given an ID of an instance of this module,
258 * this function will permanently delete the instance
259 * and any data that depends on it.
263 * @param int $id Scorm instance id
266 function scorm_delete_instance($id) {
269 if (! $scorm = $DB->get_record('scorm', array('id'=>$id))) {
275 // Delete any dependent records
276 if (! $DB->delete_records('scorm_scoes_track', array('scormid'=>$scorm->id
))) {
279 if ($scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id
))) {
280 foreach ($scoes as $sco) {
281 if (! $DB->delete_records('scorm_scoes_data', array('scoid'=>$sco->id
))) {
285 $DB->delete_records('scorm_scoes', array('scorm'=>$scorm->id
));
287 if (! $DB->delete_records('scorm', array('id'=>$scorm->id
))) {
291 /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
294 if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
297 if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
300 if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
303 if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
306 if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
309 if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
313 scorm_grade_item_delete($scorm);
319 * Return a small object with summary information about what a
320 * user has done with a given particular instance of this module
321 * Used for user activity reports.
324 * @param int $course Course id
325 * @param int $user User id
327 * @param int $scorm The scorm id
330 function scorm_user_outline($course, $user, $mod, $scorm) {
332 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
334 require_once("$CFG->libdir/gradelib.php");
335 $grades = grade_get_grades($course->id
, 'mod', 'scorm', $scorm->id
, $user->id
);
336 if (!empty($grades->items
[0]->grades
)) {
337 $grade = reset($grades->items
[0]->grades
);
338 $result = new stdClass();
339 $result->info
= get_string('grade') . ': '. $grade->str_long_grade
;
341 //datesubmitted == time created. dategraded == time modified or time overridden
342 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
343 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
344 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
345 $result->time
= $grade->dategraded
;
347 $result->time
= $grade->datesubmitted
;
356 * Print a detailed representation of what a user has done with
357 * a given particular instance of this module, for user activity reports.
361 * @param object $course
362 * @param object $user
364 * @param object $scorm
367 function scorm_user_complete($course, $user, $mod, $scorm) {
368 global $CFG, $DB, $OUTPUT;
369 require_once("$CFG->libdir/gradelib.php");
371 $liststyle = 'structlist';
375 $sometoreport = false;
378 // First Access and Last Access dates for SCOs
379 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
380 $timetracks = scorm_get_sco_runtime($scorm->id
, false, $user->id
);
381 $firstmodify = $timetracks->start
;
382 $lastmodify = $timetracks->finish
;
384 $grades = grade_get_grades($course->id
, 'mod', 'scorm', $scorm->id
, $user->id
);
385 if (!empty($grades->items
[0]->grades
)) {
386 $grade = reset($grades->items
[0]->grades
);
387 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
388 if ($grade->str_feedback
) {
389 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
393 if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
394 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
395 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
396 array($scorm->id
), 'sortorder, id', 'id, identifier, title')) {
397 if (count($orgs) <= 1) {
400 $org = new stdClass();
401 $org->identifier
= '';
404 $report .= '<div class="mod-scorm">'."\n";
405 foreach ($orgs as $org) {
406 $conditions = array();
408 if (!empty($org->identifier
)) {
409 $report .= '<div class="orgtitle">'.$org->title
.'</div>';
410 $currentorg = $org->identifier
;
411 $conditions['organization'] = $currentorg;
413 $report .= "<ul id='0' class='$liststyle'>";
414 $conditions['scorm'] = $scorm->id
;
415 if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
416 // drop keys so that we can access array sequentially
417 $scoes = array_values($scoes);
420 $parents[$level]='/';
421 foreach ($scoes as $pos => $sco) {
422 if ($parents[$level]!=$sco->parent
) {
423 if ($level>0 && $parents[$level-1]==$sco->parent
) {
424 $report .= "\t\t</ul></li>\n";
429 while (($i > 0) && ($parents[$level] != $sco->parent
)) {
430 $closelist .= "\t\t</ul></li>\n";
433 if (($i == 0) && ($sco->parent
!= $currentorg)) {
434 $report .= "\t\t<li><ul id='$sublist' class='$liststyle'>\n";
437 $report .= $closelist;
440 $parents[$level]=$sco->parent
;
443 $report .= "\t\t<li>";
444 if (isset($scoes[$pos+
1])) {
445 $nextsco = $scoes[$pos+
1];
449 if (($nextsco !== false) && ($sco->parent
!= $nextsco->parent
) && (($level==0) ||
(($level>0) && ($nextsco->parent
== $sco->identifier
)))) {
452 $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
458 if ($usertrack=scorm_get_tracks($sco->id
, $user->id
)) {
459 if ($usertrack->status
== '') {
460 $usertrack->status
= 'notattempted';
462 $strstatus = get_string($usertrack->status
, 'scorm');
463 $report .= "<img src='".$OUTPUT->pix_url($usertrack->status
, 'scorm')."' alt='$strstatus' title='$strstatus' />";
465 if ($sco->scormtype
== 'sco') {
466 $report .= '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
468 $report .= '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
471 $report .= " $sco->title $score$totaltime</li>\n";
472 if ($usertrack !== false) {
473 $sometoreport = true;
474 $report .= "\t\t\t<li><ul class='$liststyle'>\n";
475 foreach ($usertrack as $element => $value) {
476 if (substr($element, 0, 3) == 'cmi') {
477 $report .= '<li>'.$element.' => '.s($value).'</li>';
480 $report .= "\t\t\t</ul></li>\n";
483 $report .= " $sco->title</li>\n";
486 for ($i=0; $i<$level; $i++
) {
487 $report .= "\t\t</ul></li>\n";
490 $report .= "\t</ul><br />\n";
492 $report .= "</div>\n";
495 if ($firstmodify < $now) {
496 $timeago = format_time($now - $firstmodify);
497 echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")<br />\n";
499 if ($lastmodify > 0) {
500 $timeago = format_time($now - $lastmodify);
501 echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")<br />\n";
503 echo get_string('report', 'scorm').":<br />\n";
506 print_string('noactivity', 'scorm');
513 * Function to be run periodically according to the moodle cron
514 * This function searches for things that need to be done, such
515 * as sending out mail, toggling flags etc ...
521 function scorm_cron () {
524 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
526 $sitetimezone = $CFG->timezone
;
527 // Now see if there are any scorm updates to be done.
529 if (!isset($CFG->scorm_updatetimelast
)) { // To catch the first time.
530 set_config('scorm_updatetimelast', 0);
534 $updatetime = usergetmidnight($timenow, $sitetimezone);
536 if ($CFG->scorm_updatetimelast
< $updatetime and $timenow > $updatetime) {
538 set_config('scorm_updatetimelast', $timenow);
540 mtrace('Updating scorm packages which require daily update');// We are updating.
542 $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY
));
543 foreach ($scormsupdate as $scormupdate) {
544 scorm_parse($scormupdate, true);
547 // Now clear out AICC session table with old session data.
548 $cfgscorm = get_config('scorm');
549 if (!empty($cfgscorm->allowaicchacp
)) {
550 $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata
*24*60*60);
551 $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
559 * Return grade for given user or all users.
563 * @param int $scormid id of scorm
564 * @param int $userid optional user id, 0 means all users
565 * @return array array of grades, false if none
567 function scorm_get_user_grades($scorm, $userid=0) {
569 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
572 if (empty($userid)) {
573 if ($scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid", array($scorm->id
), "", "userid,null")) {
574 foreach ($scousers as $scouser) {
575 $grades[$scouser->userid
] = new stdClass();
576 $grades[$scouser->userid
]->id
= $scouser->userid
;
577 $grades[$scouser->userid
]->userid
= $scouser->userid
;
578 $grades[$scouser->userid
]->rawgrade
= scorm_grade_user($scorm, $scouser->userid
);
585 if (!$DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid", array($scorm->id
, $userid), "", "userid,null")) {
586 return false; //no attempt yet
588 $grades[$userid] = new stdClass();
589 $grades[$userid]->id
= $userid;
590 $grades[$userid]->userid
= $userid;
591 $grades[$userid]->rawgrade
= scorm_grade_user($scorm, $userid);
598 * Update grades in central gradebook
601 * @param object $scorm
602 * @param int $userid specific user only, 0 mean all
603 * @param bool $nullifnone
605 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
607 require_once($CFG->libdir
.'/gradelib.php');
608 require_once($CFG->libdir
.'/completionlib.php');
610 if ($grades = scorm_get_user_grades($scorm, $userid)) {
611 scorm_grade_item_update($scorm, $grades);
613 scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE
, $grades);
614 } else if ($userid and $nullifnone) {
615 $grade = new stdClass();
616 $grade->userid
= $userid;
617 $grade->rawgrade
= null;
618 scorm_grade_item_update($scorm, $grade);
620 scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE
);
622 scorm_grade_item_update($scorm);
627 * Update all grades in gradebook.
631 function scorm_upgrade_grades() {
634 $sql = "SELECT COUNT('x')
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 $count = $DB->count_records_sql($sql);
639 $sql = "SELECT s.*, cm.idnumber AS cmidnumber, s.course AS courseid
640 FROM {scorm} s, {course_modules} cm, {modules} m
641 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
642 $rs = $DB->get_recordset_sql($sql);
644 $pbar = new progress_bar('scormupgradegrades', 500, true);
646 foreach ($rs as $scorm) {
648 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
649 scorm_update_grades($scorm, 0, false);
650 $pbar->update($i, $count, "Updating Scorm grades ($i/$count).");
657 * Update/create grade item for given scorm
660 * @uses GRADE_TYPE_VALUE
661 * @uses GRADE_TYPE_NONE
662 * @param object $scorm object with extra cmidnumber
663 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
664 * @return object grade_item
666 function scorm_grade_item_update($scorm, $grades=null) {
668 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
669 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
670 require_once($CFG->libdir
.'/gradelib.php');
673 $params = array('itemname'=>$scorm->name
);
674 if (isset($scorm->cmidnumber
)) {
675 $params['idnumber'] = $scorm->cmidnumber
;
678 if ($scorm->grademethod
== GRADESCOES
) {
679 if ($maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id
))) {
680 $params['gradetype'] = GRADE_TYPE_VALUE
;
681 $params['grademax'] = $maxgrade;
682 $params['grademin'] = 0;
684 $params['gradetype'] = GRADE_TYPE_NONE
;
687 $params['gradetype'] = GRADE_TYPE_VALUE
;
688 $params['grademax'] = $scorm->maxgrade
;
689 $params['grademin'] = 0;
692 if ($grades === 'reset') {
693 $params['reset'] = true;
697 return grade_update('mod/scorm', $scorm->course
, 'mod', 'scorm', $scorm->id
, 0, $grades, $params);
701 * Delete grade item for given scorm
704 * @param object $scorm object
705 * @return object grade_item
707 function scorm_grade_item_delete($scorm) {
709 require_once($CFG->libdir
.'/gradelib.php');
711 return grade_update('mod/scorm', $scorm->course
, 'mod', 'scorm', $scorm->id
, 0, null, array('deleted'=>1));
715 * List the actions that correspond to a view of this module.
716 * This is used by the participation report.
718 * Note: This is not used by new logging system. Event with
719 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
720 * be considered as view action.
724 function scorm_get_view_actions() {
725 return array('pre-view', 'view', 'view all', 'report');
729 * List the actions that correspond to a post of this module.
730 * This is used by the participation report.
732 * Note: This is not used by new logging system. Event with
733 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
734 * will be considered as post action.
738 function scorm_get_post_actions() {
743 * @param object $scorm
744 * @return object $scorm
746 function scorm_option2text($scorm) {
747 $scorm_popoup_options = scorm_get_popup_options_array();
749 if (isset($scorm->popup
)) {
750 if ($scorm->popup
== 1) {
751 $optionlist = array();
752 foreach ($scorm_popoup_options as $name => $option) {
753 if (isset($scorm->$name)) {
754 $optionlist[] = $name.'='.$scorm->$name;
756 $optionlist[] = $name.'=0';
759 $scorm->options
= implode(',', $optionlist);
761 $scorm->options
= '';
765 $scorm->options
= '';
771 * Implementation of the function for printing the form elements that control
772 * whether the course reset functionality affects the scorm.
774 * @param object $mform form passed by reference
776 function scorm_reset_course_form_definition(&$mform) {
777 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
778 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
782 * Course reset form defaults.
786 function scorm_reset_course_form_defaults($course) {
787 return array('reset_scorm'=>1);
791 * Removes all grades from gradebook
795 * @param int $courseid
796 * @param string optional type
798 function scorm_reset_gradebook($courseid, $type='') {
801 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
802 FROM {scorm} s, {course_modules} cm, {modules} m
803 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
805 if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
806 foreach ($scorms as $scorm) {
807 scorm_grade_item_update($scorm, 'reset');
813 * Actual implementation of the reset course functionality, delete all the
814 * scorm attempts for course $data->courseid.
818 * @param object $data the data submitted from the reset course.
819 * @return array status array
821 function scorm_reset_userdata($data) {
824 $componentstr = get_string('modulenameplural', 'scorm');
827 if (!empty($data->reset_scorm
)) {
828 $scormssql = "SELECT s.id
832 $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid
));
834 // remove all grades from gradebook
835 if (empty($data->reset_gradebook_grades
)) {
836 scorm_reset_gradebook($data->courseid
);
839 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'scorm'), 'error'=>false);
842 // no dates to shift here
848 * Returns all other caps used in module
852 function scorm_get_extra_capabilities() {
853 return array('moodle/site:accessallgroups');
857 * Lists all file areas current user may browse
859 * @param object $course
861 * @param object $context
864 function scorm_get_file_areas($course, $cm, $context) {
866 $areas['content'] = get_string('areacontent', 'scorm');
867 $areas['package'] = get_string('areapackage', 'scorm');
872 * File browsing support for SCORM file areas
876 * @param file_browser $browser file browser instance
877 * @param array $areas file areas
878 * @param stdClass $course course object
879 * @param stdClass $cm course module object
880 * @param stdClass $context context object
881 * @param string $filearea file area
882 * @param int $itemid item ID
883 * @param string $filepath file path
884 * @param string $filename file name
885 * @return file_info instance or null if not found
887 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
890 if (!has_capability('moodle/course:managefiles', $context)) {
894 // no writing for now!
896 $fs = get_file_storage();
898 if ($filearea === 'content') {
900 $filepath = is_null($filepath) ?
'/' : $filepath;
901 $filename = is_null($filename) ?
'.' : $filename;
903 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
904 if (!$storedfile = $fs->get_file($context->id
, 'mod_scorm', 'content', 0, $filepath, $filename)) {
905 if ($filepath === '/' and $filename === '.') {
906 $storedfile = new virtual_root_file($context->id
, 'mod_scorm', 'content', 0);
912 require_once("$CFG->dirroot/mod/scorm/locallib.php");
913 return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
915 } else if ($filearea === 'package') {
916 $filepath = is_null($filepath) ?
'/' : $filepath;
917 $filename = is_null($filename) ?
'.' : $filename;
919 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
920 if (!$storedfile = $fs->get_file($context->id
, 'mod_scorm', 'package', 0, $filepath, $filename)) {
921 if ($filepath === '/' and $filename === '.') {
922 $storedfile = new virtual_root_file($context->id
, 'mod_scorm', 'package', 0);
928 return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
931 // scorm_intro handled in file_browser
937 * Serves scorm content, introduction images and packages. Implements needed access control ;-)
941 * @param stdClass $course course object
942 * @param stdClass $cm course module object
943 * @param stdClass $context context object
944 * @param string $filearea file area
945 * @param array $args extra arguments
946 * @param bool $forcedownload whether or not force download
947 * @param array $options additional options affecting the file serving
948 * @return bool false if file not found, does not return if found - just send the file
950 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
953 if ($context->contextlevel
!= CONTEXT_MODULE
) {
957 require_login($course, true, $cm);
961 if ($filearea === 'content') {
962 $revision = (int)array_shift($args); // prevents caching problems - ignored here
963 $relativepath = implode('/', $args);
964 $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
965 // TODO: add any other access restrictions here if needed!
967 } else if ($filearea === 'package') {
968 if (!has_capability('moodle/course:manageactivities', $context)) {
971 $relativepath = implode('/', $args);
972 $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
973 $lifetime = 0; // no caching here
975 } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
976 $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
977 $relativepath = implode('/', $args);
979 // Get imsmanifest file.
980 $fs = get_file_storage();
981 $files = $fs->get_area_files($context->id
, 'mod_scorm', 'package', 0, '', false);
982 $file = reset($files);
984 // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
985 $packagefilename = $file->get_filename();
986 if (strtolower($packagefilename) !== 'imsmanifest.xml') {
990 $file->send_relative_file($relativepath);
995 $fs = get_file_storage();
996 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
997 if ($filearea === 'content') { //return file not found straight away to improve performance.
1004 // finally send the file
1005 send_stored_file($file, $lifetime, 0, false, $options);
1009 * @uses FEATURE_GROUPS
1010 * @uses FEATURE_GROUPINGS
1011 * @uses FEATURE_GROUPMEMBERSONLY
1012 * @uses FEATURE_MOD_INTRO
1013 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1014 * @uses FEATURE_COMPLETION_HAS_RULES
1015 * @uses FEATURE_GRADE_HAS_GRADE
1016 * @uses FEATURE_GRADE_OUTCOMES
1017 * @param string $feature FEATURE_xx constant for requested feature
1018 * @return mixed True if module supports feature, false if not, null if doesn't know
1020 function scorm_supports($feature) {
1022 case FEATURE_GROUPS
: return false;
1023 case FEATURE_GROUPINGS
: return false;
1024 case FEATURE_GROUPMEMBERSONLY
: return true;
1025 case FEATURE_MOD_INTRO
: return true;
1026 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
1027 case FEATURE_COMPLETION_HAS_RULES
: return true;
1028 case FEATURE_GRADE_HAS_GRADE
: return true;
1029 case FEATURE_GRADE_OUTCOMES
: return true;
1030 case FEATURE_BACKUP_MOODLE2
: return true;
1031 case FEATURE_SHOW_DESCRIPTION
: return true;
1033 default: return null;
1038 * Get the filename for a temp log file
1040 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1041 * @param integer $scoid - scoid of object this log entry is for
1042 * @return string The filename as an absolute path
1044 function scorm_debug_log_filename($type, $scoid) {
1047 $logpath = $CFG->tempdir
.'/scormlogs';
1048 $logfile = $logpath.'/'.$type.'debug_'.$USER->id
.'_'.$scoid.'.log';
1053 * writes log output to a temp log file
1055 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1056 * @param string $text - text to be written to file.
1057 * @param integer $scoid - scoid of object this log entry is for.
1059 function scorm_debug_log_write($type, $text, $scoid) {
1062 $debugenablelog = get_config('scorm', 'allowapidebug');
1063 if (!$debugenablelog ||
empty($text)) {
1066 if (make_temp_directory('scormlogs/')) {
1067 $logfile = scorm_debug_log_filename($type, $scoid);
1068 @file_put_contents
($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND
);
1069 @chmod
($logfile, $CFG->filepermissions
);
1074 * Remove debug log file
1076 * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1077 * @param integer $scoid - scoid of object this log entry is for
1078 * @return boolean True if the file is successfully deleted, false otherwise
1080 function scorm_debug_log_remove($type, $scoid) {
1082 $debugenablelog = get_config('scorm', 'allowapidebug');
1083 $logfile = scorm_debug_log_filename($type, $scoid);
1084 if (!$debugenablelog ||
!file_exists($logfile)) {
1088 return @unlink
($logfile);
1092 * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1094 * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1095 * @param array $htmlarray
1098 function scorm_print_overview($courses, &$htmlarray) {
1101 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1105 if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
1109 $strscorm = get_string('modulename', 'scorm');
1110 $strduedate = get_string('duedate', 'scorm');
1112 foreach ($scorms as $scorm) {
1114 $showattemptstatus = false;
1115 if ($scorm->timeopen
) {
1116 $isopen = ($scorm->timeopen
<= $time && $time <= $scorm->timeclose
);
1118 if ($scorm->displayattemptstatus
== SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1119 $scorm->displayattemptstatus
== SCORM_DISPLAY_ATTEMPTSTATUS_MY
) {
1120 $showattemptstatus = true;
1122 if ($showattemptstatus ||
!empty($isopen) ||
!empty($scorm->timeclose
)) {
1123 $str = '<div class="scorm overview"><div class="name">'.$strscorm. ': '.
1124 '<a '.($scorm->visible ?
'':' class="dimmed"').
1125 'title="'.$strscorm.'" href="'.$CFG->wwwroot
.
1126 '/mod/scorm/view.php?id='.$scorm->coursemodule
.'">'.
1127 $scorm->name
.'</a></div>';
1128 if ($scorm->timeclose
) {
1129 $str .= '<div class="info">'.$strduedate.': '.userdate($scorm->timeclose
).'</div>';
1131 if ($showattemptstatus) {
1132 require_once($CFG->dirroot
.'/mod/scorm/locallib.php');
1133 $str .= '<div class="details">'.scorm_get_attempt_status($USER, $scorm).'</div>';
1136 if (empty($htmlarray[$scorm->course
]['scorm'])) {
1137 $htmlarray[$scorm->course
]['scorm'] = $str;
1139 $htmlarray[$scorm->course
]['scorm'] .= $str;
1146 * Return a list of page types
1147 * @param string $pagetype current page type
1148 * @param stdClass $parentcontext Block's parent context
1149 * @param stdClass $currentcontext Current context of block
1151 function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1152 $module_pagetype = array('mod-scorm-*'=>get_string('page-mod-scorm-x', 'scorm'));
1153 return $module_pagetype;
1157 * Returns the SCORM version used.
1158 * @param string $scormversion comes from $scorm->version
1159 * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1160 * @return Scorm version.
1162 function scorm_version_check($scormversion, $version='') {
1163 $scormversion = trim(strtolower($scormversion));
1164 if (empty($version) ||
$version==SCORM_12
) {
1165 if ($scormversion == 'scorm_12' ||
$scormversion == 'scorm_1.2') {
1168 if (!empty($version)) {
1172 if (empty($version) ||
$version == SCORM_13
) {
1173 if ($scormversion == 'scorm_13' ||
$scormversion == 'scorm_1.3') {
1176 if (!empty($version)) {
1180 if (empty($version) ||
$version == SCORM_AICC
) {
1181 if (strpos($scormversion, 'aicc')) {
1184 if (!empty($version)) {
1192 * Obtains the automatic completion state for this scorm based on any conditions
1193 * in scorm settings.
1195 * @param object $course Course
1196 * @param object $cm Course-module
1197 * @param int $userid User ID
1198 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1199 * @return bool True if completed, false if not. (If no conditions, then return
1200 * value depends on comparison type)
1202 function scorm_get_completion_state($course, $cm, $userid, $type) {
1208 if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance
))) {
1209 print_error('cannotfindscorm');
1211 // Only check for existence of tracks and return false if completionstatusrequired or completionscorerequired
1212 // this means that if only view is required we don't end up with a false state.
1213 if ($scorm->completionstatusrequired
!== null ||
1214 $scorm->completionscorerequired
!== null) {
1215 // Get user's tracks data.
1216 $tracks = $DB->get_records_sql(
1229 'cmi.core.lesson_status',
1230 'cmi.completion_status',
1231 'cmi.success_status',
1232 'cmi.core.score.raw',
1236 array($scorm->id
, $userid)
1240 return completion_info
::aggregate_completion_states($type, $result, false);
1245 if ($scorm->completionstatusrequired
!== null) {
1248 $statuses = array_flip(scorm_status_options());
1251 foreach ($tracks as $track) {
1252 if (!in_array($track->element
, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1256 if (array_key_exists($track->value
, $statuses)) {
1257 $nstatus |
= $statuses[$track->value
];
1261 if ($scorm->completionstatusrequired
& $nstatus) {
1262 return completion_info
::aggregate_completion_states($type, $result, true);
1264 return completion_info
::aggregate_completion_states($type, $result, false);
1270 if ($scorm->completionscorerequired
!== null) {
1273 foreach ($tracks as $track) {
1274 if (!in_array($track->element
, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1278 if (strlen($track->value
) && floatval($track->value
) >= $maxscore) {
1279 $maxscore = floatval($track->value
);
1283 if ($scorm->completionscorerequired
<= $maxscore) {
1284 return completion_info
::aggregate_completion_states($type, $result, true);
1286 return completion_info
::aggregate_completion_states($type, $result, false);
1294 * Register the ability to handle drag and drop file uploads
1295 * @return array containing details of the files / types the mod can handle
1297 function scorm_dndupload_register() {
1298 return array('files' => array(
1299 array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1304 * Handle a file that has been uploaded
1305 * @param object $uploadinfo details of the file / content that has been uploaded
1306 * @return int instance id of the newly created mod
1308 function scorm_dndupload_handle($uploadinfo) {
1310 $context = context_module
::instance($uploadinfo->coursemodule
);
1311 file_save_draft_area_files($uploadinfo->draftitemid
, $context->id
, 'mod_scorm', 'package', 0);
1312 $fs = get_file_storage();
1313 $files = $fs->get_area_files($context->id
, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1314 $file = reset($files);
1316 // Validate the file, make sure it's a valid SCORM package!
1317 $errors = scorm_validate_package($file);
1318 if (!empty($errors)) {
1321 // Create a default scorm object to pass to scorm_add_instance()!
1322 $scorm = get_config('scorm');
1323 $scorm->course
= $uploadinfo->course
->id
;
1324 $scorm->coursemodule
= $uploadinfo->coursemodule
;
1325 $scorm->cmidnumber
= '';
1326 $scorm->name
= $uploadinfo->displayname
;
1327 $scorm->scormtype
= SCORM_TYPE_LOCAL
;
1328 $scorm->reference
= $file->get_filename();
1330 $scorm->width
= $scorm->framewidth
;
1331 $scorm->height
= $scorm->frameheight
;
1333 return scorm_add_instance($scorm, null);
1337 * Sets activity completion state
1339 * @param object $scorm object
1340 * @param int $userid User ID
1341 * @param int $completionstate Completion state
1342 * @param array $grades grades array of users with grades - used when $userid = 0
1344 function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE
, $grades = array()) {
1345 $course = new stdClass();
1346 $course->id
= $scorm->course
;
1347 $completion = new completion_info($course);
1349 // Check if completion is enabled site-wide, or for the course
1350 if (!$completion->is_enabled()) {
1354 $cm = get_coursemodule_from_instance('scorm', $scorm->id
, $scorm->course
);
1355 if (empty($cm) ||
!$completion->is_enabled($cm)) {
1359 if (empty($userid)) { //we need to get all the relevant users from $grades param.
1360 foreach ($grades as $grade) {
1361 $completion->update_state($cm, $completionstate, $grade->userid
);
1364 $completion->update_state($cm, $completionstate, $userid);
1369 * Check that a Zip file contains a valid SCORM package
1371 * @param $file stored_file a Zip file.
1372 * @return array empty if no issue is found. Array of error message otherwise
1374 function scorm_validate_package($file) {
1375 $packer = get_file_packer('application/zip');
1377 if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1378 $file->import_external_file_contents();
1380 $filelist = $file->list_files($packer);
1382 if (!is_array($filelist)) {
1383 $errors['packagefile'] = get_string('badarchive', 'scorm');
1386 $badmanifestpresent = false;
1387 foreach ($filelist as $info) {
1388 if ($info->pathname
== 'imsmanifest.xml') {
1390 } else if (strpos($info->pathname
, 'imsmanifest.xml') !== false) {
1391 // This package has an imsmanifest file inside a folder of the package.
1392 $badmanifestpresent = true;
1394 if (preg_match('/\.cst$/', $info->pathname
)) {
1399 if ($badmanifestpresent) {
1400 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1402 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1410 * Check and set the correct mode and attempt when entering a SCORM package.
1412 * @param object $scorm object
1413 * @param string $newattempt should a new attempt be generated here.
1414 * @param int $attempt the attempt number this is for.
1415 * @param int $userid the userid of the user.
1416 * @param string $mode the current mode that has been selected.
1418 function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1421 if (($mode == 'browse')) {
1422 if ($scorm->hidebrowse
== 1) {
1423 // Prevent Browse mode if hidebrowse is set.
1426 // We don't need to check attempts as browse mode is set.
1430 // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1432 $tracks = $DB->get_recordset('scorm_scoes_track', array('scormid' => $scorm->id
, 'userid' => $userid,
1433 'attempt' => $attempt, 'element' => 'cmi.core.lesson_status'));
1434 foreach ($tracks as $track) {
1435 if (($track->value
== 'completed') ||
($track->value
== 'passed') ||
($track->value
== 'failed')) {
1436 $incomplete = false;
1439 break; // Found an incomplete sco, so the result as a whole is incomplete.
1444 // Validate user request to start a new attempt.
1445 if ($incomplete === true) {
1446 // The option to start a new attempt should never have been presented. Force false.
1447 $newattempt = 'off';
1448 } else if (!empty($scorm->forcenewattempt
)) {
1449 // A new attempt should be forced for already completed attempts.
1453 if (($newattempt == 'on') && (($attempt < $scorm->maxattempt
) ||
($scorm->maxattempt
== 0))) {
1456 } else { // Check if review mode should be set.
1457 if ($incomplete === true) {