b1cde8224344c8ec357a493ed793c32a21c2fc0a
[moodle.git] / mod / scorm / locallib.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 require_once("$CFG->dirroot/mod/scorm/lib.php");
18 require_once("$CFG->libdir/filelib.php");
20 /// Constants and settings for module scorm
21 define('SCORM_UPDATE_NEVER', '0');
22 define('SCORM_UPDATE_EVERYDAY', '2');
23 define('SCORM_UPDATE_EVERYTIME', '3');
25 define('SCORM_SKIPVIEW_NEVER', '0');
26 define('SCORM_SKIPVIEW_FIRST', '1');
27 define('SCORM_SKIPVIEW_ALWAYS', '2');
29 define('SCO_ALL', 0);
30 define('SCO_DATA', 1);
31 define('SCO_ONLY', 2);
33 define('GRADESCOES', '0');
34 define('GRADEHIGHEST', '1');
35 define('GRADEAVERAGE', '2');
36 define('GRADESUM', '3');
38 define('HIGHESTATTEMPT', '0');
39 define('AVERAGEATTEMPT', '1');
40 define('FIRSTATTEMPT', '2');
41 define('LASTATTEMPT', '3');
43 define('TOCJSLINK', 1);
44 define('TOCFULLURL', 2);
46 /// Local Library of functions for module scorm
48 /**
49  * @package   mod-scorm
50  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
51  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52  */
53 class scorm_package_file_info extends file_info_stored {
54     public function get_parent() {
55         if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
56             return $this->browser->get_file_info($this->context);
57         }
58         return parent::get_parent();
59     }
60     public function get_visible_name() {
61         if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
62             return $this->topvisiblename;
63         }
64         return parent::get_visible_name();
65     }
66 }
68 /**
69  * Returns an array of the popup options for SCORM and each options default value
70  *
71  * @return array an array of popup options as the key and their defaults as the value
72  */
73 function scorm_get_popup_options_array() {
74     $cfgscorm = get_config('scorm');
76     return array('scrollbars'=> isset($cfgscorm->scrollbars) ? $cfgscorm->scrollbars : 0,
77                  'directories'=> isset($cfgscorm->directories) ? $cfgscorm->directories : 0,
78                  'location'=> isset($cfgscorm->location) ? $cfgscorm->location : 0,
79                  'menubar'=> isset($cfgscorm->menubar) ? $cfgscorm->menubar : 0,
80                  'toolbar'=> isset($cfgscorm->toolbar) ? $cfgscorm->toolbar : 0,
81                  'status'=> isset($cfgscorm->status) ? $cfgscorm->status : 0);
82 }
84 /**
85  * Returns an array of the array of what grade options
86  *
87  * @return array an array of what grade options
88  */
89 function scorm_get_grade_method_array() {
90     return array (GRADESCOES => get_string('gradescoes', 'scorm'),
91                   GRADEHIGHEST => get_string('gradehighest', 'scorm'),
92                   GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
93                   GRADESUM => get_string('gradesum', 'scorm'));
94 }
96 /**
97  * Returns an array of the array of what grade options
98  *
99  * @return array an array of what grade options
100  */
101 function scorm_get_what_grade_array() {
102     return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
103                   AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
104                   FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
105                   LASTATTEMPT => get_string('lastattempt', 'scorm'));
108 /**
109  * Returns an array of the array of skip view options
110  *
111  * @return array an array of skip view options
112  */
113 function scorm_get_skip_view_array() {
114     return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
115                  SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
116                  SCORM_SKIPVIEW_ALWAYS => get_string('always'));
119 /**
120  * Returns an array of the array of hide table of contents options
121  *
122  * @return array an array of hide table of contents options
123  */
124 function scorm_get_hidetoc_array() {
125      return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
126                   SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
127                   SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
128                   SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
131 /**
132  * Returns an array of the array of update frequency options
133  *
134  * @return array an array of update frequency options
135  */
136 function scorm_get_updatefreq_array() {
137     return array(SCORM_UPDATE_NEVER => get_string('never'),
138                  SCORM_UPDATE_EVERYDAY => get_string('everyday', 'scorm'),
139                  SCORM_UPDATE_EVERYTIME => get_string('everytime', 'scorm'));
142 /**
143  * Returns an array of the array of popup display options
144  *
145  * @return array an array of popup display options
146  */
147 function scorm_get_popup_display_array() {
148     return array(0 => get_string('currentwindow', 'scorm'),
149                  1 => get_string('popup', 'scorm'));
152 /**
153  * Returns an array of the array of attempt options
154  *
155  * @return array an array of attempt options
156  */
157 function scorm_get_attempts_array() {
158     $attempts = array(0 => get_string('nolimit', 'scorm'),
159                       1 => get_string('attempt1', 'scorm'));
161     for ($i=2; $i<=6; $i++) {
162         $attempts[$i] = get_string('attemptsx', 'scorm', $i);
163     }
165     return $attempts;
168 /**
169  * Returns an array of the attempt status options
170  *
171  * @return array an array of attempt status options
172  */
173 function scorm_get_attemptstatus_array() {
174     return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO => get_string('no'),
175                  SCORM_DISPLAY_ATTEMPTSTATUS_ALL => get_string('attemptstatusall', 'scorm'),
176                  SCORM_DISPLAY_ATTEMPTSTATUS_MY => get_string('attemptstatusmy', 'scorm'),
177                  SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY => get_string('attemptstatusentry', 'scorm'));
180 /**
181  * Extracts scrom package, sets up all variables.
182  * Called whenever scorm changes
183  * @param object $scorm instance - fields are updated and changes saved into database
184  * @param bool $full force full update if true
185  * @return void
186  */
187 function scorm_parse($scorm, $full) {
188     global $CFG, $DB;
189     $cfg_scorm = get_config('scorm');
191     if (!isset($scorm->cmid)) {
192         $cm = get_coursemodule_from_instance('scorm', $scorm->id);
193         $scorm->cmid = $cm->id;
194     }
195     $context = context_module::instance($scorm->cmid);
196     $newhash = $scorm->sha1hash;
198     if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
200         $fs = get_file_storage();
201         $packagefile = false;
203         if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
204             if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
205                 if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
206                     $packagefile->import_external_file_contents();
207                 }
208                 $newhash = $packagefile->get_contenthash();
209             } else {
210                 $newhash = null;
211             }
212         } else {
213             if (!$cfg_scorm->allowtypelocalsync) {
214                 // sorry - localsync disabled
215                 return;
216             }
217             if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
218                 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
219                 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
220                 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
221                     $newhash = sha1($scorm->reference);
222                 } else {
223                     $newhash = null;
224                 }
225             }
226         }
228         if ($packagefile) {
229             if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
230                 if (strpos($scorm->version, 'SCORM') !== false) {
231                     if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
232                         // no need to update
233                         return;
234                     }
235                 } else if (strpos($scorm->version, 'AICC') !== false) {
236                     // TODO: add more sanity checks - something really exists in scorm_content area
237                     return;
238                 }
239             }
241             // now extract files
242             $fs->delete_area_files($context->id, 'mod_scorm', 'content');
244             $packer = get_file_packer('application/zip');
245             $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
247         } else if (!$full) {
248             return;
249         }
251         if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
252             require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
253             // SCORM
254             if (!scorm_parse_scorm($scorm, $manifest)) {
255                 $scorm->version = 'ERROR';
256             }
257         } else {
258             require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
259             // AICC
260             if (!scorm_parse_aicc($scorm)) {
261                 $scorm->version = 'ERROR';
262             }
263             $scorm->version = 'AICC';
264         }
266     } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
267         require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
268         // SCORM only, AICC can not be external
269         if (!scorm_parse_scorm($scorm, $scorm->reference)) {
270             $scorm->version = 'ERROR';
271         }
272         $newhash = sha1($scorm->reference);
274     } else if ($scorm->scormtype === SCORM_TYPE_AICCURL  and $cfg_scorm->allowtypeexternalaicc) {
275         require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
276         // AICC
277         if (!scorm_parse_aicc($scorm)) {
278             $scorm->version = 'ERROR';
279         }
280         $scorm->version = 'AICC';
281     } else {
282         // sorry, disabled type
283         return;
284     }
286     $scorm->revision++;
287     $scorm->sha1hash = $newhash;
288     $DB->update_record('scorm', $scorm);
292 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
293     if (!empty($haystacks)) {
294         foreach ($haystacks as $key => $element) {
295             if ($strict) {
296                 if ($element->{$item} === $needle) {
297                     return $key;
298                 }
299             } else {
300                 if ($element->{$item} == $needle) {
301                     return $key;
302                 }
303             }
304         }
305     }
306     return false;
309 function scorm_repeater($what, $times) {
310     if ($times <= 0) {
311         return null;
312     }
313     $return = '';
314     for ($i=0; $i<$times; $i++) {
315         $return .= $what;
316     }
317     return $return;
320 function scorm_external_link($link) {
321     // check if a link is external
322     $result = false;
323     $link = strtolower($link);
324     if (substr($link, 0, 7) == 'http://') {
325         $result = true;
326     } else if (substr($link, 0, 8) == 'https://') {
327         $result = true;
328     } else if (substr($link, 0, 4) == 'www.') {
329         $result = true;
330     }
331     return $result;
334 /**
335  * Returns an object containing all datas relative to the given sco ID
336  *
337  * @param integer $id The sco ID
338  * @return mixed (false if sco id does not exists)
339  */
340 function scorm_get_sco($id, $what=SCO_ALL) {
341     global $DB;
343     if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
344         $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
345         if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
346             foreach ($scodatas as $scodata) {
347                 $sco->{$scodata->name} = $scodata->value;
348             }
349         } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
350             $sco->parameters = '';
351         }
352         return $sco;
353     } else {
354         return false;
355     }
358 /**
359  * Returns an object (array) containing all the scoes data related to the given sco ID
360  *
361  * @param integer $id The sco ID
362  * @param integer $organisation an organisation ID - defaults to false if not required
363  * @return mixed (false if there are no scoes or an array)
364  */
365 function scorm_get_scoes($id, $organisation=false) {
366     global $DB;
368     $queryarray = array('scorm'=>$id);
369     if (!empty($organisation)) {
370         $queryarray['organization'] = $organisation;
371     }
372     if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
373         // Drop keys so that it is a simple array as expected.
374         $scoes = array_values($scoes);
375         foreach ($scoes as $sco) {
376             if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
377                 foreach ($scodatas as $scodata) {
378                     $sco->{$scodata->name} = $scodata->value;
379                 }
380             }
381         }
382         return $scoes;
383     } else {
384         return false;
385     }
388 function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
389     global $DB, $CFG;
391     $id = null;
393     if ($forcecompleted) {
394         //TODO - this could be broadened to encompass SCORM 2004 in future
395         if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
396             if ($track = $DB->get_record_select('scorm_scoes_track', 'userid=? AND scormid=? AND scoid=? AND attempt=? AND element=\'cmi.core.score.raw\'', array($userid, $scormid, $scoid, $attempt))) {
397                 $value = 'completed';
398             }
399         }
400         if ($element == 'cmi.core.score.raw') {
401             if ($tracktest = $DB->get_record_select('scorm_scoes_track', 'userid=? AND scormid=? AND scoid=? AND attempt=? AND element=\'cmi.core.lesson_status\'', array($userid, $scormid, $scoid, $attempt))) {
402                 if ($tracktest->value == "incomplete") {
403                     $tracktest->value = "completed";
404                     $DB->update_record('scorm_scoes_track', $tracktest);
405                 }
406             }
407         }
408         if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
409             if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
410                 $objectiveprogressstatus = true;
411                 $objectivesatisfiedstatus = false;
412                 if ($value == 'passed') {
413                     $objectivesatisfiedstatus = true;
414                 }
416                 if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
417                                                                         'scormid' => $scormid,
418                                                                         'scoid' => $scoid,
419                                                                         'attempt' => $attempt,
420                                                                         'element' => 'objectiveprogressstatus'))) {
421                     $track->value = $objectiveprogressstatus;
422                     $track->timemodified = time();
423                     $DB->update_record('scorm_scoes_track', $track);
424                     $id = $track->id;
425                 } else {
426                     $track = new stdClass();
427                     $track->userid = $userid;
428                     $track->scormid = $scormid;
429                     $track->scoid = $scoid;
430                     $track->attempt = $attempt;
431                     $track->element = 'objectiveprogressstatus';
432                     $track->value = $objectiveprogressstatus;
433                     $track->timemodified = time();
434                     $id = $DB->insert_record('scorm_scoes_track', $track);
435                 }
436                 if ($objectivesatisfiedstatus) {
437                     if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
438                                                                             'scormid' => $scormid,
439                                                                             'scoid' => $scoid,
440                                                                             'attempt' => $attempt,
441                                                                             'element' => 'objectivesatisfiedstatus'))) {
442                         $track->value = $objectivesatisfiedstatus;
443                         $track->timemodified = time();
444                         $DB->update_record('scorm_scoes_track', $track);
445                         $id = $track->id;
446                     } else {
447                         $track = new stdClass();
448                         $track->userid = $userid;
449                         $track->scormid = $scormid;
450                         $track->scoid = $scoid;
451                         $track->attempt = $attempt;
452                         $track->element = 'objectivesatisfiedstatus';
453                         $track->value = $objectivesatisfiedstatus;
454                         $track->timemodified = time();
455                         $id = $DB->insert_record('scorm_scoes_track', $track);
456                         ob_start();
457                         $filepath = $CFG->dataroot."\\temp\\tempfile.txt";
458                         $fh = fopen($filepath, "a+");
459                         var_dump($track);
460                         $string = ob_get_clean();
461                         fwrite($fh, $string);
462                         fclose($fh);
463                     }
464                 }
465             }
466         }
468     }
470     if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
471                                                             'scormid' => $scormid,
472                                                             'scoid' => $scoid,
473                                                             'attempt' => $attempt,
474                                                             'element' => $element))) {
475         if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
476             $track->value = $value;
477             $track->timemodified = time();
478             $DB->update_record('scorm_scoes_track', $track);
479             $id = $track->id;
480         }
481     } else {
482         $track = new stdClass();
483         $track->userid = $userid;
484         $track->scormid = $scormid;
485         $track->scoid = $scoid;
486         $track->attempt = $attempt;
487         $track->element = $element;
488         $track->value = $value;
489         $track->timemodified = time();
490         $id = $DB->insert_record('scorm_scoes_track', $track);
491     }
493     if (strstr($element, '.score.raw') ||
494         (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
495          && in_array($track->value, array('completed', 'passed')))) {
496         $scorm = $DB->get_record('scorm', array('id' => $scormid));
497         include_once($CFG->dirroot.'/mod/scorm/lib.php');
498         scorm_update_grades($scorm, $userid);
499     }
501     return $id;
504 /**
505  * simple quick function to return true/false if this user has tracks in this scorm
506  *
507  * @param integer $scormid The scorm ID
508  * @param integer $userid the users id
509  * @return boolean (false if there are no tracks)
510  */
511 function scorm_has_tracks($scormid, $userid) {
512     global $DB;
513     return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
516 function scorm_get_tracks($scoid, $userid, $attempt='') {
517     // Gets all tracks of specified sco and user.
518     global $DB;
520     if (empty($attempt)) {
521         if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
522             $attempt = scorm_get_last_attempt($scormid, $userid);
523         } else {
524             $attempt = 1;
525         }
526     }
527     if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid,
528                                                               'attempt'=>$attempt), 'element ASC')) {
529         $usertrack = scorm_format_interactions($tracks);
530         $usertrack->userid = $userid;
531         $usertrack->scoid = $scoid;
533         return $usertrack;
534     } else {
535         return false;
536     }
538 /**
539  * helper function to return a formatted list of interactions for reports.
540  *
541  * @param array $trackdata the records from scorm_scoes_track table
542  * @return object formatted list of interactions
543  */
544 function scorm_format_interactions($trackdata) {
545     $usertrack = new stdClass();
547     // Defined in order to unify scorm1.2 and scorm2004.
548     $usertrack->score_raw = '';
549     $usertrack->status = '';
550     $usertrack->total_time = '00:00:00';
551     $usertrack->session_time = '00:00:00';
552     $usertrack->timemodified = 0;
554     foreach ($trackdata as $track) {
555         $element = $track->element;
556         $usertrack->{$element} = $track->value;
557         switch ($element) {
558             case 'cmi.core.lesson_status':
559             case 'cmi.completion_status':
560                 if ($track->value == 'not attempted') {
561                     $track->value = 'notattempted';
562                 }
563                 $usertrack->status = $track->value;
564                 break;
565             case 'cmi.core.score.raw':
566             case 'cmi.score.raw':
567                 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
568                 break;
569             case 'cmi.core.session_time':
570             case 'cmi.session_time':
571                 $usertrack->session_time = $track->value;
572                 break;
573             case 'cmi.core.total_time':
574             case 'cmi.total_time':
575                 $usertrack->total_time = $track->value;
576                 break;
577         }
578         if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
579             $usertrack->timemodified = $track->timemodified;
580         }
581     }
583     return $usertrack;
585 /* Find the start and finsh time for a a given SCO attempt
586  *
587  * @param int $scormid SCORM Id
588  * @param int $scoid SCO Id
589  * @param int $userid User Id
590  * @param int $attemt Attempt Id
591  *
592  * @return object start and finsh time EPOC secods
593  *
594  */
595 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
596     global $DB;
598     $timedata = new stdClass();
599     $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
600     $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
601     if ($tracks) {
602         $tracks = array_values($tracks);
603     }
605     if ($tracks) {
606         $timedata->start = $tracks[0]->timemodified;
607     } else {
608         $timedata->start = false;
609     }
610     if ($tracks && $track = array_pop($tracks)) {
611         $timedata->finish = $track->timemodified;
612     } else {
613         $timedata->finish = $timedata->start;
614     }
615     return $timedata;
618 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
619     global $DB;
620     $attemptscore = new stdClass();
621     $attemptscore->scoes = 0;
622     $attemptscore->values = 0;
623     $attemptscore->max = 0;
624     $attemptscore->sum = 0;
625     $attemptscore->lastmodify = 0;
627     if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
628         return null;
629     }
631     foreach ($scoes as $sco) {
632         if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
633             if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
634                 $attemptscore->scoes++;
635             }
636             if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
637                 $attemptscore->values++;
638                 $attemptscore->sum += $userdata->score_raw;
639                 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
640                 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
641                     $attemptscore->lastmodify = $userdata->timemodified;
642                 } else {
643                     $attemptscore->lastmodify = 0;
644                 }
645             }
646         }
647     }
648     switch ($scorm->grademethod) {
649         case GRADEHIGHEST:
650             $score = (float) $attemptscore->max;
651         break;
652         case GRADEAVERAGE:
653             if ($attemptscore->values > 0) {
654                 $score = $attemptscore->sum/$attemptscore->values;
655             } else {
656                 $score = 0;
657             }
658         break;
659         case GRADESUM:
660             $score = $attemptscore->sum;
661         break;
662         case GRADESCOES:
663             $score = $attemptscore->scoes;
664         break;
665         default:
666             $score = $attemptscore->max;   // Remote Learner GRADEHIGHEST is default
667     }
669     return $score;
672 function scorm_grade_user($scorm, $userid) {
674     // ensure we dont grade user beyond $scorm->maxattempt settings
675     $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
676     if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
677         $lastattempt = $scorm->maxattempt;
678     }
680     switch ($scorm->whatgrade) {
681         case FIRSTATTEMPT:
682             return scorm_grade_user_attempt($scorm, $userid, 1);
683         break;
684         case LASTATTEMPT:
685             return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
686         break;
687         case HIGHESTATTEMPT:
688             $maxscore = 0;
689             for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
690                 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
691                 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
692             }
693             return $maxscore;
695         break;
696         case AVERAGEATTEMPT:
697             $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
698             if (empty($attemptcount)) {
699                 return 0;
700             } else {
701                 $attemptcount = count($attemptcount);
702             }
703             $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
704             $sumscore = 0;
705             for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
706                 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
707                 $sumscore += $attemptscore;
708             }
710             return round($sumscore / $attemptcount);
711         break;
712     }
715 function scorm_count_launchable($scormid, $organization='') {
716     global $DB;
718     $sqlorganization = '';
719     $params = array($scormid);
720     if (!empty($organization)) {
721         $sqlorganization = " AND organization=?";
722         $params[] = $organization;
723     }
724     return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
727 /**
728  * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
729  *
730  * @param int $scormid the id of the scorm.
731  * @param int $userid the id of the user.
732  *
733  * @return int The attempt number to use.
734  */
735 function scorm_get_last_attempt($scormid, $userid) {
736     global $DB;
738     /// Find the last attempt number for the given user id and scorm id
739     $sql = "SELECT MAX(attempt)
740               FROM {scorm_scoes_track}
741              WHERE userid = ? AND scormid = ?";
742     $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
743     if (empty($lastattempt)) {
744         return '1';
745     } else {
746         return $lastattempt;
747     }
750 /**
751  * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
752  *
753  * @param int $scormid the id of the scorm.
754  * @param int $userid the id of the user.
755  *
756  * @return int The attempt number to use.
757  */
758 function scorm_get_last_completed_attempt($scormid, $userid) {
759     global $DB;
761     /// Find the last completed attempt number for the given user id and scorm id
762     $sql = "SELECT MAX(attempt)
763               FROM {scorm_scoes_track}
764              WHERE userid = ? AND scormid = ?
765                AND (value='completed' OR value='passed')";
766     $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
767     if (empty($lastattempt)) {
768         return '1';
769     } else {
770         return $lastattempt;
771     }
774 /**
775  * Returns the full list of attempts a user has made.
776  *
777  * @param int $scormid the id of the scorm.
778  * @param int $userid the id of the user.
779  *
780  * @return array array of attemptids
781  */
782 function scorm_get_all_attempts($scormid, $userid) {
783     global $DB;
784     $attemptids = array();
785     $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
786     $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
787     foreach ($attempts as $attempt) {
788         $attemptids[] = $attempt->attempt;
789     }
790     return $attemptids;
793 function scorm_view_display ($user, $scorm, $action, $cm) {
794     global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
796     if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
797         scorm_parse($scorm, false);
798     }
800     $organization = optional_param('organization', '', PARAM_INT);
802     if ($scorm->displaycoursestructure == 1) {
803         echo $OUTPUT->box_start('generalbox boxaligncenter toc');
804         ?>
805         <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
806         <?php
807     }
808     if (empty($organization)) {
809         $organization = $scorm->launch;
810     }
811     if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
812                                          $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
813                                          $DB->sql_isempty('scorm_scoes', 'organization', false, false),
814                                          array($scorm->id), 'sortorder, id', 'id,title')) {
815         if (count($orgs) > 1) {
816             $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
817             $select->label = get_string('organizations', 'scorm');
818             $select->class = 'scorm-center';
819             echo $OUTPUT->render($select);
820         }
821     }
822     $orgidentifier = '';
823     if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
824         if (($sco->organization == '') && ($sco->launch == '')) {
825             $orgidentifier = $sco->identifier;
826         } else {
827             $orgidentifier = $sco->organization;
828         }
829     }
831     $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR));   // Just to be safe
832     if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
833         $scorm->version = 'scorm_12';
834     }
835     require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
837     $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
838     $incomplete = $result->incomplete;
840     // do we want the TOC to be displayed?
841     if ($scorm->displaycoursestructure == 1) {
842         echo $result->toc;
843         echo $OUTPUT->box_end();
844     }
846     // is this the first attempt ?
847     $attemptcount = scorm_get_attempt_count($user->id, $scorm);
849     // do not give the player launch FORM if the SCORM object is locked after the final attempt
850     if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
851         ?>
852             <div class="scorm-center">
853                <form id="scormviewform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
854         <?php
855         if ($scorm->hidebrowse == 0) {
856             print_string('mode', 'scorm');
857             echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
858             echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
859         } else {
860             echo '<input type="hidden" name="mode" value="normal" />'."\n";
861         }
862         if ($scorm->forcenewattempt == 1) {
863             if ($incomplete === false) {
864                 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
865             }
866         } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
867             ?>
868                       <br />
869                       <input type="checkbox" id="a" name="newattempt" />
870                       <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
871             <?php
872         }
873         if (!empty($scorm->popup)) {
874             echo '<input type="hidden" name="display" value="popup" />'."\n";
875         }
876         ?>
877               <br />
878               <input type="hidden" name="scoid"/>
879               <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
880               <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
881               <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
882               </form>
883           </div>
884         <?php
885     }
888 function scorm_simple_play($scorm, $user, $context, $cmid) {
889     global $DB;
891     $result = false;
893     if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
894         return $result;
895     }
897     if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
898         scorm_parse($scorm, false);
899     }
900     $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
901         $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
903     if ($scoes) {
904         $orgidentifier = '';
905         if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
906             if (($sco->organization == '') && ($sco->launch == '')) {
907                 $orgidentifier = $sco->identifier;
908             } else {
909                 $orgidentifier = $sco->organization;
910             }
911         }
912         if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
913             $sco = current($scoes);
914             $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
915                                                                 'currentorg'=>$orgidentifier,
916                                                                 'scoid'=>$sco->id));
917             if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
918                 if (!empty($scorm->forcenewattempt)) {
919                     $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
920                     if ($result->incomplete === false) {
921                         $url->param('newattempt','on');
922                     }
923                 }
924                 redirect($url);
925             }
926         }
927     }
928     return $result;
931 function scorm_get_count_users($scormid, $groupingid=null) {
932     global $CFG, $DB;
934     if (!empty($groupingid)) {
935         $sql = "SELECT COUNT(DISTINCT st.userid)
936                 FROM {scorm_scoes_track} st
937                     INNER JOIN {groups_members} gm ON st.userid = gm.userid
938                     INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
939                 WHERE st.scormid = ? AND gg.groupingid = ?
940                 ";
941         $params = array($scormid, $groupingid);
942     } else {
943         $sql = "SELECT COUNT(DISTINCT st.userid)
944                 FROM {scorm_scoes_track} st
945                 WHERE st.scormid = ?
946                 ";
947         $params = array($scormid);
948     }
950     return ($DB->count_records_sql($sql, $params));
953 /**
954  * Build up the JavaScript representation of an array element
955  *
956  * @param string $sversion SCORM API version
957  * @param array $userdata User track data
958  * @param string $element_name Name of array element to get values for
959  * @param array $children list of sub elements of this array element that also need instantiating
960  * @return None
961  */
962 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
963     // reconstitute comments_from_learner and comments_from_lms
964     $current = '';
965     $current_subelement = '';
966     $current_sub = '';
967     $count = 0;
968     $count_sub = 0;
969     $scormseperator = '_';
970     if (scorm_version_check($sversion, SCORM_13)) { //scorm 1.3 elements use a . instead of an _
971         $scormseperator = '.';
972     }
973     // filter out the ones we want
974     $element_list = array();
975     foreach ($userdata as $element => $value) {
976         if (substr($element, 0, strlen($element_name)) == $element_name) {
977             $element_list[$element] = $value;
978         }
979     }
981     // sort elements in .n array order
982     uksort($element_list, "scorm_element_cmp");
984     // generate JavaScript
985     foreach ($element_list as $element => $value) {
986         if (scorm_version_check($sversion, SCORM_13)) {
987             $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
988             preg_match('/\.(N\d+)\./', $element, $matches);
989         } else {
990             $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
991             preg_match('/\_(\d+)\./', $element, $matches);
992         }
993         if (count($matches) > 0 && $current != $matches[1]) {
994             if ($count_sub > 0) {
995                 echo '    '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
996             }
997             $current = $matches[1];
998             $count++;
999             $current_subelement = '';
1000             $current_sub = '';
1001             $count_sub = 0;
1002             $end = strpos($element, $matches[1])+strlen($matches[1]);
1003             $subelement = substr($element, 0, $end);
1004             echo '    '.$subelement." = new Object();\n";
1005             // now add the children
1006             foreach ($children as $child) {
1007                 echo '    '.$subelement.".".$child." = new Object();\n";
1008                 echo '    '.$subelement.".".$child."._children = ".$child."_children;\n";
1009             }
1010         }
1012         // now - flesh out the second level elements if there are any
1013         if (scorm_version_check($sversion, SCORM_13)) {
1014             $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1015             preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1016         } else {
1017             $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1018             preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1019         }
1021         // check the sub element type
1022         if (count($matches) > 0 && $current_subelement != $matches[1]) {
1023             if ($count_sub > 0) {
1024                 echo '    '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1025             }
1026             $current_subelement = $matches[1];
1027             $current_sub = '';
1028             $count_sub = 0;
1029             $end = strpos($element, $matches[1])+strlen($matches[1]);
1030             $subelement = substr($element, 0, $end);
1031             echo '    '.$subelement." = new Object();\n";
1032         }
1034         // now check the subelement subscript
1035         if (count($matches) > 0 && $current_sub != $matches[2]) {
1036             $current_sub = $matches[2];
1037             $count_sub++;
1038             $end = strrpos($element, $matches[2])+strlen($matches[2]);
1039             $subelement = substr($element, 0, $end);
1040             echo '    '.$subelement." = new Object();\n";
1041         }
1043         echo '    '.$element.' = \''.$value."';\n";
1044     }
1045     if ($count_sub > 0) {
1046         echo '    '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1047     }
1048     if ($count > 0) {
1049         echo '    '.$element_name.'._count = '.$count.";\n";
1050     }
1053 /**
1054  * Build up the JavaScript representation of an array element
1055  *
1056  * @param string $a left array element
1057  * @param string $b right array element
1058  * @return comparator - 0,1,-1
1059  */
1060 function scorm_element_cmp($a, $b) {
1061     preg_match('/.*?(\d+)\./', $a, $matches);
1062     $left = intval($matches[1]);
1063     preg_match('/.?(\d+)\./', $b, $matches);
1064     $right = intval($matches[1]);
1065     if ($left < $right) {
1066         return -1; // smaller
1067     } else if ($left > $right) {
1068         return 1;  // bigger
1069     } else {
1070         // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1071         if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1072             $leftterm = intval($matches[2]);
1073             $left = intval($matches[3]);
1074             if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1075                 $rightterm = intval($matches[2]);
1076                 $right = intval($matches[3]);
1077                 if ($leftterm < $rightterm) {
1078                     return -1; // smaller
1079                 } else if ($leftterm > $rightterm) {
1080                     return 1;  // bigger
1081                 } else {
1082                     if ($left < $right) {
1083                         return -1; // smaller
1084                     } else if ($left > $right) {
1085                         return 1;  // bigger
1086                     }
1087                 }
1088             }
1089         }
1090         // fall back for no second level matches or second level matches are equal
1091         return 0;  // equal to
1092     }
1095 /**
1096  * Generate the user attempt status string
1097  *
1098  * @param object $user Current context user
1099  * @param object $scorm a moodle scrom object - mdl_scorm
1100  * @return string - Attempt status string
1101  */
1102 function scorm_get_attempt_status($user, $scorm, $cm='') {
1103     global $DB, $PAGE, $OUTPUT;
1105     $attempts = scorm_get_attempt_count($user->id, $scorm, true);
1106     if (empty($attempts)) {
1107         $attemptcount = 0;
1108     } else {
1109         $attemptcount = count($attempts);
1110     }
1112     $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1113     if ($scorm->maxattempt > 0) {
1114         $result .= $scorm->maxattempt . '<br />';
1115     } else {
1116         $result .= get_string('unlimited').'<br />';
1117     }
1118     $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1120     if ($scorm->maxattempt == 1) {
1121         switch ($scorm->grademethod) {
1122             case GRADEHIGHEST:
1123                 $grademethod = get_string('gradehighest', 'scorm');
1124             break;
1125             case GRADEAVERAGE:
1126                 $grademethod = get_string('gradeaverage', 'scorm');
1127             break;
1128             case GRADESUM:
1129                 $grademethod = get_string('gradesum', 'scorm');
1130             break;
1131             case GRADESCOES:
1132                 $grademethod = get_string('gradescoes', 'scorm');
1133             break;
1134         }
1135     } else {
1136         switch ($scorm->whatgrade) {
1137             case HIGHESTATTEMPT:
1138                 $grademethod = get_string('highestattempt', 'scorm');
1139             break;
1140             case AVERAGEATTEMPT:
1141                 $grademethod = get_string('averageattempt', 'scorm');
1142             break;
1143             case FIRSTATTEMPT:
1144                 $grademethod = get_string('firstattempt', 'scorm');
1145             break;
1146             case LASTATTEMPT:
1147                 $grademethod = get_string('lastattempt', 'scorm');
1148             break;
1149         }
1150     }
1152     if (!empty($attempts)) {
1153         $i = 1;
1154         foreach ($attempts as $attempt) {
1155             $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1156             if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1157                 $gradereported = $gradereported/$scorm->maxgrade;
1158                 $gradereported = number_format($gradereported*100, 0) .'%';
1159             }
1160             $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1161             $i++;
1162         }
1163     }
1164     $calculatedgrade = scorm_grade_user($scorm, $user->id);
1165     if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1166         $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1167         $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1168     }
1169     $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1170     if (empty($attempts)) {
1171         $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1172     } else {
1173         $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1174     }
1175     $result .= '</p>';
1176     if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1177         $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1178     }
1179     if (!empty($cm)) {
1180         $context = context_module::instance($cm->id);
1181         if (has_capability('mod/scorm:deleteownresponses', $context) &&
1182             $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
1183             //check to see if any data is stored for this user:
1184             $deleteurl = new moodle_url($PAGE->url, array('action'=>'delete', 'sesskey' => sesskey()));
1185             $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1186         }
1187     }
1190     return $result;
1193 /**
1194  * Get SCORM attempt count
1195  *
1196  * @param object $user Current context user
1197  * @param object $scorm a moodle scrom object - mdl_scorm
1198  * @param bool $attempts return the list of attempts
1199  * @return int - no. of attempts so far
1200  */
1201 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1202     global $DB;
1203     $attemptcount = 0;
1204     $element = 'cmi.core.score.raw';
1205     if ($scorm->grademethod == GRADESCOES) {
1206         $element = 'cmi.core.lesson_status';
1207     }
1208     if (scorm_version_check($scorm->version, SCORM_13)) {
1209         $element = 'cmi.score.raw';
1210     }
1211     $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id), 'attempt', 'DISTINCT attempt AS attemptnumber');
1212     if ($attempts_only) {
1213         return $attempts;
1214     }
1215     if (!empty($attempts)) {
1216         $attemptcount = count($attempts);
1217     }
1218     return $attemptcount;
1221 /**
1222  * Figure out with this is a debug situation
1223  *
1224  * @param object $scorm a moodle scrom object - mdl_scorm
1225  * @return boolean - debugging true/false
1226  */
1227 function scorm_debugging($scorm) {
1228     global $CFG, $USER;
1229     $cfg_scorm = get_config('scorm');
1231     if (!$cfg_scorm->allowapidebug) {
1232         return false;
1233     }
1234     $identifier = $USER->username.':'.$scorm->name;
1235     $test = $cfg_scorm->apidebugmask;
1236     // check the regex is only a short list of safe characters
1237     if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1238         return false;
1239     }
1240     $res = false;
1241     eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1242     return $res;
1245 /**
1246  * Delete Scorm tracks for selected users
1247  *
1248  * @param array $attemptids list of attempts that need to be deleted
1249  * @param int $scorm instance
1250  *
1251  * return bool true deleted all responses, false failed deleting an attempt - stopped here
1252  */
1253 function scorm_delete_responses($attemptids, $scorm) {
1254     if (!is_array($attemptids) || empty($attemptids)) {
1255         return false;
1256     }
1258     foreach ($attemptids as $num => $attemptid) {
1259         if (empty($attemptid)) {
1260             unset($attemptids[$num]);
1261         }
1262     }
1264     foreach ($attemptids as $attempt) {
1265         $keys = explode(':', $attempt);
1266         if (count($keys) == 2) {
1267             $userid = clean_param($keys[0], PARAM_INT);
1268             $attemptid = clean_param($keys[1], PARAM_INT);
1269             if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
1270                     return false;
1271             }
1272         } else {
1273             return false;
1274         }
1275     }
1276     return true;
1279 /**
1280  * Delete Scorm tracks for selected users
1281  *
1282  * @param int $userid ID of User
1283  * @param int $scormid ID of Scorm
1284  * @param int $attemptid user attempt that need to be deleted
1285  *
1286  * return bool true suceeded
1287  */
1288 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1289     global $DB;
1291     $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1292     include_once('lib.php');
1293     scorm_update_grades($scorm, $userid, true);
1294     return true;
1297 /**
1298  * Converts SCORM duration notation to human-readable format
1299  * The function works with both SCORM 1.2 and SCORM 2004 time formats
1300  * @param $duration string SCORM duration
1301  * @return string human-readable date/time
1302  */
1303 function scorm_format_duration($duration) {
1304     // fetch date/time strings
1305     $stryears = get_string('years');
1306     $strmonths = get_string('nummonths');
1307     $strdays = get_string('days');
1308     $strhours = get_string('hours');
1309     $strminutes = get_string('minutes');
1310     $strseconds = get_string('seconds');
1312     if ($duration[0] == 'P') {
1313         // if timestamp starts with 'P' - it's a SCORM 2004 format
1314         // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1315         // and outputs filled sections, discarding leading zeroes and any format literals
1316         // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1317         $pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#', '#0*(\d+)Y#', '#0*(\d+)D#', '#P#',
1318                           '#([A-Z])0+H#', '#([A-Z])[0.]+S#', '#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
1319         $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1320                           '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1321     } else {
1322         // else we have SCORM 1.2 format there
1323         // first convert the timestamp to some SCORM 2004-like format for conveniency
1324         $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1325         // then convert in the same way as SCORM 2004
1326         $pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#', '#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
1327         $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1328     }
1330     $result = preg_replace($pattern, $replace, $duration);
1332     return $result;
1335 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1336     global $CFG, $DB, $PAGE, $OUTPUT;
1338     $modestr = '';
1339     if ($mode != 'normal') {
1340         $modestr = '&mode='.$mode;
1341     }
1343     $result = array();
1344     $incomplete = false;
1346     if (!empty($organizationsco)) {
1347         $result[0] = $organizationsco;
1348         $result[0]->isvisible = true;
1349         $result[0]->statusicon = '';
1350         $result[0]->url = '';
1351     }
1353     if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1354         // Retrieve user tracking data for each learning object.
1355         $usertracks = array();
1356         foreach ($scoes as $sco) {
1357             if (!empty($sco->launch)) {
1358                 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
1359                     if ($usertrack->status == '') {
1360                         $usertrack->status = 'notattempted';
1361                     }
1362                     $usertracks[$sco->identifier] = $usertrack;
1363                 }
1364             }
1365         }
1366         foreach ($scoes as $sco) {
1367             if (!isset($sco->isvisible)) {
1368                 $sco->isvisible = true;
1369             }
1371             if (empty($sco->title)) {
1372                 $sco->title = $sco->identifier;
1373             }
1375             if (scorm_version_check($scorm->version, SCORM_13)) {
1376                 $sco->prereq = true;
1377             } else {
1378                 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1379             }
1381             if ($sco->isvisible) {
1382                 if (!empty($sco->launch)) {
1383                     if (empty($scoid) && ($mode != 'normal')) {
1384                         $scoid = $sco->id;
1385                     }
1387                     if (isset($usertracks[$sco->identifier])) {
1388                         $usertrack = $usertracks[$sco->identifier];
1389                         $strstatus = get_string($usertrack->status,'scorm');
1391                         if ($sco->scormtype == 'sco') {
1392                             $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1393                         } else {
1394                             $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1395                         }
1397                         if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1398                             $incomplete = true;
1399                             if ($play && empty($scoid)) {
1400                                 $scoid = $sco->id;
1401                             }
1402                         }
1404                         $strsuspended = get_string('suspended', 'scorm');
1406                         $exitvar = 'cmi.core.exit';
1408                         if (scorm_version_check($scorm->version, SCORM_13)) {
1409                             $exitvar = 'cmi.exit';
1410                         }
1412                         if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1413                             $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1414                         }
1416                     } else {
1417                         if ($play && empty($scoid)) {
1418                             $scoid = $sco->id;
1419                         }
1421                         $incomplete = true;
1423                         if ($sco->scormtype == 'sco') {
1424                             $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1425                         } else {
1426                             $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1427                         }
1428                     }
1429                 }
1430             }
1432             if (empty($statusicon)) {
1433                 $sco->statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1434             } else {
1435                 $sco->statusicon = $statusicon;
1436             }
1438             $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
1439             $sco->incomplete = $incomplete;
1441             if (!in_array($sco->id, array_keys($result))) {
1442                 $result[$sco->id] = $sco;
1443             }
1444         }
1445     }
1447     // Get the parent scoes!
1448     $result = scorm_get_toc_get_parent_child($result);
1450     // Be safe, prevent warnings from showing up while returning array
1451     if (!isset($scoid)) {
1452         $scoid = '';
1453     }
1455     return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1458 function scorm_get_toc_get_parent_child(&$result) {
1459     $final = array();
1460     $level = 0;
1461     $prevparent = '/';
1463     foreach ($result as $sco) {
1464         if ($sco->parent == '/') {
1465             $final[$level][$sco->identifier] = $sco;
1466             $prevparent = $sco->identifier;
1467             unset($result[$sco->id]);
1468         } else {
1469             if ($sco->parent == $prevparent) {
1470                 $final[$level][$sco->identifier] = $sco;
1471                 $prevparent = $sco->identifier;
1472                 unset($result[$sco->id]);
1473             } else {
1474                 if (!empty($final[$level])) {
1475                     $found = false;
1476                     foreach ($final[$level] as $fin) {
1477                         if ($sco->parent == $fin->identifier) {
1478                             $found = true;
1479                         }
1480                     }
1482                     if ($found) {
1483                         $final[$level][$sco->identifier] = $sco;
1484                         unset($result[$sco->id]);
1485                         $found = false;
1486                     } else {
1487                         $level++;
1488                         $final[$level][$sco->identifier] = $sco;
1489                         unset($result[$sco->id]);
1490                     }
1491                 }
1492             }
1493         }
1494     }
1496     for ($i = 0; $i <= $level; $i++) {
1497         $prevparent = '';
1498         foreach ($final[$i] as $ident => $sco) {
1499             if (empty($prevparent)) {
1500                 $prevparent = $ident;
1501             }
1502             if (!isset($final[$i][$prevparent]->children)) {
1503                 $final[$i][$prevparent]->children = array();
1504             }
1505             if ($sco->parent == $prevparent) {
1506                 $final[$i][$prevparent]->children[] = $sco;
1507                 $prevparent = $ident;
1508             } else {
1509                 $parent = false;
1510                 foreach ($final[$i] as $identifier => $scoobj) {
1511                     if ($identifier == $sco->parent) {
1512                         $parent = $identifier;
1513                     }
1514                 }
1516                 if ($parent !== false) {
1517                     $final[$i][$parent]->children[] = $sco;
1518                 }
1519             }
1520         }
1521     }
1523     $results = array();
1524     for ($i = 0; $i <= $level; $i++) {
1525         $keys = array_keys($final[$i]);
1526         $results[] = $final[$i][$keys[0]];
1527     }
1529     return $results;
1532 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1533     global $CFG;
1535     $result = new stdClass();
1536     $result->prerequisites = true;
1537     $result->incomplete = true;
1538     $result->toc = '';
1540     if (!$children) {
1541         $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1542         $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
1543     }
1545     if (!$children) {
1546         $result->toc = "<ul>\n";
1548         if (!$play && !empty($organizationsco))  {
1549             $result->toc .= "\t<li>".$organizationsco->title."</li>\n";
1550         }
1551     }
1553     $prevsco = '';
1554     if (!empty($scoes)) {
1555         foreach ($scoes as $sco) {
1556             $result->toc .= "\t<li>\n";
1557             $scoid = $sco->id;
1559             $sco->isvisible = true;
1561             if ($sco->isvisible) {
1562                 $score = '';
1564                 if (isset($usertracks[$sco->identifier])) {
1565                     $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
1566                     if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1567                         if ($usertracks[$sco->identifier]->score_raw != '') {
1568                             $score = '('.get_string('score','scorm').':&nbsp;'.$usertracks[$sco->identifier]->score_raw.')';
1569                         }
1570                     }
1571                 }
1573                 if (!empty($sco->prereq)) {
1574                     if ($sco->id == $scoid) {
1575                         $result->prerequisites = true;
1576                     }
1578                     if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1579                         if ($sco->scormtype == 'sco') {
1580                             $result->toc .= '<span>'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1581                         } else {
1582                             $result->toc .= '<span>&nbsp;'.format_string($sco->title).'</span>';
1583                         }
1584                     } else if ($toclink == TOCFULLURL) {
1585                         $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
1586                         if (!empty($sco->launch)) {
1587                             if ($sco->scormtype == 'sco') {
1588                                 $result->toc .= $sco->statusicon.'&nbsp;<a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1589                             } else {
1590                                 $result->toc .= '&nbsp;<a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1591                             }
1592                         } else {
1593                             if ($sco->scormtype == 'sco') {
1594                                 $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title).$score."\n";
1595                             } else {
1596                                 $result->toc .= '&nbsp;'.format_string($sco->title).$score."\n";
1597                             }
1598                         }
1599                     } else {
1600                         if (!empty($sco->launch)) {
1601                             if ($sco->scormtype == 'sco') {
1602                                 $result->toc .= '<a title="'.$sco->url.'">'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'&nbsp;'.$score.'</a>';
1603                             } else {
1604                                 $result->toc .= '<a title="'.$sco->url.'">&nbsp;'.format_string($sco->title).'&nbsp;'.$score.'</a>';
1605                             }
1606                         } else {
1607                             if ($sco->scormtype == 'sco') {
1608                                 $result->toc .= '<span>'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1609                             } else {
1610                                 $result->toc .= '<span>&nbsp;'.format_string($sco->title).'</span>';
1611                             }
1612                         }
1613                     }
1615                 } else {
1616                     if ($play) {
1617                         if ($sco->scormtype == 'sco') {
1618                             $result->toc .= '<span>'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1619                         } else {
1620                             $result->toc .= '&nbsp;'.format_string($sco->title).'</span>';
1621                         }
1622                     } else {
1623                         if ($sco->scormtype == 'sco') {
1624                             $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title)."\n";
1625                         } else {
1626                             $result->toc .= '&nbsp;'.format_string($sco->title)."\n";
1627                         }
1628                     }
1629                 }
1631             } else {
1632                 $result->toc .= "\t\t&nbsp;".format_string($sco->title)."\n";
1633             }
1635             if (!empty($sco->children)) {
1636                 $result->toc .= "\n\t\t<ul>\n";
1637                 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1638                 $result->toc .= $childresult->toc;
1639                 $result->toc .= "\t\t</ul>\n";
1640                 $result->toc .= "\t</li>\n";
1641             } else {
1642                 $result->toc .= "\t</li>\n";
1643             }
1644             $prevsco = $sco;
1645         }
1646         $result->incomplete = $sco->incomplete;
1647     }
1649     if (!$children) {
1650         $result->toc .= "</ul>\n";
1651     }
1653     return $result;
1656 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1657     if (!empty($scoes)) {
1658         if (!empty($organizationsco) && !$children) {
1659             $tocmenus[$organizationsco->id] = $organizationsco->title;
1660         }
1662         $parents[$level]='/';
1663         foreach ($scoes as $sco) {
1664             if ($parents[$level] != $sco->parent) {
1665                 if ($newlevel = array_search($sco->parent, $parents)) {
1666                     $level = $newlevel;
1667                 } else {
1668                     $i = $level;
1669                     while (($i > 0) && ($parents[$level] != $sco->parent)) {
1670                         $i--;
1671                     }
1673                     if (($i == 0) && ($sco->parent != $currentorg)) {
1674                         $level++;
1675                     } else {
1676                         $level = $i;
1677                     }
1679                     $parents[$level] = $sco->parent;
1680                 }
1681             }
1683             if ($sco->prereq) {
1684                 if ($sco->scormtype == 'sco') {
1685                     $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
1686                 }
1687             } else {
1688                 if ($sco->scormtype == 'sco') {
1689                     $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
1690                 }
1691             }
1693             if (!empty($sco->children)) {
1694                 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1695             }
1696         }
1697     }
1699     return $tocmenus;
1702 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1703     global $CFG, $DB, $OUTPUT;
1705     if (empty($attempt)) {
1706         $attempt = scorm_get_attempt_count($user->id, $scorm);
1707     }
1709     $result = new stdClass();
1710     $organizationsco = null;
1712     if ($tocheader) {
1713         $result->toc = "<div id=\"scorm_layout\">\n";
1714         $result->toc .= "<div id=\"scorm_toc\">\n";
1715         $result->toc .= "<div id=\"scorm_tree\">\n";
1716     }
1718     if (!empty($currentorg)) {
1719         $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id, 'identifier'=>$currentorg));
1720         if (!empty($organizationsco->title)) {
1721             if ($play) {
1722                 $result->toctitle = $organizationsco->title;
1723             }
1724         }
1725     }
1727     $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1729     $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1731     if ($tocheader) {
1732         $result->toc .= $treeview->toc;
1733     } else {
1734         $result->toc = $treeview->toc;
1735     }
1737     if (!empty($scoes['scoid'])) {
1738         $scoid = $scoes['scoid'];
1739     }
1741     if (empty($scoid)) {
1742         $result->sco = $scoes['scoes'][0]->children[0];
1743     } else {
1744         $result->sco = scorm_get_sco($scoid);
1745     }
1747     if ($scorm->hidetoc == SCORM_TOC_POPUP) {
1748         $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $currentorg, $organizationsco);
1750         $modestr = '';
1751         if ($mode != 'normal') {
1752             $modestr = '&mode='.$mode;
1753         }
1755         $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
1756         $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
1757     }
1759     $result->prerequisites = $treeview->prerequisites;
1760     $result->incomplete = $treeview->incomplete;
1761     $result->attemptleft = $treeview->attemptleft;
1763     if ($tocheader) {
1764         $result->toc .= "</div></div></div>\n";
1765         $result->toc .= "<div id=\"scorm_navpanel\"></div>\n";
1766     }
1768     return $result;
1771 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1772     if (is_object($scoes)) {
1773         $sco = $scoes;
1774         if (isset($sco->url)) {
1775             $adlnav[$sco->id]['identifier'] = $sco->identifier;
1776             $adlnav[$sco->id]['launch'] = $sco->launch;
1777             $adlnav[$sco->id]['title'] = $sco->title;
1778             $adlnav[$sco->id]['url'] = $sco->url;
1779             $adlnav[$sco->id]['parent'] = $sco->parent;
1780             if (isset($sco->choice)) {
1781                 $adlnav[$sco->id]['choice'] = $sco->choice;
1782             }
1783             if (isset($sco->flow)) {
1784                 $adlnav[$sco->id]['flow'] = $sco->flow;
1785             } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1786                 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1787             }
1788             if (isset($sco->isvisible)) {
1789                 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1790             }
1791             if (isset($sco->parameters)) {
1792                 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1793             }
1794             if (isset($sco->hidecontinue)) {
1795                 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1796             }
1797             if (isset($sco->hideprevious)) {
1798                 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1799             }
1800             if (isset($sco->hidesuspendall)) {
1801                 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1802             }
1803             if (!empty($parentscoid)) {
1804                 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1805             }
1806             if (isset($adlnav['prevscoid'])) {
1807                 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1808                 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1809                 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1810                     $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1811                     $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1812                 }
1813             }
1814             $adlnav['prevscoid'] = $sco->id;
1815             $adlnav['prevparent'] = $sco->parent;
1816         }
1817         if (isset($sco->children)) {
1818             foreach ($sco->children as $children) {
1819                 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1820             }
1821         }
1822     } else {
1823         foreach ($scoes as $sco) {
1824             scorm_get_adlnav_json ($sco, $adlnav);
1825         }
1826         unset($adlnav['prevscoid']);
1827         unset($adlnav['prevparent']);
1828     }
1829     return json_encode($adlnav);
1832 /**
1833  * Check for the availability of a resource by URL.
1834  *
1835  * Check is performed using an HTTP HEAD call.
1836  *
1837  * @param $url string A valid URL
1838  * @return bool|string True if no issue is found. The error string message, otherwise
1839  */
1840 function scorm_check_url($url) {
1841     $curl = new curl;
1843     if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1844         // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1845         $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1846     }
1847     $cmsg = $curl->head($url);
1848     $info = $curl->get_info();
1849     if (empty($info['http_code']) || $info['http_code'] != 200) {
1850         return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
1851     }
1853     return true;