SCORM MDL-22951 New player for SCORM fixes major regression that prevents some SCORM...
[moodle.git] / mod / scorm / datamodels / scorm_12.js.php
1 <?php
2     require_once($CFG->dirroot.'/mod/scorm/locallib.php');
4     if (isset($userdata->status)) {
5         if ($userdata->status == '') {
6             $userdata->entry = 'ab-initio';
7         } else {
8             if (isset($userdata->{'cmi.core.exit'}) && ($userdata->{'cmi.core.exit'} == 'suspend')) {
9                 $userdata->entry = 'resume';
10             } else {
11                 $userdata->entry = '';
12             }
13         }
14     }
15     if (!isset($currentorg)) {
16         $currentorg = '';
17     }
18 ?>
19 //
20 // SCORM 1.2 API Implementation
21 //
22 function SCORMapi1_2() {
23     // Standard Data Type Definition
24     CMIString256 = '^[\\u0000-\\uffff]{0,255}$';
25     CMIString4096 = '^[\\u0000-\\uffff]{0,4096}$';
26     CMITime = '^([0-2]{1}[0-9]{1}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1})(\.[0-9]{1,2})?$';
27     CMITimespan = '^([0-9]{2,4}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,2})?$';
28     CMIInteger = '^\\d+$';
29     CMISInteger = '^-?([0-9]+)$';
30     CMIDecimal = '^-?([0-9]{0,3})(\.[0-9]{1,2})?$';
31     CMIIdentifier = '^[\\u0021-\\u007E]{0,255}$';
32     CMIFeedback = CMIString256; // This must be redefined
33     CMIIndex = '[._](\\d+).';
34     // Vocabulary Data Type Definition
35     CMIStatus = '^passed$|^completed$|^failed$|^incomplete$|^browsed$';
36     CMIStatus2 = '^passed$|^completed$|^failed$|^incomplete$|^browsed$|^not attempted$';
37     CMIExit = '^time-out$|^suspend$|^logout$|^$';
38     CMIType = '^true-false$|^choice$|^fill-in$|^matching$|^performance$|^sequencing$|^likert$|^numeric$';
39     CMIResult = '^correct$|^wrong$|^unanticipated$|^neutral$|^([0-9]{0,3})?(\.[0-9]{1,2})?$';
40     NAVEvent = '^previous$|^continue$';
41     // Children lists
42     cmi_children = 'core, suspend_data, launch_data, comments, objectives, student_data, student_preference, interactions';
43     core_children = 'student_id, student_name, lesson_location, credit, lesson_status, entry, score, total_time, lesson_mode, exit, session_time';
44     score_children = 'raw, min, max';
45     comments_children = 'content, location, time';
46     objectives_children = 'id, score, status';
47     correct_responses_children = 'pattern';
48     student_data_children = 'mastery_score, max_time_allowed, time_limit_action';
49     student_preference_children = 'audio, language, speed, text';
50     interactions_children = 'id, objectives, time, type, correct_responses, weighting, student_response, result, latency';
51     // Data ranges
52     score_range = '0#100';
53     audio_range = '-1#100';
54     speed_range = '-100#100';
55     weighting_range = '-100#100';
56     text_range = '-1#1';
57     // The SCORM 1.2 data model
58     var datamodel =  {
59         'cmi._children':{'defaultvalue':cmi_children, 'mod':'r', 'writeerror':'402'},
60         'cmi._version':{'defaultvalue':'3.4', 'mod':'r', 'writeerror':'402'},
61         'cmi.core._children':{'defaultvalue':core_children, 'mod':'r', 'writeerror':'402'},
62         'cmi.core.student_id':{'defaultvalue':'<?php echo $userdata->student_id ?>', 'mod':'r', 'writeerror':'403'},
63         'cmi.core.student_name':{'defaultvalue':'<?php echo $userdata->student_name ?>', 'mod':'r', 'writeerror':'403'},
64         'cmi.core.lesson_location':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.lesson_location'})?$userdata->{'cmi.core.lesson_location'}:'' ?>', 'format':CMIString256, 'mod':'rw', 'writeerror':'405'},
65         'cmi.core.credit':{'defaultvalue':'<?php echo $userdata->credit ?>', 'mod':'r', 'writeerror':'403'},
66         'cmi.core.lesson_status':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.lesson_status'})?$userdata->{'cmi.core.lesson_status'}:'' ?>', 'format':CMIStatus, 'mod':'rw', 'writeerror':'405'},
67         'cmi.core.entry':{'defaultvalue':'<?php echo $userdata->entry ?>', 'mod':'r', 'writeerror':'403'},
68         'cmi.core.score._children':{'defaultvalue':score_children, 'mod':'r', 'writeerror':'402'},
69         'cmi.core.score.raw':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.score.raw'})?$userdata->{'cmi.core.score.raw'}:'' ?>', 'format':CMIDecimal, 'range':score_range, 'mod':'rw', 'writeerror':'405'},
70         'cmi.core.score.max':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.score.max'})?$userdata->{'cmi.core.score.max'}:'' ?>', 'format':CMIDecimal, 'range':score_range, 'mod':'rw', 'writeerror':'405'},
71         'cmi.core.score.min':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.score.min'})?$userdata->{'cmi.core.score.min'}:'' ?>', 'format':CMIDecimal, 'range':score_range, 'mod':'rw', 'writeerror':'405'},
72         'cmi.core.total_time':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.total_time'})?$userdata->{'cmi.core.total_time'}:'00:00:00' ?>', 'mod':'r', 'writeerror':'403'},
73         'cmi.core.lesson_mode':{'defaultvalue':'<?php echo $userdata->mode ?>', 'mod':'r', 'writeerror':'403'},
74         'cmi.core.exit':{'defaultvalue':'<?php echo isset($userdata->{'cmi.core.exit'})?$userdata->{'cmi.core.exit'}:'' ?>', 'format':CMIExit, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
75         'cmi.core.session_time':{'format':CMITimespan, 'mod':'w', 'defaultvalue':'00:00:00', 'readerror':'404', 'writeerror':'405'},
76         'cmi.suspend_data':{'defaultvalue':'<?php echo isset($userdata->{'cmi.suspend_data'})?$userdata->{'cmi.suspend_data'}:'' ?>', 'format':CMIString4096, 'mod':'rw', 'writeerror':'405'},
77         'cmi.launch_data':{'defaultvalue':'<?php echo isset($userdata->datafromlms)?$userdata->datafromlms:'' ?>', 'mod':'r', 'writeerror':'403'},
78         'cmi.comments':{'defaultvalue':'<?php echo isset($userdata->{'cmi.comments'})?$userdata->{'cmi.comments'}:'' ?>', 'format':CMIString4096, 'mod':'rw', 'writeerror':'405'},
79         // deprecated evaluation attributes
80         'cmi.evaluation.comments._count':{'defaultvalue':'0', 'mod':'r', 'writeerror':'402'},
81         'cmi.evaluation.comments._children':{'defaultvalue':comments_children, 'mod':'r', 'writeerror':'402'},
82         'cmi.evaluation.comments.n.content':{'defaultvalue':'', 'pattern':CMIIndex, 'format':CMIString256, 'mod':'rw', 'writeerror':'405'},
83         'cmi.evaluation.comments.n.location':{'defaultvalue':'', 'pattern':CMIIndex, 'format':CMIString256, 'mod':'rw', 'writeerror':'405'},
84         'cmi.evaluation.comments.n.time':{'defaultvalue':'', 'pattern':CMIIndex, 'format':CMITime, 'mod':'rw', 'writeerror':'405'},
85         'cmi.comments_from_lms':{'mod':'r', 'writeerror':'403'},
86         'cmi.objectives._children':{'defaultvalue':objectives_children, 'mod':'r', 'writeerror':'402'},
87         'cmi.objectives._count':{'mod':'r', 'defaultvalue':'0', 'writeerror':'402'},
88         'cmi.objectives.n.id':{'pattern':CMIIndex, 'format':CMIIdentifier, 'mod':'rw', 'writeerror':'405'},
89         'cmi.objectives.n.score._children':{'pattern':CMIIndex, 'mod':'r', 'writeerror':'402'},
90         'cmi.objectives.n.score.raw':{'defaultvalue':'', 'pattern':CMIIndex, 'format':CMIDecimal, 'range':score_range, 'mod':'rw', 'writeerror':'405'},
91         'cmi.objectives.n.score.min':{'defaultvalue':'', 'pattern':CMIIndex, 'format':CMIDecimal, 'range':score_range, 'mod':'rw', 'writeerror':'405'},
92         'cmi.objectives.n.score.max':{'defaultvalue':'', 'pattern':CMIIndex, 'format':CMIDecimal, 'range':score_range, 'mod':'rw', 'writeerror':'405'},
93         'cmi.objectives.n.status':{'pattern':CMIIndex, 'format':CMIStatus2, 'mod':'rw', 'writeerror':'405'},
94         'cmi.student_data._children':{'defaultvalue':student_data_children, 'mod':'r', 'writeerror':'402'},
95         'cmi.student_data.mastery_score':{'defaultvalue':'<?php echo isset($userdata->masteryscore)?$userdata->masteryscore:'' ?>', 'mod':'r', 'writeerror':'403'},
96         'cmi.student_data.max_time_allowed':{'defaultvalue':'<?php echo isset($userdata->maxtimeallowed)?$userdata->maxtimeallowed:'' ?>', 'mod':'r', 'writeerror':'403'},
97         'cmi.student_data.time_limit_action':{'defaultvalue':'<?php echo isset($userdata->timelimitaction)?$userdata->timelimitaction:'' ?>', 'mod':'r', 'writeerror':'403'},
98         'cmi.student_preference._children':{'defaultvalue':student_preference_children, 'mod':'r', 'writeerror':'402'},
99         'cmi.student_preference.audio':{'defaultvalue':'0', 'format':CMISInteger, 'range':audio_range, 'mod':'rw', 'writeerror':'405'},
100         'cmi.student_preference.language':{'defaultvalue':'', 'format':CMIString256, 'mod':'rw', 'writeerror':'405'},
101         'cmi.student_preference.speed':{'defaultvalue':'0', 'format':CMISInteger, 'range':speed_range, 'mod':'rw', 'writeerror':'405'},
102         'cmi.student_preference.text':{'defaultvalue':'0', 'format':CMISInteger, 'range':text_range, 'mod':'rw', 'writeerror':'405'},
103         'cmi.interactions._children':{'defaultvalue':interactions_children, 'mod':'r', 'writeerror':'402'},
104         'cmi.interactions._count':{'mod':'r', 'defaultvalue':'0', 'writeerror':'402'},
105         'cmi.interactions.n.id':{'pattern':CMIIndex, 'format':CMIIdentifier, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
106         'cmi.interactions.n.objectives._count':{'pattern':CMIIndex, 'mod':'r', 'defaultvalue':'0', 'writeerror':'402'},
107         'cmi.interactions.n.objectives.n.id':{'pattern':CMIIndex, 'format':CMIIdentifier, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
108         'cmi.interactions.n.time':{'pattern':CMIIndex, 'format':CMITime, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
109         'cmi.interactions.n.type':{'pattern':CMIIndex, 'format':CMIType, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
110         'cmi.interactions.n.correct_responses._count':{'pattern':CMIIndex, 'mod':'r', 'defaultvalue':'0', 'writeerror':'402'},
111         'cmi.interactions.n.correct_responses.n.pattern':{'pattern':CMIIndex, 'format':CMIFeedback, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
112         'cmi.interactions.n.weighting':{'pattern':CMIIndex, 'format':CMIDecimal, 'range':weighting_range, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
113         'cmi.interactions.n.student_response':{'pattern':CMIIndex, 'format':CMIFeedback, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
114         'cmi.interactions.n.result':{'pattern':CMIIndex, 'format':CMIResult, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
115         'cmi.interactions.n.latency':{'pattern':CMIIndex, 'format':CMITimespan, 'mod':'w', 'readerror':'404', 'writeerror':'405'},
116         'nav.event':{'defaultvalue':'', 'format':NAVEvent, 'mod':'w', 'readerror':'404', 'writeerror':'405'}
117     };
118     //
119     // Datamodel inizialization
120     //
121     var cmi = new Object();
122         cmi.core = new Object();
123         cmi.core.score = new Object();
124         cmi.objectives = new Object();
125         cmi.student_data = new Object();
126         cmi.student_preference = new Object();
127         cmi.interactions = new Object();
128         // deprecated evaluation attributes
129         cmi.evaluation = new Object();
130         cmi.evaluation.comments = new Object();
132     // Navigation Object
133     var nav = new Object();
135     for (element in datamodel) {
136         if (element.match(/\.n\./) == null) {
137             if ((typeof eval('datamodel["'+element+'"].defaultvalue')) != 'undefined') {
138                 eval(element+' = datamodel["'+element+'"].defaultvalue;');
139             } else {
140                 eval(element+' = "";');
141             }
142         }
143     }
145 <?php
146      // reconstitute objectives
147     scorm_reconstitute_array_element($scorm->version, $userdata, 'cmi.objectives', array('score'));
148     scorm_reconstitute_array_element($scorm->version, $userdata, 'cmi.interactions', array('objectives', 'correct_responses'));
149     ?>
151     if (cmi.core.lesson_status == '') {
152         cmi.core.lesson_status = 'not attempted';
153     }
155     //
156     // API Methods definition
157     //
158     var Initialized = false;
160     function LMSInitialize (param) {
161         errorCode = "0";
162         if (param == "") {
163             if (!Initialized) {
164                 Initialized = true;
165                 errorCode = "0";
166                 <?php
167                     if (scorm_debugging($scorm)) {
168                         //echo 'alert("Initialized SCORM 1.2");';
169                         echo 'LogAPICall("LMSInitialize", param, "", errorCode);';
170                     }
171                 ?>
172                 return "true";
173             } else {
174                 errorCode = "101";
175             }
176         } else {
177             errorCode = "201";
178         }
179         <?php
180             if (scorm_debugging($scorm)) {
181                 echo 'LogAPICall("LMSInitialize", param, "", errorCode);';
182             }
183         ?>
184         return "false";
185     }
188     this.connectPrereqCallback = {
190         success: function(o) {
191             scorm_tree_node = YAHOO.widget.TreeView.getTree('scorm_tree');
192             if (o.responseText !== undefined) {
193                 if (scorm_tree_node && o.responseText) {
194                     var hnode = scorm_tree_node.getHighlightedNode();
195                     var hidx = null;
196                     if (hnode) {
197                         hidx = hnode.index + scorm_tree_node.getNodeCount();
198                     }
199                     // all gone
200                     var root_node = scorm_tree_node.getRoot();
201                         scorm_tree_node.removeNode(root_node.children[0]);
202                     }
203                     // make sure the temporary tree element is not there
204                     var el_old_tree = document.getElementById('scormtree123');
205                     if (el_old_tree) {
206                         el_old_tree.parentNode.removeChild(el_old_tree);
207                     }
208                     var el_new_tree = document.createElement('div');
209                     var pagecontent = document.getElementById("page-content");
210                     el_new_tree.setAttribute('id','scormtree123');
211                     el_new_tree.innerHTML = o.responseText;
212                     // make sure it doesnt show
213                     el_new_tree.style.display = 'none';
214                     pagecontent.appendChild(el_new_tree)
215                     // ignore the first level element as this is the title
216                     scorm_tree_node.buildTreeFromMarkup(el_new_tree.firstChild.firstChild);
217                     var el = document.getElementById('scormtree123');
218                     el.parentNode.removeChild(el);
219                     scorm_tree_node.expandAll();
220                     scorm_tree_node.render();
221                     if (hidx != null) {
222                         hnode = scorm_tree_node.getNodeByIndex(hidx);
223                         if (hnode) {
224                             hnode.highlight();
225                             hnode.focus();
226                         }
227                     }
228                 }
229         },
231         failure: function(o) {
232             // do some sort of error handling
233             var sURL = "<?php echo $CFG->wwwroot; ?>" + "/mod/scorm/prereqs.php?a=<?php echo $scorm->id ?>&scoid=<?php echo $scoid ?>&attempt=<?php echo $attempt ?>&mode=<?php echo $mode ?>&currentorg=<?php echo $currentorg ?>&sesskey=<?php echo sesskey(); ?>";
234             alert('Prerequisites update failed - must restart SCORM player');
235             window.location.href = sURL;
236         }
238     };
241     function LMSFinish (param) {
242         errorCode = "0";
243         if (param == "") {
244             if (Initialized) {
245                 Initialized = false;
246                 result = StoreData(cmi,true);
247                 // trigger TOC update
248                 //alert('trigger TOC update');
249                 var sURL = "<?php echo $CFG->wwwroot; ?>" + "/mod/scorm/prereqs.php?a=<?php echo $scorm->id ?>&scoid=<?php echo $scoid ?>&attempt=<?php echo $attempt ?>&mode=<?php echo $mode ?>&currentorg=<?php echo $currentorg ?>&sesskey=<?php echo sesskey(); ?>";
250                 YAHOO.util.Connect.asyncRequest('GET', sURL, this.connectPrereqCallback, null);
251                 if (nav.event != '') {
252                     if (nav.event == 'continue') {
253                         setTimeout('top.document.location=top.next;',500);
254                     } else {
255                         setTimeout('top.document.location=top.prev;',500);
256                     }
257                 } else {
258                     if (<?php echo $scorm->auto ?> == 1) {
259                         setTimeout('top.document.location=top.next;',500);
260                     }
261                 }
262                 <?php
263                     if (scorm_debugging($scorm)) {
264                         echo 'LogAPICall("LMSFinish", "AJAXResult", result, 0);';
265                     }
266                 ?>
267                 result = ('true' == result) ? 'true' : 'false';
268                 errorCode = (result == 'true')? '0' : '101';
269                 <?php
270                     if (scorm_debugging($scorm)) {
271                         //echo 'alert("Finished SCORM 1.2");';
272                         echo 'LogAPICall("LMSFinish", "result", result, 0);';
273                         echo 'LogAPICall("LMSFinish", param, "", 0);';
274                     }
275                 ?>
276                 return result;
277             } else {
278                 errorCode = "301";
279             }
280         } else {
281             errorCode = "201";
282         }
283         <?php
284             if (scorm_debugging($scorm)) {
285                 echo 'LogAPICall("LMSFinish", param, "", errorCode);';
286             }
287         ?>
288         return "false";
289     }
291     function LMSGetValue (element) {
292         errorCode = "0";
293         if (Initialized) {
294             if (element !="") {
295                 expression = new RegExp(CMIIndex,'g');
296                 elementmodel = String(element).replace(expression,'.n.');
297                 if ((typeof eval('datamodel["'+elementmodel+'"]')) != "undefined") {
298                     if (eval('datamodel["'+elementmodel+'"].mod') != 'w') {
299                         element = String(element).replace(expression, "_$1.");
300                         elementIndexes = element.split('.');
301                         subelement = 'cmi';
302                         i = 1;
303                         while ((i < elementIndexes.length) && (typeof eval(subelement) != "undefined")) {
304                             subelement += '.'+elementIndexes[i++];
305                         }
306                             if (subelement == element) {
307                             errorCode = "0";
308                             <?php
309                                 if (scorm_debugging($scorm)) {
310                                    //echo 'alert(element+": "+eval(element));';
311                                     echo 'LogAPICall("LMSGetValue", element, eval(element), 0);';
312                                 }
313                             ?>
314                             return eval(element);
315                         } else {
316                             errorCode = "0"; // Need to check if it is the right errorCode
317                         }
318                     } else {
319                         errorCode = eval('datamodel["'+elementmodel+'"].readerror');
320                     }
321                 } else {
322                     childrenstr = '._children';
323                     countstr = '._count';
324                     if (elementmodel.substr(elementmodel.length-childrenstr.length,elementmodel.length) == childrenstr) {
325                         parentmodel = elementmodel.substr(0,elementmodel.length-childrenstr.length);
326                         if ((typeof eval('datamodel["'+parentmodel+'"]')) != "undefined") {
327                             errorCode = "202";
328                         } else {
329                             errorCode = "201";
330                         }
331                     } else if (elementmodel.substr(elementmodel.length-countstr.length,elementmodel.length) == countstr) {
332                         parentmodel = elementmodel.substr(0,elementmodel.length-countstr.length);
333                         if ((typeof eval('datamodel["'+parentmodel+'"]')) != "undefined") {
334                             errorCode = "203";
335                         } else {
336                             errorCode = "201";
337                         }
338                     } else {
339                         errorCode = "201";
340                     }
341                 }
342             } else {
343                 errorCode = "201";
344             }
345         } else {
346             errorCode = "301";
347         }
348         <?php
349             if (scorm_debugging($scorm)) {
350                 echo 'LogAPICall("LMSGetValue", element, "", errorCode);';
351             }
352         ?>
353         return "";
354     }
356     function LMSSetValue (element,value) {
357         errorCode = "0";
358         if (Initialized) {
359             if (element != "") {
360                 expression = new RegExp(CMIIndex,'g');
361                 elementmodel = String(element).replace(expression,'.n.');
362                 if ((typeof eval('datamodel["'+elementmodel+'"]')) != "undefined") {
363                     if (eval('datamodel["'+elementmodel+'"].mod') != 'r') {
364                         expression = new RegExp(eval('datamodel["'+elementmodel+'"].format'));
365                         value = value+'';
366                         matches = value.match(expression);
367                         if (matches != null) {
368                             //Create dynamic data model element
369                             if (element != elementmodel) {
370                                 elementIndexes = element.split('.');
371                                 subelement = 'cmi';
372                                 for (i=1;i < elementIndexes.length-1;i++) {
373                                     elementIndex = elementIndexes[i];
374                                     if (elementIndexes[i+1].match(/^\d+$/)) {
375                                         if ((typeof eval(subelement+'.'+elementIndex)) == "undefined") {
376                                             eval(subelement+'.'+elementIndex+' = new Object();');
377                                             eval(subelement+'.'+elementIndex+'._count = 0;');
378                                         }
379                                         if (elementIndexes[i+1] == eval(subelement+'.'+elementIndex+'._count')) {
380                                             eval(subelement+'.'+elementIndex+'._count++;');
381                                         }
382                                         if (elementIndexes[i+1] > eval(subelement+'.'+elementIndex+'._count')) {
383                                             errorCode = "201";
384                                         }
385                                         subelement = subelement.concat('.'+elementIndex+'_'+elementIndexes[i+1]);
386                                         i++;
387                                     } else {
388                                         subelement = subelement.concat('.'+elementIndex);
389                                     }
390                                     if ((typeof eval(subelement)) == "undefined") {
391                                         eval(subelement+' = new Object();');
392                                         if (subelement.substr(0,14) == 'cmi.objectives') {
393                                             eval(subelement+'.score = new Object();');
394                                             eval(subelement+'.score._children = score_children;');
395                                             eval(subelement+'.score.raw = "";');
396                                             eval(subelement+'.score.min = "";');
397                                             eval(subelement+'.score.max = "";');
398                                         }
399                                         if (subelement.substr(0,16) == 'cmi.interactions') {
400                                             eval(subelement+'.objectives = new Object();');
401                                             eval(subelement+'.objectives._count = 0;');
402                                             eval(subelement+'.correct_responses = new Object();');
403                                             eval(subelement+'.correct_responses._count = 0;');
404                                         }
405                                     }
406                                 }
407                                 element = subelement.concat('.'+elementIndexes[elementIndexes.length-1]);
408                             }
409                             //Store data
410                             if (errorCode == "0") {
411                                 if ((typeof eval('datamodel["'+elementmodel+'"].range')) != "undefined") {
412                                     range = eval('datamodel["'+elementmodel+'"].range');
413                                     ranges = range.split('#');
414                                     value = value*1.0;
415                                     if ((value >= ranges[0]) && (value <= ranges[1])) {
416                                         eval(element+'=value;');
417                                         errorCode = "0";
418                                         <?php
419                                             if (scorm_debugging($scorm)) {
420                                                 echo 'LogAPICall("LMSSetValue", element, value, errorCode);';
421                                                 //echo 'alert(element+":= "+value);';
422                                             }
423                                         ?>
424                                         return "true";
425                                     } else {
426                                         errorCode = eval('datamodel["'+elementmodel+'"].writeerror');
427                                     }
428                                 } else {
429                                     if (element == 'cmi.comments') {
430                                         cmi.comments = cmi.comments + value;
431                                     } else {
432                                         eval(element+'=value;');
433                                     }
434                                     errorCode = "0";
435                                     <?php
436                                         if (scorm_debugging($scorm)) {
437                                             echo 'LogAPICall("LMSSetValue", element, value, errorCode);';
438                                             //echo 'alert(element+":= "+value);';
439                                         }
440                                     ?>
441                                     return "true";
442                                 }
443                             }
444                         } else {
445                             errorCode = eval('datamodel["'+elementmodel+'"].writeerror');
446                         }
447                     } else {
448                         errorCode = eval('datamodel["'+elementmodel+'"].writeerror');
449                     }
450                 } else {
451                     errorCode = "201"
452                 }
453             } else {
454                 errorCode = "201";
455             }
456         } else {
457             errorCode = "301";
458         }
459        <?php
460         if (scorm_debugging($scorm)) {
461             echo 'LogAPICall("LMSSetValue", element, value, errorCode);';
462         }
463         ?>
464         return "false";
465     }
467     function LMSCommit (param) {
468         errorCode = "0";
469         if (param == "") {
470             if (Initialized) {
471                 result = StoreData(cmi,false);
472                 <?php
473                     if (scorm_debugging($scorm)) {
474                         echo 'LogAPICall("Commit", param, "", 0);';
475                         //echo 'alert("Data Commited");';
476                     }
477                 ?>
478                 <?php
479                     if (scorm_debugging($scorm)) {
480                         echo 'LogAPICall("LMSCommit", "AJAXResult", result, 0);';
481                     }
482                 ?>
483                 result = ('true' == result) ? 'true' : 'false';
484                 errorCode = (result ==' true')? '0' : '101';
485                 <?php 
486                     if (scorm_debugging($scorm)) {
487                         //echo 'alert("Finished SCORM 1.2");';
488                         echo 'LogAPICall("LMSCommit", "result", result, 0);';
489                         echo 'LogAPICall("LMSCommit", param, "", 0);';
490                     }
491                 ?>
492                 return result;
493             } else {
494                 errorCode = "301";
495             }
496         } else {
497             errorCode = "201";
498         }
499         <?php
500             if (scorm_debugging($scorm)) {
501                 echo 'LogAPICall("LMSCommit", param, "", 0);';
502             }
503         ?>
504         return "false";
505     }
507     function LMSGetLastError () {
508      <?php
509         if (scorm_debugging($scorm)) {
510             echo 'LogAPICall("LMSGetLastError", "", "", errorCode);';
511         }
512     ?>
513         return errorCode;
514     }
516     function LMSGetErrorString (param) {
517         if (param != "") {
518             var errorString = new Array();
519             errorString["0"] = "No error";
520             errorString["101"] = "General exception";
521             errorString["201"] = "Invalid argument error";
522             errorString["202"] = "Element cannot have children";
523             errorString["203"] = "Element not an array - cannot have count";
524             errorString["301"] = "Not initialized";
525             errorString["401"] = "Not implemented error";
526             errorString["402"] = "Invalid set value, element is a keyword";
527             errorString["403"] = "Element is read only";
528             errorString["404"] = "Element is write only";
529             errorString["405"] = "Incorrect data type";
530             <?php
531             if (scorm_debugging($scorm)) {
532                 echo 'LogAPICall("LMSGetErrorString", param,  errorString[param], 0);';
533             }
534              ?>
535             return errorString[param];
536         } else {
537            <?php
538             if (scorm_debugging($scorm)) {
539                 echo 'LogAPICall("LMSGetErrorString", param,  "No error string found!", 0);';
540             }
541              ?>
542            return "";
543         }
544     }
546     function LMSGetDiagnostic (param) {
547         if (param == "") {
548             param = errorCode;
549         }
550         <?php
551             if (scorm_debugging($scorm)) {
552                 echo 'LogAPICall("LMSGetDiagnostic", param, param, 0);';
553             }
554         ?>
555         return param;
556     }
558     function AddTime (first, second) {
559         var sFirst = first.split(":");
560         var sSecond = second.split(":");
561         var cFirst = sFirst[2].split(".");
562         var cSecond = sSecond[2].split(".");
563         var change = 0;
565         FirstCents = 0;  //Cents
566         if (cFirst.length > 1) {
567             FirstCents = parseInt(cFirst[1],10);
568         }
569         SecondCents = 0;
570         if (cSecond.length > 1) {
571             SecondCents = parseInt(cSecond[1],10);
572         }
573         var cents = FirstCents + SecondCents;
574         change = Math.floor(cents / 100);
575         cents = cents - (change * 100);
576         if (Math.floor(cents) < 10) {
577             cents = "0" + cents.toString();
578         }
580         var secs = parseInt(cFirst[0],10)+parseInt(cSecond[0],10)+change;  //Seconds
581         change = Math.floor(secs / 60);
582         secs = secs - (change * 60);
583         if (Math.floor(secs) < 10) {
584             secs = "0" + secs.toString();
585         }
587         mins = parseInt(sFirst[1],10)+parseInt(sSecond[1],10)+change;   //Minutes
588         change = Math.floor(mins / 60);
589         mins = mins - (change * 60);
590         if (mins < 10) {
591             mins = "0" + mins.toString();
592         }
594         hours = parseInt(sFirst[0],10)+parseInt(sSecond[0],10)+change;  //Hours
595         if (hours < 10) {
596             hours = "0" + hours.toString();
597         }
599         if (cents != '0') {
600             return hours + ":" + mins + ":" + secs + '.' + cents;
601         } else {
602             return hours + ":" + mins + ":" + secs;
603         }
604     }
606     function TotalTime() {
607         total_time = AddTime(cmi.core.total_time, cmi.core.session_time);
608         return '&'+underscore('cmi.core.total_time')+'='+encodeURIComponent(total_time);
609     }
611     function CollectData(data,parent) {
612         var datastring = '';
613         for (property in data) {
614             if (typeof data[property] == 'object') {
615                 datastring += CollectData(data[property],parent+'.'+property);
616             } else {
617                 element = parent+'.'+property;
618                 expression = new RegExp(CMIIndex,'g');
619                 elementmodel = String(element).replace(expression,'.n.');
620                 if (elementmodel != "cmi.core.session_time") {
621                     if ((typeof eval('datamodel["'+elementmodel+'"]')) != "undefined") {
622                         if (eval('datamodel["'+elementmodel+'"].mod') != 'r') {
623                             elementstring = '&'+underscore(element)+'='+encodeURIComponent(data[property]);
624                             if ((typeof eval('datamodel["'+elementmodel+'"].defaultvalue')) != "undefined") {
625                                 if (eval('datamodel["'+elementmodel+'"].defaultvalue') != data[property] || eval('typeof(datamodel["'+elementmodel+'"].defaultvalue)') != typeof(data[property])) {
626                                     datastring += elementstring;
627                                     eval('datamodel["'+elementmodel+'"].defaultvalue=data[property];');
628                                 }
629                             } else {
630                                 datastring += elementstring;
631                                 eval('datamodel["'+elementmodel+'"].defaultvalue=data[property];');
632                             }
633                         }
634                     }
635                 }
636             }
637         }
638         return datastring;
639     }
641     function StoreData(data,storetotaltime) {
642         if (storetotaltime) {
643             if (cmi.core.lesson_status == 'not attempted') {
644                 cmi.core.lesson_status = 'completed';
645             }
646             if (cmi.core.lesson_mode == 'normal') {
647                 if (cmi.core.credit == 'credit') {
648                     if (cmi.student_data.mastery_score != '' && cmi.core.score.raw != '') {
649                         if (parseFloat(cmi.core.score.raw) >= parseFloat(cmi.student_data.mastery_score)) {
650                             cmi.core.lesson_status = 'passed';
651                         } else {
652                             cmi.core.lesson_status = 'failed';
653                         }
654                     }
655                 }
656             }
657             if (cmi.core.lesson_mode == 'browse') {
658                 if (datamodel['cmi.core.lesson_status'].defaultvalue == '' && cmi.core.lesson_status == 'not attempted') {
659                     cmi.core.lesson_status = 'browsed';
660                 }
661             }
662             datastring = CollectData(data,'cmi');
663             datastring += TotalTime();
664         } else {
665             datastring = CollectData(data,'cmi');
666         }
667         datastring += '&attempt=<?php echo $attempt ?>';
668         datastring += '&scoid=<?php echo $scoid ?>';
670         var myRequest = NewHttpReq();
671         //alert('going to:' + "<?php p($CFG->wwwroot) ?>/mod/scorm/datamodel.php" + "id=<?php p($id) ?>&a=<?php p($a) ?>&sesskey=<?php echo sesskey() ?>"+datastring);
672         result = DoRequest(myRequest,"<?php p($CFG->wwwroot) ?>/mod/scorm/datamodel.php","id=<?php p($id) ?>&a=<?php p($a) ?>&sesskey=<?php echo sesskey() ?>"+datastring);
673         results = String(result).split('\n');
674         errorCode = results[1];
675         return results[0];
676     }
678     this.LMSInitialize = LMSInitialize;
679     this.LMSFinish = LMSFinish;
680     this.LMSGetValue = LMSGetValue;
681     this.LMSSetValue = LMSSetValue;
682     this.LMSCommit = LMSCommit;
683     this.LMSGetLastError = LMSGetLastError;
684     this.LMSGetErrorString = LMSGetErrorString;
685     this.LMSGetDiagnostic = LMSGetDiagnostic;
688 var API = new SCORMapi1_2();
690 <?php
691 // pull in the debugging utilities
692 if (scorm_debugging($scorm)) {
693     include_once($CFG->dirroot.'/mod/scorm/datamodels/debug.js.php');
694     echo 'AppendToLog("Moodle SCORM 1.2 API Loaded, Activity: '.$scorm->name.', SCO: '.$sco->identifier.'", 0);';
696  ?>