PageRenderTime 69ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/mod/scorm/locallib.php

https://bitbucket.org/moodle/moodle
PHP | 2505 lines | 1849 code | 248 blank | 408 comment | 564 complexity | a7be4ad0ea071443075fc55fd7f0eb0b MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Library of internal classes and functions for module SCORM
  18. *
  19. * @package mod_scorm
  20. * @copyright 1999 onwards Roberto Pinna
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. require_once("$CFG->dirroot/mod/scorm/lib.php");
  24. require_once("$CFG->libdir/filelib.php");
  25. // Constants and settings for module scorm.
  26. define('SCORM_UPDATE_NEVER', '0');
  27. define('SCORM_UPDATE_EVERYDAY', '2');
  28. define('SCORM_UPDATE_EVERYTIME', '3');
  29. define('SCORM_SKIPVIEW_NEVER', '0');
  30. define('SCORM_SKIPVIEW_FIRST', '1');
  31. define('SCORM_SKIPVIEW_ALWAYS', '2');
  32. define('SCO_ALL', 0);
  33. define('SCO_DATA', 1);
  34. define('SCO_ONLY', 2);
  35. define('GRADESCOES', '0');
  36. define('GRADEHIGHEST', '1');
  37. define('GRADEAVERAGE', '2');
  38. define('GRADESUM', '3');
  39. define('HIGHESTATTEMPT', '0');
  40. define('AVERAGEATTEMPT', '1');
  41. define('FIRSTATTEMPT', '2');
  42. define('LASTATTEMPT', '3');
  43. define('TOCJSLINK', 1);
  44. define('TOCFULLURL', 2);
  45. define('SCORM_FORCEATTEMPT_NO', 0);
  46. define('SCORM_FORCEATTEMPT_ONCOMPLETE', 1);
  47. define('SCORM_FORCEATTEMPT_ALWAYS', 2);
  48. // Local Library of functions for module scorm.
  49. /**
  50. * @package mod_scorm
  51. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  52. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  53. */
  54. class scorm_package_file_info extends file_info_stored {
  55. public function get_parent() {
  56. if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
  57. return $this->browser->get_file_info($this->context);
  58. }
  59. return parent::get_parent();
  60. }
  61. public function get_visible_name() {
  62. if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
  63. return $this->topvisiblename;
  64. }
  65. return parent::get_visible_name();
  66. }
  67. }
  68. /**
  69. * Returns an array of the popup options for SCORM and each options default value
  70. *
  71. * @return array an array of popup options as the key and their defaults as the value
  72. */
  73. function scorm_get_popup_options_array() {
  74. $cfgscorm = get_config('scorm');
  75. return array('scrollbars' => isset($cfgscorm->scrollbars) ? $cfgscorm->scrollbars : 0,
  76. 'directories' => isset($cfgscorm->directories) ? $cfgscorm->directories : 0,
  77. 'location' => isset($cfgscorm->location) ? $cfgscorm->location : 0,
  78. 'menubar' => isset($cfgscorm->menubar) ? $cfgscorm->menubar : 0,
  79. 'toolbar' => isset($cfgscorm->toolbar) ? $cfgscorm->toolbar : 0,
  80. 'status' => isset($cfgscorm->status) ? $cfgscorm->status : 0);
  81. }
  82. /**
  83. * Returns an array of the array of what grade options
  84. *
  85. * @return array an array of what grade options
  86. */
  87. function scorm_get_grade_method_array() {
  88. return array (GRADESCOES => get_string('gradescoes', 'scorm'),
  89. GRADEHIGHEST => get_string('gradehighest', 'scorm'),
  90. GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
  91. GRADESUM => get_string('gradesum', 'scorm'));
  92. }
  93. /**
  94. * Returns an array of the array of what grade options
  95. *
  96. * @return array an array of what grade options
  97. */
  98. function scorm_get_what_grade_array() {
  99. return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
  100. AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
  101. FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
  102. LASTATTEMPT => get_string('lastattempt', 'scorm'));
  103. }
  104. /**
  105. * Returns an array of the array of skip view options
  106. *
  107. * @return array an array of skip view options
  108. */
  109. function scorm_get_skip_view_array() {
  110. return array(SCORM_SKIPVIEW_NEVER => get_string('never'),
  111. SCORM_SKIPVIEW_FIRST => get_string('firstaccess', 'scorm'),
  112. SCORM_SKIPVIEW_ALWAYS => get_string('always'));
  113. }
  114. /**
  115. * Returns an array of the array of hide table of contents options
  116. *
  117. * @return array an array of hide table of contents options
  118. */
  119. function scorm_get_hidetoc_array() {
  120. return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
  121. SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
  122. SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
  123. SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
  124. }
  125. /**
  126. * Returns an array of the array of update frequency options
  127. *
  128. * @return array an array of update frequency options
  129. */
  130. function scorm_get_updatefreq_array() {
  131. return array(SCORM_UPDATE_NEVER => get_string('never'),
  132. SCORM_UPDATE_EVERYDAY => get_string('everyday', 'scorm'),
  133. SCORM_UPDATE_EVERYTIME => get_string('everytime', 'scorm'));
  134. }
  135. /**
  136. * Returns an array of the array of popup display options
  137. *
  138. * @return array an array of popup display options
  139. */
  140. function scorm_get_popup_display_array() {
  141. return array(0 => get_string('currentwindow', 'scorm'),
  142. 1 => get_string('popup', 'scorm'));
  143. }
  144. /**
  145. * Returns an array of the array of navigation buttons display options
  146. *
  147. * @return array an array of navigation buttons display options
  148. */
  149. function scorm_get_navigation_display_array() {
  150. return array(SCORM_NAV_DISABLED => get_string('no'),
  151. SCORM_NAV_UNDER_CONTENT => get_string('undercontent', 'scorm'),
  152. SCORM_NAV_FLOATING => get_string('floating', 'scorm'));
  153. }
  154. /**
  155. * Returns an array of the array of attempt options
  156. *
  157. * @return array an array of attempt options
  158. */
  159. function scorm_get_attempts_array() {
  160. $attempts = array(0 => get_string('nolimit', 'scorm'),
  161. 1 => get_string('attempt1', 'scorm'));
  162. for ($i = 2; $i <= 6; $i++) {
  163. $attempts[$i] = get_string('attemptsx', 'scorm', $i);
  164. }
  165. return $attempts;
  166. }
  167. /**
  168. * Returns an array of the attempt status options
  169. *
  170. * @return array an array of attempt status options
  171. */
  172. function scorm_get_attemptstatus_array() {
  173. return array(SCORM_DISPLAY_ATTEMPTSTATUS_NO => get_string('no'),
  174. SCORM_DISPLAY_ATTEMPTSTATUS_ALL => get_string('attemptstatusall', 'scorm'),
  175. SCORM_DISPLAY_ATTEMPTSTATUS_MY => get_string('attemptstatusmy', 'scorm'),
  176. SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY => get_string('attemptstatusentry', 'scorm'));
  177. }
  178. /**
  179. * Returns an array of the force attempt options
  180. *
  181. * @return array an array of attempt options
  182. */
  183. function scorm_get_forceattempt_array() {
  184. return array(SCORM_FORCEATTEMPT_NO => get_string('no'),
  185. SCORM_FORCEATTEMPT_ONCOMPLETE => get_string('forceattemptoncomplete', 'scorm'),
  186. SCORM_FORCEATTEMPT_ALWAYS => get_string('forceattemptalways', 'scorm'));
  187. }
  188. /**
  189. * Extracts scrom package, sets up all variables.
  190. * Called whenever scorm changes
  191. * @param object $scorm instance - fields are updated and changes saved into database
  192. * @param bool $full force full update if true
  193. * @return void
  194. */
  195. function scorm_parse($scorm, $full) {
  196. global $CFG, $DB;
  197. $cfgscorm = get_config('scorm');
  198. if (!isset($scorm->cmid)) {
  199. $cm = get_coursemodule_from_instance('scorm', $scorm->id);
  200. $scorm->cmid = $cm->id;
  201. }
  202. $context = context_module::instance($scorm->cmid);
  203. $newhash = $scorm->sha1hash;
  204. if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
  205. $fs = get_file_storage();
  206. $packagefile = false;
  207. $packagefileimsmanifest = false;
  208. if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
  209. if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
  210. if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
  211. $packagefile->import_external_file_contents();
  212. }
  213. $newhash = $packagefile->get_contenthash();
  214. if (strtolower($packagefile->get_filename()) == 'imsmanifest.xml') {
  215. $packagefileimsmanifest = true;
  216. }
  217. } else {
  218. $newhash = null;
  219. }
  220. } else {
  221. if (!$cfgscorm->allowtypelocalsync) {
  222. // Sorry - localsync disabled.
  223. return;
  224. }
  225. if ($scorm->reference !== '') {
  226. $fs->delete_area_files($context->id, 'mod_scorm', 'package');
  227. $filerecord = array('contextid' => $context->id, 'component' => 'mod_scorm', 'filearea' => 'package',
  228. 'itemid' => 0, 'filepath' => '/');
  229. if ($packagefile = $fs->create_file_from_url($filerecord, $scorm->reference, array('calctimeout' => true), true)) {
  230. $newhash = $packagefile->get_contenthash();
  231. } else {
  232. $newhash = null;
  233. }
  234. }
  235. }
  236. if ($packagefile) {
  237. if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
  238. if (strpos($scorm->version, 'SCORM') !== false) {
  239. if ($packagefileimsmanifest || $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
  240. // No need to update.
  241. return;
  242. }
  243. } else if (strpos($scorm->version, 'AICC') !== false) {
  244. // TODO: add more sanity checks - something really exists in scorm_content area.
  245. return;
  246. }
  247. }
  248. if (!$packagefileimsmanifest) {
  249. // Now extract files.
  250. $fs->delete_area_files($context->id, 'mod_scorm', 'content');
  251. $packer = get_file_packer('application/zip');
  252. $packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
  253. }
  254. } else if (!$full) {
  255. return;
  256. }
  257. if ($packagefileimsmanifest) {
  258. require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
  259. // Direct link to imsmanifest.xml file.
  260. if (!scorm_parse_scorm($scorm, $packagefile)) {
  261. $scorm->version = 'ERROR';
  262. }
  263. } else if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
  264. require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
  265. // SCORM.
  266. if (!scorm_parse_scorm($scorm, $manifest)) {
  267. $scorm->version = 'ERROR';
  268. }
  269. } else {
  270. require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
  271. // AICC.
  272. $result = scorm_parse_aicc($scorm);
  273. if (!$result) {
  274. $scorm->version = 'ERROR';
  275. } else {
  276. $scorm->version = 'AICC';
  277. }
  278. }
  279. } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfgscorm->allowtypeexternal) {
  280. require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
  281. // SCORM only, AICC can not be external.
  282. if (!scorm_parse_scorm($scorm, $scorm->reference)) {
  283. $scorm->version = 'ERROR';
  284. }
  285. $newhash = sha1($scorm->reference);
  286. } else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfgscorm->allowtypeexternalaicc) {
  287. require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
  288. // AICC.
  289. $result = scorm_parse_aicc($scorm);
  290. if (!$result) {
  291. $scorm->version = 'ERROR';
  292. } else {
  293. $scorm->version = 'AICC';
  294. }
  295. } else {
  296. // Sorry, disabled type.
  297. return;
  298. }
  299. $scorm->revision++;
  300. $scorm->sha1hash = $newhash;
  301. $DB->update_record('scorm', $scorm);
  302. }
  303. function scorm_array_search($item, $needle, $haystacks, $strict=false) {
  304. if (!empty($haystacks)) {
  305. foreach ($haystacks as $key => $element) {
  306. if ($strict) {
  307. if ($element->{$item} === $needle) {
  308. return $key;
  309. }
  310. } else {
  311. if ($element->{$item} == $needle) {
  312. return $key;
  313. }
  314. }
  315. }
  316. }
  317. return false;
  318. }
  319. function scorm_repeater($what, $times) {
  320. if ($times <= 0) {
  321. return null;
  322. }
  323. $return = '';
  324. for ($i = 0; $i < $times; $i++) {
  325. $return .= $what;
  326. }
  327. return $return;
  328. }
  329. function scorm_external_link($link) {
  330. // Check if a link is external.
  331. $result = false;
  332. $link = strtolower($link);
  333. if (substr($link, 0, 7) == 'http://') {
  334. $result = true;
  335. } else if (substr($link, 0, 8) == 'https://') {
  336. $result = true;
  337. } else if (substr($link, 0, 4) == 'www.') {
  338. $result = true;
  339. }
  340. return $result;
  341. }
  342. /**
  343. * Returns an object containing all datas relative to the given sco ID
  344. *
  345. * @param integer $id The sco ID
  346. * @return mixed (false if sco id does not exists)
  347. */
  348. function scorm_get_sco($id, $what=SCO_ALL) {
  349. global $DB;
  350. if ($sco = $DB->get_record('scorm_scoes', array('id' => $id))) {
  351. $sco = ($what == SCO_DATA) ? new stdClass() : $sco;
  352. if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id)))) {
  353. foreach ($scodatas as $scodata) {
  354. $sco->{$scodata->name} = $scodata->value;
  355. }
  356. } else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id))))) {
  357. $sco->parameters = '';
  358. }
  359. return $sco;
  360. } else {
  361. return false;
  362. }
  363. }
  364. /**
  365. * Returns an object (array) containing all the scoes data related to the given sco ID
  366. *
  367. * @param integer $id The sco ID
  368. * @param integer $organisation an organisation ID - defaults to false if not required
  369. * @return mixed (false if there are no scoes or an array)
  370. */
  371. function scorm_get_scoes($id, $organisation=false) {
  372. global $DB;
  373. $queryarray = array('scorm' => $id);
  374. if (!empty($organisation)) {
  375. $queryarray['organization'] = $organisation;
  376. }
  377. if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
  378. // Drop keys so that it is a simple array as expected.
  379. $scoes = array_values($scoes);
  380. foreach ($scoes as $sco) {
  381. if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $sco->id))) {
  382. foreach ($scodatas as $scodata) {
  383. $sco->{$scodata->name} = $scodata->value;
  384. }
  385. }
  386. }
  387. return $scoes;
  388. } else {
  389. return false;
  390. }
  391. }
  392. function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false, $trackdata = null) {
  393. global $DB, $CFG;
  394. $id = null;
  395. if ($forcecompleted) {
  396. // TODO - this could be broadened to encompass SCORM 2004 in future.
  397. if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
  398. if ($track = $DB->get_record_select('scorm_scoes_track',
  399. 'userid=? AND scormid=? AND scoid=? AND attempt=? '.
  400. 'AND element=\'cmi.core.score.raw\'',
  401. array($userid, $scormid, $scoid, $attempt))) {
  402. $value = 'completed';
  403. }
  404. }
  405. if ($element == 'cmi.core.score.raw') {
  406. if ($tracktest = $DB->get_record_select('scorm_scoes_track',
  407. 'userid=? AND scormid=? AND scoid=? AND attempt=? '.
  408. 'AND element=\'cmi.core.lesson_status\'',
  409. array($userid, $scormid, $scoid, $attempt))) {
  410. if ($tracktest->value == "incomplete") {
  411. $tracktest->value = "completed";
  412. $DB->update_record('scorm_scoes_track', $tracktest);
  413. }
  414. }
  415. }
  416. if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
  417. if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => 'objectivesetbycontent'))) {
  418. $objectiveprogressstatus = true;
  419. $objectivesatisfiedstatus = false;
  420. if ($value == 'passed') {
  421. $objectivesatisfiedstatus = true;
  422. }
  423. if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
  424. 'scormid' => $scormid,
  425. 'scoid' => $scoid,
  426. 'attempt' => $attempt,
  427. 'element' => 'objectiveprogressstatus'))) {
  428. $track->value = $objectiveprogressstatus;
  429. $track->timemodified = time();
  430. $DB->update_record('scorm_scoes_track', $track);
  431. $id = $track->id;
  432. } else {
  433. $track = new stdClass();
  434. $track->userid = $userid;
  435. $track->scormid = $scormid;
  436. $track->scoid = $scoid;
  437. $track->attempt = $attempt;
  438. $track->element = 'objectiveprogressstatus';
  439. $track->value = $objectiveprogressstatus;
  440. $track->timemodified = time();
  441. $id = $DB->insert_record('scorm_scoes_track', $track);
  442. }
  443. if ($objectivesatisfiedstatus) {
  444. if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
  445. 'scormid' => $scormid,
  446. 'scoid' => $scoid,
  447. 'attempt' => $attempt,
  448. 'element' => 'objectivesatisfiedstatus'))) {
  449. $track->value = $objectivesatisfiedstatus;
  450. $track->timemodified = time();
  451. $DB->update_record('scorm_scoes_track', $track);
  452. $id = $track->id;
  453. } else {
  454. $track = new stdClass();
  455. $track->userid = $userid;
  456. $track->scormid = $scormid;
  457. $track->scoid = $scoid;
  458. $track->attempt = $attempt;
  459. $track->element = 'objectivesatisfiedstatus';
  460. $track->value = $objectivesatisfiedstatus;
  461. $track->timemodified = time();
  462. $id = $DB->insert_record('scorm_scoes_track', $track);
  463. }
  464. }
  465. }
  466. }
  467. }
  468. $track = null;
  469. if ($trackdata !== null) {
  470. if (isset($trackdata[$element])) {
  471. $track = $trackdata[$element];
  472. }
  473. } else {
  474. $track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
  475. 'scormid' => $scormid,
  476. 'scoid' => $scoid,
  477. 'attempt' => $attempt,
  478. 'element' => $element));
  479. }
  480. if ($track) {
  481. if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
  482. if ($track->value != $value) {
  483. $track->value = $value;
  484. $track->timemodified = time();
  485. $DB->update_record('scorm_scoes_track', $track);
  486. }
  487. $id = $track->id;
  488. }
  489. } else {
  490. $track = new stdClass();
  491. $track->userid = $userid;
  492. $track->scormid = $scormid;
  493. $track->scoid = $scoid;
  494. $track->attempt = $attempt;
  495. $track->element = $element;
  496. $track->value = $value;
  497. $track->timemodified = time();
  498. $id = $DB->insert_record('scorm_scoes_track', $track);
  499. $track->id = $id;
  500. }
  501. // Trigger updating grades based on a given set of SCORM CMI elements.
  502. $scorm = false;
  503. if (in_array($element, array('cmi.core.score.raw', 'cmi.score.raw')) ||
  504. (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
  505. && in_array($track->value, array('completed', 'passed')))) {
  506. $scorm = $DB->get_record('scorm', array('id' => $scormid));
  507. include_once($CFG->dirroot.'/mod/scorm/lib.php');
  508. scorm_update_grades($scorm, $userid);
  509. }
  510. // Trigger CMI element events.
  511. if (in_array($element, array('cmi.core.score.raw', 'cmi.score.raw')) ||
  512. (in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
  513. && in_array($track->value, array('completed', 'failed', 'passed')))) {
  514. if (!$scorm) {
  515. $scorm = $DB->get_record('scorm', array('id' => $scormid));
  516. }
  517. $cm = get_coursemodule_from_instance('scorm', $scormid);
  518. $data = array(
  519. 'other' => array('attemptid' => $attempt, 'cmielement' => $element, 'cmivalue' => $track->value),
  520. 'objectid' => $scorm->id,
  521. 'context' => context_module::instance($cm->id),
  522. 'relateduserid' => $userid
  523. );
  524. if (in_array($element, array('cmi.core.score.raw', 'cmi.score.raw'))) {
  525. // Create score submitted event.
  526. $event = \mod_scorm\event\scoreraw_submitted::create($data);
  527. } else {
  528. // Create status submitted event.
  529. $event = \mod_scorm\event\status_submitted::create($data);
  530. }
  531. // Fix the missing track keys when the SCORM track record already exists, see $trackdata in datamodel.php.
  532. // There, for performances reasons, columns are limited to: element, id, value, timemodified.
  533. // Missing fields are: userid, scormid, scoid, attempt.
  534. $track->userid = $userid;
  535. $track->scormid = $scormid;
  536. $track->scoid = $scoid;
  537. $track->attempt = $attempt;
  538. // Trigger submitted event.
  539. $event->add_record_snapshot('scorm_scoes_track', $track);
  540. $event->add_record_snapshot('course_modules', $cm);
  541. $event->add_record_snapshot('scorm', $scorm);
  542. $event->trigger();
  543. }
  544. return $id;
  545. }
  546. /**
  547. * simple quick function to return true/false if this user has tracks in this scorm
  548. *
  549. * @param integer $scormid The scorm ID
  550. * @param integer $userid the users id
  551. * @return boolean (false if there are no tracks)
  552. */
  553. function scorm_has_tracks($scormid, $userid) {
  554. global $DB;
  555. return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
  556. }
  557. function scorm_get_tracks($scoid, $userid, $attempt='') {
  558. // Gets all tracks of specified sco and user.
  559. global $DB;
  560. if (empty($attempt)) {
  561. if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id' => $scoid))) {
  562. $attempt = scorm_get_last_attempt($scormid, $userid);
  563. } else {
  564. $attempt = 1;
  565. }
  566. }
  567. if ($tracks = $DB->get_records('scorm_scoes_track', array('userid' => $userid, 'scoid' => $scoid,
  568. 'attempt' => $attempt), 'element ASC')) {
  569. $usertrack = scorm_format_interactions($tracks);
  570. $usertrack->userid = $userid;
  571. $usertrack->scoid = $scoid;
  572. return $usertrack;
  573. } else {
  574. return false;
  575. }
  576. }
  577. /**
  578. * helper function to return a formatted list of interactions for reports.
  579. *
  580. * @param array $trackdata the records from scorm_scoes_track table
  581. * @return object formatted list of interactions
  582. */
  583. function scorm_format_interactions($trackdata) {
  584. $usertrack = new stdClass();
  585. // Defined in order to unify scorm1.2 and scorm2004.
  586. $usertrack->score_raw = '';
  587. $usertrack->status = '';
  588. $usertrack->total_time = '00:00:00';
  589. $usertrack->session_time = '00:00:00';
  590. $usertrack->timemodified = 0;
  591. foreach ($trackdata as $track) {
  592. $element = $track->element;
  593. $usertrack->{$element} = $track->value;
  594. switch ($element) {
  595. case 'cmi.core.lesson_status':
  596. case 'cmi.completion_status':
  597. if ($track->value == 'not attempted') {
  598. $track->value = 'notattempted';
  599. }
  600. $usertrack->status = $track->value;
  601. break;
  602. case 'cmi.core.score.raw':
  603. case 'cmi.score.raw':
  604. $usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
  605. break;
  606. case 'cmi.core.session_time':
  607. case 'cmi.session_time':
  608. $usertrack->session_time = $track->value;
  609. break;
  610. case 'cmi.core.total_time':
  611. case 'cmi.total_time':
  612. $usertrack->total_time = $track->value;
  613. break;
  614. }
  615. if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
  616. $usertrack->timemodified = $track->timemodified;
  617. }
  618. }
  619. return $usertrack;
  620. }
  621. /* Find the start and finsh time for a a given SCO attempt
  622. *
  623. * @param int $scormid SCORM Id
  624. * @param int $scoid SCO Id
  625. * @param int $userid User Id
  626. * @param int $attemt Attempt Id
  627. *
  628. * @return object start and finsh time EPOC secods
  629. *
  630. */
  631. function scorm_get_sco_runtime($scormid, $scoid, $userid, $attempt=1) {
  632. global $DB;
  633. $timedata = new stdClass();
  634. $params = array('userid' => $userid, 'scormid' => $scormid, 'attempt' => $attempt);
  635. if (!empty($scoid)) {
  636. $params['scoid'] = $scoid;
  637. }
  638. $tracks = $DB->get_records('scorm_scoes_track', $params, "timemodified ASC");
  639. if ($tracks) {
  640. $tracks = array_values($tracks);
  641. }
  642. if ($tracks) {
  643. $timedata->start = $tracks[0]->timemodified;
  644. } else {
  645. $timedata->start = false;
  646. }
  647. if ($tracks && $track = array_pop($tracks)) {
  648. $timedata->finish = $track->timemodified;
  649. } else {
  650. $timedata->finish = $timedata->start;
  651. }
  652. return $timedata;
  653. }
  654. function scorm_grade_user_attempt($scorm, $userid, $attempt=1) {
  655. global $DB;
  656. $attemptscore = new stdClass();
  657. $attemptscore->scoes = 0;
  658. $attemptscore->values = 0;
  659. $attemptscore->max = 0;
  660. $attemptscore->sum = 0;
  661. $attemptscore->lastmodify = 0;
  662. if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
  663. return null;
  664. }
  665. foreach ($scoes as $sco) {
  666. if ($userdata = scorm_get_tracks($sco->id, $userid, $attempt)) {
  667. if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
  668. $attemptscore->scoes++;
  669. }
  670. if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type == 'sco' && isset($userdata->score_raw))) {
  671. $attemptscore->values++;
  672. $attemptscore->sum += $userdata->score_raw;
  673. $attemptscore->max = ($userdata->score_raw > $attemptscore->max) ? $userdata->score_raw : $attemptscore->max;
  674. if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
  675. $attemptscore->lastmodify = $userdata->timemodified;
  676. } else {
  677. $attemptscore->lastmodify = 0;
  678. }
  679. }
  680. }
  681. }
  682. switch ($scorm->grademethod) {
  683. case GRADEHIGHEST:
  684. $score = (float) $attemptscore->max;
  685. break;
  686. case GRADEAVERAGE:
  687. if ($attemptscore->values > 0) {
  688. $score = $attemptscore->sum / $attemptscore->values;
  689. } else {
  690. $score = 0;
  691. }
  692. break;
  693. case GRADESUM:
  694. $score = $attemptscore->sum;
  695. break;
  696. case GRADESCOES:
  697. $score = $attemptscore->scoes;
  698. break;
  699. default:
  700. $score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default.
  701. }
  702. return $score;
  703. }
  704. function scorm_grade_user($scorm, $userid) {
  705. // Ensure we dont grade user beyond $scorm->maxattempt settings.
  706. $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
  707. if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
  708. $lastattempt = $scorm->maxattempt;
  709. }
  710. switch ($scorm->whatgrade) {
  711. case FIRSTATTEMPT:
  712. return scorm_grade_user_attempt($scorm, $userid, scorm_get_first_attempt($scorm->id, $userid));
  713. break;
  714. case LASTATTEMPT:
  715. return scorm_grade_user_attempt($scorm, $userid, scorm_get_last_completed_attempt($scorm->id, $userid));
  716. break;
  717. case HIGHESTATTEMPT:
  718. $maxscore = 0;
  719. for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
  720. $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
  721. $maxscore = $attemptscore > $maxscore ? $attemptscore : $maxscore;
  722. }
  723. return $maxscore;
  724. break;
  725. case AVERAGEATTEMPT:
  726. $attemptcount = scorm_get_attempt_count($userid, $scorm, true, true);
  727. if (empty($attemptcount)) {
  728. return 0;
  729. } else {
  730. $attemptcount = count($attemptcount);
  731. }
  732. $lastattempt = scorm_get_last_attempt($scorm->id, $userid);
  733. $sumscore = 0;
  734. for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
  735. $attemptscore = scorm_grade_user_attempt($scorm, $userid, $attempt);
  736. $sumscore += $attemptscore;
  737. }
  738. return round($sumscore / $attemptcount);
  739. break;
  740. }
  741. }
  742. function scorm_count_launchable($scormid, $organization='') {
  743. global $DB;
  744. $sqlorganization = '';
  745. $params = array($scormid);
  746. if (!empty($organization)) {
  747. $sqlorganization = " AND organization=?";
  748. $params[] = $organization;
  749. }
  750. return $DB->count_records_select('scorm_scoes', "scorm = ? $sqlorganization AND ".
  751. $DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
  752. $params);
  753. }
  754. /**
  755. * Returns the last attempt used - if no attempts yet, returns 1 for first attempt
  756. *
  757. * @param int $scormid the id of the scorm.
  758. * @param int $userid the id of the user.
  759. *
  760. * @return int The attempt number to use.
  761. */
  762. function scorm_get_last_attempt($scormid, $userid) {
  763. global $DB;
  764. // Find the last attempt number for the given user id and scorm id.
  765. $sql = "SELECT MAX(attempt)
  766. FROM {scorm_scoes_track}
  767. WHERE userid = ? AND scormid = ?";
  768. $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
  769. if (empty($lastattempt)) {
  770. return '1';
  771. } else {
  772. return $lastattempt;
  773. }
  774. }
  775. /**
  776. * Returns the first attempt used - if no attempts yet, returns 1 for first attempt.
  777. *
  778. * @param int $scormid the id of the scorm.
  779. * @param int $userid the id of the user.
  780. *
  781. * @return int The first attempt number.
  782. */
  783. function scorm_get_first_attempt($scormid, $userid) {
  784. global $DB;
  785. // Find the first attempt number for the given user id and scorm id.
  786. $sql = "SELECT MIN(attempt)
  787. FROM {scorm_scoes_track}
  788. WHERE userid = ? AND scormid = ?";
  789. $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
  790. if (empty($lastattempt)) {
  791. return '1';
  792. } else {
  793. return $lastattempt;
  794. }
  795. }
  796. /**
  797. * Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
  798. *
  799. * @param int $scormid the id of the scorm.
  800. * @param int $userid the id of the user.
  801. *
  802. * @return int The attempt number to use.
  803. */
  804. function scorm_get_last_completed_attempt($scormid, $userid) {
  805. global $DB;
  806. // Find the last completed attempt number for the given user id and scorm id.
  807. $sql = "SELECT MAX(attempt)
  808. FROM {scorm_scoes_track}
  809. WHERE userid = ? AND scormid = ?
  810. AND (".$DB->sql_compare_text('value')." = ".$DB->sql_compare_text('?')." OR ".
  811. $DB->sql_compare_text('value')." = ".$DB->sql_compare_text('?').")";
  812. $lastattempt = $DB->get_field_sql($sql, array($userid, $scormid, 'completed', 'passed'));
  813. if (empty($lastattempt)) {
  814. return '1';
  815. } else {
  816. return $lastattempt;
  817. }
  818. }
  819. /**
  820. * Returns the full list of attempts a user has made.
  821. *
  822. * @param int $scormid the id of the scorm.
  823. * @param int $userid the id of the user.
  824. *
  825. * @return array array of attemptids
  826. */
  827. function scorm_get_all_attempts($scormid, $userid) {
  828. global $DB;
  829. $attemptids = array();
  830. $sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
  831. $attempts = $DB->get_records_sql($sql, array($userid, $scormid));
  832. foreach ($attempts as $attempt) {
  833. $attemptids[] = $attempt->attempt;
  834. }
  835. return $attemptids;
  836. }
  837. /**
  838. * Displays the entry form and toc if required.
  839. *
  840. * @param stdClass $user user object
  841. * @param stdClass $scorm scorm object
  842. * @param string $action base URL for the organizations select box
  843. * @param stdClass $cm course module object
  844. */
  845. function scorm_print_launch ($user, $scorm, $action, $cm) {
  846. global $CFG, $DB, $OUTPUT;
  847. if ($scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
  848. scorm_parse($scorm, false);
  849. }
  850. $organization = optional_param('organization', '', PARAM_INT);
  851. if ($scorm->displaycoursestructure == 1) {
  852. echo $OUTPUT->box_start('generalbox boxaligncenter toc container', 'toc');
  853. echo html_writer::div(get_string('contents', 'scorm'), 'structurehead');
  854. }
  855. if (empty($organization)) {
  856. $organization = $scorm->launch;
  857. }
  858. if ($orgs = $DB->get_records_select_menu('scorm_scoes', 'scorm = ? AND '.
  859. $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
  860. $DB->sql_isempty('scorm_scoes', 'organization', false, false),
  861. array($scorm->id), 'sortorder, id', 'id,title')) {
  862. if (count($orgs) > 1) {
  863. $select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
  864. $select->label = get_string('organizations', 'scorm');
  865. $select->class = 'scorm-center';
  866. echo $OUTPUT->render($select);
  867. }
  868. }
  869. $orgidentifier = '';
  870. if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
  871. if (($sco->organization == '') && ($sco->launch == '')) {
  872. $orgidentifier = $sco->identifier;
  873. } else {
  874. $orgidentifier = $sco->organization;
  875. }
  876. }
  877. $scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe.
  878. if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
  879. $scorm->version = 'scorm_12';
  880. }
  881. require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
  882. $result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
  883. $incomplete = $result->incomplete;
  884. // Get latest incomplete sco to launch first if force new attempt isn't set to always.
  885. if (!empty($result->sco->id) && $scorm->forcenewattempt != SCORM_FORCEATTEMPT_ALWAYS) {
  886. $launchsco = $result->sco->id;
  887. } else {
  888. // Use launch defined by SCORM package.
  889. $launchsco = $scorm->launch;
  890. }
  891. // Do we want the TOC to be displayed?
  892. if ($scorm->displaycoursestructure == 1) {
  893. echo $result->toc;
  894. echo $OUTPUT->box_end();
  895. }
  896. // Is this the first attempt ?
  897. $attemptcount = scorm_get_attempt_count($user->id, $scorm);
  898. // Do not give the player launch FORM if the SCORM object is locked after the final attempt.
  899. if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
  900. echo html_writer::start_div('scorm-center');
  901. echo html_writer::start_tag('form', array('id' => 'scormviewform',
  902. 'method' => 'post',
  903. 'action' => $CFG->wwwroot.'/mod/scorm/player.php',
  904. 'class' => 'container'));
  905. if ($scorm->hidebrowse == 0) {
  906. print_string('mode', 'scorm');
  907. echo ': '.html_writer::empty_tag('input', array('type' => 'radio', 'id' => 'b', 'name' => 'mode',
  908. 'value' => 'browse', 'class' => 'mr-1')).
  909. html_writer::label(get_string('browse', 'scorm'), 'b');
  910. echo html_writer::empty_tag('input', array('type' => 'radio',
  911. 'id' => 'n', 'name' => 'mode',
  912. 'value' => 'normal', 'checked' => 'checked',
  913. 'class' => 'mx-1')).
  914. html_writer::label(get_string('normal', 'scorm'), 'n');
  915. } else {
  916. echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'mode', 'value' => 'normal'));
  917. }
  918. if (!empty($scorm->forcenewattempt)) {
  919. if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS ||
  920. ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ONCOMPLETE && $incomplete === false)) {
  921. echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'newattempt', 'value' => 'on'));
  922. }
  923. } else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
  924. echo html_writer::empty_tag('br');
  925. echo html_writer::checkbox('newattempt', 'on', false, '', array('id' => 'a'));
  926. echo html_writer::label(get_string('newattempt', 'scorm'), 'a');
  927. }
  928. if (!empty($scorm->popup)) {
  929. echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'display', 'value' => 'popup'));
  930. }
  931. echo html_writer::empty_tag('br');
  932. echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scoid', 'value' => $launchsco));
  933. echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'cm', 'value' => $cm->id));
  934. echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'currentorg', 'value' => $orgidentifier));
  935. echo html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('enter', 'scorm'),
  936. 'class' => 'btn btn-primary'));
  937. echo html_writer::end_tag('form');
  938. echo html_writer::end_div();
  939. }
  940. }
  941. function scorm_simple_play($scorm, $user, $context, $cmid) {
  942. global $DB;
  943. $result = false;
  944. if (has_capability('mod/scorm:viewreport', $context)) {
  945. // If this user can view reports, don't skipview so they can see links to reports.
  946. return $result;
  947. }
  948. if ($scorm->updatefreq == SCORM_UPDATE_EVERYTIME) {
  949. scorm_parse($scorm, false);
  950. }
  951. $scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
  952. $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
  953. if ($scoes) {
  954. $orgidentifier = '';
  955. if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
  956. if (($sco->organization == '') && ($sco->launch == '')) {
  957. $orgidentifier = $sco->identifier;
  958. } else {
  959. $orgidentifier = $sco->organization;
  960. }
  961. }
  962. if ($scorm->skipview >= SCORM_SKIPVIEW_FIRST) {
  963. $sco = current($scoes);
  964. $result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
  965. $url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id, 'currentorg' => $orgidentifier));
  966. // Set last incomplete sco to launch first if forcenewattempt not set to always.
  967. if (!empty($result->sco->id) && $scorm->forcenewattempt != SCORM_FORCEATTEMPT_ALWAYS) {
  968. $url->param('scoid', $result->sco->id);
  969. } else {
  970. $url->param('scoid', $sco->id);
  971. }
  972. if ($scorm->skipview == SCORM_SKIPVIEW_ALWAYS || !scorm_has_tracks($scorm->id, $user->id)) {
  973. if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS ||
  974. ($result->incomplete === false && $scorm->forcenewattempt == SCORM_FORCEATTEMPT_ONCOMPLETE)) {
  975. $url->param('newattempt', 'on');
  976. }
  977. redirect($url);
  978. }
  979. }
  980. }
  981. return $result;
  982. }
  983. function scorm_get_count_users($scormid, $groupingid=null) {
  984. global $CFG, $DB;
  985. if (!empty($groupingid)) {
  986. $sql = "SELECT COUNT(DISTINCT st.userid)
  987. FROM {scorm_scoes_track} st
  988. INNER JOIN {groups_members} gm ON st.userid = gm.userid
  989. INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
  990. WHERE st.scormid = ? AND gg.groupingid = ?
  991. ";
  992. $params = array($scormid, $groupingid);
  993. } else {
  994. $sql = "SELECT COUNT(DISTINCT st.userid)
  995. FROM {scorm_scoes_track} st
  996. WHERE st.scormid = ?
  997. ";
  998. $params = array($scormid);
  999. }
  1000. return ($DB->count_records_sql($sql, $params));
  1001. }
  1002. /**
  1003. * Build up the JavaScript representation of an array element
  1004. *
  1005. * @param string $sversion SCORM API version
  1006. * @param array $userdata User track data
  1007. * @param string $elementname Name of array element to get values for
  1008. * @param array $children list of sub elements of this array element that also need instantiating
  1009. * @return Javascript array elements
  1010. */
  1011. function scorm_reconstitute_array_element($sversion, $userdata, $elementname, $children) {
  1012. // Reconstitute comments_from_learner and comments_from_lms.
  1013. $current = '';
  1014. $currentsubelement = '';
  1015. $currentsub = '';
  1016. $count = 0;
  1017. $countsub = 0;
  1018. $scormseperator = '_';
  1019. $return = '';
  1020. if (scorm_version_check($sversion, SCORM_13)) { // Scorm 1.3 elements use a . instead of an _ .
  1021. $scormseperator = '.';
  1022. }
  1023. // Filter out the ones we want.
  1024. $elementlist = array();
  1025. foreach ($userdata as $element => $value) {
  1026. if (substr($element, 0, strlen($elementname)) == $elementname) {
  1027. $elementlist[$element] = $value;
  1028. }
  1029. }
  1030. // Sort elements in .n array order.
  1031. uksort($elementlist, "scorm_element_cmp");
  1032. // Generate JavaScript.
  1033. foreach ($elementlist as $element => $value) {
  1034. if (scorm_version_check($sversion, SCORM_13)) {
  1035. $element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
  1036. preg_match('/\.(N\d+)\./', $element, $matches);
  1037. } else {
  1038. $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
  1039. preg_match('/\_(\d+)\./', $element, $matches);
  1040. }
  1041. if (count($matches) > 0 && $current != $matches[1]) {
  1042. if ($countsub > 0) {
  1043. $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
  1044. }
  1045. $current = $matches[1];
  1046. $count++;
  1047. $currentsubelement = '';
  1048. $currentsub = '';
  1049. $countsub = 0;
  1050. $end = strpos($element, $matches[1]) + strlen($matches[1]);
  1051. $subelement = substr($element, 0, $end);
  1052. $return .= ' '.$subelement." = new Object();\n";
  1053. // Now add the children.
  1054. foreach ($children as $child) {
  1055. $return .= ' '.$subelement.".".$child." = new Object();\n";
  1056. $return .= ' '.$subelement.".".$child."._children = ".$child."_children;\n";
  1057. }
  1058. }
  1059. // Now - flesh out the second level elements if there are any.
  1060. if (scorm_version_check($sversion, SCORM_13)) {
  1061. $element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
  1062. preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
  1063. } else {
  1064. $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
  1065. preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
  1066. }
  1067. // Check the sub element type.
  1068. if (count($matches) > 0 && $currentsubelement != $matches[1]) {
  1069. if ($countsub > 0) {
  1070. $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
  1071. }
  1072. $currentsubelement = $matches[1];
  1073. $currentsub = '';
  1074. $countsub = 0;
  1075. $end = strpos($element, $matches[1]) + strlen($matches[1]);
  1076. $subelement = substr($element, 0, $end);
  1077. $return .= ' '.$subelement." = new Object();\n";
  1078. }
  1079. // Now check the subelement subscript.
  1080. if (count($matches) > 0 && $currentsub != $matches[2]) {
  1081. $currentsub = $matches[2];
  1082. $countsub++;
  1083. $end = strrpos($element, $matches[2]) + strlen($matches[2]);
  1084. $subelement = substr($element, 0, $end);
  1085. $return .= ' '.$subelement." = new Object();\n";
  1086. }
  1087. $return .= ' '.$element.' = '.json_encode($value).";\n";
  1088. }
  1089. if ($countsub > 0) {
  1090. $return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
  1091. }
  1092. if ($count > 0) {
  1093. $return .= ' '.$elementname.'._count = '.$count.";\n";
  1094. }
  1095. return $return;
  1096. }
  1097. /**
  1098. * Build up the JavaScript representation of an array element
  1099. *
  1100. * @param string $a left array element
  1101. * @param string $b right array element
  1102. * @return comparator - 0,1,-1
  1103. */
  1104. function scorm_element_cmp($a, $b) {
  1105. preg_match('/.*?(\d+)\./', $a, $matches);
  1106. $left = intval($matches[1]);
  1107. preg_match('/.?(\d+)\./', $b, $matches);
  1108. $right = intval($matches[1]);
  1109. if ($left < $right) {
  1110. return -1; // Smaller.
  1111. } else if ($left > $right) {
  1112. return 1; // Bigger.
  1113. } else {
  1114. // Look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern.
  1115. if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
  1116. $leftterm = intval($matches[2]);
  1117. $left = intval($matches[3]);
  1118. if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
  1119. $rightterm = intval($matches[2]);
  1120. $right = intval($matches[3]);
  1121. if ($leftterm < $rightterm) {
  1122. return -1; // Smaller.
  1123. } else if ($leftterm > $rightterm) {
  1124. return 1; // Bigger.
  1125. } else {
  1126. if ($left < $right) {
  1127. return -1; // Smaller.
  1128. } else if ($left > $right) {
  1129. return 1; // Bigger.
  1130. }
  1131. }
  1132. }
  1133. }
  1134. // Fall back for no second level matches or second level matches are equal.
  1135. return 0; // Equal to.
  1136. }
  1137. }
  1138. /**
  1139. * Generate the user attempt status string
  1140. *
  1141. * @param object $user Current context user
  1142. * @param object $scorm a moodle scrom object - mdl_scorm
  1143. * @return string - Attempt status string
  1144. */
  1145. function scorm_get_attempt_status($user, $scorm, $cm='') {
  1146. global $DB, $PAGE, $OUTPUT;
  1147. $attempts = scorm_get_attempt_count($user->id, $scorm, true);
  1148. if (empty($attempts)) {
  1149. $attemptcount = 0;
  1150. } else {
  1151. $attemptcount = count($attempts);
  1152. }
  1153. $result = html_writer::start_tag('p').get_string('noattemptsallowed', 'scorm').': ';
  1154. if ($scorm->maxattempt > 0) {
  1155. $result .= $scorm->maxattempt . html_writer::empty_tag('br');
  1156. } else {
  1157. $result .= get_string('unlimited').html_writer::empty_tag('br');
  1158. }
  1159. $result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . html_writer::empty_tag('br');
  1160. if ($scorm->maxattempt == 1) {
  1161. switch ($scorm->grademethod) {
  1162. case GRADEHIGHEST:
  1163. $grademethod = get_string('gradehighest', 'scorm');
  1164. break;
  1165. case GRADEAVERAGE:
  1166. $grademethod = get_string('gradeaverage', 'scorm');
  1167. break;
  1168. case GRADESUM:
  1169. $grademethod = get_string('gradesum', 'scorm');
  1170. break;
  1171. case GRADESCOES:
  1172. $grademethod = get_string('gradescoes', 'scorm');
  1173. break;
  1174. }
  1175. } else {
  1176. switch ($scorm->whatgrade) {
  1177. case HIGHESTATTEMPT:
  1178. $grademethod = get_string('highestattempt', 'scorm');
  1179. break;
  1180. case AVERAGEATTEMPT:
  1181. $grademethod = get_string('averageattempt', 'scorm');
  1182. break;
  1183. case FIRSTATTEMPT:
  1184. $grademethod = get_string('firstattempt', 'scorm');
  1185. break;
  1186. case LASTATTEMPT:
  1187. $grademethod = get_string('lastattempt', 'scorm');
  1188. break;
  1189. }
  1190. }
  1191. if (!empty($attempts)) {
  1192. $i = 1;
  1193. foreach ($attempts as $attempt) {
  1194. $gradereported = scorm_grade_user_attempt($scorm, $user->id, $attempt->attemptnumber);
  1195. if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
  1196. $gradereported = $gradereported / $scorm->maxgrade;
  1197. $gradereported = number_format($gradereported * 100, 0) .'%';
  1198. }
  1199. $result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .html_writer::empty_tag('br');
  1200. $i++;
  1201. }
  1202. }
  1203. $calculatedgrade = scorm_grade_user($scorm, $user->id);
  1204. if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
  1205. $calculatedgrade = $calculatedgrade / $scorm->maxgrade;
  1206. $calculatedgrade = number_format($calculatedgrade * 100, 0) .'%';
  1207. }
  1208. $result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
  1209. if (empty($attempts)) {
  1210. $result .= html_writer::empty_tag('br').get_string('gradereported', 'scorm').
  1211. ': '.get_string('none').html_writer::empty_tag('br');
  1212. } else {
  1213. $result .= html_writer::empty_tag('br').get_string('gradereported', 'scorm').
  1214. ': '.$calculatedgrade.html_writer::empty_tag('br');
  1215. }
  1216. $result .= html_writer::end_tag('p');
  1217. if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
  1218. $result .= html_writer::tag('p', get_string('exceededmaxattempts', 'scorm'), array('class' => 'exceededmaxattempts'));
  1219. }
  1220. if (!empty($cm)) {
  1221. $context = context_module::instance($cm->id);
  1222. if (has_capability('mod/scorm:deleteownresponses', $context) &&
  1223. $DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
  1224. // Check to see if any data is stored for this user.
  1225. $deleteurl = new moodle_url($PAGE->url, array('action' => 'delete', 'sesskey' => sesskey()));
  1226. $result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
  1227. }
  1228. }
  1229. return $result;
  1230. }
  1231. /**
  1232. * Get SCORM attempt count
  1233. *
  1234. * @param object $user Current context user
  1235. * @param object $scorm a moodle scrom object - mdl_scorm
  1236. * @param bool $returnobjects if true returns a object with attempts, if false returns count of attempts.
  1237. * @param bool $ignoremissingcompletion - ignores attempts that haven't reported a grade/completion.
  1238. * @return int - no. of attempts so far
  1239. */
  1240. function scorm_get_attempt_count($userid, $scorm, $returnobjects = false, $ignoremissingcompletion = false) {
  1241. global $DB;
  1242. // Historically attempts that don't report these elements haven't been included in the average attempts grading method
  1243. // we may want to change this in future, but to avoid unexpected grade decreases we're leaving this in. MDL-43222 .
  1244. if (scorm_version_check($scorm->version, SCORM_13)) {
  1245. $element = 'cmi.score.raw';
  1246. } else if ($scorm->grademethod == GRADESCOES) {
  1247. $element = 'cmi.core.lesson_status';
  1248. } else {
  1249. $element = 'cmi.core.score.raw';
  1250. }
  1251. if ($returnobjects) {
  1252. $params = array('userid' => $userid, 'scormid' => $scorm->id);
  1253. if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
  1254. $params['element'] = $element;
  1255. }
  1256. $attempts = $DB->get_records('scorm_scoes_track', $params, 'attempt', 'DISTINCT attempt AS attemptnumber');
  1257. return $attempts;
  1258. } else {
  1259. $params = array($userid, $scorm->id);
  1260. $sql = "SELECT COUNT(DISTINCT attempt)
  1261. FROM {scorm_scoes_track}
  1262. WHERE userid = ? AND scormid = ?";
  1263. if ($ignoremissingcompletion) { // Exclude attempts that don't have the completion element requested.
  1264. $sql .= ' AND element = ?';
  1265. $params[] = $element;
  1266. }
  1267. $attemptscount = $DB->count_records_sql($sql, $params);
  1268. return $attemptscount;
  1269. }
  1270. }
  1271. /**
  1272. * Figure out with this is a debug situation
  1273. *
  1274. * @param object $scorm a moodle scrom object - mdl_scorm
  1275. * @return boolean - debugging true/false
  1276. */
  1277. function scorm_debugging($scorm) {
  1278. global $USER;
  1279. $cfgscorm = get_config('scorm');
  1280. if (!$cfgscorm->allowapidebug) {
  1281. return false;
  1282. }
  1283. $identifier = $USER->username.':'.$scorm->name;
  1284. $test = $cfgscorm->apidebugmask;
  1285. // Check the regex is only a short list of safe characters.
  1286. if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
  1287. return false;
  1288. }
  1289. if (preg_match('/^'.$test.'/', $identifier)) {
  1290. return true;
  1291. }
  1292. return false;
  1293. }
  1294. /**
  1295. * Delete Scorm tracks for selected users
  1296. *
  1297. * @param array $attemptids list of attempts that need to be deleted
  1298. * @param stdClass $scorm instance
  1299. *
  1300. * @return bool true deleted all responses, false failed deleting an attempt - stopped here
  1301. */
  1302. function scorm_delete_responses($attemptids, $scorm) {
  1303. if (!is_array($attemptids) || empty($attemptids)) {
  1304. return false;
  1305. }
  1306. foreach ($attemptids as $num => $attemptid) {
  1307. if (empty($attemptid)) {
  1308. unset($attemptids[$num]);
  1309. }
  1310. }
  1311. foreach ($attemptids as $attempt) {
  1312. $keys = explode(':', $attempt);
  1313. if (count($keys) == 2) {
  1314. $userid = clean_param($keys[0], PARAM_INT);
  1315. $attemptid = clean_param($keys[1], PARAM_INT);
  1316. if (!$userid || !$attemptid || !scorm_delete_attempt($userid, $scorm, $attemptid)) {
  1317. return false;
  1318. }
  1319. } else {
  1320. return false;
  1321. }
  1322. }
  1323. return true;
  1324. }
  1325. /**
  1326. * Delete Scorm tracks for selected users
  1327. *
  1328. * @param int $userid ID of User
  1329. * @param stdClass $scorm Scorm object
  1330. * @param int $attemptid user attempt that need to be deleted
  1331. *
  1332. * @return bool true suceeded
  1333. */
  1334. function scorm_delete_attempt($userid, $scorm, $attemptid) {
  1335. global $DB;
  1336. $DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
  1337. $cm = get_coursemodule_from_instance('scorm', $scorm->id);
  1338. // Trigger instances list viewed event.
  1339. $event = \mod_scorm\event\attempt_deleted::create(array(
  1340. 'other' => array('attemptid' => $attemptid),
  1341. 'context' => context_module::instance($cm->id),
  1342. 'relateduserid' => $userid
  1343. ));
  1344. $event->add_record_snapshot('course_modules', $cm);
  1345. $event->add_record_snapshot('scorm', $scorm);
  1346. $event->trigger();
  1347. include_once('lib.php');
  1348. scorm_update_grades($scorm, $userid, true);
  1349. return true;
  1350. }
  1351. /**
  1352. * Converts SCORM duration notation to human-readable format
  1353. * The function works with both SCORM 1.2 and SCORM 2004 time formats
  1354. * @param $duration string SCORM duration
  1355. * @return string human-readable date/time
  1356. */
  1357. function scorm_format_duration($duration) {
  1358. // Fetch date/time strings.
  1359. $stryears = get_string('years');
  1360. $strmonths = get_string('nummonths');
  1361. $strdays = get_string('days');
  1362. $strhours = get_string('hours');
  1363. $strminutes = get_string('minutes');
  1364. $strseconds = get_string('seconds');
  1365. if ($duration[0] == 'P') {
  1366. // If timestamp starts with 'P' - it's a SCORM 2004 format
  1367. // this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
  1368. // and outputs filled sections, discarding leading zeroes and any format literals
  1369. // also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
  1370. $pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#',
  1371. '#0*(\d+)Y#', '#0*(\d+)D#', '#P#', '#([A-Z])0+H#', '#([A-Z])[0.]+S#',
  1372. '#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#',
  1373. '#0*([\d.]+)S#', '#T#' );
  1374. $replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ',
  1375. '', '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ',
  1376. '0.$1 '.$strseconds, '$1 '.$strseconds, '');
  1377. } else {
  1378. // Else we have SCORM 1.2 format there
  1379. // first convert the timestamp to some SCORM 2004-like format for conveniency.
  1380. $duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
  1381. // Then convert in the same way as SCORM 2004.
  1382. $pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#',
  1383. '#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
  1384. $replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ',
  1385. '0.$1 '.$strseconds, '$1 '.$strseconds, '' );
  1386. }
  1387. $result = preg_replace($pattern, $replace, $duration);
  1388. return $result;
  1389. }
  1390. function scorm_get_toc_object($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='',
  1391. $play=false, $organizationsco=null) {
  1392. global $CFG, $DB, $PAGE, $OUTPUT;
  1393. // Always pass the mode even if empty as that is what is done elsewhere and the urls have to match.
  1394. $modestr = '&mode=';
  1395. if ($mode != 'normal') {
  1396. $modestr = '&mode='.$mode;
  1397. }
  1398. $result = array();
  1399. $incomplete = false;
  1400. if (!empty($organizationsco)) {
  1401. $result[0] = $organizationsco;
  1402. $result[0]->isvisible = 'true';
  1403. $result[0]->statusicon = '';
  1404. $result[0]->url = '';
  1405. }
  1406. if ($scoes = scorm_get_scoes($scorm->id, $currentorg)) {
  1407. // Retrieve user tracking data for each learning object.
  1408. $usertracks = array();
  1409. foreach ($scoes as $sco) {
  1410. if (!empty($sco->launch)) {
  1411. if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
  1412. if ($usertrack->status == '') {
  1413. $usertrack->status = 'notattempted';
  1414. }
  1415. $usertracks[$sco->identifier] = $usertrack;
  1416. }
  1417. }
  1418. }
  1419. foreach ($scoes as $sco) {
  1420. if (!isset($sco->isvisible)) {
  1421. $sco->isvisible = 'true';
  1422. }
  1423. if (empty($sco->title)) {
  1424. $sco->title = $sco->identifier;
  1425. }
  1426. if (scorm_version_check($scorm->version, SCORM_13)) {
  1427. $sco->prereq = true;
  1428. } else {
  1429. $sco->prereq = empty($sco->prerequisites) || scorm_eval_prerequisites($sco->prerequisites, $usertracks);
  1430. }
  1431. if ($sco->isvisible === 'true') {
  1432. if (!empty($sco->launch)) {
  1433. // Set first sco to launch if in browse/review mode.
  1434. if (empty($scoid) && ($mode != 'normal')) {
  1435. $scoid = $sco->id;
  1436. }
  1437. if (isset($usertracks[$sco->identifier])) {
  1438. $usertrack = $usertracks[$sco->identifier];
  1439. // Check we have a valid status string identifier.
  1440. if ($statusstringexists = get_string_manager()->string_exists($usertrack->status, 'scorm')) {
  1441. $strstatus = get_string($usertrack->status, 'scorm');
  1442. } else {
  1443. $strstatus = get_string('invalidstatus', 'scorm');
  1444. }
  1445. if ($sco->scormtype == 'sco') {
  1446. // Assume if we didn't get a valid status string, we don't have an icon either.
  1447. $statusicon = $OUTPUT->pix_icon($statusstringexists ? $usertrack->status : 'incomplete',
  1448. $strstatus, 'scorm');
  1449. } else {
  1450. $statusicon = $OUTPUT->pix_icon('asset', get_string('assetlaunched', 'scorm'), 'scorm');
  1451. }
  1452. if (($usertrack->status == 'notattempted') ||
  1453. ($usertrack->status == 'incomplete') ||
  1454. ($usertrack->status == 'browsed')) {
  1455. $incomplete = true;
  1456. if (empty($scoid)) {
  1457. $scoid = $sco->id;
  1458. }
  1459. }
  1460. $strsuspended = get_string('suspended', 'scorm');
  1461. $exitvar = 'cmi.core.exit';
  1462. if (scorm_version_check($scorm->version, SCORM_13)) {
  1463. $exitvar = 'cmi.exit';
  1464. }
  1465. if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
  1466. $statusicon = $OUTPUT->pix_icon('suspend', $strstatus.' - '.$strsuspended, 'scorm');
  1467. }
  1468. } else {
  1469. if (empty($scoid)) {
  1470. $scoid = $sco->id;
  1471. }
  1472. $incomplete = true;
  1473. if ($sco->scormtype == 'sco') {
  1474. $statusicon = $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
  1475. } else {
  1476. $statusicon = $OUTPUT->pix_icon('asset', get_string('asset', 'scorm'), 'scorm');
  1477. }
  1478. }
  1479. }
  1480. }
  1481. if (empty($statusicon)) {
  1482. $sco->statusicon = $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
  1483. } else {
  1484. $sco->statusicon = $statusicon;
  1485. }
  1486. $sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'&currentorg='.$currentorg.$modestr.'&attempt='.$attempt;
  1487. $sco->incomplete = $incomplete;
  1488. if (!in_array($sco->id, array_keys($result))) {
  1489. $result[$sco->id] = $sco;
  1490. }
  1491. }
  1492. }
  1493. // Get the parent scoes!
  1494. $result = scorm_get_toc_get_parent_child($result, $currentorg);
  1495. // Be safe, prevent warnings from showing up while returning array.
  1496. if (!isset($scoid)) {
  1497. $scoid = '';
  1498. }
  1499. return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
  1500. }
  1501. function scorm_get_toc_get_parent_child(&$result, $currentorg) {
  1502. $final = array();
  1503. $level = 0;
  1504. // Organization is always the root, prevparent.
  1505. if (!empty($currentorg)) {
  1506. $prevparent = $currentorg;
  1507. } else {
  1508. $prevparent = '/';
  1509. }
  1510. foreach ($result as $sco) {
  1511. if ($sco->parent == '/') {
  1512. $final[$level][$sco->identifier] = $sco;
  1513. $prevparent = $sco->identifier;
  1514. unset($result[$sco->id]);
  1515. } else {
  1516. if ($sco->parent == $prevparent) {
  1517. $final[$level][$sco->identifier] = $sco;
  1518. $prevparent = $sco->identifier;
  1519. unset($result[$sco->id]);
  1520. } else {
  1521. if (!empty($final[$level])) {
  1522. $found = false;
  1523. foreach ($final[$level] as $fin) {
  1524. if ($sco->parent == $fin->identifier) {
  1525. $found = true;
  1526. }
  1527. }
  1528. if ($found) {
  1529. $final[$level][$sco->identifier] = $sco;
  1530. unset($result[$sco->id]);
  1531. $found = false;
  1532. } else {
  1533. $level++;
  1534. $final[$level][$sco->identifier] = $sco;
  1535. unset($result[$sco->id]);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. }
  1541. for ($i = 0; $i <= $level; $i++) {
  1542. $prevparent = '';
  1543. foreach ($final[$i] as $ident => $sco) {
  1544. if (empty($prevparent)) {
  1545. $prevparent = $ident;
  1546. }
  1547. if (!isset($final[$i][$prevparent]->children)) {
  1548. $final[$i][$prevparent]->children = array();
  1549. }
  1550. if ($sco->parent == $prevparent) {
  1551. $final[$i][$prevparent]->children[] = $sco;
  1552. $prevparent = $ident;
  1553. } else {
  1554. $parent = false;
  1555. foreach ($final[$i] as $identifier => $scoobj) {
  1556. if ($identifier == $sco->parent) {
  1557. $parent = $identifier;
  1558. }
  1559. }
  1560. if ($parent !== false) {
  1561. $final[$i][$parent]->children[] = $sco;
  1562. }
  1563. }
  1564. }
  1565. }
  1566. $results = array();
  1567. for ($i = 0; $i <= $level; $i++) {
  1568. $keys = array_keys($final[$i]);
  1569. $results[] = $final[$i][$keys[0]];
  1570. }
  1571. return $results;
  1572. }
  1573. function scorm_format_toc_for_treeview($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='',
  1574. $attempt='', $play=false, $organizationsco=null, $children=false) {
  1575. global $CFG;
  1576. $result = new stdClass();
  1577. $result->prerequisites = true;
  1578. $result->incomplete = true;
  1579. $result->toc = '';
  1580. if (!$children) {
  1581. $attemptsmade = scorm_get_attempt_count($user->id, $scorm);
  1582. $result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
  1583. }
  1584. if (!$children) {
  1585. $result->toc = html_writer::start_tag('ul');
  1586. if (!$play && !empty($organizationsco)) {
  1587. $result->toc .= html_writer::start_tag('li').$organizationsco->title.html_writer::end_tag('li');
  1588. }
  1589. }
  1590. $prevsco = '';
  1591. if (!empty($scoes)) {
  1592. foreach ($scoes as $sco) {
  1593. if ($sco->isvisible === 'false') {
  1594. continue;
  1595. }
  1596. $result->toc .= html_writer::start_tag('li');
  1597. $scoid = $sco->id;
  1598. $score = '';
  1599. if (isset($usertracks[$sco->identifier])) {
  1600. $viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
  1601. if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
  1602. if ($usertracks[$sco->identifier]->score_raw != '') {
  1603. $score = '('.get_string('score', 'scorm').':&nbsp;'.$usertracks[$sco->identifier]->score_raw.')';
  1604. }
  1605. }
  1606. }
  1607. if (!empty($sco->prereq)) {
  1608. if ($sco->id == $scoid) {
  1609. $result->prerequisites = true;
  1610. }
  1611. if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
  1612. if ($sco->scormtype == 'sco') {
  1613. $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
  1614. } else {
  1615. $result->toc .= html_writer::span('&nbsp;'.format_string($sco->title));
  1616. }
  1617. } else if ($toclink == TOCFULLURL) {
  1618. $url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
  1619. if (!empty($sco->launch)) {
  1620. if ($sco->scormtype == 'sco') {
  1621. $result->toc .= $sco->statusicon.'&nbsp;';
  1622. $result->toc .= html_writer::link($url, format_string($sco->title)).$score;
  1623. } else {
  1624. $result->toc .= '&nbsp;'.html_writer::link($url, format_string($sco->title),
  1625. array('data-scoid' => $sco->id)).$score;
  1626. }
  1627. } else {
  1628. if ($sco->scormtype == 'sco') {
  1629. $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title).$score;
  1630. } else {
  1631. $result->toc .= '&nbsp;'.format_string($sco->title).$score;
  1632. }
  1633. }
  1634. } else {
  1635. if (!empty($sco->launch)) {
  1636. if ($sco->scormtype == 'sco') {
  1637. $result->toc .= html_writer::tag('a', $sco->statusicon.'&nbsp;'.
  1638. format_string($sco->title).'&nbsp;'.$score,
  1639. array('data-scoid' => $sco->id, 'title' => $sco->url));
  1640. } else {
  1641. $result->toc .= html_writer::tag('a', '&nbsp;'.format_string($sco->title).'&nbsp;'.$score,
  1642. array('data-scoid' => $sco->id, 'title' => $sco->url));
  1643. }
  1644. } else {
  1645. if ($sco->scormtype == 'sco') {
  1646. $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
  1647. } else {
  1648. $result->toc .= html_writer::span('&nbsp;'.format_string($sco->title));
  1649. }
  1650. }
  1651. }
  1652. } else {
  1653. if ($play) {
  1654. if ($sco->scormtype == 'sco') {
  1655. $result->toc .= html_writer::span($sco->statusicon.'&nbsp;'.format_string($sco->title));
  1656. } else {
  1657. $result->toc .= '&nbsp;'.format_string($sco->title).html_writer::end_span();
  1658. }
  1659. } else {
  1660. if ($sco->scormtype == 'sco') {
  1661. $result->toc .= $sco->statusicon.'&nbsp;'.format_string($sco->title);
  1662. } else {
  1663. $result->toc .= '&nbsp;'.format_string($sco->title);
  1664. }
  1665. }
  1666. }
  1667. if (!empty($sco->children)) {
  1668. $result->toc .= html_writer::start_tag('ul');
  1669. $childresult = scorm_format_toc_for_treeview($user, $scorm, $sco->children, $usertracks, $cmid,
  1670. $toclink, $currentorg, $attempt, $play, $organizationsco, true);
  1671. // Is any of the children incomplete?
  1672. $sco->incomplete = $childresult->incomplete;
  1673. $result->toc .= $childresult->toc;
  1674. $result->toc .= html_writer::end_tag('ul');
  1675. $result->toc .= html_writer::end_tag('li');
  1676. } else {
  1677. $result->toc .= html_writer::end_tag('li');
  1678. }
  1679. $prevsco = $sco;
  1680. }
  1681. $result->incomplete = $sco->incomplete;
  1682. }
  1683. if (!$children) {
  1684. $result->toc .= html_writer::end_tag('ul');
  1685. }
  1686. return $result;
  1687. }
  1688. function scorm_format_toc_for_droplist($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null,
  1689. $children=false, $level=0, $tocmenus=array()) {
  1690. if (!empty($scoes)) {
  1691. if (!empty($organizationsco) && !$children) {
  1692. $tocmenus[$organizationsco->id] = $organizationsco->title;
  1693. }
  1694. $parents[$level] = '/';
  1695. foreach ($scoes as $sco) {
  1696. if ($parents[$level] != $sco->parent) {
  1697. if ($newlevel = array_search($sco->parent, $parents)) {
  1698. $level = $newlevel;
  1699. } else {
  1700. $i = $level;
  1701. while (($i > 0) && ($parents[$level] != $sco->parent)) {
  1702. $i--;
  1703. }
  1704. if (($i == 0) && ($sco->parent != $currentorg)) {
  1705. $level++;
  1706. } else {
  1707. $level = $i;
  1708. }
  1709. $parents[$level] = $sco->parent;
  1710. }
  1711. }
  1712. if ($sco->scormtype == 'sco') {
  1713. $tocmenus[$sco->id] = scorm_repeater('&minus;', $level) . '&gt;' . format_string($sco->title);
  1714. }
  1715. if (!empty($sco->children)) {
  1716. $tocmenus = scorm_format_toc_for_droplist($scorm, $sco->children, $usertracks, $currentorg,
  1717. $organizationsco, true, $level, $tocmenus);
  1718. }
  1719. }
  1720. }
  1721. return $tocmenus;
  1722. }
  1723. function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal',
  1724. $attempt='', $play=false, $tocheader=false) {
  1725. global $CFG, $DB, $OUTPUT;
  1726. if (empty($attempt)) {
  1727. $attempt = scorm_get_last_attempt($scorm->id, $user->id);
  1728. }
  1729. $result = new stdClass();
  1730. $organizationsco = null;
  1731. if ($tocheader) {
  1732. $result->toc = html_writer::start_div('yui3-g-r', array('id' => 'scorm_layout'));
  1733. $result->toc .= html_writer::start_div('yui3-u-1-5 loading', array('id' => 'scorm_toc'));
  1734. $result->toc .= html_writer::div('', '', array('id' => 'scorm_toc_title'));
  1735. $result->toc .= html_writer::start_div('', array('id' => 'scorm_tree'));
  1736. }
  1737. if (!empty($currentorg)) {
  1738. $organizationsco = $DB->get_record('scorm_scoes', array('scorm' => $scorm->id, 'identifier' => $currentorg));
  1739. if (!empty($organizationsco->title)) {
  1740. if ($play) {
  1741. $result->toctitle = $organizationsco->title;
  1742. }
  1743. }
  1744. }
  1745. $scoes = scorm_get_toc_object($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
  1746. $treeview = scorm_format_toc_for_treeview($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid,
  1747. $toclink, $currentorg, $attempt, $play, $organizationsco, false);
  1748. if ($tocheader) {
  1749. $result->toc .= $treeview->toc;
  1750. } else {
  1751. $result->toc = $treeview->toc;
  1752. }
  1753. if (!empty($scoes['scoid'])) {
  1754. $scoid = $scoes['scoid'];
  1755. }
  1756. if (empty($scoid)) {
  1757. // If this is a normal package with an org sco and child scos get the first child.
  1758. if (!empty($scoes['scoes'][0]->children)) {
  1759. $result->sco = $scoes['scoes'][0]->children[0];
  1760. } else { // This package only has one sco - it may be a simple external AICC package.
  1761. $result->sco = $scoes['scoes'][0];
  1762. }
  1763. } else {
  1764. $result->sco = scorm_get_sco($scoid);
  1765. }
  1766. if ($scorm->hidetoc == SCORM_TOC_POPUP) {
  1767. $tocmenu = scorm_format_toc_for_droplist($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'],
  1768. $currentorg, $organizationsco);
  1769. $modestr = '';
  1770. if ($mode != 'normal') {
  1771. $modestr = '&mode='.$mode;
  1772. }
  1773. $url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'&currentorg='.$currentorg.$modestr);
  1774. $result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
  1775. }
  1776. $result->prerequisites = $treeview->prerequisites;
  1777. $result->incomplete = $treeview->incomplete;
  1778. $result->attemptleft = $treeview->attemptleft;
  1779. if ($tocheader) {
  1780. $result->toc .= html_writer::end_div().html_writer::end_div();
  1781. $result->toc .= html_writer::start_div('loading', array('id' => 'scorm_toc_toggle'));
  1782. $result->toc .= html_writer::tag('button', '', array('id' => 'scorm_toc_toggle_btn')).html_writer::end_div();
  1783. $result->toc .= html_writer::start_div('', array('id' => 'scorm_content'));
  1784. $result->toc .= html_writer::div('', '', array('id' => 'scorm_navpanel'));
  1785. $result->toc .= html_writer::end_div().html_writer::end_div();
  1786. }
  1787. return $result;
  1788. }
  1789. function scorm_get_adlnav_json ($scoes, &$adlnav = array(), $parentscoid = null) {
  1790. if (is_object($scoes)) {
  1791. $sco = $scoes;
  1792. if (isset($sco->url)) {
  1793. $adlnav[$sco->id]['identifier'] = $sco->identifier;
  1794. $adlnav[$sco->id]['launch'] = $sco->launch;
  1795. $adlnav[$sco->id]['title'] = $sco->title;
  1796. $adlnav[$sco->id]['url'] = $sco->url;
  1797. $adlnav[$sco->id]['parent'] = $sco->parent;
  1798. if (isset($sco->choice)) {
  1799. $adlnav[$sco->id]['choice'] = $sco->choice;
  1800. }
  1801. if (isset($sco->flow)) {
  1802. $adlnav[$sco->id]['flow'] = $sco->flow;
  1803. } else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
  1804. $adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
  1805. }
  1806. if (isset($sco->isvisible)) {
  1807. $adlnav[$sco->id]['isvisible'] = $sco->isvisible;
  1808. }
  1809. if (isset($sco->parameters)) {
  1810. $adlnav[$sco->id]['parameters'] = $sco->parameters;
  1811. }
  1812. if (isset($sco->hidecontinue)) {
  1813. $adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
  1814. }
  1815. if (isset($sco->hideprevious)) {
  1816. $adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
  1817. }
  1818. if (isset($sco->hidesuspendall)) {
  1819. $adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
  1820. }
  1821. if (!empty($parentscoid)) {
  1822. $adlnav[$sco->id]['parentscoid'] = $parentscoid;
  1823. }
  1824. if (isset($adlnav['prevscoid'])) {
  1825. $adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
  1826. $adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
  1827. if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
  1828. $adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
  1829. $adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
  1830. }
  1831. }
  1832. $adlnav['prevscoid'] = $sco->id;
  1833. $adlnav['prevparent'] = $sco->parent;
  1834. }
  1835. if (isset($sco->children)) {
  1836. foreach ($sco->children as $children) {
  1837. scorm_get_adlnav_json($children, $adlnav, $sco->id);
  1838. }
  1839. }
  1840. } else {
  1841. foreach ($scoes as $sco) {
  1842. scorm_get_adlnav_json ($sco, $adlnav);
  1843. }
  1844. unset($adlnav['prevscoid']);
  1845. unset($adlnav['prevparent']);
  1846. }
  1847. return json_encode($adlnav);
  1848. }
  1849. /**
  1850. * Check for the availability of a resource by URL.
  1851. *
  1852. * Check is performed using an HTTP HEAD call.
  1853. *
  1854. * @param $url string A valid URL
  1855. * @return bool|string True if no issue is found. The error string message, otherwise
  1856. */
  1857. function scorm_check_url($url) {
  1858. $curl = new curl;
  1859. // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}.
  1860. $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5));
  1861. $cmsg = $curl->head($url);
  1862. $info = $curl->get_info();
  1863. if (empty($info['http_code']) || $info['http_code'] != 200) {
  1864. return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
  1865. }
  1866. return true;
  1867. }
  1868. /**
  1869. * Check for a parameter in userdata and return it if it's set
  1870. * or return the value from $ifempty if its empty
  1871. *
  1872. * @param stdClass $userdata Contains user's data
  1873. * @param string $param parameter that should be checked
  1874. * @param string $ifempty value to be replaced with if $param is not set
  1875. * @return string value from $userdata->$param if its not empty, or $ifempty
  1876. */
  1877. function scorm_isset($userdata, $param, $ifempty = '') {
  1878. if (isset($userdata->$param)) {
  1879. return $userdata->$param;
  1880. } else {
  1881. return $ifempty;
  1882. }
  1883. }
  1884. /**
  1885. * Check if the current sco is launchable
  1886. * If not, find the next launchable sco
  1887. *
  1888. * @param stdClass $scorm Scorm object
  1889. * @param integer $scoid id of scorm_scoes record.
  1890. * @return integer scoid of correct sco to launch or empty if one cannot be found, which will trigger first sco.
  1891. */
  1892. function scorm_check_launchable_sco($scorm, $scoid) {
  1893. global $DB;
  1894. if ($sco = scorm_get_sco($scoid, SCO_ONLY)) {
  1895. if ($sco->launch == '') {
  1896. // This scoid might be a top level org that can't be launched, find the first launchable sco after this sco.
  1897. $scoes = $DB->get_records_select('scorm_scoes',
  1898. 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).
  1899. ' AND id > ?', array($scorm->id, $sco->id), 'sortorder, id', 'id', 0, 1);
  1900. if (!empty($scoes)) {
  1901. $sco = reset($scoes); // Get first item from the list.
  1902. return $sco->id;
  1903. }
  1904. } else {
  1905. return $sco->id;
  1906. }
  1907. }
  1908. // Returning 0 will cause default behaviour which will find the first launchable sco in the package.
  1909. return 0;
  1910. }
  1911. /**
  1912. * Check if a SCORM is available for the current user.
  1913. *
  1914. * @param stdClass $scorm SCORM record
  1915. * @param boolean $checkviewreportcap Check the scorm:viewreport cap
  1916. * @param stdClass $context Module context, required if $checkviewreportcap is set to true
  1917. * @param int $userid User id override
  1918. * @return array status (available or not and possible warnings)
  1919. * @since Moodle 3.0
  1920. */
  1921. function scorm_get_availability_status($scorm, $checkviewreportcap = false, $context = null, $userid = null) {
  1922. $open = true;
  1923. $closed = false;
  1924. $warnings = array();
  1925. $timenow = time();
  1926. if (!empty($scorm->timeopen) and $scorm->timeopen > $timenow) {
  1927. $open = false;
  1928. }
  1929. if (!empty($scorm->timeclose) and $timenow > $scorm->timeclose) {
  1930. $closed = true;
  1931. }
  1932. if (!$open or $closed) {
  1933. if ($checkviewreportcap and !empty($context) and has_capability('mod/scorm:viewreport', $context, $userid)) {
  1934. return array(true, $warnings);
  1935. }
  1936. if (!$open) {
  1937. $warnings['notopenyet'] = userdate($scorm->timeopen);
  1938. }
  1939. if ($closed) {
  1940. $warnings['expired'] = userdate($scorm->timeclose);
  1941. }
  1942. return array(false, $warnings);
  1943. }
  1944. // Scorm is available.
  1945. return array(true, $warnings);
  1946. }
  1947. /**
  1948. * Requires a SCORM package to be available for the current user.
  1949. *
  1950. * @param stdClass $scorm SCORM record
  1951. * @param boolean $checkviewreportcap Check the scorm:viewreport cap
  1952. * @param stdClass $context Module context, required if $checkviewreportcap is set to true
  1953. * @throws moodle_exception
  1954. * @since Moodle 3.0
  1955. */
  1956. function scorm_require_available($scorm, $checkviewreportcap = false, $context = null) {
  1957. list($available, $warnings) = scorm_get_availability_status($scorm, $checkviewreportcap, $context);
  1958. if (!$available) {
  1959. $reason = current(array_keys($warnings));
  1960. throw new moodle_exception($reason, 'scorm', '', $warnings[$reason]);
  1961. }
  1962. }
  1963. /**
  1964. * Return a SCO object and the SCO launch URL
  1965. *
  1966. * @param stdClass $scorm SCORM object
  1967. * @param int $scoid The SCO id in database
  1968. * @param stdClass $context context object
  1969. * @return array the SCO object and URL
  1970. * @since Moodle 3.1
  1971. */
  1972. function scorm_get_sco_and_launch_url($scorm, $scoid, $context) {
  1973. global $CFG, $DB;
  1974. if (!empty($scoid)) {
  1975. // Direct SCO request.
  1976. if ($sco = scorm_get_sco($scoid)) {
  1977. if ($sco->launch == '') {
  1978. // Search for the next launchable sco.
  1979. if ($scoes = $DB->get_records_select(
  1980. 'scorm_scoes',
  1981. 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).' AND id > ?',
  1982. array($scorm->id, $sco->id),
  1983. 'sortorder, id')) {
  1984. $sco = current($scoes);
  1985. }
  1986. }
  1987. }
  1988. }
  1989. // If no sco was found get the first of SCORM package.
  1990. if (!isset($sco)) {
  1991. $scoes = $DB->get_records_select(
  1992. 'scorm_scoes',
  1993. 'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
  1994. array($scorm->id),
  1995. 'sortorder, id'
  1996. );
  1997. $sco = current($scoes);
  1998. }
  1999. $connector = '';
  2000. $version = substr($scorm->version, 0, 4);
  2001. if ((isset($sco->parameters) && (!empty($sco->parameters))) || ($version == 'AICC')) {
  2002. if (stripos($sco->launch, '?') !== false) {
  2003. $connector = '&';
  2004. } else {
  2005. $connector = '?';
  2006. }
  2007. if ((isset($sco->parameters) && (!empty($sco->parameters))) && ($sco->parameters[0] == '?')) {
  2008. $sco->parameters = substr($sco->parameters, 1);
  2009. }
  2010. }
  2011. if ($version == 'AICC') {
  2012. require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
  2013. $aiccsid = scorm_aicc_get_hacp_session($scorm->id);
  2014. if (empty($aiccsid)) {
  2015. $aiccsid = sesskey();
  2016. }
  2017. $scoparams = '';
  2018. if (isset($sco->parameters) && (!empty($sco->parameters))) {
  2019. $scoparams = '&'. $sco->parameters;
  2020. }
  2021. $launcher = $sco->launch.$connector.'aicc_sid='.$aiccsid.'&aicc_url='.$CFG->wwwroot.'/mod/scorm/aicc.php'.$scoparams;
  2022. } else {
  2023. if (isset($sco->parameters) && (!empty($sco->parameters))) {
  2024. $launcher = $sco->launch.$connector.$sco->parameters;
  2025. } else {
  2026. $launcher = $sco->launch;
  2027. }
  2028. }
  2029. if (scorm_external_link($sco->launch)) {
  2030. // TODO: does this happen?
  2031. $scolaunchurl = $launcher;
  2032. } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
  2033. // Remote learning activity.
  2034. $scolaunchurl = dirname($scorm->reference).'/'.$launcher;
  2035. } else if ($scorm->scormtype === SCORM_TYPE_LOCAL && strtolower($scorm->reference) == 'imsmanifest.xml') {
  2036. // This SCORM content sits in a repository that allows relative links.
  2037. $scolaunchurl = "$CFG->wwwroot/pluginfile.php/$context->id/mod_scorm/imsmanifest/$scorm->revision/$launcher";
  2038. } else if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
  2039. // Note: do not convert this to use moodle_url().
  2040. // SCORM does not work without slasharguments and moodle_url() encodes querystring vars.
  2041. $scolaunchurl = "$CFG->wwwroot/pluginfile.php/$context->id/mod_scorm/content/$scorm->revision/$launcher";
  2042. }
  2043. return array($sco, $scolaunchurl);
  2044. }
  2045. /**
  2046. * Trigger the scorm_launched event.
  2047. *
  2048. * @param stdClass $scorm scorm object
  2049. * @param stdClass $sco sco object
  2050. * @param stdClass $cm course module object
  2051. * @param stdClass $context context object
  2052. * @param string $scourl SCO URL
  2053. * @since Moodle 3.1
  2054. */
  2055. function scorm_launch_sco($scorm, $sco, $cm, $context, $scourl) {
  2056. $event = \mod_scorm\event\sco_launched::create(array(
  2057. 'objectid' => $sco->id,
  2058. 'context' => $context,
  2059. 'other' => array('instanceid' => $scorm->id, 'loadedcontent' => $scourl)
  2060. ));
  2061. $event->add_record_snapshot('course_modules', $cm);
  2062. $event->add_record_snapshot('scorm', $scorm);
  2063. $event->add_record_snapshot('scorm_scoes', $sco);
  2064. $event->trigger();
  2065. }
  2066. /**
  2067. * This is really a little language parser for AICC_SCRIPT
  2068. * evaluates the expression and returns a boolean answer
  2069. * see 2.3.2.5.1. Sequencing/Navigation Today - from the SCORM 1.2 spec (CAM).
  2070. * Also used by AICC packages.
  2071. *
  2072. * @param string $prerequisites the aicc_script prerequisites expression
  2073. * @param array $usertracks the tracked user data of each SCO visited
  2074. * @return boolean
  2075. */
  2076. function scorm_eval_prerequisites($prerequisites, $usertracks) {
  2077. // This is really a little language parser - AICC_SCRIPT is the reference
  2078. // see 2.3.2.5.1. Sequencing/Navigation Today - from the SCORM 1.2 spec.
  2079. $element = '';
  2080. $stack = array();
  2081. $statuses = array(
  2082. 'passed' => 'passed',
  2083. 'completed' => 'completed',
  2084. 'failed' => 'failed',
  2085. 'incomplete' => 'incomplete',
  2086. 'browsed' => 'browsed',
  2087. 'not attempted' => 'notattempted',
  2088. 'p' => 'passed',
  2089. 'c' => 'completed',
  2090. 'f' => 'failed',
  2091. 'i' => 'incomplete',
  2092. 'b' => 'browsed',
  2093. 'n' => 'notattempted'
  2094. );
  2095. $i = 0;
  2096. // Expand the amp entities.
  2097. $prerequisites = preg_replace('/&amp;/', '&', $prerequisites);
  2098. // Find all my parsable tokens.
  2099. $prerequisites = preg_replace('/(&|\||\(|\)|\~)/', '\t$1\t', $prerequisites);
  2100. // Expand operators.
  2101. $prerequisites = preg_replace('/&/', '&&', $prerequisites);
  2102. $prerequisites = preg_replace('/\|/', '||', $prerequisites);
  2103. // Now - grab all the tokens.
  2104. $elements = explode('\t', trim($prerequisites));
  2105. // Process each token to build an expression to be evaluated.
  2106. $stack = array();
  2107. foreach ($elements as $element) {
  2108. $element = trim($element);
  2109. if (empty($element)) {
  2110. continue;
  2111. }
  2112. if (!preg_match('/^(&&|\|\||\(|\))$/', $element)) {
  2113. // Create each individual expression.
  2114. // Search for ~ = <> X*{} .
  2115. // Sets like 3*{S34, S36, S37, S39}.
  2116. if (preg_match('/^(\d+)\*\{(.+)\}$/', $element, $matches)) {
  2117. $repeat = $matches[1];
  2118. $set = explode(',', $matches[2]);
  2119. $count = 0;
  2120. foreach ($set as $setelement) {
  2121. if (isset($usertracks[$setelement]) &&
  2122. ($usertracks[$setelement]->status == 'completed' || $usertracks[$setelement]->status == 'passed')) {
  2123. $count++;
  2124. }
  2125. }
  2126. if ($count >= $repeat) {
  2127. $element = 'true';
  2128. } else {
  2129. $element = 'false';
  2130. }
  2131. } else if ($element == '~') {
  2132. // Not maps ~.
  2133. $element = '!';
  2134. } else if (preg_match('/^(.+)(\=|\<\>)(.+)$/', $element, $matches)) {
  2135. // Other symbols = | <> .
  2136. $element = trim($matches[1]);
  2137. if (isset($usertracks[$element])) {
  2138. $value = trim(preg_replace('/(\'|\")/', '', $matches[3]));
  2139. if (isset($statuses[$value])) {
  2140. $value = $statuses[$value];
  2141. }
  2142. $elementprerequisitematch = (strcmp($usertracks[$element]->status, $value) == 0);
  2143. if ($matches[2] == '<>') {
  2144. $element = $elementprerequisitematch ? 'false' : 'true';
  2145. } else {
  2146. $element = $elementprerequisitematch ? 'true' : 'false';
  2147. }
  2148. } else {
  2149. $element = 'false';
  2150. }
  2151. } else {
  2152. // Everything else must be an element defined like S45 ...
  2153. if (isset($usertracks[$element]) &&
  2154. ($usertracks[$element]->status == 'completed' || $usertracks[$element]->status == 'passed')) {
  2155. $element = 'true';
  2156. } else {
  2157. $element = 'false';
  2158. }
  2159. }
  2160. }
  2161. $stack[] = ' '.$element.' ';
  2162. }
  2163. return eval('return '.implode($stack).';');
  2164. }
  2165. /**
  2166. * Update the calendar entries for this scorm activity.
  2167. *
  2168. * @param stdClass $scorm the row from the database table scorm.
  2169. * @param int $cmid The coursemodule id
  2170. * @return bool
  2171. */
  2172. function scorm_update_calendar(stdClass $scorm, $cmid) {
  2173. global $DB, $CFG;
  2174. require_once($CFG->dirroot.'/calendar/lib.php');
  2175. // Scorm start calendar events.
  2176. $event = new stdClass();
  2177. $event->eventtype = SCORM_EVENT_TYPE_OPEN;
  2178. // The SCORM_EVENT_TYPE_OPEN event should only be an action event if no close time is specified.
  2179. $event->type = empty($scorm->timeclose) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
  2180. if ($event->id = $DB->get_field('event', 'id',
  2181. array('modulename' => 'scorm', 'instance' => $scorm->id, 'eventtype' => $event->eventtype))) {
  2182. if ((!empty($scorm->timeopen)) && ($scorm->timeopen > 0)) {
  2183. // Calendar event exists so update it.
  2184. $event->name = get_string('calendarstart', 'scorm', $scorm->name);
  2185. $event->description = format_module_intro('scorm', $scorm, $cmid, false);
  2186. $event->format = FORMAT_HTML;
  2187. $event->timestart = $scorm->timeopen;
  2188. $event->timesort = $scorm->timeopen;
  2189. $event->visible = instance_is_visible('scorm', $scorm);
  2190. $event->timeduration = 0;
  2191. $calendarevent = calendar_event::load($event->id);
  2192. $calendarevent->update($event, false);
  2193. } else {
  2194. // Calendar event is on longer needed.
  2195. $calendarevent = calendar_event::load($event->id);
  2196. $calendarevent->delete();
  2197. }
  2198. } else {
  2199. // Event doesn't exist so create one.
  2200. if ((!empty($scorm->timeopen)) && ($scorm->timeopen > 0)) {
  2201. $event->name = get_string('calendarstart', 'scorm', $scorm->name);
  2202. $event->description = format_module_intro('scorm', $scorm, $cmid, false);
  2203. $event->format = FORMAT_HTML;
  2204. $event->courseid = $scorm->course;
  2205. $event->groupid = 0;
  2206. $event->userid = 0;
  2207. $event->modulename = 'scorm';
  2208. $event->instance = $scorm->id;
  2209. $event->timestart = $scorm->timeopen;
  2210. $event->timesort = $scorm->timeopen;
  2211. $event->visible = instance_is_visible('scorm', $scorm);
  2212. $event->timeduration = 0;
  2213. calendar_event::create($event, false);
  2214. }
  2215. }
  2216. // Scorm end calendar events.
  2217. $event = new stdClass();
  2218. $event->type = CALENDAR_EVENT_TYPE_ACTION;
  2219. $event->eventtype = SCORM_EVENT_TYPE_CLOSE;
  2220. if ($event->id = $DB->get_field('event', 'id',
  2221. array('modulename' => 'scorm', 'instance' => $scorm->id, 'eventtype' => $event->eventtype))) {
  2222. if ((!empty($scorm->timeclose)) && ($scorm->timeclose > 0)) {
  2223. // Calendar event exists so update it.
  2224. $event->name = get_string('calendarend', 'scorm', $scorm->name);
  2225. $event->description = format_module_intro('scorm', $scorm, $cmid, false);
  2226. $event->format = FORMAT_HTML;
  2227. $event->timestart = $scorm->timeclose;
  2228. $event->timesort = $scorm->timeclose;
  2229. $event->visible = instance_is_visible('scorm', $scorm);
  2230. $event->timeduration = 0;
  2231. $calendarevent = calendar_event::load($event->id);
  2232. $calendarevent->update($event, false);
  2233. } else {
  2234. // Calendar event is on longer needed.
  2235. $calendarevent = calendar_event::load($event->id);
  2236. $calendarevent->delete();
  2237. }
  2238. } else {
  2239. // Event doesn't exist so create one.
  2240. if ((!empty($scorm->timeclose)) && ($scorm->timeclose > 0)) {
  2241. $event->name = get_string('calendarend', 'scorm', $scorm->name);
  2242. $event->description = format_module_intro('scorm', $scorm, $cmid, false);
  2243. $event->format = FORMAT_HTML;
  2244. $event->courseid = $scorm->course;
  2245. $event->groupid = 0;
  2246. $event->userid = 0;
  2247. $event->modulename = 'scorm';
  2248. $event->instance = $scorm->id;
  2249. $event->timestart = $scorm->timeclose;
  2250. $event->timesort = $scorm->timeclose;
  2251. $event->visible = instance_is_visible('scorm', $scorm);
  2252. $event->timeduration = 0;
  2253. calendar_event::create($event, false);
  2254. }
  2255. }
  2256. return true;
  2257. }