MDL-34231 SCORM: use correct calculation of attemptsleft
[moodle.git] / mod / scorm / locallib.php
CommitLineData
e5dd8e3b 1<?php
f7b5c6aa
DM
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/>.
f69db63e 16
9528568b 17require_once("$CFG->dirroot/mod/scorm/lib.php");
64f93798 18require_once("$CFG->libdir/filelib.php");
9528568b 19
a30b6819 20/// Constants and settings for module scorm
8aba9cda
DM
21define('SCORM_UPDATE_NEVER', '0');
22define('SCORM_UPDATE_EVERYDAY', '2');
23define('SCORM_UPDATE_EVERYTIME', '3');
a679d64d 24
fece4fd6
DM
25define('SCORM_SKIPVIEW_NEVER', '0');
26define('SCORM_SKIPVIEW_FIRST', '1');
27define('SCORM_SKIPVIEW_ALWAYS', '2');
28
b3659259 29define('SCO_ALL', 0);
30define('SCO_DATA', 1);
31define('SCO_ONLY', 2);
a30b6819 32
33define('GRADESCOES', '0');
34define('GRADEHIGHEST', '1');
35define('GRADEAVERAGE', '2');
36define('GRADESUM', '3');
a30b6819 37
38define('HIGHESTATTEMPT', '0');
39define('AVERAGEATTEMPT', '1');
40define('FIRSTATTEMPT', '2');
41define('LASTATTEMPT', '3');
a30b6819 42
7cc7cf58
DM
43define('TOCJSLINK', 1);
44define('TOCFULLURL', 2);
45
9528568b 46/// Local Library of functions for module scorm
a30b6819 47
64f93798
PS
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 */
53class 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}
67
30fc6e2d 68/**
69 * Returns an array of the popup options for SCORM and each options default value
7554f671 70 *
30fc6e2d 71 * @return array an array of popup options as the key and their defaults as the value
72 */
ca4eda13 73function scorm_get_popup_options_array() {
30fc6e2d 74 global $CFG;
75 $cfg_scorm = get_config('scorm');
7554f671 76
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,
1adc77e6 80 'location'=> isset($cfg_scorm->location) ? $cfg_scorm->location : 0,
7554f671 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);
30fc6e2d 84}
85
86/**
87 * Returns an array of the array of what grade options
7554f671 88 *
30fc6e2d 89 * @return array an array of what grade options
90 */
ca4eda13 91function scorm_get_grade_method_array() {
30fc6e2d 92 return array (GRADESCOES => get_string('gradescoes', 'scorm'),
93 GRADEHIGHEST => get_string('gradehighest', 'scorm'),
94 GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
7554f671 95 GRADESUM => get_string('gradesum', 'scorm'));
30fc6e2d 96}
97
98/**
99 * Returns an array of the array of what grade options
7554f671 100 *
30fc6e2d 101 * @return array an array of what grade options
102 */
ca4eda13 103function scorm_get_what_grade_array() {
30fc6e2d 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'));
108}
109
110/**
111 * Returns an array of the array of skip view options
7554f671 112 *
30fc6e2d 113 * @return array an array of skip view options
114 */
ca4eda13 115function scorm_get_skip_view_array() {
fece4fd6
DM
116 return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
117 SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
118 SCORM_SKIPVIEW_ALWAYS => get_string('always'));
30fc6e2d 119}
120
121/**
122 * Returns an array of the array of hide table of contents options
7554f671 123 *
30fc6e2d 124 * @return array an array of hide table of contents options
125 */
ca4eda13 126function scorm_get_hidetoc_array() {
5f65d37c 127 return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
99da7a95
DM
128 SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
129 SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
130 SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
30fc6e2d 131}
132
133/**
134 * Returns an array of the array of update frequency options
7554f671 135 *
30fc6e2d 136 * @return array an array of update frequency options
137 */
ca4eda13 138function scorm_get_updatefreq_array() {
8aba9cda
DM
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'));
30fc6e2d 142}
143
144/**
145 * Returns an array of the array of popup display options
7554f671 146 *
30fc6e2d 147 * @return array an array of popup display options
148 */
ca4eda13 149function scorm_get_popup_display_array() {
d67eb434 150 return array(0 => get_string('currentwindow', 'scorm'),
30fc6e2d 151 1 => get_string('popup', 'scorm'));
152}
153
154/**
155 * Returns an array of the array of attempt options
7554f671 156 *
30fc6e2d 157 * @return array an array of attempt options
158 */
ca4eda13
DM
159function scorm_get_attempts_array() {
160 $attempts = array(0 => get_string('nolimit', 'scorm'),
161 1 => get_string('attempt1', 'scorm'));
7554f671 162
30fc6e2d 163 for ($i=2; $i<=6; $i++) {
ca4eda13 164 $attempts[$i] = get_string('attemptsx', 'scorm', $i);
30fc6e2d 165 }
7554f671 166
30fc6e2d 167 return $attempts;
168}
9528568b 169/**
170 * Extracts scrom package, sets up all variables.
171 * Called whenever scorm changes
172 * @param object $scorm instance - fields are updated and changes saved into database
173 * @param bool $full force full update if true
174 * @return void
175 */
176function scorm_parse($scorm, $full) {
177 global $CFG, $DB;
30fc6e2d 178 $cfg_scorm = get_config('scorm');
8aee93f1 179
9528568b 180 if (!isset($scorm->cmid)) {
181 $cm = get_coursemodule_from_instance('scorm', $scorm->id);
182 $scorm->cmid = $cm->id;
183 }
184 $context = get_context_instance(CONTEXT_MODULE, $scorm->cmid);
185 $newhash = $scorm->sha1hash;
a30b6819 186
9528568b 187 if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
a30b6819 188
9528568b 189 $fs = get_file_storage();
190 $packagefile = false;
f69db63e 191
9528568b 192 if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
64f93798 193 if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
9528568b 194 $newhash = $packagefile->get_contenthash();
195 } else {
196 $newhash = null;
197 }
198 } else {
30fc6e2d 199 if (!$cfg_scorm->allowtypelocalsync) {
9528568b 200 // sorry - localsync disabled
201 return;
202 }
203 if ($scorm->reference !== '' and (!$full or $scorm->sha1hash !== sha1($scorm->reference))) {
64f93798
PS
204 $fs->delete_area_files($context->id, 'mod_scorm', 'package');
205 $file_record = array('contextid'=>$context->id, 'component'=>'mod_scorm', 'filearea'=>'package', 'itemid'=>0, 'filepath'=>'/');
60b5a2fe 206 if ($packagefile = $fs->create_file_from_url($file_record, $scorm->reference, array('calctimeout' => true))) {
9528568b 207 $newhash = sha1($scorm->reference);
5c1ac70c 208 } else {
9528568b 209 $newhash = null;
5c1ac70c 210 }
f69db63e 211 }
212 }
f69db63e 213
9528568b 214 if ($packagefile) {
215 if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
216 if (strpos($scorm->version, 'SCORM') !== false) {
64f93798 217 if ($fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 218 // no need to update
219 return;
e4aa175a 220 }
9528568b 221 } else if (strpos($scorm->version, 'AICC') !== false) {
222 // TODO: add more sanity checks - something really exists in scorm_content area
223 return;
224 }
225 }
226
227 // now extract files
64f93798 228 $fs->delete_area_files($context->id, 'mod_scorm', 'content');
9528568b 229
230 $packer = get_file_packer('application/zip');
64f93798 231 $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
9528568b 232
233 } else if (!$full) {
234 return;
235 }
236
64f93798 237 if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
9528568b 238 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
239 // SCORM
240 if (!scorm_parse_scorm($scorm, $manifest)) {
241 $scorm->version = 'ERROR';
242 }
243 } else {
244 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
245 // AICC
246 if (!scorm_parse_aicc($scorm)) {
247 $scorm->version = 'ERROR';
248 }
4388bd45 249 $scorm->version = 'AICC';
9528568b 250 }
251
30fc6e2d 252 } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfg_scorm->allowtypeexternal) {
9528568b 253 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
254 // SCORM only, AICC can not be external
255 if (!scorm_parse_scorm($scorm, $scorm->reference)) {
256 $scorm->version = 'ERROR';
257 }
258 $newhash = sha1($scorm->reference);
259
30fc6e2d 260 } else if ($scorm->scormtype === SCORM_TYPE_IMSREPOSITORY and !empty($CFG->repositoryactivate) and $cfg_scorm->allowtypeimsrepository) {
9528568b 261 if (!$full and $scorm->sha1hash === sha1($scorm->reference)) {
262 return;
263 }
264 require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
ca4eda13 265 if (!scorm_parse_scorm($scorm, $CFG->repository.substr($scorm->reference, 1).'/imsmanifest.xml')) {
9528568b 266 $scorm->version = 'ERROR';
267 }
268 $newhash = sha1($scorm->reference);
4388bd45
DM
269 } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfg_scorm->allowtypeexternalaicc) {
270 require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
271 // AICC
272 if (!scorm_parse_aicc($scorm)) {
273 $scorm->version = 'ERROR';
274 }
275 $scorm->version = 'AICC';
e4aa175a 276 } else {
9528568b 277 // sorry, disabled type
278 return;
e4aa175a 279 }
9528568b 280
281 $scorm->revision++;
282 $scorm->sha1hash = $newhash;
283 $DB->update_record('scorm', $scorm);
e4aa175a 284}
285
9528568b 286
2b3447c3 287function scorm_array_search($item, $needle, $haystacks, $strict=false) {
288 if (!empty($haystacks)) {
289 foreach ($haystacks as $key => $element) {
290 if ($strict) {
291 if ($element->{$item} === $needle) {
292 return $key;
293 }
294 } else {
295 if ($element->{$item} == $needle) {
296 return $key;
e4aa175a 297 }
298 }
e4aa175a 299 }
300 }
2b3447c3 301 return false;
e4aa175a 302}
303
2b3447c3 304function scorm_repeater($what, $times) {
305 if ($times <= 0) {
306 return null;
307 }
308 $return = '';
ca4eda13 309 for ($i=0; $i<$times; $i++) {
2b3447c3 310 $return .= $what;
311 }
312 return $return;
313}
e4aa175a 314
2b3447c3 315function scorm_external_link($link) {
ca4eda13 316 // check if a link is external
2b3447c3 317 $result = false;
318 $link = strtolower($link);
ca4eda13 319 if (substr($link, 0, 7) == 'http://') {
2b3447c3 320 $result = true;
ca4eda13 321 } else if (substr($link, 0, 8) == 'https://') {
2b3447c3 322 $result = true;
ca4eda13 323 } else if (substr($link, 0, 4) == 'www.') {
2b3447c3 324 $result = true;
325 }
326 return $result;
e4aa175a 327}
328
b3659259 329/**
ca4eda13
DM
330 * Returns an object containing all datas relative to the given sco ID
331 *
332 * @param integer $id The sco ID
333 * @return mixed (false if sco id does not exists)
334 */
335function scorm_get_sco($id, $what=SCO_ALL) {
bf347041 336 global $DB;
337
338 if ($sco = $DB->get_record('scorm_scoes', array('id'=>$id))) {
b3659259 339 $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
bf347041 340 if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id)))) {
b3659259 341 foreach ($scodatas as $scodata) {
c31f631b 342 $sco->{$scodata->name} = $scodata->value;
b3659259 343 }
bf347041 344 } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$id))))) {
9528568b 345 $sco->parameters = '';
b3659259 346 }
347 return $sco;
348 } else {
349 return false;
350 }
351}
82605bea 352
353/**
ca4eda13
DM
354 * Returns an object (array) containing all the scoes data related to the given sco ID
355 *
356 * @param integer $id The sco ID
357 * @param integer $organisation an organisation ID - defaults to false if not required
358 * @return mixed (false if there are no scoes or an array)
359 */
360function scorm_get_scoes($id, $organisation=false) {
b44c704f 361 global $DB;
362
82605bea 363 $organizationsql = '';
b44c704f 364 $queryarray = array('scorm'=>$id);
82605bea 365 if (!empty($organisation)) {
b44c704f 366 $queryarray['organization'] = $organisation;
82605bea 367 }
b44c704f 368 if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'id ASC')) {
82605bea 369 // drop keys so that it is a simple array as expected
370 $scoes = array_values($scoes);
371 foreach ($scoes as $sco) {
ca4eda13 372 if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid'=>$sco->id))) {
82605bea 373 foreach ($scodatas as $scodata) {
2fd0e9fe 374 $sco->{$scodata->name} = $scodata->value;
82605bea 375 }
376 }
377 }
378 return $scoes;
379 } else {
380 return false;
381 }
382}
383
ca4eda13 384function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false) {
86996ffe 385 global $DB, $CFG;
bf347041 386
e4aa175a 387 $id = null;
6381fa56 388
389 if ($forcecompleted) {
390 //TODO - this could be broadened to encompass SCORM 2004 in future
391 if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
ca4eda13 392 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))) {
6381fa56 393 $value = 'completed';
394 }
395 }
396 if ($element == 'cmi.core.score.raw') {
ca4eda13 397 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))) {
6381fa56 398 if ($tracktest->value == "incomplete") {
399 $tracktest->value = "completed";
ca4eda13 400 $DB->update_record('scorm_scoes_track', $tracktest);
6381fa56 401 }
402 }
403 }
404 }
405
ca4eda13 406 if ($track = $DB->get_record('scorm_scoes_track', array('userid'=>$userid, 'scormid'=>$scormid, 'scoid'=>$scoid, 'attempt'=>$attempt, 'element'=>$element))) {
d1818fdc 407 if ($element != 'x.start.time' ) { //don't update x.start.time - keep the original value.
454f5aee 408 $track->value = $value;
d1818fdc 409 $track->timemodified = time();
ca4eda13 410 $DB->update_record('scorm_scoes_track', $track);
dd88de0e 411 $id = $track->id;
d1818fdc 412 }
e4aa175a 413 } else {
37ca1722 414 $track = new stdClass();
e4aa175a 415 $track->userid = $userid;
416 $track->scormid = $scormid;
417 $track->scoid = $scoid;
418 $track->attempt = $attempt;
419 $track->element = $element;
454f5aee 420 $track->value = $value;
e4aa175a 421 $track->timemodified = time();
ca4eda13 422 $id = $DB->insert_record('scorm_scoes_track', $track);
e4aa175a 423 }
9528568b 424
9528568b 425 if (strstr($element, '.score.raw') ||
94db2749
AB
426 (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
427 && in_array($track->value, array('completed', 'passed')))) {
a0b36684 428 $scorm = $DB->get_record('scorm', array('id' => $scormid));
86996ffe 429 include_once($CFG->dirroot.'/mod/scorm/lib.php');
7f7946fd 430 scorm_update_grades($scorm, $userid);
d23121ab 431 }
9528568b 432
e4aa175a 433 return $id;
434}
435
ca4eda13
DM
436function scorm_get_tracks($scoid, $userid, $attempt='') {
437 /// Gets all tracks of specified sco and user
bf347041 438 global $CFG, $DB;
e4aa175a 439
440 if (empty($attempt)) {
ca4eda13
DM
441 if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id'=>$scoid))) {
442 $attempt = scorm_get_last_attempt($scormid, $userid);
e4aa175a 443 } else {
444 $attempt = 1;
445 }
446 }
ca4eda13 447 if ($tracks = $DB->get_records('scorm_scoes_track', array('userid'=>$userid, 'scoid'=>$scoid, 'attempt'=>$attempt), 'element ASC')) {
39790bd8 448 $usertrack = new stdClass();
e4aa175a 449 $usertrack->userid = $userid;
9528568b 450 $usertrack->scoid = $scoid;
a30b6819 451 // Defined in order to unify scorm1.2 and scorm2004
e4aa175a 452 $usertrack->score_raw = '';
e4aa175a 453 $usertrack->status = '';
e4aa175a 454 $usertrack->total_time = '00:00:00';
455 $usertrack->session_time = '00:00:00';
456 $usertrack->timemodified = 0;
457 foreach ($tracks as $track) {
458 $element = $track->element;
459 $usertrack->{$element} = $track->value;
460 switch ($element) {
f69db63e 461 case 'cmi.core.lesson_status':
462 case 'cmi.completion_status':
463 if ($track->value == 'not attempted') {
464 $track->value = 'notattempted';
9528568b 465 }
f69db63e 466 $usertrack->status = $track->value;
9528568b 467 break;
e4aa175a 468 case 'cmi.core.score.raw':
469 case 'cmi.score.raw':
0d55dd4d 470 $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
9528568b 471 break;
e4aa175a 472 case 'cmi.core.session_time':
473 case 'cmi.session_time':
474 $usertrack->session_time = $track->value;
9528568b 475 break;
e4aa175a 476 case 'cmi.core.total_time':
477 case 'cmi.total_time':
478 $usertrack->total_time = $track->value;
9528568b 479 break;
480 }
e4aa175a 481 if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
482 $usertrack->timemodified = $track->timemodified;
9528568b 483 }
3505e82b 484 }
9528568b 485 if (is_array($usertrack)) {
07b905ae 486 ksort($usertrack);
487 }
e4aa175a 488 return $usertrack;
489 } else {
490 return false;
491 }
492}
493
51c1c4e1 494
495/* Find the start and finsh time for a a given SCO attempt
496 *
497 * @param int $scormid SCORM Id
498 * @param int $scoid SCO Id
499 * @param int $userid User Id
500 * @param int $attemt Attempt Id
501 *
502 * @return object start and finsh time EPOC secods
503 *
504 */
505function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
4454447d 506 global $DB;
51c1c4e1 507
39790bd8 508 $timedata = new stdClass();
51c1c4e1 509 $sql = !empty($scoid) ? "userid=$userid AND scormid=$scormid AND scoid=$scoid AND attempt=$attempt" : "userid=$userid AND scormid=$scormid AND attempt=$attempt";
ca4eda13 510 $tracks = $DB->get_records_select('scorm_scoes_track', "$sql ORDER BY timemodified ASC");
51c1c4e1 511 if ($tracks) {
512 $tracks = array_values($tracks);
513 }
514
c86a91d5 515 if ($tracks) {
51c1c4e1 516 $timedata->start = $tracks[0]->timemodified;
ca4eda13 517 } else {
51c1c4e1 518 $timedata->start = false;
519 }
520 if ($tracks && $track = array_pop($tracks)) {
521 $timedata->finish = $track->timemodified;
ca4eda13 522 } else {
51c1c4e1 523 $timedata->finish = $timedata->start;
524 }
525 return $timedata;
526}
527
528
2b3447c3 529function scorm_get_user_data($userid) {
bf347041 530 global $DB;
ca4eda13
DM
531 /// Gets user info required to display the table of scorm results
532 /// for report.php
e4aa175a 533
629f5021 534 return $DB->get_record('user', array('id'=>$userid), user_picture::fields());
2b3447c3 535}
e4aa175a 536
c0f6b608 537function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
bf347041 538 global $DB;
37ca1722 539 $attemptscore = new stdClass();
a30b6819 540 $attemptscore->scoes = 0;
541 $attemptscore->values = 0;
542 $attemptscore->max = 0;
543 $attemptscore->sum = 0;
544 $attemptscore->lastmodify = 0;
9528568b 545
bf347041 546 if (!$scoes = $DB->get_records('scorm_scoes', array('scorm'=>$scorm->id))) {
ca4eda13 547 return null;
e4aa175a 548 }
e4aa175a 549
9528568b 550 foreach ($scoes as $sco) {
ca4eda13 551 if ($userdata=scorm_get_tracks($sco->id, $userid, $attempt)) {
2b3447c3 552 if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
a30b6819 553 $attemptscore->scoes++;
9528568b 554 }
5c2aa157 555 if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type=='sco' && isset($userdata->score_raw))) {
a30b6819 556 $attemptscore->values++;
557 $attemptscore->sum += $userdata->score_raw;
558 $attemptscore->max = ($userdata->score_raw > $attemptscore->max)?$userdata->score_raw:$attemptscore->max;
559 if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
560 $attemptscore->lastmodify = $userdata->timemodified;
561 } else {
562 $attemptscore->lastmodify = 0;
563 }
9528568b 564 }
565 }
e4aa175a 566 }
03751efe 567 switch ($scorm->grademethod) {
a30b6819 568 case GRADEHIGHEST:
0d55dd4d 569 $score = (float) $attemptscore->max;
9528568b 570 break;
a30b6819 571 case GRADEAVERAGE:
572 if ($attemptscore->values > 0) {
573 $score = $attemptscore->sum/$attemptscore->values;
5c1ac70c 574 } else {
a30b6819 575 $score = 0;
9528568b 576 }
577 break;
a30b6819 578 case GRADESUM:
579 $score = $attemptscore->sum;
9528568b 580 break;
a30b6819 581 case GRADESCOES:
582 $score = $attemptscore->scoes;
7ef16bf9 583 break;
584 default:
585 $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default
5c1ac70c 586 }
a30b6819 587
c0f6b608 588 return $score;
a30b6819 589}
590
8c5516dc 591function scorm_grade_user($scorm, $userid) {
a30b6819 592
03751efe 593 // ensure we dont grade user beyond $scorm->maxattempt settings
7ce6eb87 594 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
ca4eda13 595 if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
7ce6eb87 596 $lastattempt = $scorm->maxattempt;
597 }
598
03751efe 599 switch ($scorm->whatgrade) {
a30b6819 600 case FIRSTATTEMPT:
8c5516dc 601 return scorm_grade_user_attempt($scorm, $userid, 1);
9528568b 602 break;
a30b6819 603 case LASTATTEMPT:
8c5516dc 604 return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
a30b6819 605 break;
606 case HIGHESTATTEMPT:
a30b6819 607 $maxscore = 0;
a30b6819 608 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
609 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
610 $maxscore = $attemptscore > $maxscore ? $attemptscore: $maxscore;
a30b6819 611 }
8c5516dc
DM
612 return $maxscore;
613
a30b6819 614 break;
615 case AVERAGEATTEMPT:
b1ca5d31 616 $attemptcount = scorm_get_attempt_count($userid, $scorm, true);
b1ca5d31
DM
617 if (empty($attemptcount)) {
618 return 0;
619 } else {
620 $attemptcount = count($attemptcount);
621 }
a30b6819 622 $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
623 $sumscore = 0;
624 for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
8c5516dc
DM
625 $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
626 $sumscore += $attemptscore;
a30b6819 627 }
628
b1ca5d31 629 return round($sumscore / $attemptcount);
a30b6819 630 break;
631 }
e4aa175a 632}
633
ca4eda13 634function scorm_count_launchable($scormid, $organization='') {
bf347041 635 global $DB;
636
637 $sqlorganization = '';
638 $params = array($scormid);
8e45ba45 639 if (!empty($organization)) {
bf347041 640 $sqlorganization = " AND organization=?";
641 $params[] = $organization;
8e45ba45 642 }
ca4eda13 643 return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), $params);
e4aa175a 644}
645
fa3a1652
DM
646/**
647 * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
648 *
649 * @param int $scormid the id of the scorm.
650 * @param int $userid the id of the user.
651 *
652 * @return int The attempt number to use.
653 */
2b3447c3 654function scorm_get_last_attempt($scormid, $userid) {
bf347041 655 global $DB;
656
ca4eda13 657 /// Find the last attempt number for the given user id and scorm id
fa3a1652
DM
658 $sql = "SELECT MAX(attempt)
659 FROM {scorm_scoes_track}
660 WHERE userid = ? AND scormid = ?";
661 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
662 if (empty($lastattempt)) {
663 return '1';
6381fa56 664 } else {
fa3a1652 665 return $lastattempt;
e4aa175a 666 }
e4aa175a 667}
668
fa3a1652
DM
669/**
670 * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
671 *
672 * @param int $scormid the id of the scorm.
673 * @param int $userid the id of the user.
674 *
675 * @return int The attempt number to use.
676 */
2276208a
DM
677function scorm_get_last_completed_attempt($scormid, $userid) {
678 global $DB;
679
fa3a1652
DM
680 /// Find the last completed attempt number for the given user id and scorm id
681 $sql = "SELECT MAX(attempt)
682 FROM {scorm_scoes_track}
683 WHERE userid = ? AND scormid = ?
684 AND (value='completed' OR value='passed')";
685 $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
686 if (empty($lastattempt)) {
687 return '1';
2276208a 688 } else {
fa3a1652 689 return $lastattempt;
2276208a
DM
690 }
691}
692
ca4eda13 693function scorm_course_format_display($user, $course) {
f2a1963c 694 global $CFG, $DB, $PAGE, $OUTPUT;
e4aa175a 695
696 $strupdate = get_string('update');
ca4eda13 697 $context = get_context_instance(CONTEXT_COURSE, $course->id);
e4aa175a 698
699 echo '<div class="mod-scorm">';
700 if ($scorms = get_all_instances_in_course('scorm', $course)) {
9528568b 701 // The module SCORM activity with the least id is the course
e4aa175a 702 $scorm = current($scorms);
703 if (! $cm = get_coursemodule_from_instance('scorm', $scorm->id, $course->id)) {
08b56f93 704 print_error('invalidcoursemodule');
e4aa175a 705 }
aab23f98 706 $contextmodule = get_context_instance(CONTEXT_MODULE, $cm->id);
4201a746 707 if ((has_capability('mod/scorm:skipview', $contextmodule))) {
666efc14 708 scorm_simple_play($scorm, $user, $contextmodule, $cm->id);
aab23f98 709 }
e4aa175a 710 $colspan = '';
711 $headertext = '<table width="100%"><tr><td class="title">'.get_string('name').': <b>'.format_string($scorm->name).'</b>';
2b3447c3 712 if (has_capability('moodle/course:manageactivities', $context)) {
830dd6e9 713 if ($PAGE->user_is_editing()) {
e4aa175a 714 // Display update icon
715 $path = $CFG->wwwroot.'/course';
716 $headertext .= '<span class="commands">'.
717 '<a title="'.$strupdate.'" href="'.$path.'/mod.php?update='.$cm->id.'&amp;sesskey='.sesskey().'">'.
b5d0cafc 718 '<img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.$strupdate.'" /></a></span>';
e4aa175a 719 }
720 $headertext .= '</td>';
721 // Display report link
bf347041 722 $trackedusers = $DB->get_record('scorm_scoes_track', array('scormid'=>$scorm->id), 'count(distinct(userid)) as c');
e4aa175a 723 if ($trackedusers->c > 0) {
724 $headertext .= '<td class="reportlink">'.
4aea3cc7 725 '<a href="'.$CFG->wwwroot.'/mod/scorm/report.php?id='.$cm->id.'">'.
ca4eda13 726 get_string('viewallreports', 'scorm', $trackedusers->c).'</a>';
e4aa175a 727 } else {
ca4eda13 728 $headertext .= '<td class="reportlink">'.get_string('noreports', 'scorm');
e4aa175a 729 }
730 $colspan = ' colspan="2"';
9528568b 731 }
ac3668bf 732 $headertext .= '</td></tr><tr><td'.$colspan.'>'.get_string('summary').':<br />'.format_module_intro('scorm', $scorm, $scorm->coursemodule).'</td></tr></table>';
ca4eda13 733 echo $OUTPUT->box($headertext, 'generalbox boxwidthwide');
39340358 734 scorm_view_display($user, $scorm, 'view.php?id='.$course->id, $cm);
e4aa175a 735 } else {
0d699c24 736 if (has_capability('moodle/course:update', $context)) {
e4aa175a 737 // Create a new activity
444ff001
DM
738 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'section'=>'0', 'sesskey'=>sesskey(),'add'=>'scorm'));
739 redirect($url);
e4aa175a 740 } else {
6aff538a 741 echo $OUTPUT->notification('Could not find a scorm course here');
e4aa175a 742 }
743 }
744 echo '</div>';
745}
746
39340358 747function scorm_view_display ($user, $scorm, $action, $cm) {
e6b9308a 748 global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
ab3b00e1 749
8aba9cda 750 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
9528568b 751 scorm_parse($scorm, false);
ab3b00e1 752 }
753
e4aa175a 754 $organization = optional_param('organization', '', PARAM_INT);
755
ca4eda13 756 if ($scorm->displaycoursestructure == 1) {
30bce58e 757 echo $OUTPUT->box_start('generalbox boxaligncenter toc');
ca4eda13
DM
758 ?>
759 <div class="structurehead"><?php print_string('contents', 'scorm') ?></div>
760 <?php
6381fa56 761 }
e4aa175a 762 if (empty($organization)) {
763 $organization = $scorm->launch;
764 }
2e3c31bc 765 if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
84ab3289
DM
766 $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
767 $DB->sql_isempty('scorm_scoes', 'organization', false, false),
ca4eda13 768 array($scorm->id), 'id', 'id,title')) {
e4aa175a 769 if (count($orgs) > 1) {
edc28287 770 $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
ca4eda13 771 $select->label = get_string('organizations', 'scorm');
edc28287
PS
772 $select->class = 'scorm-center';
773 echo $OUTPUT->render($select);
e4aa175a 774 }
775 }
776 $orgidentifier = '';
b3659259 777 if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
778 if (($sco->organization == '') && ($sco->launch == '')) {
779 $orgidentifier = $sco->identifier;
e4aa175a 780 } else {
b3659259 781 $orgidentifier = $sco->organization;
e4aa175a 782 }
783 }
28ffbff3 784
2b3447c3 785 $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe
dbe7e6f6 786 if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
787 $scorm->version = 'scorm_12';
788 }
2b3447c3 789 require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
790
ca4eda13 791 $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
e4aa175a 792 $incomplete = $result->incomplete;
28ffbff3 793
6381fa56 794 // do we want the TOC to be displayed?
ca4eda13 795 if ($scorm->displaycoursestructure == 1) {
6381fa56 796 echo $result->toc;
6aff538a 797 echo $OUTPUT->box_end();
6381fa56 798 }
7554f671 799
6381fa56 800 // is this the first attempt ?
b1ca5d31 801 $attemptcount = scorm_get_attempt_count($user->id, $scorm);
7554f671 802
6381fa56 803 // do not give the player launch FORM if the SCORM object is locked after the final attempt
804 if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
ca4eda13 805 ?>
52a9a9b5 806 <div class="scorm-center">
d5159fb8 807 <form id="scormviewform" method="post" action="<?php echo $CFG->wwwroot ?>/mod/scorm/player.php">
ca4eda13
DM
808 <?php
809 if ($scorm->hidebrowse == 0) {
810 print_string('mode', 'scorm');
811 echo ': <input type="radio" id="b" name="mode" value="browse" /><label for="b">'.get_string('browse', 'scorm').'</label>'."\n";
812 echo '<input type="radio" id="n" name="mode" value="normal" checked="checked" /><label for="n">'.get_string('normal', 'scorm')."</label>\n";
813 } else {
814 echo '<input type="hidden" name="mode" value="normal" />'."\n";
815 }
816 if ($scorm->forcenewattempt == 1) {
817 if ($incomplete === false) {
818 echo '<input type="hidden" name="newattempt" value="on" />'."\n";
819 }
820 } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
821 ?>
6381fa56 822 <br />
823 <input type="checkbox" id="a" name="newattempt" />
ca4eda13
DM
824 <label for="a"><?php print_string('newattempt', 'scorm') ?></label>
825 <?php
826 }
e6b9308a 827 if ($COURSE->format != 'scorm' && !empty($scorm->popup)) {
d5159fb8
DM
828 echo '<input type="hidden" name="display" value="popup" />'."\n";
829 }
ca4eda13 830 ?>
e4aa175a 831 <br />
4675994a 832 <input type="hidden" name="scoid"/>
3d00d6ab 833 <input type="hidden" name="cm" value="<?php echo $cm->id ?>"/>
e4aa175a 834 <input type="hidden" name="currentorg" value="<?php echo $orgidentifier ?>" />
ca4eda13 835 <input type="submit" value="<?php print_string('enter', 'scorm') ?>" />
e4aa175a 836 </form>
837 </div>
ca4eda13 838 <?php
6381fa56 839 }
e4aa175a 840}
6280b17a 841
666efc14 842function scorm_simple_play($scorm, $user, $context, $cmid) {
bf347041 843 global $DB;
844
9316beca 845 $result = false;
846
64f93798 847 if (has_capability('mod/scorm:viewreport', $context)) { //if this user can view reports, don't skipview so they can see links to reports.
489797d9
DM
848 return $result;
849 }
9316beca 850
64100280
DM
851 if ($scorm->scormtype != SCORM_TYPE_LOCAL && $scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
852 scorm_parse($scorm, false);
853 }
84ab3289 854 $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'id', 'id');
9316beca 855
7325b016 856 if ($scoes) {
c5803aaa
DM
857 $orgidentifier = '';
858 if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
859 if (($sco->organization == '') && ($sco->launch == '')) {
860 $orgidentifier = $sco->identifier;
861 } else {
862 $orgidentifier = $sco->organization;
863 }
864 }
9316beca 865 if ($scorm->skipview >= 1) {
866 $sco = current($scoes);
aab23f98
DM
867 $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
868 'currentorg'=>$orgidentifier,
869 'scoid'=>$sco->id));
870 if ($scorm->skipview == 2 || scorm_get_tracks($sco->id, $user->id) === false) {
666efc14
DM
871 if (!empty($scorm->forcenewattempt)) {
872 $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
873 if ($result->incomplete === false) {
874 $url->param('newattempt','on');
875 }
876 }
aab23f98 877 redirect($url);
9316beca 878 }
879 }
880 }
881 return $result;
28ffbff3 882}
d8c9d8a1 883
884function scorm_get_count_users($scormid, $groupingid=null) {
bf347041 885 global $CFG, $DB;
9528568b 886
98da6021 887 if (!empty($groupingid)) {
d8c9d8a1 888 $sql = "SELECT COUNT(DISTINCT st.userid)
bf347041 889 FROM {scorm_scoes_track} st
890 INNER JOIN {groups_members} gm ON st.userid = gm.userid
9528568b 891 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
bf347041 892 WHERE st.scormid = ? AND gg.groupingid = ?
d8c9d8a1 893 ";
bf347041 894 $params = array($scormid, $groupingid);
d8c9d8a1 895 } else {
896 $sql = "SELECT COUNT(DISTINCT st.userid)
9528568b 897 FROM {scorm_scoes_track} st
bf347041 898 WHERE st.scormid = ?
d8c9d8a1 899 ";
bf347041 900 $params = array($scormid);
d8c9d8a1 901 }
9528568b 902
bf347041 903 return ($DB->count_records_sql($sql, $params));
d8c9d8a1 904}
905
527af457 906/**
ca4eda13
DM
907 * Build up the JavaScript representation of an array element
908 *
909 * @param string $sversion SCORM API version
910 * @param array $userdata User track data
911 * @param string $element_name Name of array element to get values for
912 * @param array $children list of sub elements of this array element that also need instantiating
913 * @return None
914 */
527af457 915function scorm_reconstitute_array_element($sversion, $userdata, $element_name, $children) {
916 // reconstitute comments_from_learner and comments_from_lms
917 $current = '';
bf34ac0f 918 $current_subelement = '';
919 $current_sub = '';
527af457 920 $count = 0;
bf34ac0f 921 $count_sub = 0;
6b635d44 922 $scormseperator = '_';
e6402b54 923 if (scorm_version_check($sversion, SCORM_13)) { //scorm 1.3 elements use a . instead of an _
ca4eda13 924 $scormseperator = '.';
6b635d44 925 }
527af457 926 // filter out the ones we want
927 $element_list = array();
ca4eda13
DM
928 foreach ($userdata as $element => $value) {
929 if (substr($element, 0, strlen($element_name)) == $element_name) {
527af457 930 $element_list[$element] = $value;
931 }
932 }
7554f671 933
527af457 934 // sort elements in .n array order
935 uksort($element_list, "scorm_element_cmp");
7554f671 936
527af457 937 // generate JavaScript
ca4eda13 938 foreach ($element_list as $element => $value) {
e6402b54 939 if (scorm_version_check($sversion, SCORM_13)) {
b6293233 940 $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
527af457 941 preg_match('/\.(N\d+)\./', $element, $matches);
942 } else {
b6293233 943 $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
527af457 944 preg_match('/\_(\d+)\./', $element, $matches);
945 }
946 if (count($matches) > 0 && $current != $matches[1]) {
bf34ac0f 947 if ($count_sub > 0) {
6b635d44 948 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 949 }
7554f671 950 $current = $matches[1];
527af457 951 $count++;
bf34ac0f 952 $current_subelement = '';
953 $current_sub = '';
954 $count_sub = 0;
ca4eda13
DM
955 $end = strpos($element, $matches[1])+strlen($matches[1]);
956 $subelement = substr($element, 0, $end);
527af457 957 echo ' '.$subelement." = new Object();\n";
958 // now add the children
959 foreach ($children as $child) {
960 echo ' '.$subelement.".".$child." = new Object();\n";
961 echo ' '.$subelement.".".$child."._children = ".$child."_children;\n";
962 }
963 }
7554f671 964
bf34ac0f 965 // now - flesh out the second level elements if there are any
e6402b54 966 if (scorm_version_check($sversion, SCORM_13)) {
b6293233 967 $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
bf34ac0f 968 preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
969 } else {
b6293233 970 $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
bf34ac0f 971 preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
972 }
7554f671 973
bf34ac0f 974 // check the sub element type
975 if (count($matches) > 0 && $current_subelement != $matches[1]) {
976 if ($count_sub > 0) {
03e9a122 977 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 978 }
979 $current_subelement = $matches[1];
980 $current_sub = '';
981 $count_sub = 0;
ca4eda13
DM
982 $end = strpos($element, $matches[1])+strlen($matches[1]);
983 $subelement = substr($element, 0, $end);
bf34ac0f 984 echo ' '.$subelement." = new Object();\n";
985 }
7554f671 986
bf34ac0f 987 // now check the subelement subscript
988 if (count($matches) > 0 && $current_sub != $matches[2]) {
7554f671 989 $current_sub = $matches[2];
bf34ac0f 990 $count_sub++;
ca4eda13
DM
991 $end = strrpos($element, $matches[2])+strlen($matches[2]);
992 $subelement = substr($element, 0, $end);
bf34ac0f 993 echo ' '.$subelement." = new Object();\n";
994 }
7554f671 995
527af457 996 echo ' '.$element.' = \''.$value."';\n";
997 }
bf34ac0f 998 if ($count_sub > 0) {
6b635d44 999 echo ' '.$element_name.$scormseperator.$current.'.'.$current_subelement.'._count = '.$count_sub.";\n";
bf34ac0f 1000 }
527af457 1001 if ($count > 0) {
1002 echo ' '.$element_name.'._count = '.$count.";\n";
1003 }
1004}
1005
1006/**
ca4eda13
DM
1007 * Build up the JavaScript representation of an array element
1008 *
1009 * @param string $a left array element
1010 * @param string $b right array element
1011 * @return comparator - 0,1,-1
1012 */
527af457 1013function scorm_element_cmp($a, $b) {
bf34ac0f 1014 preg_match('/.*?(\d+)\./', $a, $matches);
527af457 1015 $left = intval($matches[1]);
bf34ac0f 1016 preg_match('/.?(\d+)\./', $b, $matches);
527af457 1017 $right = intval($matches[1]);
1018 if ($left < $right) {
1019 return -1; // smaller
ca4eda13 1020 } else if ($left > $right) {
527af457 1021 return 1; // bigger
1022 } else {
bf34ac0f 1023 // look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern
1024 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
1025 $leftterm = intval($matches[2]);
1026 $left = intval($matches[3]);
1027 if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
1028 $rightterm = intval($matches[2]);
1029 $right = intval($matches[3]);
1030 if ($leftterm < $rightterm) {
1031 return -1; // smaller
ca4eda13 1032 } else if ($leftterm > $rightterm) {
bf34ac0f 1033 return 1; // bigger
1034 } else {
1035 if ($left < $right) {
1036 return -1; // smaller
ca4eda13 1037 } else if ($left > $right) {
bf34ac0f 1038 return 1; // bigger
1039 }
1040 }
1041 }
1042 }
1043 // fall back for no second level matches or second level matches are equal
527af457 1044 return 0; // equal to
1045 }
1046}
6381fa56 1047
1048/**
ca4eda13
DM
1049 * Generate the user attempt status string
1050 *
1051 * @param object $user Current context user
1052 * @param object $scorm a moodle scrom object - mdl_scorm
1053 * @return string - Attempt status string
1054 */
d32e353e
DM
1055function scorm_get_attempt_status($user, $scorm, $cm='') {
1056 global $DB, $PAGE, $OUTPUT;
7554f671 1057
b1ca5d31 1058 $attempts = scorm_get_attempt_count($user->id, $scorm, true);
ca4eda13 1059 if (empty($attempts)) {
6381fa56 1060 $attemptcount = 0;
1061 } else {
1062 $attemptcount = count($attempts);
1063 }
7554f671 1064
6381fa56 1065 $result = '<p>'.get_string('noattemptsallowed', 'scorm').': ';
1066 if ($scorm->maxattempt > 0) {
4f4a8acf 1067 $result .= $scorm->maxattempt . '<br />';
6381fa56 1068 } else {
4f4a8acf 1069 $result .= get_string('unlimited').'<br />';
6381fa56 1070 }
4f4a8acf 1071 $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . '<br />';
6381fa56 1072
b1ca5d31
DM
1073 if ($scorm->maxattempt == 1) {
1074 switch ($scorm->grademethod) {
1075 case GRADEHIGHEST:
1076 $grademethod = get_string('gradehighest', 'scorm');
1077 break;
1078 case GRADEAVERAGE:
1079 $grademethod = get_string('gradeaverage', 'scorm');
1080 break;
1081 case GRADESUM:
1082 $grademethod = get_string('gradesum', 'scorm');
1083 break;
1084 case GRADESCOES:
1085 $grademethod = get_string('gradescoes', 'scorm');
1086 break;
1087 }
ca4eda13
DM
1088 } else {
1089 switch ($scorm->whatgrade) {
b1ca5d31
DM
1090 case HIGHESTATTEMPT:
1091 $grademethod = get_string('highestattempt', 'scorm');
1092 break;
1093 case AVERAGEATTEMPT:
1094 $grademethod = get_string('averageattempt', 'scorm');
1095 break;
1096 case FIRSTATTEMPT:
1097 $grademethod = get_string('firstattempt', 'scorm');
1098 break;
1099 case LASTATTEMPT:
1100 $grademethod = get_string('lastattempt', 'scorm');
1101 break;
1102 }
ca4eda13 1103 }
7554f671 1104
ca4eda13 1105 if (!empty($attempts)) {
b1ca5d31 1106 $i = 1;
ca4eda13 1107 foreach ($attempts as $attempt) {
6381fa56 1108 $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
4f4a8acf
DM
1109 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1110 $gradereported = $gradereported/$scorm->maxgrade;
1111 $gradereported = number_format($gradereported*100, 0) .'%';
1112 }
1113 $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .'<br />';
b1ca5d31 1114 $i++;
6381fa56 1115 }
1116 }
b1ca5d31 1117 $calculatedgrade = scorm_grade_user($scorm, $user->id);
4f4a8acf
DM
1118 if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
1119 $calculatedgrade = $calculatedgrade/$scorm->maxgrade;
1120 $calculatedgrade = number_format($calculatedgrade*100, 0) .'%';
1121 }
6381fa56 1122 $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
ca4eda13
DM
1123 if (empty($attempts)) {
1124 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . get_string('none') . '<br />';
6381fa56 1125 } else {
ca4eda13 1126 $result .= '<br />' . get_string('gradereported', 'scorm') . ': ' . $calculatedgrade . '<br />';
6381fa56 1127 }
1128 $result .= '</p>';
1129 if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
ca4eda13 1130 $result .= '<p><font color="#cc0000">'.get_string('exceededmaxattempts', 'scorm').'</font></p>';
6381fa56 1131 }
d32e353e
DM
1132 if (!empty($cm)) {
1133 $context = context_module::instance($cm->id);
a12b1d75
DM
1134 if (has_capability('mod/scorm:deleteownresponses', $context) &&
1135 $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
1136 //check to see if any data is stored for this user:
d32e353e
DM
1137 $deleteurl = new moodle_url($PAGE->url, array('action'=>'delete', 'sesskey' => sesskey()));
1138 $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
1139 }
1140 }
1141
1142
6381fa56 1143 return $result;
1144}
1145
1146/**
ca4eda13
DM
1147 * Get SCORM attempt count
1148 *
1149 * @param object $user Current context user
1150 * @param object $scorm a moodle scrom object - mdl_scorm
1151 * @param bool $attempts return the list of attempts
1152 * @return int - no. of attempts so far
1153 */
b1ca5d31 1154function scorm_get_attempt_count($userid, $scorm, $attempts_only=false) {
6381fa56 1155 global $DB;
1156 $attemptcount = 0;
1157 $element = 'cmi.core.score.raw';
78b203ca
DM
1158 if ($scorm->grademethod == GRADESCOES) {
1159 $element = 'cmi.core.lesson_status';
1160 }
e6402b54 1161 if (scorm_version_check($scorm->version, SCORM_13)) {
6381fa56 1162 $element = 'cmi.score.raw';
1163 }
ca4eda13 1164 $attempts = $DB->get_records_select('scorm_scoes_track', "element=? AND userid=? AND scormid=?", array($element, $userid, $scorm->id), 'attempt', 'DISTINCT attempt AS attemptnumber');
e24445c7
PH
1165 if ($attempts_only) {
1166 return $attempts;
1167 }
ca4eda13 1168 if (!empty($attempts)) {
6381fa56 1169 $attemptcount = count($attempts);
1170 }
1171 return $attemptcount;
1172}
1881df27 1173
1174/**
ca4eda13
DM
1175 * Figure out with this is a debug situation
1176 *
1177 * @param object $scorm a moodle scrom object - mdl_scorm
1178 * @return boolean - debugging true/false
1179 */
1881df27 1180function scorm_debugging($scorm) {
1181 global $CFG, $USER;
30fc6e2d 1182 $cfg_scorm = get_config('scorm');
7554f671 1183
30fc6e2d 1184 if (!$cfg_scorm->allowapidebug) {
1881df27 1185 return false;
1186 }
1187 $identifier = $USER->username.':'.$scorm->name;
30fc6e2d 1188 $test = $cfg_scorm->apidebugmask;
1881df27 1189 // check the regex is only a short list of safe characters
1190 if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
1191 return false;
1192 }
1193 $res = false;
1194 eval('$res = preg_match(\'/^'.$test.'/\', $identifier) ? true : false;');
1195 return $res;
1196}
7554f671 1197
1198/**
ca4eda13
DM
1199 * Delete Scorm tracks for selected users
1200 *
1201 * @param array $attemptids list of attempts that need to be deleted
1202 * @param int $scorm instance
1203 *
1204 * return bool true deleted all responses, false failed deleting an attempt - stopped here
1205 */
8716cc35 1206function scorm_delete_responses($attemptids, $scorm) {
ca4eda13 1207 if (!is_array($attemptids) || empty($attemptids)) {
7554f671 1208 return false;
1209 }
1210
ca4eda13
DM
1211 foreach ($attemptids as $num => $attemptid) {
1212 if (empty($attemptid)) {
7554f671 1213 unset($attemptids[$num]);
1214 }
1215 }
1216
ca4eda13 1217 foreach ($attemptids as $attempt) {
7554f671 1218 $keys = explode(':', $attempt);
1219 if (count($keys) == 2) {
1220 $userid = clean_param($keys[0], PARAM_INT);
1221 $attemptid = clean_param($keys[1], PARAM_INT);
8716cc35 1222 if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
7554f671 1223 return false;
1224 }
1225 } else {
1226 return false;
1227 }
1228 }
1229 return true;
1230}
1231
1232/**
ca4eda13
DM
1233 * Delete Scorm tracks for selected users
1234 *
1235 * @param int $userid ID of User
1236 * @param int $scormid ID of Scorm
1237 * @param int $attemptid user attempt that need to be deleted
1238 *
1239 * return bool true suceeded
1240 */
8716cc35 1241function scorm_delete_attempt($userid, $scorm, $attemptid) {
7554f671 1242 global $DB;
1243
8716cc35
DM
1244 $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
1245 include_once('lib.php');
1246 scorm_update_grades($scorm, $userid, true);
7554f671 1247 return true;
1248}
00c1677a
DM
1249
1250/**
2700b283 1251 * Converts SCORM duration notation to human-readable format
00c1677a 1252 * The function works with both SCORM 1.2 and SCORM 2004 time formats
2700b283 1253 * @param $duration string SCORM duration
00c1677a
DM
1254 * @return string human-readable date/time
1255 */
2700b283 1256function scorm_format_duration($duration) {
00c1677a 1257 // fetch date/time strings
119d64ee 1258 $stryears = get_string('years');
00c1677a 1259 $strmonths = get_string('nummonths');
119d64ee
DM
1260 $strdays = get_string('days');
1261 $strhours = get_string('hours');
1262 $strminutes = get_string('minutes');
1263 $strseconds = get_string('seconds');
64f93798 1264
2700b283 1265 if ($duration[0] == 'P') {
00c1677a
DM
1266 // if timestamp starts with 'P' - it's a SCORM 2004 format
1267 // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
1268 // and outputs filled sections, discarding leading zeroes and any format literals
1269 // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero
1270 $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#',
1271 '#([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#' );
119d64ee
DM
1272 $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ', '',
1273 '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '');
00c1677a
DM
1274 } else {
1275 // else we have SCORM 1.2 format there
1276 // first convert the timestamp to some SCORM 2004-like format for conveniency
2700b283 1277 $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
00c1677a
DM
1278 // then convert in the same way as SCORM 2004
1279 $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#' );
119d64ee 1280 $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ', '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
00c1677a 1281 }
64f93798 1282
2700b283 1283 $result = preg_replace($pattern, $replace, $duration);
00c1677a
DM
1284
1285 return $result;
1286}
0797000a
DM
1287
1288function scorm_get_toc($user,$scorm,$cmid,$toclink=TOCJSLINK,$currentorg='',$scoid='',$mode='normal',$attempt='',$play=false, $tocheader=false) {
1289 global $CFG, $DB, $PAGE, $OUTPUT;
1290
1291 $modestr = '';
1292 if ($mode == 'browse') {
1293 $modestr = '&amp;mode='.$mode;
1294 }
1295
1296 $result = new stdClass();
1297 if ($tocheader) {
1298 $result->toc = '<div id="scorm_layout">';
1299 $result->toc .= '<div id="scorm_toc">';
1300 $result->toc .= '<div id="scorm_tree">';
1301 }
1302 $result->toc .= '<ul>';
1303 $tocmenus = array();
1304 $result->prerequisites = true;
1305 $incomplete = false;
1306
1307 //
1308 // Get the current organization infos
1309 //
1310 if (!empty($currentorg)) {
1311 if (($organizationtitle = $DB->get_field('scorm_scoes','title', array('scorm'=>$scorm->id,'identifier'=>$currentorg))) != '') {
1312 if ($play) {
1313 $result->toctitle = "$organizationtitle";
1314 }
1315 else {
1316 $result->toc .= "\t<li>$organizationtitle</li>\n";
1317 }
1318 $tocmenus[] = $organizationtitle;
1319 }
1320 }
1321
1322 //
1323 // If not specified retrieve the last attempt number
1324 //
8bdac11f 1325 $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
0797000a 1326 if (empty($attempt)) {
8bdac11f 1327 $attempt = $attemptsmade;
0797000a 1328 }
8bdac11f 1329 $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
0797000a
DM
1330 if ($scoes = scorm_get_scoes($scorm->id, $currentorg)){
1331 //
1332 // Retrieve user tracking data for each learning object
1333 //
1334 $usertracks = array();
1335 foreach ($scoes as $sco) {
1336 if (!empty($sco->launch)) {
0797000a
DM
1337 if ($usertrack = scorm_get_tracks($sco->id,$user->id,$attempt)) {
1338 if ($usertrack->status == '') {
1339 $usertrack->status = 'notattempted';
1340 }
1341 $usertracks[$sco->identifier] = $usertrack;
1342 }
1343 }
1344 }
1345
1346 $level=0;
1347 $sublist=1;
1348 $previd = 0;
1349 $nextid = 0;
1350 $findnext = false;
1351 $parents[$level]='/';
6917eee8 1352 $prevsco = '';
0797000a
DM
1353 foreach ($scoes as $pos => $sco) {
1354 $isvisible = false;
1355 $sco->title = $sco->title;
1356 if (!isset($sco->isvisible) || (isset($sco->isvisible) && ($sco->isvisible == 'true'))) {
1357 $isvisible = true;
1358 }
1359 if ($parents[$level] != $sco->parent) {
8ac8aae4
MS
1360 $newlevel = array_search($sco->parent,$parents);
1361 if ($newlevel !== false) {
0797000a
DM
1362 for ($i=0; $i<($level-$newlevel); $i++) {
1363 $result->toc .= "\t\t</li></ul></li>\n";
1364 }
1365 $level = $newlevel;
1366 } else {
1367 $i = $level;
1368 $closelist = '';
1369 while (($i > 0) && ($parents[$level] != $sco->parent)) {
8cb7096b 1370 if ($i === 1 && $level > 1) {
b6c88d75
DM
1371 $closelist .= "\t\t</ul></li>\n";
1372 } else {
1373 $closelist .= "\t</li></ul></li>\n";
1374 }
0797000a
DM
1375 $i--;
1376 }
1377 if (($i == 0) && ($sco->parent != $currentorg)) {
b6c88d75 1378 $result->toc .= "\n\t<ul>\n";
0797000a
DM
1379 $level++;
1380 } else {
1381 $result->toc .= $closelist;
1382 $level = $i;
1383 }
1384 $parents[$level] = $sco->parent;
1385 }
1386 }
1387 if ($isvisible) {
1388 $result->toc .= "<li>";
1389 }
1390 if (isset($scoes[$pos+1])) {
1391 $nextsco = $scoes[$pos+1];
1392 } else {
1393 $nextsco = false;
1394 }
1395 $nextisvisible = false;
1396 if (($nextsco !== false) && (!isset($nextsco->isvisible) || (isset($nextsco->isvisible) && ($nextsco->isvisible == 'true')))) {
1397 $nextisvisible = true;
1398 }
1399 if ($nextisvisible && ($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
1400 (($level==0) || (($level>0) && ($nextsco->parent == $sco->identifier)))) {
1401 $sublist++;
1402 }
1403 if (empty($sco->title)) {
1404 $sco->title = $sco->identifier;
1405 }
b6c88d75
DM
1406 if ($isvisible) {
1407 if (!empty($sco->launch)) {
0797000a
DM
1408 $score = '';
1409 if (empty($scoid) && ($mode != 'normal')) {
1410 $scoid = $sco->id;
1411 }
1412 if (isset($usertracks[$sco->identifier])) {
1413 $usertrack = $usertracks[$sco->identifier];
1414 $strstatus = get_string($usertrack->status,'scorm');
1415 if ($sco->scormtype == 'sco') {
1416 $statusicon = '<img src="'.$OUTPUT->pix_url($usertrack->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" />';
1417 } else {
1418 $statusicon = '<img src="'.$OUTPUT->pix_url('assetc', 'scorm').'" alt="'.get_string('assetlaunched','scorm').'" title="'.get_string('assetlaunched','scorm').'" />';
1419 }
1420
1421 if (($usertrack->status == 'notattempted') || ($usertrack->status == 'incomplete') || ($usertrack->status == 'browsed')) {
1422 $incomplete = true;
1423 if ($play && empty($scoid)) {
1424 $scoid = $sco->id;
1425 }
1426 }
1427 if ($usertrack->score_raw != '' && has_capability('mod/scorm:viewscores', get_context_instance(CONTEXT_MODULE,$cmid))) {
1428 $score = '('.get_string('score','scorm').':&nbsp;'.$usertrack->score_raw.')';
1429 }
1430 $strsuspended = get_string('suspended','scorm');
1431 $exitvar = 'cmi.core.exit';
e6402b54 1432 if (scorm_version_check($scorm->version, SCORM_13)) {
0797000a
DM
1433 $exitvar = 'cmi.exit';
1434 }
1435 if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
1436 $statusicon = '<img src="'.$OUTPUT->pix_url('suspend', 'scorm').'" alt="'.$strstatus.' - '.$strsuspended.'" title="'.$strstatus.' - '.$strsuspended.'" />';
1437 }
1438 } else {
1439 if ($play && empty($scoid)) {
1440 $scoid = $sco->id;
1441 }
1442 $incomplete = true;
1443 if ($sco->scormtype == 'sco') {
1444 $statusicon = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.get_string('notattempted','scorm').'" title="'.get_string('notattempted','scorm').'" />';
1445 } else {
1446 $statusicon = '<img src="'.$OUTPUT->pix_url('asset', 'scorm').'" alt="'.get_string('asset','scorm').'" title="'.get_string('asset','scorm').'" />';
1447 }
1448 }
1449 if ($sco->id == $scoid) {
1450 $findnext = true;
1451 }
1452
1453 if (($nextid == 0) && (scorm_count_launchable($scorm->id,$currentorg) > 1) && ($nextsco!==false) && (!$findnext)) {
1454 if (!empty($sco->launch)) {
1455 $previd = $sco->id;
1456 }
1457 }
e6402b54 1458 if (scorm_version_check($scorm->version, SCORM_13)) {
0797000a
DM
1459 require_once($CFG->dirroot.'/mod/scorm/datamodels/sequencinglib.php');
1460 $prereq = scorm_seq_evaluate($sco->id,$usertracks);
1461 } else {
1462 //TODO: split check for sco->prerequisites only for AICC as I think that's the only case it's set.
1463 $prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites,$usertracks);
1464 }
1465 if ($prereq) {
1466 if ($sco->id == $scoid) {
1467 $result->prerequisites = true;
1468 }
6917eee8
DM
1469 if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
1470 $result->toc .= '<span>'.$statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1471 } else if ($toclink == TOCFULLURL) { //display toc with urls for structure page
0797000a
DM
1472 $url = $CFG->wwwroot.'/mod/scorm/player.php?a='.$scorm->id.'&amp;currentorg='.$currentorg.$modestr.'&amp;scoid='.$sco->id;
1473 $result->toc .= $statusicon.'&nbsp;<a href="'.$url.'">'.format_string($sco->title).'</a>'.$score."\n";
1474 } else { //display toc for inside scorm player
1475 if ($sco->launch) {
1476 $link = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
1477 $result->toc .= '<a title="'.$link.'">'.$statusicon.'&nbsp;'.format_string($sco->title).'&nbsp;'.$score.'</a>';
1478 } else {
1479 $result->toc .= '<span>'.$statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1480 }
1481 }
1482 $tocmenus[$sco->id] = scorm_repeater('&minus;',$level) . '&gt;' . format_string($sco->title);
1483 } else {
1484 if ($sco->id == $scoid) {
1485 $result->prerequisites = false;
1486 }
1487 if ($play) {
1488 // should be disabled
1489 $result->toc .= '<span>'.$statusicon.'&nbsp;'.format_string($sco->title).'</span>';
1490 } else {
1491 $result->toc .= $statusicon.'&nbsp;'.format_string($sco->title)."\n";
1492 }
1493 }
b6c88d75
DM
1494 } else {
1495 $result->toc .= '&nbsp;'.format_string($sco->title);
1496 }
1497 if (($nextsco === false) || $nextsco->parent == $sco->parent) {
1498 $result->toc .= "</li>\n";
0797000a 1499 }
0797000a
DM
1500 }
1501 if (($nextsco !== false) && ($nextid == 0) && ($findnext)) {
1502 if (!empty($nextsco->launch)) {
1503 $nextid = $nextsco->id;
1504 }
1505 }
6917eee8 1506 $prevsco = $sco;
0797000a
DM
1507 }
1508 for ($i=0;$i<$level;$i++) {
1509 $result->toc .= "\t\t</ul></li>\n";
1510 }
1511
1512 if ($play) {
f35b5884
DM
1513 // it is possible that $scoid is still not set, in this case we don't want an empty object
1514 if ($scoid) {
1515 $sco = scorm_get_sco($scoid);
8a4561ac 1516 }
0797000a
DM
1517 $sco->previd = $previd;
1518 $sco->nextid = $nextid;
1519 $result->sco = $sco;
1520 $result->incomplete = $incomplete;
1521 } else {
1522 $result->incomplete = $incomplete;
1523 }
1524 }
1525 $result->toc .= '</ul>';
1526
1527 // NEW IMS TOC
1528 if ($tocheader) {
1529 $result->toc .= '</div></div></div>';
1530 $result->toc .= '<div id="scorm_navpanel"></div>';
1531 }
1532
0797000a 1533 $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
3211569a 1534 $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenus, $sco->id, null, "tocmenu");
0797000a
DM
1535
1536 return $result;
701570b5 1537}