Revert "MDL-35380 SCORM: improve check for imsmanifest file and consolidate into...
[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     global $CFG;
75     $cfg_scorm = get_config('scorm');
77     return array('resizable'=> isset($cfg_scorm->resizable) ? $cfg_scorm->resizable : 0,
78                  'scrollbars'=> isset($cfg_scorm->scrollbars) ? $cfg_scorm->scrollbars : 0,
79                  'directories'=> isset($cfg_scorm->directories) ? $cfg_scorm->directories : 0,
80                  'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
81                  'menubar'=> isset($cfg_scorm->menubar) ? $cfg_scorm->menubar : 0,
82                  'toolbar'=> isset($cfg_scorm->toolbar) ? $cfg_scorm->toolbar : 0,
83                  'status'=> isset($cfg_scorm->status) ? $cfg_scorm->status : 0);
84 }
86 /**
87  * Returns an array of the array of what grade options
88  *
89  * @return array an array of what grade options
90  */
91 function scorm_get_grade_method_array() {
92     return array (GRADESCOES => get_string('gradescoes', 'scorm'),
93                   GRADEHIGHEST => get_string('gradehighest', 'scorm'),
94                   GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
95                   GRADESUM => get_string('gradesum', 'scorm'));
96 }
98 /**
99  * Returns an array of the array of what grade options
100  *
101  * @return array an array of what grade options
102  */
103 function scorm_get_what_grade_array() {
104     return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
105                   AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
106                   FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
107                   LASTATTEMPT => get_string('lastattempt', 'scorm'));
110 /**
111  * Returns an array of the array of skip view options
112  *
113  * @return array an array of skip view options
114  */
115 function scorm_get_skip_view_array() {
116     return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
117                  SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
118                  SCORM_SKIPVIEW_ALWAYS => get_string('always'));
121 /**
122  * Returns an array of the array of hide table of contents options
123  *
124  * @return array an array of hide table of contents options
125  */
126 function scorm_get_hidetoc_array() {
127      return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
128                   SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
129                   SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
130                   SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
133 /**
134  * Returns an array of the array of update frequency options
135  *
136  * @return array an array of update frequency options
137  */
138 function scorm_get_updatefreq_array() {
139     return array(SCORM_UPDATE_NEVER => get_string('never'),
140                  SCORM_UPDATE_EVERYDAY => get_string('everyday', 'scorm'),
141                  SCORM_UPDATE_EVERYTIME => get_string('everytime', 'scorm'));
144 /**
145  * Returns an array of the array of popup display options
146  *
147  * @return array an array of popup display options
148  */
149 function scorm_get_popup_display_array() {
150     return array(0 => get_string('currentwindow', 'scorm'),
151                  1 => get_string('popup', 'scorm'));
154 /**
155  * Returns an array of the array of attempt options
156  *
157  * @return array an array of attempt options
158  */
159 function scorm_get_attempts_array() {
160     $attempts = array(0 => get_string('nolimit', 'scorm'),
161                       1 => get_string('attempt1', 'scorm'));
163     for ($i=2; $i<=6; $i++) {
164         $attempts[$i] = get_string('attemptsx', 'scorm', $i);
165     }
167     return $attempts;
170 /**
171  * Returns an array of the attempt status options
172  *
173  * @return array an array of attempt status options
174  */
175 function scorm_get_attemptstatus_array() {
176     return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO => get_string('no'),
177                  SCORM_DISPLAY_ATTEMPTSTATUS_ALL => get_string('attemptstatusall', 'scorm'),
178                  SCORM_DISPLAY_ATTEMPTSTATUS_MY => get_string('attemptstatusmy', 'scorm'),
179                  SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY => get_string('attemptstatusentry', 'scorm'));
182 /**
183  * Extracts scrom package, sets up all variables.
184  * Called whenever scorm changes
185  * @param object $scorm instance - fields are updated and changes saved into database
186  * @param bool $full force full update if true
187  * @return void
188  */
189 function scorm_parse($scorm, $full) {
190     global $CFG, $DB;
191     $cfg_scorm = get_config('scorm');
193     if (!isset($scorm->cmid)) {
194         $cm = get_coursemodule_from_instance('scorm', $scorm->id);
195         $scorm->cmid = $cm->id;
196     }
197     $context = context_module::instance($scorm->cmid);
198     $newhash = $scorm->sha1hash;
200     if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
202         $fs = get_file_storage();
203         $packagefile = false;
205         if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
206             if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
207                 $newhash = $packagefile->get_contenthash();
208             } else {
209                 $newhash = null;
210             }
211         } else {
212             if (!$cfg_scorm->allowtypelocalsync) {
213                 // sorry - localsync disabled
214                 return;
215             }
216             if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
217                 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
218                 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
219                 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
220                     $newhash = sha1($scorm->reference);
221                 } else {
222                     $newhash = null;
223                 }
224             }
225         }
227         if ($packagefile) {
228             if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
229                 if (strpos($scorm->version, 'SCORM') !== false) {
230                     if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
231                         // no need to update
232                         return;
233                     }
234                 } else if (strpos($scorm->version, 'AICC') !== false) {
235                     // TODO: add more sanity checks - something really exists in scorm_content area
236                     return;
237                 }
238             }
240             // now extract files
241             $fs->delete_area_files($context->id, 'mod_scorm', 'content');
243             $packer = get_file_packer('application/zip');
244             $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
246         } else if (!$full) {
247             return;
248         }
250         if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
251             require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
252             // SCORM
253             if (!scorm_parse_scorm($scorm, $manifest)) {
254                 $scorm->version = 'ERROR';
255             }
256         } else {
257             require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
258             // AICC
259             if (!scorm_parse_aicc($scorm)) {
260                 $scorm->version = 'ERROR';
261             }
262             $scorm->version = 'AICC';
263         }
265     } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
266         require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
267         // SCORM only, AICC can not be external
268         if (!scorm_parse_scorm($scorm, $scorm->reference)) {
269             $scorm->version = 'ERROR';
270         }
271         $newhash = sha1($scorm->reference);
273     } else if ($scorm->scormtype === SCORM_TYPE_AICCURL  and $cfg_scorm->allowtypeexternalaicc) {
274         require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
275         // AICC
276         if (!scorm_parse_aicc($scorm)) {
277             $scorm->version = 'ERROR';
278         }
279         $scorm->version = 'AICC';
280     } else {
281         // sorry, disabled type
282         return;
283     }
285     $scorm->revision++;
286     $scorm->sha1hash = $newhash;
287     $DB->update_record('scorm', $scorm);
291 function scorm_array_search($item, $needle, $haystacks, $strict=false) {
292     if (!empty($haystacks)) {
293         foreach ($haystacks as $key => $element) {
294             if ($strict) {
295                 if ($element->{$item} === $needle) {
296                     return $key;
297                 }
298             } else {
299                 if ($element->{$item} == $needle) {
300                     return $key;
301                 }
302             }
303         }
304     }
305     return false;
308 function scorm_repeater($what, $times) {
309     if ($times <= 0) {
310         return null;
311     }
312     $return = '';
313     for ($i=0; $i<$times; $i++) {
314         $return .= $what;
315     }
316     return $return;
319 function scorm_external_link($link) {
320     // check if a link is external
321     $result = false;
322     $link = strtolower($link);
323     if (substr($link, 0, 7) == 'http://') {
324         $result = true;
325     } else if (substr($link, 0, 8) == 'https://') {
326         $result = true;
327     } else if (substr($link, 0, 4) == 'www.') {
328         $result = true;
329     }
330     return $result;
333 /**
334  * Returns an object containing all datas relative to the given sco ID
335  *
336  * @param integer $id The sco ID
337  * @return mixed (false if sco id does not exists)
338  */
339 function scorm_get_sco($id, $what=SCO_ALL) {
340     global $DB;
342     if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
343         $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
344         if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
345             foreach ($scodatas as $scodata) {
346                 $sco->{$scodata->name} = $scodata->value;
347             }
348         } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
349             $sco->parameters = '';
350         }
351         return $sco;
352     } else {
353         return false;
354     }
357 /**
358  * Returns an object (array) containing all the scoes data related to the given sco ID
359  *
360  * @param integer $id The sco ID
361  * @param integer $organisation an organisation ID - defaults to false if not required
362  * @return mixed (false if there are no scoes or an array)
363  */
364 function scorm_get_scoes($id, $organisation=false) {
365     global $DB;
367     $organizationsql = '';
368     $queryarray = array('scorm'=>$id);
369     if (!empty($organisation)) {
370         $queryarray['organization'] = $organisation;
371     }
372     if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
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 $CFG, $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, 'attempt'=>$attempt), 'element ASC')) {
528         $usertrack = new stdClass();
529         $usertrack->userid = $userid;
530         $usertrack->scoid = $scoid;
531         // Defined in order to unify scorm1.2 and scorm2004
532         $usertrack->score_raw = '';
533         $usertrack->status = '';
534         $usertrack->total_time = '00:00:00';
535         $usertrack->session_time = '00:00:00';
536         $usertrack->timemodified = 0;
537         foreach ($tracks as $track) {
538             $element = $track->element;
539             $usertrack->{$element} = $track->value;
540             switch ($element) {
541                 case 'cmi.core.lesson_status':
542                 case 'cmi.completion_status':
543                     if ($track->value == 'not attempted') {
544                         $track->value = 'notattempted';
545                     }
546                     $usertrack->status = $track->value;
547                 break;
548                 case 'cmi.core.score.raw':
549                 case 'cmi.score.raw':
550                     $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
551                 break;
552                 case 'cmi.core.session_time':
553                 case 'cmi.session_time':
554                     $usertrack->session_time = $track->value;
555                 break;
556                 case 'cmi.core.total_time':
557                 case 'cmi.total_time':
558                     $usertrack->total_time = $track->value;
559                 break;
560             }
561             if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
562                 $usertrack->timemodified = $track->timemodified;
563             }
564         }
565         if (is_array($usertrack)) {
566             ksort($usertrack);
567         }
568         return $usertrack;
569     } else {
570         return false;
571     }
575 /* Find the start and finsh time for a a given SCO attempt
576  *
577  * @param int $scormid SCORM Id
578  * @param int $scoid SCO Id
579  * @param int $userid User Id
580  * @param int $attemt Attempt Id
581  *
582  * @return object start and finsh time EPOC secods
583  *
584  */
585 function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
586     global $DB;
588     $timedata = new stdClass();
589     $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
590     $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
591     if ($tracks) {
592         $tracks = array_values($tracks);
593     }
595     if ($tracks) {
596         $timedata->start = $tracks[0]->timemodified;
597     } else {
598         $timedata->start = false;
599     }
600     if ($tracks && $track = array_pop($tracks)) {
601         $timedata->finish = $track->timemodified;
602     } else {
603         $timedata->finish = $timedata->start;
604     }
605     return $timedata;
609 function scorm_get_user_data($userid) {
610     global $DB;
611     /// Gets user info required to display the table of scorm results
612     /// for report.php
614     return $DB->get_record('user', array('id'=>$userid), user_picture::fields());
617 function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
618     global $DB;
619     $attemptscore = new stdClass();
620     $attemptscore->scoes = 0;
621     $attemptscore->values = 0;
622     $attemptscore->max = 0;
623     $attemptscore->sum = 0;
624     $attemptscore->lastmodify = 0;
626     if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
627         return null;
628     }
630     foreach ($scoes as $sco) {
631         if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
632             if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
633                 $attemptscore->scoes++;
634             }
635             if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
636                 $attemptscore->values++;
637                 $attemptscore->sum += $userdata->score_raw;
638                 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
639                 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
640                     $attemptscore->lastmodify = $userdata->timemodified;
641                 } else {
642                     $attemptscore->lastmodify = 0;
643                 }
644             }
645         }
646     }
647     switch ($scorm->grademethod) {
648         case GRADEHIGHEST:
649             $score = (float) $attemptscore->max;
650         break;
651         case GRADEAVERAGE:
652             if ($attemptscore->values > 0) {
653                 $score = $attemptscore->sum/$attemptscore->values;
654             } else {
655                 $score = 0;
656             }
657         break;
658         case GRADESUM:
659             $score = $attemptscore->sum;
660         break;
661         case GRADESCOES:
662             $score = $attemptscore->scoes;
663         break;
664         default:
665             $score = $attemptscore->max;   // Remote Learner GRADEHIGHEST is default
666     }
668     return $score;
671 function scorm_grade_user($scorm, $userid) {
673     // ensure we dont grade user beyond $scorm->maxattempt settings
674     $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
675     if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
676         $lastattempt = $scorm->maxattempt;
677     }
679     switch ($scorm->whatgrade) {
680         case FIRSTATTEMPT:
681             return scorm_grade_user_attempt($scorm, $userid, 1);
682         break;
683         case LASTATTEMPT:
684             return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
685         break;
686         case HIGHESTATTEMPT:
687             $maxscore = 0;
688             for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
689                 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
690                 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
691             }
692             return $maxscore;
694         break;
695         case AVERAGEATTEMPT:
696             $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
697             if (empty($attemptcount)) {
698                 return 0;
699             } else {
700                 $attemptcount = count($attemptcount);
701             }
702             $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
703             $sumscore = 0;
704             for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
705                 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
706                 $sumscore += $attemptscore;
707             }
709             return round($sumscore / $attemptcount);
710         break;
711     }
714 function scorm_count_launchable($scormid, $organization='') {
715     global $DB;
717     $sqlorganization = '';
718     $params = array($scormid);
719     if (!empty($organization)) {
720         $sqlorganization = " AND organization=?";
721         $params[] = $organization;
722     }
723     return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
726 /**
727  * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
728  *
729  * @param int $scormid the id of the scorm.
730  * @param int $userid the id of the user.
731  *
732  * @return int The attempt number to use.
733  */
734 function scorm_get_last_attempt($scormid, $userid) {
735     global $DB;
737     /// Find the last attempt number for the given user id and scorm id
738     $sql = "SELECT MAX(attempt)
739               FROM {scorm_scoes_track}
740              WHERE userid = ? AND scormid = ?";
741     $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
742     if (empty($lastattempt)) {
743         return '1';
744     } else {
745         return $lastattempt;
746     }
749 /**
750  * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
751  *
752  * @param int $scormid the id of the scorm.
753  * @param int $userid the id of the user.
754  *
755  * @return int The attempt number to use.
756  */
757 function scorm_get_last_completed_attempt($scormid, $userid) {
758     global $DB;
760     /// Find the last completed attempt number for the given user id and scorm id
761     $sql = "SELECT MAX(attempt)
762               FROM {scorm_scoes_track}
763              WHERE userid = ? AND scormid = ?
764                AND (value='completed' OR value='passed')";
765     $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
766     if (empty($lastattempt)) {
767         return '1';
768     } else {
769         return $lastattempt;
770     }
773 function scorm_course_format_display($user, $course) {
774     global $CFG, $DB, $PAGE, $OUTPUT;
776     $strupdate = get_string('update');
777     $context = context_course::instance($course->id);
779     echo '<div class="mod-scorm">';
780     if ($scorms = get_all_instances_in_course('scorm', $course)) {
781         // The module SCORM activity with the least id is the course
782         $scorm = current($scorms);
783         if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
784             print_error('invalidcoursemodule');
785         }
786         $contextmodule = context_module::instance($cm->id);
787         if ((has_capability('mod/scorm:skipview', $contextmodule))) {
788             scorm_simple_play($scorm, $user, $contextmodule, $cm->id);
789         }
790         $colspan = '';
791         $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
792         if (has_capability('moodle/course:manageactivities', $context)) {
793             if ($PAGE->user_is_editing()) {
794                 // Display update icon
795                 $path = $CFG->wwwroot.'/course';
796                 $headertext .= '<span class="commands">'.
797                         '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&amp;sesskey='.sesskey().'">'.
798                         '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
799             }
800             $headertext .= '</td>';
801             // Display report link
802             $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
803             if ($trackedusers->c > 0) {
804                 $headertext .= '<td class="reportlink">'.
805                               '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
806                                get_string('viewallreports', 'scorm', $trackedusers->c).'</a>';
807             } else {
808                 $headertext .= '<td class="reportlink">'.get_string('noreports', 'scorm');
809             }
810             $colspan = ' colspan="2"';
811         }
812         $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
813         echo $OUTPUT->box($headertext, 'generalbox boxwidthwide');
814         scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm);
815     } else {
816         if (has_capability('moodle/course:update', $context)) {
817             // Create a new activity
818             $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'section'=>'0', 'sesskey'=>sesskey(),'add'=>'scorm'));
819             redirect($url);
820         } else {
821             echo $OUTPUT->notification('Could not find a scorm course here');
822         }
823     }
824     echo '</div>';
827 function scorm_view_display ($user, $scorm, $action, $cm) {
828     global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
830     if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
831         scorm_parse($scorm, false);
832     }
834     $organization = optional_param('organization', '', PARAM_INT);
836     if ($scorm->displaycoursestructure == 1) {
837         echo $OUTPUT->box_start('generalbox boxaligncenter toc');
838         ?>
839         <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
840         <?php
841     }
842     if (empty($organization)) {
843         $organization = $scorm->launch;
844     }
845     if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
846                                          $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
847                                          $DB->sql_isempty('scorm_scoes', 'organization', false, false),
848                                          array($scorm->id), 'id', 'id,title')) {
849         if (count($orgs) > 1) {
850             $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
851             $select->label = get_string('organizations', 'scorm');
852             $select->class = 'scorm-center';
853             echo $OUTPUT->render($select);
854         }
855     }
856     $orgidentifier = '';
857     if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
858         if (($sco->organization == '') && ($sco->launch == '')) {
859             $orgidentifier = $sco->identifier;
860         } else {
861             $orgidentifier = $sco->organization;
862         }
863     }
865     $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR));   // Just to be safe
866     if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
867         $scorm->version = 'scorm_12';
868     }
869     require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
871     $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
872     $incomplete = $result->incomplete;
874     // do we want the TOC to be displayed?
875     if ($scorm->displaycoursestructure == 1) {
876         echo $result->toc;
877         echo $OUTPUT->box_end();
878     }
880     // is this the first attempt ?
881     $attemptcount = scorm_get_attempt_count($user->id, $scorm);
883     // do not give the player launch FORM if the SCORM object is locked after the final attempt
884     if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
885         ?>
886             <div class="scorm-center">
887                <form id="scormviewform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
888         <?php
889         if ($scorm->hidebrowse == 0) {
890             print_string('mode', 'scorm');
891             echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
892             echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
893         } else {
894             echo '<input type="hidden" name="mode" value="normal" />'."\n";
895         }
896         if ($scorm->forcenewattempt == 1) {
897             if ($incomplete === false) {
898                 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
899             }
900         } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
901             ?>
902                       <br />
903                       <input type="checkbox" id="a" name="newattempt" />
904                       <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
905             <?php
906         }
907         if ($COURSE->format != 'scorm' && !empty($scorm->popup)) {
908             echo '<input type="hidden" name="display" value="popup" />'."\n";
909         }
910         ?>
911               <br />
912               <input type="hidden" name="scoid"/>
913               <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
914               <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
915               <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
916               </form>
917           </div>
918         <?php
919     }
922 function scorm_simple_play($scorm, $user, $context, $cmid) {
923     global $DB;
925     $result = false;
927     if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
928         return $result;
929     }
931     if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
932         scorm_parse($scorm, false);
933     }
934     $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
936     if ($scoes) {
937         $orgidentifier = '';
938         if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
939             if (($sco->organization == '') && ($sco->launch == '')) {
940                 $orgidentifier = $sco->identifier;
941             } else {
942                 $orgidentifier = $sco->organization;
943             }
944         }
945         if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
946             $sco = current($scoes);
947             $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
948                                                                 'currentorg'=>$orgidentifier,
949                                                                 'scoid'=>$sco->id));
950             if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
951                 if (!empty($scorm->forcenewattempt)) {
952                     $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
953                     if ($result->incomplete === false) {
954                         $url->param('newattempt','on');
955                     }
956                 }
957                 redirect($url);
958             }
959         }
960     }
961     return $result;
964 function scorm_get_count_users($scormid, $groupingid=null) {
965     global $CFG, $DB;
967     if (!empty($groupingid)) {
968         $sql = "SELECT COUNT(DISTINCT st.userid)
969                 FROM {scorm_scoes_track} st
970                     INNER JOIN {groups_members} gm ON st.userid = gm.userid
971                     INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
972                 WHERE st.scormid = ? AND gg.groupingid = ?
973                 ";
974         $params = array($scormid, $groupingid);
975     } else {
976         $sql = "SELECT COUNT(DISTINCT st.userid)
977                 FROM {scorm_scoes_track} st
978                 WHERE st.scormid = ?
979                 ";
980         $params = array($scormid);
981     }
983     return ($DB->count_records_sql($sql, $params));
986 /**
987  * Build up the JavaScript representation of an array element
988  *
989  * @param string $sversion SCORM API version
990  * @param array $userdata User track data
991  * @param string $element_name Name of array element to get values for
992  * @param array $children list of sub elements of this array element that also need instantiating
993  * @return None
994  */
995 function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
996     // reconstitute comments_from_learner and comments_from_lms
997     $current = '';
998     $current_subelement = '';
999     $current_sub = '';
1000     $count = 0;
1001     $count_sub = 0;
1002     $scormseperator = '_';
1003     if (scorm_version_check($sversion, SCORM_13)) { //scorm 1.3 elements use a . instead of an _
1004         $scormseperator = '.';
1005     }
1006     // filter out the ones we want
1007     $element_list = array();
1008     foreach ($userdata as $element => $value) {
1009         if (substr($element, 0, strlen($element_name)) == $element_name) {
1010             $element_list[$element] = $value;
1011         }
1012     }
1014     // sort elements in .n array order
1015     uksort($element_list, "scorm_element_cmp");
1017     // generate JavaScript
1018     foreach ($element_list as $element => $value) {
1019         if (scorm_version_check($sversion, SCORM_13)) {
1020             $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
1021             preg_match('/\.(N\d+)\./', $element, $matches);
1022         } else {
1023             $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
1024             preg_match('/\_(\d+)\./', $element, $matches);
1025         }
1026         if (count($matches) > 0 && $current != $matches[1]) {
1027             if ($count_sub > 0) {
1028                 echo '    '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1029             }
1030             $current = $matches[1];
1031             $count++;
1032             $current_subelement = '';
1033             $current_sub = '';
1034             $count_sub = 0;
1035             $end = strpos($element, $matches[1])+strlen($matches[1]);
1036             $subelement = substr($element, 0, $end);
1037             echo '    '.$subelement." = new Object();\n";
1038             // now add the children
1039             foreach ($children as $child) {
1040                 echo '    '.$subelement.".".$child." = new Object();\n";
1041                 echo '    '.$subelement.".".$child."._children = ".$child."_children;\n";
1042             }
1043         }
1045         // now - flesh out the second level elements if there are any
1046         if (scorm_version_check($sversion, SCORM_13)) {
1047             $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
1048             preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
1049         } else {
1050             $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
1051             preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
1052         }
1054         // check the sub element type
1055         if (count($matches) > 0 && $current_subelement != $matches[1]) {
1056             if ($count_sub > 0) {
1057                 echo '    '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1058             }
1059             $current_subelement = $matches[1];
1060             $current_sub = '';
1061             $count_sub = 0;
1062             $end = strpos($element, $matches[1])+strlen($matches[1]);
1063             $subelement = substr($element, 0, $end);
1064             echo '    '.$subelement." = new Object();\n";
1065         }
1067         // now check the subelement subscript
1068         if (count($matches) > 0 && $current_sub != $matches[2]) {
1069             $current_sub = $matches[2];
1070             $count_sub++;
1071             $end = strrpos($element, $matches[2])+strlen($matches[2]);
1072             $subelement = substr($element, 0, $end);
1073             echo '    '.$subelement." = new Object();\n";
1074         }
1076         echo '    '.$element.' = \''.$value."';\n";
1077     }
1078     if ($count_sub > 0) {
1079         echo '    '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
1080     }
1081     if ($count > 0) {
1082         echo '    '.$element_name.'._count = '.$count.";\n";
1083     }
1086 /**
1087  * Build up the JavaScript representation of an array element
1088  *
1089  * @param string $a left array element
1090  * @param string $b right array element
1091  * @return comparator - 0,1,-1
1092  */
1093 function scorm_element_cmp($a, $b) {
1094     preg_match('/.*?(\d+)\./', $a, $matches);
1095     $left = intval($matches[1]);
1096     preg_match('/.?(\d+)\./', $b, $matches);
1097     $right = intval($matches[1]);
1098     if ($left < $right) {
1099         return -1; // smaller
1100     } else if ($left > $right) {
1101         return 1;  // bigger
1102     } else {
1103         // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1104         if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1105             $leftterm = intval($matches[2]);
1106             $left = intval($matches[3]);
1107             if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1108                 $rightterm = intval($matches[2]);
1109                 $right = intval($matches[3]);
1110                 if ($leftterm < $rightterm) {
1111                     return -1; // smaller
1112                 } else if ($leftterm > $rightterm) {
1113                     return 1;  // bigger
1114                 } else {
1115                     if ($left < $right) {
1116                         return -1; // smaller
1117                     } else if ($left > $right) {
1118                         return 1;  // bigger
1119                     }
1120                 }
1121             }
1122         }
1123         // fall back for no second level matches or second level matches are equal
1124         return 0;  // equal to
1125     }
1128 /**
1129  * Generate the user attempt status string
1130  *
1131  * @param object $user Current context user
1132  * @param object $scorm a moodle scrom object - mdl_scorm
1133  * @return string - Attempt status string
1134  */
1135 function scorm_get_attempt_status($user, $scorm, $cm='') {
1136     global $DB, $PAGE, $OUTPUT;
1138     $attempts = scorm_get_attempt_count($user->id, $scorm, true);
1139     if (empty($attempts)) {
1140         $attemptcount = 0;
1141     } else {
1142         $attemptcount = count($attempts);
1143     }
1145     $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1146     if ($scorm->maxattempt > 0) {
1147         $result .= $scorm->maxattempt . '<br />';
1148     } else {
1149         $result .= get_string('unlimited').'<br />';
1150     }
1151     $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
1153     if ($scorm->maxattempt == 1) {
1154         switch ($scorm->grademethod) {
1155             case GRADEHIGHEST:
1156                 $grademethod = get_string('gradehighest', 'scorm');
1157             break;
1158             case GRADEAVERAGE:
1159                 $grademethod = get_string('gradeaverage', 'scorm');
1160             break;
1161             case GRADESUM:
1162                 $grademethod = get_string('gradesum', 'scorm');
1163             break;
1164             case GRADESCOES:
1165                 $grademethod = get_string('gradescoes', 'scorm');
1166             break;
1167         }
1168     } else {
1169         switch ($scorm->whatgrade) {
1170             case HIGHESTATTEMPT:
1171                 $grademethod = get_string('highestattempt', 'scorm');
1172             break;
1173             case AVERAGEATTEMPT:
1174                 $grademethod = get_string('averageattempt', 'scorm');
1175             break;
1176             case FIRSTATTEMPT:
1177                 $grademethod = get_string('firstattempt', 'scorm');
1178             break;
1179             case LASTATTEMPT:
1180                 $grademethod = get_string('lastattempt', 'scorm');
1181             break;
1182         }
1183     }
1185     if (!empty($attempts)) {
1186         $i = 1;
1187         foreach ($attempts as $attempt) {
1188             $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
1189             if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1190                 $gradereported = $gradereported/$scorm->maxgrade;
1191                 $gradereported = number_format($gradereported*100, 0) .'%';
1192             }
1193             $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
1194             $i++;
1195         }
1196     }
1197     $calculatedgrade = scorm_grade_user($scorm, $user->id);
1198     if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1199         $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1200         $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1201     }
1202     $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
1203     if (empty($attempts)) {
1204         $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
1205     } else {
1206         $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
1207     }
1208     $result .= '</p>';
1209     if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
1210         $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
1211     }
1212     if (!empty($cm)) {
1213         $context = context_module::instance($cm->id);
1214         if (has_capability('mod/scorm:deleteownresponses', $context) &&
1215             $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
1216             //check to see if any data is stored for this user:
1217             $deleteurl = new moodle_url($PAGE->url, array('action'=>'delete', 'sesskey' => sesskey()));
1218             $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1219         }
1220     }
1223     return $result;
1226 /**
1227  * Get SCORM attempt count
1228  *
1229  * @param object $user Current context user
1230  * @param object $scorm a moodle scrom object - mdl_scorm
1231  * @param bool $attempts return the list of attempts
1232  * @return int - no. of attempts so far
1233  */
1234 function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
1235     global $DB;
1236     $attemptcount = 0;
1237     $element = 'cmi.core.score.raw';
1238     if ($scorm->grademethod == GRADESCOES) {
1239         $element = 'cmi.core.lesson_status';
1240     }
1241     if (scorm_version_check($scorm->version, SCORM_13)) {
1242         $element = 'cmi.score.raw';
1243     }
1244     $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id), 'attempt', 'DISTINCT attempt AS attemptnumber');
1245     if ($attempts_only) {
1246         return $attempts;
1247     }
1248     if (!empty($attempts)) {
1249         $attemptcount = count($attempts);
1250     }
1251     return $attemptcount;
1254 /**
1255  * Figure out with this is a debug situation
1256  *
1257  * @param object $scorm a moodle scrom object - mdl_scorm
1258  * @return boolean - debugging true/false
1259  */
1260 function scorm_debugging($scorm) {
1261     global $CFG, $USER;
1262     $cfg_scorm = get_config('scorm');
1264     if (!$cfg_scorm->allowapidebug) {
1265         return false;
1266     }
1267     $identifier = $USER->username.':'.$scorm->name;
1268     $test = $cfg_scorm->apidebugmask;
1269     // check the regex is only a short list of safe characters
1270     if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1271         return false;
1272     }
1273     $res = false;
1274     eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1275     return $res;
1278 /**
1279  * Delete Scorm tracks for selected users
1280  *
1281  * @param array $attemptids list of attempts that need to be deleted
1282  * @param int $scorm instance
1283  *
1284  * return bool true deleted all responses, false failed deleting an attempt - stopped here
1285  */
1286 function scorm_delete_responses($attemptids, $scorm) {
1287     if (!is_array($attemptids) || empty($attemptids)) {
1288         return false;
1289     }
1291     foreach ($attemptids as $num => $attemptid) {
1292         if (empty($attemptid)) {
1293             unset($attemptids[$num]);
1294         }
1295     }
1297     foreach ($attemptids as $attempt) {
1298         $keys = explode(':', $attempt);
1299         if (count($keys) == 2) {
1300             $userid = clean_param($keys[0], PARAM_INT);
1301             $attemptid = clean_param($keys[1], PARAM_INT);
1302             if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
1303                     return false;
1304             }
1305         } else {
1306             return false;
1307         }
1308     }
1309     return true;
1312 /**
1313  * Delete Scorm tracks for selected users
1314  *
1315  * @param int $userid ID of User
1316  * @param int $scormid ID of Scorm
1317  * @param int $attemptid user attempt that need to be deleted
1318  *
1319  * return bool true suceeded
1320  */
1321 function scorm_delete_attempt($userid, $scorm, $attemptid) {
1322     global $DB;
1324     $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1325     include_once('lib.php');
1326     scorm_update_grades($scorm, $userid, true);
1327     return true;
1330 /**
1331  * Converts SCORM duration notation to human-readable format
1332  * The function works with both SCORM 1.2 and SCORM 2004 time formats
1333  * @param $duration string SCORM duration
1334  * @return string human-readable date/time
1335  */
1336 function scorm_format_duration($duration) {
1337     // fetch date/time strings
1338     $stryears = get_string('years');
1339     $strmonths = get_string('nummonths');
1340     $strdays = get_string('days');
1341     $strhours = get_string('hours');
1342     $strminutes = get_string('minutes');
1343     $strseconds = get_string('seconds');
1345     if ($duration[0] == 'P') {
1346         // if timestamp starts with 'P' - it's a SCORM 2004 format
1347         // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1348         // and outputs filled sections, discarding leading zeroes and any format literals
1349         // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1350         $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#',
1351                           '#([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#' );
1352         $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1353                           '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
1354     } else {
1355         // else we have SCORM 1.2 format there
1356         // first convert the timestamp to some SCORM 2004-like format for conveniency
1357         $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
1358         // then convert in the same way as SCORM 2004
1359         $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#' );
1360         $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
1361     }
1363     $result = preg_replace($pattern, $replace, $duration);
1365     return $result;
1368 function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $organizationsco=null) {
1369     global $CFG, $DB, $PAGE, $OUTPUT;
1371     $modestr = '';
1372     if ($mode == 'browse') {
1373         $modestr = '&amp;mode='.$mode;
1374     }
1376     $result = array();
1377     $incomplete = false;
1379     if (!empty($organizationsco)) {
1380         $result[0] = $organizationsco;
1381         $result[0]->isvisible = true;
1382         $result[0]->statusicon = '';
1383         $result[0]->url = '';
1384     }
1386     if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1387         // Retrieve user tracking data for each learning object.
1388         $usertracks = array();
1389         foreach ($scoes as $sco) {
1390             if (!empty($sco->launch)) {
1391                 if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
1392                     if ($usertrack->status == '') {
1393                         $usertrack->status = 'notattempted';
1394                     }
1395                     $usertracks[$sco->identifier] = $usertrack;
1396                 }
1397             }
1398         }
1399         foreach ($scoes as $sco) {
1400             if (!isset($sco->isvisible)) {
1401                 $sco->isvisible = true;
1402             }
1404             if (empty($sco->title)) {
1405                 $sco->title = $sco->identifier;
1406             }
1408             if (scorm_version_check($scorm->version, SCORM_13)) {
1409                 $sco->prereq = true;
1410             } else {
1411                 $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
1412             }
1414             if ($sco->isvisible) {
1415                 if (!empty($sco->launch)) {
1416                     if (empty($scoid) && ($mode != 'normal')) {
1417                         $scoid = $sco->id;
1418                     }
1420                     if (isset($usertracks[$sco->identifier])) {
1421                         $usertrack = $usertracks[$sco->identifier];
1422                         $strstatus = get_string($usertrack->status,'scorm');
1424                         if ($sco->scormtype == 'sco') {
1425                             $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1426                         } else {
1427                             $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('assetlaunched', 'scorm').'" title="'.get_string('assetlaunched', 'scorm').'" />';
1428                         }
1430                         if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1431                             $incomplete = true;
1432                             if ($play && empty($scoid)) {
1433                                 $scoid = $sco->id;
1434                             }
1435                         }
1437                         $strsuspended = get_string('suspended', 'scorm');
1439                         $exitvar = 'cmi.core.exit';
1441                         if (scorm_version_check($scorm->version, SCORM_13)) {
1442                             $exitvar = 'cmi.exit';
1443                         }
1445                         if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1446                             $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1447                         }
1449                     } else {
1450                         if ($play && empty($scoid)) {
1451                             $scoid = $sco->id;
1452                         }
1454                         $incomplete = true;
1456                         if ($sco->scormtype == 'sco') {
1457                             $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1458                         } else {
1459                             $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset', 'scorm').'" title="'.get_string('asset', 'scorm').'" />';
1460                         }
1461                     }
1462                 }
1463             }
1465             if (empty($statusicon)) {
1466                 $sco->statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted', 'scorm').'" title="'.get_string('notattempted', 'scorm').'" />';
1467             } else {
1468                 $sco->statusicon = $statusicon;
1469             }
1471             $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
1472             $sco->incomplete = $incomplete;
1474             if (!in_array($sco->id, array_keys($result))) {
1475                 $result[$sco->id] = $sco;
1476             }
1477         }
1478     }
1480     // Get the parent scoes!
1481     $result = scorm_get_toc_get_parent_child($result);
1483     // Be safe, prevent warnings from showing up while returning array
1484     if (!isset($scoid)) {
1485         $scoid = '';
1486     }
1488     return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
1491 function scorm_get_toc_get_parent_child(&$result) {
1492     $final = array();
1493     $level = 0;
1494     $prevparent = '/';
1495     ksort($result);
1497     foreach ($result as $sco) {
1498         if ($sco->parent == '/') {
1499             $final[$level][$sco->identifier] = $sco;
1500             $prevparent = $sco->identifier;
1501             unset($result[$sco->id]);
1502         } else {
1503             if ($sco->parent == $prevparent) {
1504                 $final[$level][$sco->identifier] = $sco;
1505                 $prevparent = $sco->identifier;
1506                 unset($result[$sco->id]);
1507             } else {
1508                 if (!empty($final[$level])) {
1509                     $found = false;
1510                     foreach ($final[$level] as $fin) {
1511                         if ($sco->parent == $fin->identifier) {
1512                             $found = true;
1513                         }
1514                     }
1516                     if ($found) {
1517                         $final[$level][$sco->identifier] = $sco;
1518                         unset($result[$sco->id]);
1519                         $found = false;
1520                     } else {
1521                         $level++;
1522                         $final[$level][$sco->identifier] = $sco;
1523                         unset($result[$sco->id]);
1524                     }
1525                 }
1526             }
1527         }
1528     }
1530     for ($i = 0; $i <= $level; $i++) {
1531         $prevparent = '';
1532         foreach ($final[$i] as $ident => $sco) {
1533             if (empty($prevparent)) {
1534                 $prevparent = $ident;
1535             }
1536             if (!isset($final[$i][$prevparent]->children)) {
1537                 $final[$i][$prevparent]->children = array();
1538             }
1539             if ($sco->parent == $prevparent) {
1540                 $final[$i][$prevparent]->children[] = $sco;
1541                 $prevparent = $ident;
1542             } else {
1543                 $parent = false;
1544                 foreach ($final[$i] as $identifier => $scoobj) {
1545                     if ($identifier == $sco->parent) {
1546                         $parent = $identifier;
1547                     }
1548                 }
1550                 if ($parent !== false) {
1551                     $final[$i][$parent]->children[] = $sco;
1552                 }
1553             }
1554         }
1555     }
1557     $results = array();
1558     for ($i = 0; $i <= $level; $i++) {
1559         $keys = array_keys($final[$i]);
1560         $results[] = $final[$i][$keys[0]];
1561     }
1563     return $results;
1566 function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='', $attempt='', $play=false, $organizationsco=null, $children=false) {
1567     global $CFG;
1569     $result = new stdClass();
1570     $result->prerequisites = true;
1571     $result->incomplete = true;
1572     $result->toc = '';
1574     if (!$children) {
1575         $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
1576         $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
1577     }
1579     if (!$children) {
1580         $result->toc = "<ul>\n";
1582         if (!$play && !empty($organizationsco))  {
1583             $result->toc .= "\t<li>".$organizationsco->title."</li>\n";
1584         }
1585     }
1587     $prevsco = '';
1588     if (!empty($scoes)) {
1589         foreach ($scoes as $sco) {
1590             $result->toc .= "\t<li>\n";
1591             $scoid = $sco->id;
1593             $sco->isvisible = true;
1595             if ($sco->isvisible) {
1596                 $score = '';
1598                 if (isset($usertracks[$sco->identifier])) {
1599                     $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
1600                     if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
1601                         if ($usertracks[$sco->identifier]->score_raw != '') {
1602                             $score = '('.get_string('score','scorm').':&nbsp;'.$usertracks[$sco->identifier]->score_raw.')';
1603                         }
1604                     }
1605                 }
1607                 if (!empty($sco->prereq)) {
1608                     if ($sco->id == $scoid) {
1609                         $result->prerequisites = true;
1610                     }
1612                     if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1613                         if ($sco->scormtype == 'sco') {
1614                             $result->toc .= '<span>'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1615                         } else {
1616                             $result->toc .= '<span>&nbsp;'.format_string($sco->title).'</span>';
1617                         }
1618                     } else if ($toclink == TOCFULLURL) {
1619                         $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
1620                         if (!empty($sco->launch)) {
1621                             if ($sco->scormtype == 'sco') {
1622                                 $result->toc .= $sco->statusicon.'&nbsp;<a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1623                             } else {
1624                                 $result->toc .= '&nbsp;<a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1625                             }
1626                         } else {
1627                             if ($sco->scormtype == 'sco') {
1628                                 $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title).$score."\n";
1629                             } else {
1630                                 $result->toc .= '&nbsp;'.format_string($sco->title).$score."\n";
1631                             }
1632                         }
1633                     } else {
1634                         if (!empty($sco->launch)) {
1635                             if ($sco->scormtype == 'sco') {
1636                                 $result->toc .= '<a title="'.$sco->url.'">'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'&nbsp;'.$score.'</a>';
1637                             } else {
1638                                 $result->toc .= '<a title="'.$sco->url.'">&nbsp;'.format_string($sco->title).'&nbsp;'.$score.'</a>';
1639                             }
1640                         } else {
1641                             if ($sco->scormtype == 'sco') {
1642                                 $result->toc .= '<span>'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1643                             } else {
1644                                 $result->toc .= '<span>&nbsp;'.format_string($sco->title).'</span>';
1645                             }
1646                         }
1647                     }
1649                 } else {
1650                     if ($play) {
1651                         if ($sco->scormtype == 'sco') {
1652                             $result->toc .= '<span>'.$sco->statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1653                         } else {
1654                             $result->toc .= '&nbsp;'.format_string($sco->title).'</span>';
1655                         }
1656                     } else {
1657                         if ($sco->scormtype == 'sco') {
1658                             $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title)."\n";
1659                         } else {
1660                             $result->toc .= '&nbsp;'.format_string($sco->title)."\n";
1661                         }
1662                     }
1663                 }
1665             } else {
1666                 $result->toc .= "\t\t&nbsp;".format_string($sco->title)."\n";
1667             }
1669             if (!empty($sco->children)) {
1670                 $result->toc .= "\n\t\t<ul>\n";
1671                 $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, true);
1672                 $result->toc .= $childresult->toc;
1673                 $result->toc .= "\t\t</ul>\n";
1674                 $result->toc .= "\t</li>\n";
1675             } else {
1676                 $result->toc .= "\t</li>\n";
1677             }
1678             $prevsco = $sco;
1679         }
1680         $result->incomplete = $sco->incomplete;
1681     }
1683     if (!$children) {
1684         $result->toc .= "</ul>\n";
1685     }
1687     return $result;
1690 function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null, $children=false, $level=0, $tocmenus=array()) {
1691     if (!empty($scoes)) {
1692         if (!empty($organizationsco) && !$children) {
1693             $tocmenus[$organizationsco->id] = $organizationsco->title;
1694         }
1696         $parents[$level]='/';
1697         foreach ($scoes as $sco) {
1698             if ($parents[$level] != $sco->parent) {
1699                 if ($newlevel = array_search($sco->parent, $parents)) {
1700                     $level = $newlevel;
1701                 } else {
1702                     $i = $level;
1703                     while (($i > 0) && ($parents[$level] != $sco->parent)) {
1704                         $i--;
1705                     }
1707                     if (($i == 0) && ($sco->parent != $currentorg)) {
1708                         $level++;
1709                     } else {
1710                         $level = $i;
1711                     }
1713                     $parents[$level] = $sco->parent;
1714                 }
1715             }
1717             if ($sco->prereq) {
1718                 if ($sco->scormtype == 'sco') {
1719                     $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
1720                 }
1721             } else {
1722                 if ($sco->scormtype == 'sco') {
1723                     $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
1724                 }
1725             }
1727             if (!empty($sco->children)) {
1728                 $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg, $organizationsco, true, $level, $tocmenus);
1729             }
1730         }
1731     }
1733     return $tocmenus;
1736 function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal', $attempt='', $play=false, $tocheader=false) {
1737     global $CFG, $DB, $OUTPUT;
1739     if (empty($attempt)) {
1740         $attempt = scorm_get_attempt_count($user->id, $scorm);
1741     }
1743     $result = new stdClass();
1744     $organizationsco = null;
1746     if ($tocheader) {
1747         $result->toc = "<div id=\"scorm_layout\">\n";
1748         $result->toc .= "<div id=\"scorm_toc\">\n";
1749         $result->toc .= "<div id=\"scorm_tree\">\n";
1750     }
1752     if (!empty($currentorg)) {
1753         $organizationsco = $DB->get_record('scorm_scoes', array('scorm'=>$scorm->id, 'identifier'=>$currentorg));
1754         if (!empty($organizationsco->title)) {
1755             if ($play) {
1756                 $result->toctitle = $organizationsco->title;
1757             }
1758         }
1759     }
1761     $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
1763     $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid, $toclink, $currentorg, $attempt, $play, $organizationsco, false);
1765     if ($tocheader) {
1766         $result->toc .= $treeview->toc;
1767     } else {
1768         $result->toc = $treeview->toc;
1769     }
1771     if (!empty($scoes['scoid'])) {
1772         $scoid = $scoes['scoid'];
1773     }
1775     if (empty($scoid)) {
1776         $result->sco = $scoes['scoes'][0]->children[0];
1777     } else {
1778         $result->sco = scorm_get_sco($scoid);
1779     }
1781     if ($scorm->hidetoc == SCORM_TOC_POPUP) {
1782         $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $currentorg, $organizationsco);
1784         $modestr = '';
1785         if ($mode == 'browse') {
1786             $modestr = '&amp;mode='.$mode;
1787         }
1789         $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
1790         $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
1791     }
1793     $result->prerequisites = $treeview->prerequisites;
1794     $result->incomplete = $treeview->incomplete;
1795     $result->attemptleft = $treeview->attemptleft;
1797     if ($tocheader) {
1798         $result->toc .= "</div></div></div>\n";
1799         $result->toc .= "<div id=\"scorm_navpanel\"></div>\n";
1800     }
1802     return $result;
1805 function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
1806     if (is_object($scoes)) {
1807         $sco = $scoes;
1808         if (isset($sco->url)) {
1809             $adlnav[$sco->id]['identifier'] = $sco->identifier;
1810             $adlnav[$sco->id]['launch'] = $sco->launch;
1811             $adlnav[$sco->id]['title'] = $sco->title;
1812             $adlnav[$sco->id]['url'] = $sco->url;
1813             $adlnav[$sco->id]['parent'] = $sco->parent;
1814             if (isset($sco->choice)) {
1815                 $adlnav[$sco->id]['choice'] = $sco->choice;
1816             }
1817             if (isset($sco->flow)) {
1818                 $adlnav[$sco->id]['flow'] = $sco->flow;
1819             } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
1820                 $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
1821             }
1822             if (isset($sco->isvisible)) {
1823                 $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
1824             }
1825             if (isset($sco->parameters)) {
1826                 $adlnav[$sco->id]['parameters'] = $sco->parameters;
1827             }
1828             if (isset($sco->hidecontinue)) {
1829                 $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
1830             }
1831             if (isset($sco->hideprevious)) {
1832                 $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
1833             }
1834             if (isset($sco->hidesuspendall)) {
1835                 $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
1836             }
1837             if (!empty($parentscoid)) {
1838                 $adlnav[$sco->id]['parentscoid'] = $parentscoid;
1839             }
1840             if (isset($adlnav['prevscoid'])) {
1841                 $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
1842                 $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
1843                 if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
1844                     $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
1845                     $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
1846                 }
1847             }
1848             $adlnav['prevscoid'] = $sco->id;
1849             $adlnav['prevparent'] = $sco->parent;
1850         }
1851         if (isset($sco->children)) {
1852             foreach ($sco->children as $children) {
1853                 scorm_get_adlnav_json($children, $adlnav, $sco->id);
1854             }
1855         }
1856     } else {
1857         foreach ($scoes as $sco) {
1858             scorm_get_adlnav_json ($sco, $adlnav);
1859         }
1860         unset($adlnav['prevscoid']);
1861         unset($adlnav['prevparent']);
1862     }
1863     return json_encode($adlnav);
1866 /**
1867  * Check for the availability of a resource by URL.
1868  *
1869  * Check is performed using an HTTP HEAD call.
1870  *
1871  * @param $url string A valid URL
1872  * @return bool|string True if no issue is found. The error string message, otherwise
1873  */
1874 function scorm_check_url($url) {
1875     $curl = new curl;
1877     if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1878         // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
1879         $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
1880     }
1881     $cmsg = $curl->head($url);
1882     $info = $curl->get_info();
1883     if (empty($info['http_code']) || $info['http_code'] != 200) {
1884         return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
1885     }
1887     return true;