Updated the 19 build version to 20080928
[moodle.git] / mod / scorm / lib.php
blob104db0fa7f610fdca773dd47ee3ddb7c3f55195c
1 <?php // $Id$
3 /**
4 * Given an object containing all the necessary data,
5 * (defined by the form in mod.html) this function
6 * will create a new instance and return the id number
7 * of the new instance.
9 * @param mixed $scorm Form data
10 * @return int
12 //require_once('locallib.php');
13 function scorm_add_instance($scorm) {
14 global $CFG;
16 require_once('locallib.php');
18 if (($packagedata = scorm_check_package($scorm)) != null) {
19 $scorm->pkgtype = $packagedata->pkgtype;
20 $scorm->datadir = $packagedata->datadir;
21 $scorm->launch = $packagedata->launch;
22 $scorm->parse = 1;
24 $scorm->timemodified = time();
25 if (!scorm_external_link($scorm->reference)) {
26 $scorm->md5hash = md5_file($CFG->dataroot.'/'.$scorm->course.'/'.$scorm->reference);
27 } else {
28 $scorm->dir = $CFG->dataroot.'/'.$scorm->course.'/moddata/scorm';
29 $scorm->md5hash = md5_file($scorm->dir.$scorm->datadir.'/'.basename($scorm->reference));
32 $scorm = scorm_option2text($scorm);
33 $scorm->width = str_replace('%','',$scorm->width);
34 $scorm->height = str_replace('%','',$scorm->height);
36 //sanitize submitted values a bit
37 $scorm->width = clean_param($scorm->width, PARAM_INT);
38 $scorm->height = clean_param($scorm->height, PARAM_INT);
40 if (!isset($scorm->whatgrade)) {
41 $scorm->whatgrade = 0;
43 $scorm->grademethod = ($scorm->whatgrade * 10) + $scorm->grademethod;
45 $id = insert_record('scorm', $scorm);
47 if (scorm_external_link($scorm->reference) || ((basename($scorm->reference) != 'imsmanifest.xml') && ($scorm->reference[0] != '#'))) {
48 // Rename temp scorm dir to scorm id
49 $scorm->dir = $CFG->dataroot.'/'.$scorm->course.'/moddata/scorm';
50 if (file_exists($scorm->dir.'/'.$id)) {
51 //delete directory as it shouldn't exist! - most likely there from an old moodle install with old files in dataroot
52 scorm_delete_files($scorm->dir.'/'.$id);
54 rename($scorm->dir.$scorm->datadir,$scorm->dir.'/'.$id);
57 // Parse scorm manifest
58 if ($scorm->parse == 1) {
59 $scorm->id = $id;
60 $scorm->launch = scorm_parse($scorm);
61 set_field('scorm','launch',$scorm->launch,'id',$scorm->id);
64 scorm_grade_item_update(stripslashes_recursive($scorm));
66 return $id;
67 } else {
68 print_error('badpackage','scorm');
72 /**
73 * Given an object containing all the necessary data,
74 * (defined by the form in mod.html) this function
75 * will update an existing instance with new data.
77 * @param mixed $scorm Form data
78 * @return int
80 function scorm_update_instance($scorm) {
81 global $CFG;
83 require_once('locallib.php');
85 $scorm->parse = 0;
86 if (($packagedata = scorm_check_package($scorm)) != null) {
87 $scorm->pkgtype = $packagedata->pkgtype;
88 if ($packagedata->launch == 0) {
89 $scorm->launch = $packagedata->launch;
90 $scorm->datadir = $packagedata->datadir;
91 $scorm->parse = 1;
92 if (!scorm_external_link($scorm->reference) && $scorm->reference[0] != '#') { //dont set md5hash if this is from a repo.
93 $scorm->md5hash = md5_file($CFG->dataroot.'/'.$scorm->course.'/'.$scorm->reference);
94 } elseif($scorm->reference[0] != '#') { //dont set md5hash if this is from a repo.
95 $scorm->dir = $CFG->dataroot.'/'.$scorm->course.'/moddata/scorm';
96 $scorm->md5hash = md5_file($scorm->dir.$scorm->datadir.'/'.basename($scorm->reference));
101 $scorm->timemodified = time();
102 $scorm->id = $scorm->instance;
104 $scorm = scorm_option2text($scorm);
105 $scorm->width = str_replace('%','',$scorm->width);
106 $scorm->height = str_replace('%','',$scorm->height);
108 if (!isset($scorm->whatgrade)) {
109 $scorm->whatgrade = 0;
111 $scorm->grademethod = ($scorm->whatgrade * 10) + $scorm->grademethod;
113 // Check if scorm manifest needs to be reparsed
114 if ($scorm->parse == 1) {
115 $scorm->dir = $CFG->dataroot.'/'.$scorm->course.'/moddata/scorm';
116 if (is_dir($scorm->dir.'/'.$scorm->id)) {
117 scorm_delete_files($scorm->dir.'/'.$scorm->id);
119 if (isset($scorm->datadir) && ($scorm->datadir != $scorm->id) &&
120 (scorm_external_link($scorm->reference) || ((basename($scorm->reference) != 'imsmanifest.xml') && ($scorm->reference[0] != '#')))) {
121 rename($scorm->dir.$scorm->datadir,$scorm->dir.'/'.$scorm->id);
124 $scorm->launch = scorm_parse($scorm);
125 } else {
126 $oldscorm = get_record('scorm','id',$scorm->id);
127 $scorm->reference = $oldscorm->reference; // This fix a problem with Firefox when the teacher choose Cancel on overwrite question
130 if ($result = update_record('scorm', $scorm)) {
131 scorm_grade_item_update(stripslashes_recursive($scorm));
132 //scorm_grade_item_update($scorm); // John Macklins fix - dont think this is needed
135 return $result;
139 * Given an ID of an instance of this module,
140 * this function will permanently delete the instance
141 * and any data that depends on it.
143 * @param int $id Scorm instance id
144 * @return boolean
146 function scorm_delete_instance($id) {
148 global $CFG;
150 if (! $scorm = get_record('scorm', 'id', $id)) {
151 return false;
154 $result = true;
156 $scorm->dir = $CFG->dataroot.'/'.$scorm->course.'/moddata/scorm';
157 if (is_dir($scorm->dir.'/'.$scorm->id)) {
158 // Delete any dependent files
159 require_once('locallib.php');
160 scorm_delete_files($scorm->dir.'/'.$scorm->id);
163 // Delete any dependent records
164 if (! delete_records('scorm_scoes_track', 'scormid', $scorm->id)) {
165 $result = false;
167 if ($scoes = get_records('scorm_scoes','scorm',$scorm->id)) {
168 foreach ($scoes as $sco) {
169 if (! delete_records('scorm_scoes_data', 'scoid', $sco->id)) {
170 $result = false;
173 delete_records('scorm_scoes', 'scorm', $scorm->id);
174 } else {
175 $result = false;
177 if (! delete_records('scorm', 'id', $scorm->id)) {
178 $result = false;
181 /*if (! delete_records('scorm_sequencing_controlmode', 'scormid', $scorm->id)) {
182 $result = false;
184 if (! delete_records('scorm_sequencing_rolluprules', 'scormid', $scorm->id)) {
185 $result = false;
187 if (! delete_records('scorm_sequencing_rolluprule', 'scormid', $scorm->id)) {
188 $result = false;
190 if (! delete_records('scorm_sequencing_rollupruleconditions', 'scormid', $scorm->id)) {
191 $result = false;
193 if (! delete_records('scorm_sequencing_rolluprulecondition', 'scormid', $scorm->id)) {
194 $result = false;
196 if (! delete_records('scorm_sequencing_rulecondition', 'scormid', $scorm->id)) {
197 $result = false;
199 if (! delete_records('scorm_sequencing_ruleconditions', 'scormid', $scorm->id)) {
200 $result = false;
201 }*/
203 scorm_grade_item_delete(stripslashes_recursive($scorm));
205 return $result;
209 * Return a small object with summary information about what a
210 * user has done with a given particular instance of this module
211 * Used for user activity reports.
213 * @param int $course Course id
214 * @param int $user User id
215 * @param int $mod
216 * @param int $scorm The scorm id
217 * @return mixed
219 function scorm_user_outline($course, $user, $mod, $scorm) {
220 global $CFG;
221 require_once('locallib.php');
223 $return = scorm_grade_user($scorm, $user->id, true);
225 return $return;
229 * Print a detailed representation of what a user has done with
230 * a given particular instance of this module, for user activity reports.
232 * @param int $course Course id
233 * @param int $user User id
234 * @param int $mod
235 * @param int $scorm The scorm id
236 * @return boolean
238 function scorm_user_complete($course, $user, $mod, $scorm) {
239 global $CFG;
241 $liststyle = 'structlist';
242 $scormpixdir = $CFG->modpixpath.'/scorm/pix';
243 $now = time();
244 $firstmodify = $now;
245 $lastmodify = 0;
246 $sometoreport = false;
247 $report = '';
249 if ($orgs = get_records_select('scorm_scoes',"scorm='$scorm->id' AND organization='' AND launch=''",'id','id,identifier,title')) {
250 if (count($orgs) <= 1) {
251 unset($orgs);
252 $orgs[]->identifier = '';
254 $report .= '<div class="mod-scorm">'."\n";
255 foreach ($orgs as $org) {
256 $organizationsql = '';
257 $currentorg = '';
258 if (!empty($org->identifier)) {
259 $report .= '<div class="orgtitle">'.$org->title.'</div>';
260 $currentorg = $org->identifier;
261 $organizationsql = "AND organization='$currentorg'";
263 $report .= "<ul id='0' class='$liststyle'>";
264 if ($scoes = get_records_select('scorm_scoes',"scorm='$scorm->id' $organizationsql order by id ASC")){
265 // drop keys so that we can access array sequentially
266 $scoes = array_values($scoes);
267 $level=0;
268 $sublist=1;
269 $parents[$level]='/';
270 foreach ($scoes as $pos=>$sco) {
271 if ($parents[$level]!=$sco->parent) {
272 if ($level>0 && $parents[$level-1]==$sco->parent) {
273 $report .= "\t\t</ul></li>\n";
274 $level--;
275 } else {
276 $i = $level;
277 $closelist = '';
278 while (($i > 0) && ($parents[$level] != $sco->parent)) {
279 $closelist .= "\t\t</ul></li>\n";
280 $i--;
282 if (($i == 0) && ($sco->parent != $currentorg)) {
283 $report .= "\t\t<li><ul id='$sublist' class='$liststyle'>\n";
284 $level++;
285 } else {
286 $report .= $closelist;
287 $level = $i;
289 $parents[$level]=$sco->parent;
292 $report .= "\t\t<li>";
293 if (isset($scoes[$pos+1])) {
294 $nextsco = $scoes[$pos+1];
295 } else {
296 $nextsco = false;
298 if (($nextsco !== false) && ($sco->parent != $nextsco->parent) && (($level==0) || (($level>0) && ($nextsco->parent == $sco->identifier)))) {
299 $sublist++;
300 } else {
301 $report .= '<img src="'.$scormpixdir.'/spacer.gif" alt="" />';
304 if ($sco->launch) {
305 require_once('locallib.php');
306 $score = '';
307 $totaltime = '';
308 if ($usertrack=scorm_get_tracks($sco->id,$user->id)) {
309 if ($usertrack->status == '') {
310 $usertrack->status = 'notattempted';
312 $strstatus = get_string($usertrack->status,'scorm');
313 $report .= "<img src='".$scormpixdir.'/'.$usertrack->status.".gif' alt='$strstatus' title='$strstatus' />";
314 if ($usertrack->timemodified != 0) {
315 if ($usertrack->timemodified > $lastmodify) {
316 $lastmodify = $usertrack->timemodified;
318 if ($usertrack->timemodified < $firstmodify) {
319 $firstmodify = $usertrack->timemodified;
322 } else {
323 if ($sco->scormtype == 'sco') {
324 $report .= '<img src="'.$scormpixdir.'/'.'notattempted.gif" alt="'.get_string('notattempted','scorm').'" title="'.get_string('notattempted','scorm').'" />';
325 } else {
326 $report .= '<img src="'.$scormpixdir.'/'.'asset.gif" alt="'.get_string('asset','scorm').'" title="'.get_string('asset','scorm').'" />';
329 $report .= "&nbsp;$sco->title $score$totaltime</li>\n";
330 if ($usertrack !== false) {
331 $sometoreport = true;
332 $report .= "\t\t\t<li><ul class='$liststyle'>\n";
333 foreach($usertrack as $element => $value) {
334 if (substr($element,0,3) == 'cmi') {
335 $report .= '<li>'.$element.' => '.$value.'</li>';
338 $report .= "\t\t\t</ul></li>\n";
340 } else {
341 $report .= "&nbsp;$sco->title</li>\n";
344 for ($i=0;$i<$level;$i++) {
345 $report .= "\t\t</ul></li>\n";
348 $report .= "\t</ul><br />\n";
350 $report .= "</div>\n";
352 if ($sometoreport) {
353 if ($firstmodify < $now) {
354 $timeago = format_time($now - $firstmodify);
355 echo get_string('firstaccess','scorm').': '.userdate($firstmodify).' ('.$timeago.")<br />\n";
357 if ($lastmodify > 0) {
358 $timeago = format_time($now - $lastmodify);
359 echo get_string('lastaccess','scorm').': '.userdate($lastmodify).' ('.$timeago.")<br />\n";
361 echo get_string('report','scorm').":<br />\n";
362 echo $report;
363 } else {
364 print_string('noactivity','scorm');
367 return true;
371 * Function to be run periodically according to the moodle cron
372 * This function searches for things that need to be done, such
373 * as sending out mail, toggling flags etc ...
375 * @return boolean
377 function scorm_cron () {
379 global $CFG;
381 require_once('locallib.php');
383 $sitetimezone = $CFG->timezone;
384 /// Now see if there are any digest mails waiting to be sent, and if we should send them
385 if (!isset($CFG->scorm_updatetimelast)) { // To catch the first time
386 set_config('scorm_updatetimelast', 0);
389 $timenow = time();
390 $updatetime = usergetmidnight($timenow, $sitetimezone) + ($CFG->scorm_updatetime * 3600);
392 if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
394 set_config('scorm_updatetimelast', $timenow);
396 mtrace('Updating scorm packages which require daily update');//We are updating
398 $scormsupdate = get_records('scorm','updatefreq',UPDATE_EVERYDAY);
399 if (!empty($scormsupdate)) {
400 foreach($scormsupdate as $scormupdate) {
401 $scormupdate->instance = $scormupdate->id;
402 $id = scorm_update_instance($scormupdate);
407 return true;
411 * Return grade for given user or all users.
413 * @param int $scormid id of scorm
414 * @param int $userid optional user id, 0 means all users
415 * @return array array of grades, false if none
417 function scorm_get_user_grades($scorm, $userid=0) {
418 global $CFG;
419 require_once('locallib.php');
421 $grades = array();
422 if (empty($userid)) {
423 if ($scousers = get_records_select('scorm_scoes_track', "scormid='$scorm->id' GROUP BY userid", "", "userid,null")) {
424 foreach ($scousers as $scouser) {
425 $grades[$scouser->userid] = new object();
426 $grades[$scouser->userid]->id = $scouser->userid;
427 $grades[$scouser->userid]->userid = $scouser->userid;
428 $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
430 } else {
431 return false;
434 } else {
435 if (!get_records_select('scorm_scoes_track', "scormid='$scorm->id' AND userid='$userid' GROUP BY userid", "", "userid,null")) {
436 return false; //no attempt yet
438 $grades[$userid] = new object();
439 $grades[$userid]->id = $userid;
440 $grades[$userid]->userid = $userid;
441 $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
444 return $grades;
448 * Update grades in central gradebook
450 * @param object $scorm null means all scormbases
451 * @param int $userid specific user only, 0 mean all
453 function scorm_update_grades($scorm=null, $userid=0, $nullifnone=true) {
454 global $CFG;
455 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
456 require_once($CFG->libdir.'/gradelib.php');
459 if ($scorm != null) {
460 if ($grades = scorm_get_user_grades($scorm, $userid)) {
461 scorm_grade_item_update($scorm, $grades);
463 } else if ($userid and $nullifnone) {
464 $grade = new object();
465 $grade->userid = $userid;
466 $grade->rawgrade = NULL;
467 scorm_grade_item_update($scorm, $grade);
469 } else {
470 scorm_grade_item_update($scorm);
473 } else {
474 $sql = "SELECT s.*, cm.idnumber as cmidnumber
475 FROM {$CFG->prefix}scorm s, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
476 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
477 if ($rs = get_recordset_sql($sql)) {
478 while ($scorm = rs_fetch_next_record($rs)) {
479 scorm_update_grades($scorm, 0, false);
481 rs_close($rs);
487 * Update/create grade item for given scorm
489 * @param object $scorm object with extra cmidnumber
490 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
491 * @return object grade_item
493 function scorm_grade_item_update($scorm, $grades=NULL) {
494 global $CFG;
495 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
496 require_once($CFG->libdir.'/gradelib.php');
499 $params = array('itemname'=>$scorm->name);
500 if (isset($scorm->cmidnumber)) {
501 $params['idnumber'] = $scorm->cmidnumber;
504 if (($scorm->grademethod % 10) == 0) { // GRADESCOES
505 if ($maxgrade = count_records_select('scorm_scoes',"scorm='$scorm->id' AND launch<>'".sql_empty()."'")) {
506 $params['gradetype'] = GRADE_TYPE_VALUE;
507 $params['grademax'] = $maxgrade;
508 $params['grademin'] = 0;
509 } else {
510 $params['gradetype'] = GRADE_TYPE_NONE;
512 } else {
513 $params['gradetype'] = GRADE_TYPE_VALUE;
514 $params['grademax'] = $scorm->maxgrade;
515 $params['grademin'] = 0;
518 if ($grades === 'reset') {
519 $params['reset'] = true;
520 $grades = NULL;
523 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
527 * Delete grade item for given scorm
529 * @param object $scorm object
530 * @return object grade_item
532 function scorm_grade_item_delete($scorm) {
533 global $CFG;
534 require_once($CFG->libdir.'/gradelib.php');
536 return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, NULL, array('deleted'=>1));
539 function scorm_get_view_actions() {
540 return array('pre-view','view','view all','report');
543 function scorm_get_post_actions() {
544 return array();
547 function scorm_option2text($scorm) {
548 global $SCORM_POPUP_OPTIONS;
549 if (isset($scorm->popup)) {
550 if ($scorm->popup == 1) {
551 $optionlist = array();
552 foreach ($SCORM_POPUP_OPTIONS as $name => $option) {
553 if (isset($scorm->$name)) {
554 $optionlist[] = $name.'='.$scorm->$name;
555 } else {
556 $optionlist[] = $name.'=0';
559 $scorm->options = implode(',', $optionlist);
560 } else {
561 $scorm->options = '';
563 } else {
564 $scorm->popup = 0;
565 $scorm->options = '';
567 return $scorm;
571 * Implementation of the function for printing the form elements that control
572 * whether the course reset functionality affects the scorm.
573 * @param $mform form passed by reference
575 function scorm_reset_course_form_definition(&$mform) {
576 $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
577 $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts','scorm'));
581 * Course reset form defaults.
583 function scorm_reset_course_form_defaults($course) {
584 return array('reset_scorm'=>1);
588 * Removes all grades from gradebook
589 * @param int $courseid
590 * @param string optional type
592 function scorm_reset_gradebook($courseid, $type='') {
593 global $CFG;
595 $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
596 FROM {$CFG->prefix}scorm s, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
597 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=$courseid";
599 if ($scorms = get_records_sql($sql)) {
600 foreach ($scorms as $scorm) {
601 scorm_grade_item_update($scorm, 'reset');
607 * Actual implementation of the rest coures functionality, delete all the
608 * scorm attempts for course $data->courseid.
609 * @param $data the data submitted from the reset course.
610 * @return array status array
612 function scorm_reset_userdata($data) {
613 global $CFG;
615 $componentstr = get_string('modulenameplural', 'scorm');
616 $status = array();
618 if (!empty($data->reset_scorm)) {
619 $scormssql = "SELECT s.id
620 FROM {$CFG->prefix}scorm s
621 WHERE s.course={$data->courseid}";
623 delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)");
625 // remove all grades from gradebook
626 if (empty($data->reset_gradebook_grades)) {
627 scorm_reset_gradebook($data->courseid);
630 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'scorm'), 'error'=>false);
633 // no dates to shift here
635 return $status;
639 * Returns all other caps used in module
641 function scorm_get_extra_capabilities() {
642 return array('moodle/site:accessallgroups');