a3d17cd75086047ebf99b1c936074dbe1fa84377
[moodle.git] / mod / scorm / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * @package   mod-scorm
19  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
20  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21  */
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);
48 /**
49  * Return an array of status options
50  *
51  * Optionally with translated strings
52  *
53  * @param   bool    $with_strings   (optional)
54  * @return  array
55  */
56 function scorm_status_options($with_strings = false) {
57     // Id's are important as they are bits
58     $options = array(
59         2 => 'passed',
60         4 => 'completed'
61     );
63     if ($with_strings) {
64         foreach ($options as $key => $value) {
65             $options[$key] = get_string('completionstatus_'.$value, 'scorm');
66         }
67     }
69     return $options;
70 }
73 /**
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.
78  *
79  * @global stdClass
80  * @global object
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
88  */
89 function scorm_add_instance($scorm, $mform=null) {
90     global $CFG, $DB;
92     require_once($CFG->dirroot.'/mod/scorm/locallib.php');
94     if (empty($scorm->timeopen)) {
95         $scorm->timeopen = 0;
96     }
97     if (empty($scorm->timeclose)) {
98         $scorm->timeclose = 0;
99     }
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;
112     }
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;
135             }
136         }
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.
145     } else {
146         return false;
147     }
149     // Save reference.
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);
161     return $record->id;
164 /**
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.
168  *
169  * @global stdClass
170  * @global object
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
177  * @return bool
178  */
179 function scorm_update_instance($scorm, $mform=null) {
180     global $CFG, $DB;
182     require_once($CFG->dirroot.'/mod/scorm/locallib.php');
184     if (empty($scorm->timeopen)) {
185         $scorm->timeopen = 0;
186     }
187     if (empty($scorm->timeclose)) {
188         $scorm->timeclose = 0;
189     }
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;
211             }
212         }
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.
221     } else {
222         return false;
223     }
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;
232     }
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);
248     return true;
251 /**
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.
255  *
256  * @global stdClass
257  * @global object
258  * @param int $id Scorm instance id
259  * @return boolean
260  */
261 function scorm_delete_instance($id) {
262     global $CFG, $DB;
264     if (! $scorm = $DB->get_record('scorm', array('id'=>$id))) {
265         return false;
266     }
268     $result = true;
270     // Delete any dependent records
271     if (! $DB->delete_records('scorm_scoes_track', array('scormid'=>$scorm->id))) {
272         $result = false;
273     }
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))) {
277                 $result = false;
278             }
279         }
280         $DB->delete_records('scorm_scoes', array('scorm'=>$scorm->id));
281     }
282     if (! $DB->delete_records('scorm', array('id'=>$scorm->id))) {
283         $result = false;
284     }
286     /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
287         $result = false;
288     }
289     if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
290         $result = false;
291     }
292     if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
293         $result = false;
294     }
295     if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
296         $result = false;
297     }
298     if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
299         $result = false;
300     }
301     if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
302         $result = false;
303     }
304     if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
305         $result = false;
306     }*/
308     scorm_grade_item_delete($scorm);
310     return $result;
313 /**
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.
317  *
318  * @global stdClass
319  * @param int $course Course id
320  * @param int $user User id
321  * @param int $mod
322  * @param int $scorm The scorm id
323  * @return mixed
324  */
325 function scorm_user_outline($course, $user, $mod, $scorm) {
326     global $CFG;
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;
341         } else {
342             $result->time = $grade->datesubmitted;
343         }
345         return $result;
346     }
347     return null;
350 /**
351  * Print a detailed representation of what a user has done with
352  * a given particular instance of this module, for user activity reports.
353  *
354  * @global stdClass
355  * @global object
356  * @param object $course
357  * @param object $user
358  * @param object $mod
359  * @param object $scorm
360  * @return boolean
361  */
362 function scorm_user_complete($course, $user, $mod, $scorm) {
363     global $CFG, $DB, $OUTPUT;
364     require_once("$CFG->libdir/gradelib.php");
366     $liststyle = 'structlist';
367     $now = time();
368     $firstmodify = $now;
369     $lastmodify = 0;
370     $sometoreport = false;
371     $report = '';
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);
385         }
386     }
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) {
393             unset($orgs);
394             $orgs = array();
395             $org = new stdClass();
396             $org->identifier = '';
397             $orgs[] = $org;
398         }
399         $report .= '<div class="mod-scorm">'."\n";
400         foreach ($orgs as $org) {
401             $conditions = array();
402             $currentorg = '';
403             if (!empty($org->identifier)) {
404                 $report .= '<div class="orgtitle">'.$org->title.'</div>';
405                 $currentorg = $org->identifier;
406                 $conditions['organization'] = $currentorg;
407             }
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);
413                 $level=0;
414                 $sublist=1;
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";
420                             $level--;
421                         } else {
422                             $i = $level;
423                             $closelist = '';
424                             while (($i > 0) && ($parents[$level] != $sco->parent)) {
425                                 $closelist .= "\t\t</ul></li>\n";
426                                 $i--;
427                             }
428                             if (($i == 0) && ($sco->parent != $currentorg)) {
429                                 $report .= "\t\t<li><ul id='$sublist' class='$liststyle'>\n";
430                                 $level++;
431                             } else {
432                                 $report .= $closelist;
433                                 $level = $i;
434                             }
435                             $parents[$level]=$sco->parent;
436                         }
437                     }
438                     $report .= "\t\t<li>";
439                     if (isset($scoes[$pos+1])) {
440                         $nextsco = $scoes[$pos+1];
441                     } else {
442                         $nextsco = false;
443                     }
444                     if (($nextsco !== false) && ($sco->parent != $nextsco->parent) && (($level==0) || (($level>0) && ($nextsco->parent == $sco->identifier)))) {
445                         $sublist++;
446                     } else {
447                         $report .= '<img src="'.$OUTPUT->pix_url('spacer', 'scorm').'" alt="" />';
448                     }
450                     if ($sco->launch) {
451                         $score = '';
452                         $totaltime = '';
453                         if ($usertrack=scorm_get_tracks($sco->id, $user->id)) {
454                             if ($usertrack->status == '') {
455                                 $usertrack->status = 'notattempted';
456                             }
457                             $strstatus = get_string($usertrack->status, 'scorm');
458                             $report .= "<img src='".$OUTPUT->pix_url($usertrack->status, 'scorm')."' alt='$strstatus' title='$strstatus' />";
459                         } else {
460                             if ($sco->scormtype == 'sco') {
461                                 $report .= '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
462                             } else {
463                                 $report .= '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
464                             }
465                         }
466                         $report .= "&nbsp;$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>';
473                                 }
474                             }
475                             $report .= "\t\t\t</ul></li>\n";
476                         }
477                     } else {
478                         $report .= "&nbsp;$sco->title</li>\n";
479                     }
480                 }
481                 for ($i=0; $i<$level; $i++) {
482                     $report .= "\t\t</ul></li>\n";
483                 }
484             }
485             $report .= "\t</ul><br />\n";
486         }
487         $report .= "</div>\n";
488     }
489     if ($sometoreport) {
490         if ($firstmodify < $now) {
491             $timeago = format_time($now - $firstmodify);
492             echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")<br />\n";
493         }
494         if ($lastmodify > 0) {
495             $timeago = format_time($now - $lastmodify);
496             echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")<br />\n";
497         }
498         echo get_string('report', 'scorm').":<br />\n";
499         echo $report;
500     } else {
501         print_string('noactivity', 'scorm');
502     }
504     return true;
507 /**
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 ...
511  *
512  * @global stdClass
513  * @global object
514  * @return boolean
515  */
516 function scorm_cron () {
517     global $CFG, $DB;
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);
526     }
528     $timenow = time();
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);
540         }
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));
547         }
548     }
550     return true;
553 /**
554  * Return grade for given user or all users.
555  *
556  * @global stdClass
557  * @global object
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
561  */
562 function scorm_get_user_grades($scorm, $userid=0) {
563     global $CFG, $DB;
564     require_once($CFG->dirroot.'/mod/scorm/locallib.php');
566     $grades = array();
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);
574             }
575         } else {
576             return false;
577         }
579     } else {
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
582         }
583         $grades[$userid] = new stdClass();
584         $grades[$userid]->id         = $userid;
585         $grades[$userid]->userid     = $userid;
586         $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
587     }
589     return $grades;
592 /**
593  * Update grades in central gradebook
594  *
595  * @category grade
596  * @param object $scorm
597  * @param int $userid specific user only, 0 mean all
598  * @param bool $nullifnone
599  */
600 function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
601     global $CFG;
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);
607         //set complete
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);
614         //set incomplete.
615         scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
616     } else {
617         scorm_grade_item_update($scorm);
618     }
621 /**
622  * Update all grades in gradebook.
623  *
624  * @global object
625  */
626 function scorm_upgrade_grades() {
627     global $DB;
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);
638     if ($rs->valid()) {
639         $pbar = new progress_bar('scormupgradegrades', 500, true);
640         $i=0;
641         foreach ($rs as $scorm) {
642             $i++;
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).");
646         }
647     }
648     $rs->close();
651 /**
652  * Update/create grade item for given scorm
653  *
654  * @category grade
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
660  */
661 function scorm_grade_item_update($scorm, $grades=null) {
662     global $CFG, $DB;
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');
666     }
668     $params = array('itemname'=>$scorm->name);
669     if (isset($scorm->cmidnumber)) {
670         $params['idnumber'] = $scorm->cmidnumber;
671     }
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;
678         } else {
679             $params['gradetype'] = GRADE_TYPE_NONE;
680         }
681     } else {
682         $params['gradetype'] = GRADE_TYPE_VALUE;
683         $params['grademax']  = $scorm->maxgrade;
684         $params['grademin']  = 0;
685     }
687     if ($grades  === 'reset') {
688         $params['reset'] = true;
689         $grades = null;
690     }
692     return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
695 /**
696  * Delete grade item for given scorm
697  *
698  * @category grade
699  * @param object $scorm object
700  * @return object grade_item
701  */
702 function scorm_grade_item_delete($scorm) {
703     global $CFG;
704     require_once($CFG->libdir.'/gradelib.php');
706     return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted'=>1));
709 /**
710  * @return array
711  */
712 function scorm_get_view_actions() {
713     return array('pre-view', 'view', 'view all', 'report');
716 /**
717  * @return array
718  */
719 function scorm_get_post_actions() {
720     return array();
723 /**
724  * @param object $scorm
725  * @return object $scorm
726  */
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;
736                 } else {
737                     $optionlist[] = $name.'=0';
738                 }
739             }
740             $scorm->options = implode(',', $optionlist);
741         } else {
742             $scorm->options = '';
743         }
744     } else {
745         $scorm->popup = 0;
746         $scorm->options = '';
747     }
748     return $scorm;
751 /**
752  * Implementation of the function for printing the form elements that control
753  * whether the course reset functionality affects the scorm.
754  *
755  * @param object $mform form passed by reference
756  */
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'));
762 /**
763  * Course reset form defaults.
764  *
765  * @return array
766  */
767 function scorm_reset_course_form_defaults($course) {
768     return array('reset_scorm'=>1);
771 /**
772  * Removes all grades from gradebook
773  *
774  * @global stdClass
775  * @global object
776  * @param int $courseid
777  * @param string optional type
778  */
779 function scorm_reset_gradebook($courseid, $type='') {
780     global $CFG, $DB;
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');
789         }
790     }
793 /**
794  * Actual implementation of the reset course functionality, delete all the
795  * scorm attempts for course $data->courseid.
796  *
797  * @global stdClass
798  * @global object
799  * @param object $data the data submitted from the reset course.
800  * @return array status array
801  */
802 function scorm_reset_userdata($data) {
803     global $CFG, $DB;
805     $componentstr = get_string('modulenameplural', 'scorm');
806     $status = array();
808     if (!empty($data->reset_scorm)) {
809         $scormssql = "SELECT s.id
810                          FROM {scorm} s
811                         WHERE s.course=?";
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);
818         }
820         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'scorm'), 'error'=>false);
821     }
823     // no dates to shift here
825     return $status;
828 /**
829  * Returns all other caps used in module
830  *
831  * @return array
832  */
833 function scorm_get_extra_capabilities() {
834     return array('moodle/site:accessallgroups');
837 /**
838  * Lists all file areas current user may browse
839  *
840  * @param object $course
841  * @param object $cm
842  * @param object $context
843  * @return array
844  */
845 function scorm_get_file_areas($course, $cm, $context) {
846     $areas = array();
847     $areas['content'] = get_string('areacontent', 'scorm');
848     $areas['package'] = get_string('areapackage', 'scorm');
849     return $areas;
852 /**
853  * File browsing support for SCORM file areas
854  *
855  * @package  mod_scorm
856  * @category files
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
867  */
868 function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
869     global $CFG;
871     if (!has_capability('moodle/course:managefiles', $context)) {
872         return null;
873     }
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);
888             } else {
889                 // not found
890                 return null;
891             }
892         }
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);
904             } else {
905                 // not found
906                 return null;
907             }
908         }
909         return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
910     }
912     // scorm_intro handled in file_browser
914     return false;
917 /**
918  * Serves scorm content, introduction images and packages. Implements needed access control ;-)
919  *
920  * @package  mod_scorm
921  * @category files
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
930  */
931 function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
932     global $CFG;
934     if ($context->contextlevel != CONTEXT_MODULE) {
935         return false;
936     }
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)) {
950             return false;
951         }
952         $relativepath = implode('/', $args);
953         $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
954         $lifetime = 0; // no caching here
956     } else {
957         return false;
958     }
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.
963             send_header_404();
964             die;
965         }
966         return false;
967     }
969     // finally send the file
970     send_stored_file($file, $lifetime, 0, false, $options);
973 /**
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
984  */
985 function scorm_supports($feature) {
986     switch($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;
999     }
1002 /**
1003  * Get the filename for a temp log file
1004  *
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
1008  */
1009 function scorm_debug_log_filename($type, $scoid) {
1010     global $CFG, $USER;
1012     $logpath = $CFG->tempdir.'/scormlogs';
1013     $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1014     return $logfile;
1017 /**
1018  * writes log output to a temp log file
1019  *
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.
1023  */
1024 function scorm_debug_log_write($type, $text, $scoid) {
1025     global $CFG;
1027     $debugenablelog = get_config('scorm', 'allowapidebug');
1028     if (!$debugenablelog || empty($text)) {
1029         return;
1030     }
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);
1035     }
1038 /**
1039  * Remove debug log file
1040  *
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
1044  */
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)) {
1050         return false;
1051     }
1053     return @unlink($logfile);
1056 /**
1057  * writes overview info for course_overview block - displays upcoming scorm objects that have a due date
1058  *
1059  * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1060  * @param array $htmlarray
1061  * @return mixed
1062  */
1063 function scorm_print_overview($courses, &$htmlarray) {
1064     global $USER, $CFG;
1066     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1067         return array();
1068     }
1070     if (!$scorms = get_all_instances_in_courses('scorm', $courses)) {
1071         return;
1072     }
1074     $strscorm   = get_string('modulename', 'scorm');
1075     $strduedate = get_string('duedate', 'scorm');
1077     foreach ($scorms as $scorm) {
1078         $time = time();
1079         $showattemptstatus = false;
1080         if ($scorm->timeopen) {
1081             $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose);
1082         }
1083         if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL ||
1084                 $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) {
1085             $showattemptstatus = true;
1086         }
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>';
1095             }
1096             if ($showattemptstatus) {
1097                 require_once($CFG->dirroot.'/mod/scorm/locallib.php');
1098                 $str .= '<div class="details">'.scorm_get_attempt_status($USER, $scorm).'</div>';
1099             }
1100             $str .= '</div>';
1101             if (empty($htmlarray[$scorm->course]['scorm'])) {
1102                 $htmlarray[$scorm->course]['scorm'] = $str;
1103             } else {
1104                 $htmlarray[$scorm->course]['scorm'] .= $str;
1105             }
1106         }
1107     }
1110 /**
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
1115  */
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;
1121 /**
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.
1126  */
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') {
1131             return SCORM_12;
1132         }
1133         if (!empty($version)) {
1134             return false;
1135         }
1136     }
1137     if (empty($version) || $version == SCORM_13) {
1138         if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1139             return SCORM_13;
1140         }
1141         if (!empty($version)) {
1142             return false;
1143         }
1144     }
1145     if (empty($version) || $version == SCORM_AICC) {
1146         if (strpos($scormversion, 'aicc')) {
1147             return SCORM_AICC;
1148         }
1149         if (!empty($version)) {
1150             return false;
1151         }
1152     }
1153     return false;
1156 /**
1157  * Obtains the automatic completion state for this scorm based on any conditions
1158  * in scorm settings.
1159  *
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)
1166  */
1167 function scorm_get_completion_state($course, $cm, $userid, $type) {
1168     global $DB;
1170     $result = $type;
1172     // Get scorm
1173     if (!$scorm = $DB->get_record('scorm', array('id' => $cm->instance))) {
1174         print_error('cannotfindscorm');
1175     }
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(
1182             "
1183             SELECT
1184                 id,
1185                 element,
1186                 value
1187             FROM
1188                 {scorm_scoes_track}
1189             WHERE
1190                 scormid = ?
1191             AND userid = ?
1192             AND element IN
1193             (
1194                 'cmi.core.lesson_status',
1195                 'cmi.completion_status',
1196                 'cmi.success_status',
1197                 'cmi.core.score.raw',
1198                 'cmi.score.raw'
1199             )
1200             ",
1201             array($scorm->id, $userid)
1202         );
1204         if (!$tracks) {
1205             return completion_info::aggregate_completion_states($type, $result, false);
1206         }
1207     }
1209     // Check for status
1210     if ($scorm->completionstatusrequired !== null) {
1212         // Get status
1213         $statuses = array_flip(scorm_status_options());
1214         $nstatus = 0;
1216         foreach ($tracks as $track) {
1217             if (!in_array($track->element, array('cmi.core.lesson_status', 'cmi.completion_status', 'cmi.success_status'))) {
1218                 continue;
1219             }
1221             if (array_key_exists($track->value, $statuses)) {
1222                 $nstatus |= $statuses[$track->value];
1223             }
1224         }
1226         if ($scorm->completionstatusrequired & $nstatus) {
1227             return completion_info::aggregate_completion_states($type, $result, true);
1228         } else {
1229             return completion_info::aggregate_completion_states($type, $result, false);
1230         }
1232     }
1234     // Check for score
1235     if ($scorm->completionscorerequired !== null) {
1236         $maxscore = -1;
1238         foreach ($tracks as $track) {
1239             if (!in_array($track->element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
1240                 continue;
1241             }
1243             if (strlen($track->value) && floatval($track->value) >= $maxscore) {
1244                 $maxscore = floatval($track->value);
1245             }
1246         }
1248         if ($scorm->completionscorerequired <= $maxscore) {
1249             return completion_info::aggregate_completion_states($type, $result, true);
1250         } else {
1251             return completion_info::aggregate_completion_states($type, $result, false);
1252         }
1253     }
1255     return $result;
1258 /**
1259  * Register the ability to handle drag and drop file uploads
1260  * @return array containing details of the files / types the mod can handle
1261  */
1262 function scorm_dndupload_register() {
1263     return array('files' => array(
1264         array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1265     ));
1268 /**
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
1272  */
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)) {
1284         return false;
1285     }
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();
1294     $scorm->intro = '';
1295     $scorm->width = $scorm->framewidth;
1296     $scorm->height = $scorm->frameheight;
1298     return scorm_add_instance($scorm, null);
1301 /**
1302  * Sets activity completion state
1303  *
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
1308  */
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()) {
1316         return;
1317     }
1319     $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1320     if (empty($cm) || !$completion->is_enabled($cm)) {
1321             return;
1322     }
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);
1327         }
1328     } else {
1329         $completion->update_state($cm, $completionstate, $userid);
1330     }
1333 /**
1334  * Check that a Zip file contains a valid SCORM package
1335  *
1336  * @param $file stored_file a Zip file.
1337  * @return array empty if no issue is found. Array of error message otherwise
1338  */
1339 function scorm_validate_package($file) {
1340     $packer = get_file_packer('application/zip');
1341     $errors = array();
1342     if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1343         $file->import_external_file_contents();
1344     }
1345     $filelist = $file->list_files($packer);
1347     if (!is_array($filelist)) {
1348         $errors['packagefile'] = get_string('badarchive', 'scorm');
1349     } else {
1350         $aiccfound = false;
1351         $badmanifestpresent = false;
1352         foreach ($filelist as $info) {
1353             if ($info->pathname == 'imsmanifest.xml') {
1354                 return array();
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;
1358             }
1359             if (preg_match('/\.cst$/', $info->pathname)) {
1360                 return array();
1361             }
1362         }
1363         if (!$aiccfound) {
1364             if ($badmanifestpresent) {
1365                 $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1366             } else {
1367                 $errors['packagefile'] = get_string('nomanifest', 'scorm');
1368             }
1369         }
1370     }
1371     return $errors;
1374 /**
1375  * Check and set the correct mode and attempt when entering a SCORM package.
1376  *
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.
1382  */
1383 function scorm_check_mode($scorm, $newattempt, &$attempt, $userid, &$mode) {
1384     global $DB;
1385     if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1386         $attempt++;
1387         $mode = 'normal';
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')) {
1396                 $mode = 'review';
1397             } else { // Found an incomplete sco so exit and use normal mode.
1398                 $mode = 'normal';
1399                 break;
1400             }
1401         }
1402         $tracks->close();
1403     } else if (($mode == 'browse') && ($scorm->hidebrowse == 1)) { // Prevent Browse mode if hidebrowse is set.
1404         $mode = 'normal';
1405     }