Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/mod/scorm/ -> lib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 401 and 402] [Versions 401 and 403]

   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  /**
  18   * @package   mod_scorm
  19   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  20   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21   */
  22  defined('MOODLE_INTERNAL') || die();
  23  
  24  /** SCORM_TYPE_LOCAL = local */
  25  define('SCORM_TYPE_LOCAL', 'local');
  26  /** SCORM_TYPE_LOCALSYNC = localsync */
  27  define('SCORM_TYPE_LOCALSYNC', 'localsync');
  28  /** SCORM_TYPE_EXTERNAL = external */
  29  define('SCORM_TYPE_EXTERNAL', 'external');
  30  /** SCORM_TYPE_AICCURL = external AICC url */
  31  define('SCORM_TYPE_AICCURL', 'aiccurl');
  32  
  33  define('SCORM_TOC_SIDE', 0);
  34  define('SCORM_TOC_HIDDEN', 1);
  35  define('SCORM_TOC_POPUP', 2);
  36  define('SCORM_TOC_DISABLED', 3);
  37  
  38  // Used to show/hide navigation buttons and set their position.
  39  define('SCORM_NAV_DISABLED', 0);
  40  define('SCORM_NAV_UNDER_CONTENT', 1);
  41  define('SCORM_NAV_FLOATING', 2);
  42  
  43  // Used to check what SCORM version is being used.
  44  define('SCORM_12', 1);
  45  define('SCORM_13', 2);
  46  define('SCORM_AICC', 3);
  47  
  48  // List of possible attemptstatusdisplay options.
  49  define('SCORM_DISPLAY_ATTEMPTSTATUS_NO', 0);
  50  define('SCORM_DISPLAY_ATTEMPTSTATUS_ALL', 1);
  51  define('SCORM_DISPLAY_ATTEMPTSTATUS_MY', 2);
  52  define('SCORM_DISPLAY_ATTEMPTSTATUS_ENTRY', 3);
  53  
  54  define('SCORM_EVENT_TYPE_OPEN', 'open');
  55  define('SCORM_EVENT_TYPE_CLOSE', 'close');
  56  
  57  require_once (__DIR__ . '/deprecatedlib.php');
  58  
  59  /**
  60   * Return an array of status options
  61   *
  62   * Optionally with translated strings
  63   *
  64   * @param   bool    $with_strings   (optional)
  65   * @return  array
  66   */
  67  function scorm_status_options($withstrings = false) {
  68      // Id's are important as they are bits.
  69      $options = array(
  70          2 => 'passed',
  71          4 => 'completed'
  72      );
  73  
  74      if ($withstrings) {
  75          foreach ($options as $key => $value) {
  76              $options[$key] = get_string('completionstatus_'.$value, 'scorm');
  77          }
  78      }
  79  
  80      return $options;
  81  }
  82  
  83  
  84  /**
  85   * Given an object containing all the necessary data,
  86   * (defined by the form in mod_form.php) this function
  87   * will create a new instance and return the id number
  88   * of the new instance.
  89   *
  90   * @global stdClass
  91   * @global object
  92   * @uses CONTEXT_MODULE
  93   * @uses SCORM_TYPE_LOCAL
  94   * @uses SCORM_TYPE_LOCALSYNC
  95   * @uses SCORM_TYPE_EXTERNAL
  96   * @param object $scorm Form data
  97   * @param object $mform
  98   * @return int new instance id
  99   */
 100  function scorm_add_instance($scorm, $mform=null) {
 101      global $CFG, $DB;
 102  
 103      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 104  
 105      if (empty($scorm->timeopen)) {
 106          $scorm->timeopen = 0;
 107      }
 108      if (empty($scorm->timeclose)) {
 109          $scorm->timeclose = 0;
 110      }
 111      if (empty($scorm->completionstatusallscos)) {
 112          $scorm->completionstatusallscos = 0;
 113      }
 114      $cmid       = $scorm->coursemodule;
 115      $cmidnumber = $scorm->cmidnumber;
 116      $courseid   = $scorm->course;
 117  
 118      $context = context_module::instance($cmid);
 119  
 120      $scorm = scorm_option2text($scorm);
 121      $scorm->width  = (int)str_replace('%', '', $scorm->width);
 122      $scorm->height = (int)str_replace('%', '', $scorm->height);
 123  
 124      if (!isset($scorm->whatgrade)) {
 125          $scorm->whatgrade = 0;
 126      }
 127  
 128      $id = $DB->insert_record('scorm', $scorm);
 129  
 130      // Update course module record - from now on this instance properly exists and all function may be used.
 131      $DB->set_field('course_modules', 'instance', $id, array('id' => $cmid));
 132  
 133      // Reload scorm instance.
 134      $record = $DB->get_record('scorm', array('id' => $id));
 135  
 136      // Store the package and verify.
 137      if ($record->scormtype === SCORM_TYPE_LOCAL) {
 138          if (!empty($scorm->packagefile)) {
 139              $fs = get_file_storage();
 140              $fs->delete_area_files($context->id, 'mod_scorm', 'package');
 141              file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
 142                  0, array('subdirs' => 0, 'maxfiles' => 1));
 143              // Get filename of zip that was uploaded.
 144              $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
 145              $file = reset($files);
 146              $filename = $file->get_filename();
 147              if ($filename !== false) {
 148                  $record->reference = $filename;
 149              }
 150          }
 151  
 152      } else if ($record->scormtype === SCORM_TYPE_LOCALSYNC) {
 153          $record->reference = $scorm->packageurl;
 154      } else if ($record->scormtype === SCORM_TYPE_EXTERNAL) {
 155          $record->reference = $scorm->packageurl;
 156      } else if ($record->scormtype === SCORM_TYPE_AICCURL) {
 157          $record->reference = $scorm->packageurl;
 158          $record->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
 159      } else {
 160          return false;
 161      }
 162  
 163      // Save reference.
 164      $DB->update_record('scorm', $record);
 165  
 166      // Extra fields required in grade related functions.
 167      $record->course     = $courseid;
 168      $record->cmidnumber = $cmidnumber;
 169      $record->cmid       = $cmid;
 170  
 171      scorm_parse($record, true);
 172  
 173      scorm_grade_item_update($record);
 174      scorm_update_calendar($record, $cmid);
 175      if (!empty($scorm->completionexpected)) {
 176          \core_completion\api::update_completion_date_event($cmid, 'scorm', $record, $scorm->completionexpected);
 177      }
 178  
 179      return $record->id;
 180  }
 181  
 182  /**
 183   * Given an object containing all the necessary data,
 184   * (defined by the form in mod_form.php) this function
 185   * will update an existing instance with new data.
 186   *
 187   * @global stdClass
 188   * @global object
 189   * @uses CONTEXT_MODULE
 190   * @uses SCORM_TYPE_LOCAL
 191   * @uses SCORM_TYPE_LOCALSYNC
 192   * @uses SCORM_TYPE_EXTERNAL
 193   * @param object $scorm Form data
 194   * @param object $mform
 195   * @return bool
 196   */
 197  function scorm_update_instance($scorm, $mform=null) {
 198      global $CFG, $DB;
 199  
 200      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 201  
 202      if (empty($scorm->timeopen)) {
 203          $scorm->timeopen = 0;
 204      }
 205      if (empty($scorm->timeclose)) {
 206          $scorm->timeclose = 0;
 207      }
 208      if (empty($scorm->completionstatusallscos)) {
 209          $scorm->completionstatusallscos = 0;
 210      }
 211  
 212      $cmid       = $scorm->coursemodule;
 213      $cmidnumber = $scorm->cmidnumber;
 214      $courseid   = $scorm->course;
 215  
 216      $scorm->id = $scorm->instance;
 217  
 218      $context = context_module::instance($cmid);
 219  
 220      if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
 221          if (!empty($scorm->packagefile)) {
 222              $fs = get_file_storage();
 223              $fs->delete_area_files($context->id, 'mod_scorm', 'package');
 224              file_save_draft_area_files($scorm->packagefile, $context->id, 'mod_scorm', 'package',
 225                  0, array('subdirs' => 0, 'maxfiles' => 1));
 226              // Get filename of zip that was uploaded.
 227              $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
 228              $file = reset($files);
 229              $filename = $file->get_filename();
 230              if ($filename !== false) {
 231                  $scorm->reference = $filename;
 232              }
 233          }
 234  
 235      } else if ($scorm->scormtype === SCORM_TYPE_LOCALSYNC) {
 236          $scorm->reference = $scorm->packageurl;
 237      } else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
 238          $scorm->reference = $scorm->packageurl;
 239      } else if ($scorm->scormtype === SCORM_TYPE_AICCURL) {
 240          $scorm->reference = $scorm->packageurl;
 241          $scorm->hidetoc = SCORM_TOC_DISABLED; // TOC is useless for direct AICCURL so disable it.
 242      } else {
 243          return false;
 244      }
 245  
 246      $scorm = scorm_option2text($scorm);
 247      $scorm->width        = (int)str_replace('%', '', $scorm->width);
 248      $scorm->height       = (int)str_replace('%', '', $scorm->height);
 249      $scorm->timemodified = time();
 250  
 251      if (!isset($scorm->whatgrade)) {
 252          $scorm->whatgrade = 0;
 253      }
 254  
 255      $DB->update_record('scorm', $scorm);
 256      // We need to find this out before we blow away the form data.
 257      $completionexpected = (!empty($scorm->completionexpected)) ? $scorm->completionexpected : null;
 258  
 259      $scorm = $DB->get_record('scorm', array('id' => $scorm->id));
 260  
 261      // Extra fields required in grade related functions.
 262      $scorm->course   = $courseid;
 263      $scorm->idnumber = $cmidnumber;
 264      $scorm->cmid     = $cmid;
 265  
 266      scorm_parse($scorm, (bool)$scorm->updatefreq);
 267  
 268      scorm_grade_item_update($scorm);
 269      scorm_update_grades($scorm);
 270      scorm_update_calendar($scorm, $cmid);
 271      \core_completion\api::update_completion_date_event($cmid, 'scorm', $scorm, $completionexpected);
 272  
 273      return true;
 274  }
 275  
 276  /**
 277   * Given an ID of an instance of this module,
 278   * this function will permanently delete the instance
 279   * and any data that depends on it.
 280   *
 281   * @global stdClass
 282   * @global object
 283   * @param int $id Scorm instance id
 284   * @return boolean
 285   */
 286  function scorm_delete_instance($id) {
 287      global $CFG, $DB;
 288  
 289      if (! $scorm = $DB->get_record('scorm', array('id' => $id))) {
 290          return false;
 291      }
 292  
 293      $result = true;
 294  
 295      // Delete any dependent records.
 296      if (! $DB->delete_records('scorm_scoes_track', array('scormid' => $scorm->id))) {
 297          $result = false;
 298      }
 299      if ($scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id))) {
 300          foreach ($scoes as $sco) {
 301              if (! $DB->delete_records('scorm_scoes_data', array('scoid' => $sco->id))) {
 302                  $result = false;
 303              }
 304          }
 305          $DB->delete_records('scorm_scoes', array('scorm' => $scorm->id));
 306      }
 307  
 308      scorm_grade_item_delete($scorm);
 309  
 310      // We must delete the module record after we delete the grade item.
 311      if (! $DB->delete_records('scorm', array('id' => $scorm->id))) {
 312          $result = false;
 313      }
 314  
 315      /*if (! $DB->delete_records('scorm_sequencing_controlmode', array('scormid'=>$scorm->id))) {
 316          $result = false;
 317      }
 318      if (! $DB->delete_records('scorm_sequencing_rolluprules', array('scormid'=>$scorm->id))) {
 319          $result = false;
 320      }
 321      if (! $DB->delete_records('scorm_sequencing_rolluprule', array('scormid'=>$scorm->id))) {
 322          $result = false;
 323      }
 324      if (! $DB->delete_records('scorm_sequencing_rollupruleconditions', array('scormid'=>$scorm->id))) {
 325          $result = false;
 326      }
 327      if (! $DB->delete_records('scorm_sequencing_rolluprulecondition', array('scormid'=>$scorm->id))) {
 328          $result = false;
 329      }
 330      if (! $DB->delete_records('scorm_sequencing_rulecondition', array('scormid'=>$scorm->id))) {
 331          $result = false;
 332      }
 333      if (! $DB->delete_records('scorm_sequencing_ruleconditions', array('scormid'=>$scorm->id))) {
 334          $result = false;
 335      }*/
 336  
 337      return $result;
 338  }
 339  
 340  /**
 341   * Return a small object with summary information about what a
 342   * user has done with a given particular instance of this module
 343   * Used for user activity reports.
 344   *
 345   * @global stdClass
 346   * @param int $course Course id
 347   * @param int $user User id
 348   * @param int $mod
 349   * @param int $scorm The scorm id
 350   * @return mixed
 351   */
 352  function scorm_user_outline($course, $user, $mod, $scorm) {
 353      global $CFG;
 354      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 355  
 356      require_once("$CFG->libdir/gradelib.php");
 357      $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
 358      if (!empty($grades->items[0]->grades)) {
 359          $grade = reset($grades->items[0]->grades);
 360          $result = (object) [
 361              'time' => grade_get_date_for_user_grade($grade, $user),
 362          ];
 363          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 364              $result->info = get_string('gradenoun') . ': '. $grade->str_long_grade;
 365          } else {
 366              $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
 367          }
 368  
 369          return $result;
 370      }
 371      return null;
 372  }
 373  
 374  /**
 375   * Print a detailed representation of what a user has done with
 376   * a given particular instance of this module, for user activity reports.
 377   *
 378   * @global stdClass
 379   * @global object
 380   * @param object $course
 381   * @param object $user
 382   * @param object $mod
 383   * @param object $scorm
 384   * @return boolean
 385   */
 386  function scorm_user_complete($course, $user, $mod, $scorm) {
 387      global $CFG, $DB, $OUTPUT;
 388      require_once("$CFG->libdir/gradelib.php");
 389  
 390      $liststyle = 'structlist';
 391      $now = time();
 392      $firstmodify = $now;
 393      $lastmodify = 0;
 394      $sometoreport = false;
 395      $report = '';
 396  
 397      // First Access and Last Access dates for SCOs.
 398      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 399      $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
 400      $firstmodify = $timetracks->start;
 401      $lastmodify = $timetracks->finish;
 402  
 403      $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
 404      if (!empty($grades->items[0]->grades)) {
 405          $grade = reset($grades->items[0]->grades);
 406          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 407              echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade);
 408              if ($grade->str_feedback) {
 409                  echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
 410              }
 411          } else {
 412              echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
 413          }
 414      }
 415  
 416      if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
 417                                           $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
 418                                           $DB->sql_isempty('scorm_scoes', 'organization', false, false),
 419                                           array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
 420          if (count($orgs) <= 1) {
 421              unset($orgs);
 422              $orgs = array();
 423              $org = new stdClass();
 424              $org->identifier = '';
 425              $orgs[] = $org;
 426          }
 427          $report .= html_writer::start_div('mod-scorm');
 428          foreach ($orgs as $org) {
 429              $conditions = array();
 430              $currentorg = '';
 431              if (!empty($org->identifier)) {
 432                  $report .= html_writer::div($org->title, 'orgtitle');
 433                  $currentorg = $org->identifier;
 434                  $conditions['organization'] = $currentorg;
 435              }
 436              $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
 437                  $conditions['scorm'] = $scorm->id;
 438              if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
 439                  // Drop keys so that we can access array sequentially.
 440                  $scoes = array_values($scoes);
 441                  $level = 0;
 442                  $sublist = 1;
 443                  $parents[$level] = '/';
 444                  foreach ($scoes as $pos => $sco) {
 445                      if ($parents[$level] != $sco->parent) {
 446                          if ($level > 0 && $parents[$level - 1] == $sco->parent) {
 447                              $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
 448                              $level--;
 449                          } else {
 450                              $i = $level;
 451                              $closelist = '';
 452                              while (($i > 0) && ($parents[$level] != $sco->parent)) {
 453                                  $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
 454                                  $i--;
 455                              }
 456                              if (($i == 0) && ($sco->parent != $currentorg)) {
 457                                  $report .= html_writer::start_tag('li');
 458                                  $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
 459                                  $level++;
 460                              } else {
 461                                  $report .= $closelist;
 462                                  $level = $i;
 463                              }
 464                              $parents[$level] = $sco->parent;
 465                          }
 466                      }
 467                      $report .= html_writer::start_tag('li');
 468                      if (isset($scoes[$pos + 1])) {
 469                          $nextsco = $scoes[$pos + 1];
 470                      } else {
 471                          $nextsco = false;
 472                      }
 473                      if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
 474                              (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
 475                          $sublist++;
 476                      } else {
 477                          $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
 478                      }
 479  
 480                      if ($sco->launch) {
 481                          $score = '';
 482                          $totaltime = '';
 483                          if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
 484                              if ($usertrack->status == '') {
 485                                  $usertrack->status = 'notattempted';
 486                              }
 487                              $strstatus = get_string($usertrack->status, 'scorm');
 488                              $report .= $OUTPUT->pix_icon($usertrack->status, $strstatus, 'scorm');
 489                          } else {
 490                              if ($sco->scormtype == 'sco') {
 491                                  $report .= $OUTPUT->pix_icon('notattempted', get_string('notattempted', 'scorm'), 'scorm');
 492                              } else {
 493                                  $report .= $OUTPUT->pix_icon('asset', get_string('asset', 'scorm'), 'scorm');
 494                              }
 495                          }
 496                          $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
 497                          if ($usertrack !== false) {
 498                              $sometoreport = true;
 499                              $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
 500                              foreach ($usertrack as $element => $value) {
 501                                  if (substr($element, 0, 3) == 'cmi') {
 502                                      $report .= html_writer::tag('li', s($element) . ' => ' . s($value));
 503                                  }
 504                              }
 505                              $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
 506                          }
 507                      } else {
 508                          $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
 509                      }
 510                  }
 511                  for ($i = 0; $i < $level; $i++) {
 512                      $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
 513                  }
 514              }
 515              $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
 516          }
 517          $report .= html_writer::end_div();
 518      }
 519      if ($sometoreport) {
 520          if ($firstmodify < $now) {
 521              $timeago = format_time($now - $firstmodify);
 522              echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
 523          }
 524          if ($lastmodify > 0) {
 525              $timeago = format_time($now - $lastmodify);
 526              echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
 527          }
 528          echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
 529          echo $report;
 530      } else {
 531          print_string('noactivity', 'scorm');
 532      }
 533  
 534      return true;
 535  }
 536  
 537  /**
 538   * Function to be run periodically according to the moodle Tasks API
 539   * This function searches for things that need to be done, such
 540   * as sending out mail, toggling flags etc ...
 541   *
 542   * @global stdClass
 543   * @global object
 544   * @return boolean
 545   */
 546  function scorm_cron_scheduled_task () {
 547      global $CFG, $DB;
 548  
 549      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 550  
 551      $sitetimezone = core_date::get_server_timezone();
 552      // Now see if there are any scorm updates to be done.
 553  
 554      if (!isset($CFG->scorm_updatetimelast)) {    // To catch the first time.
 555          set_config('scorm_updatetimelast', 0);
 556      }
 557  
 558      $timenow = time();
 559      $updatetime = usergetmidnight($timenow, $sitetimezone);
 560  
 561      if ($CFG->scorm_updatetimelast < $updatetime and $timenow > $updatetime) {
 562  
 563          set_config('scorm_updatetimelast', $timenow);
 564  
 565          mtrace('Updating scorm packages which require daily update');// We are updating.
 566  
 567          $scormsupdate = $DB->get_records('scorm', array('updatefreq' => SCORM_UPDATE_EVERYDAY));
 568          foreach ($scormsupdate as $scormupdate) {
 569              scorm_parse($scormupdate, true);
 570          }
 571  
 572          // Now clear out AICC session table with old session data.
 573          $cfgscorm = get_config('scorm');
 574          if (!empty($cfgscorm->allowaicchacp)) {
 575              $expiretime = time() - ($cfgscorm->aicchacpkeepsessiondata * 24 * 60 * 60);
 576              $DB->delete_records_select('scorm_aicc_session', 'timemodified < ?', array($expiretime));
 577          }
 578      }
 579  
 580      return true;
 581  }
 582  
 583  /**
 584   * Return grade for given user or all users.
 585   *
 586   * @global stdClass
 587   * @global object
 588   * @param int $scormid id of scorm
 589   * @param int $userid optional user id, 0 means all users
 590   * @return array array of grades, false if none
 591   */
 592  function scorm_get_user_grades($scorm, $userid=0) {
 593      global $CFG, $DB;
 594      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 595  
 596      $grades = array();
 597      if (empty($userid)) {
 598          $scousers = $DB->get_records_select('scorm_scoes_track', "scormid=? GROUP BY userid",
 599                                              array($scorm->id), "", "userid,null");
 600          if ($scousers) {
 601              foreach ($scousers as $scouser) {
 602                  $grades[$scouser->userid] = new stdClass();
 603                  $grades[$scouser->userid]->id         = $scouser->userid;
 604                  $grades[$scouser->userid]->userid     = $scouser->userid;
 605                  $grades[$scouser->userid]->rawgrade = scorm_grade_user($scorm, $scouser->userid);
 606              }
 607          } else {
 608              return false;
 609          }
 610  
 611      } else {
 612          $preattempt = $DB->get_records_select('scorm_scoes_track', "scormid=? AND userid=? GROUP BY userid",
 613                                                  array($scorm->id, $userid), "", "userid,null");
 614          if (!$preattempt) {
 615              return false; // No attempt yet.
 616          }
 617          $grades[$userid] = new stdClass();
 618          $grades[$userid]->id         = $userid;
 619          $grades[$userid]->userid     = $userid;
 620          $grades[$userid]->rawgrade = scorm_grade_user($scorm, $userid);
 621      }
 622  
 623      return $grades;
 624  }
 625  
 626  /**
 627   * Update grades in central gradebook
 628   *
 629   * @category grade
 630   * @param object $scorm
 631   * @param int $userid specific user only, 0 mean all
 632   * @param bool $nullifnone
 633   */
 634  function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
 635      global $CFG;
 636      require_once($CFG->libdir.'/gradelib.php');
 637      require_once($CFG->libdir.'/completionlib.php');
 638  
 639      if ($grades = scorm_get_user_grades($scorm, $userid)) {
 640          scorm_grade_item_update($scorm, $grades);
 641          // Set complete.
 642          scorm_set_completion($scorm, $userid, COMPLETION_COMPLETE, $grades);
 643      } else if ($userid and $nullifnone) {
 644          $grade = new stdClass();
 645          $grade->userid   = $userid;
 646          $grade->rawgrade = null;
 647          scorm_grade_item_update($scorm, $grade);
 648          // Set incomplete.
 649          scorm_set_completion($scorm, $userid, COMPLETION_INCOMPLETE);
 650      } else {
 651          scorm_grade_item_update($scorm);
 652      }
 653  }
 654  
 655  /**
 656   * Update/create grade item for given scorm
 657   *
 658   * @category grade
 659   * @uses GRADE_TYPE_VALUE
 660   * @uses GRADE_TYPE_NONE
 661   * @param object $scorm object with extra cmidnumber
 662   * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
 663   * @return object grade_item
 664   */
 665  function scorm_grade_item_update($scorm, $grades=null) {
 666      global $CFG, $DB;
 667      require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 668      if (!function_exists('grade_update')) { // Workaround for buggy PHP versions.
 669          require_once($CFG->libdir.'/gradelib.php');
 670      }
 671  
 672      $params = array('itemname' => $scorm->name);
 673      if (isset($scorm->cmidnumber)) {
 674          $params['idnumber'] = $scorm->cmidnumber;
 675      }
 676  
 677      if ($scorm->grademethod == GRADESCOES) {
 678          $maxgrade = $DB->count_records_select('scorm_scoes', 'scorm = ? AND '.
 679                                                  $DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id));
 680          if ($maxgrade) {
 681              $params['gradetype'] = GRADE_TYPE_VALUE;
 682              $params['grademax']  = $maxgrade;
 683              $params['grademin']  = 0;
 684          } else {
 685              $params['gradetype'] = GRADE_TYPE_NONE;
 686          }
 687      } else {
 688          $params['gradetype'] = GRADE_TYPE_VALUE;
 689          $params['grademax']  = $scorm->maxgrade;
 690          $params['grademin']  = 0;
 691      }
 692  
 693      if ($grades === 'reset') {
 694          $params['reset'] = true;
 695          $grades = null;
 696      }
 697  
 698      return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades, $params);
 699  }
 700  
 701  /**
 702   * Delete grade item for given scorm
 703   *
 704   * @category grade
 705   * @param object $scorm object
 706   * @return object grade_item
 707   */
 708  function scorm_grade_item_delete($scorm) {
 709      global $CFG;
 710      require_once($CFG->libdir.'/gradelib.php');
 711  
 712      return grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, null, array('deleted' => 1));
 713  }
 714  
 715  /**
 716   * List the actions that correspond to a view of this module.
 717   * This is used by the participation report.
 718   *
 719   * Note: This is not used by new logging system. Event with
 720   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
 721   *       be considered as view action.
 722   *
 723   * @return array
 724   */
 725  function scorm_get_view_actions() {
 726      return array('pre-view', 'view', 'view all', 'report');
 727  }
 728  
 729  /**
 730   * List the actions that correspond to a post of this module.
 731   * This is used by the participation report.
 732   *
 733   * Note: This is not used by new logging system. Event with
 734   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
 735   *       will be considered as post action.
 736   *
 737   * @return array
 738   */
 739  function scorm_get_post_actions() {
 740      return array();
 741  }
 742  
 743  /**
 744   * @param object $scorm
 745   * @return object $scorm
 746   */
 747  function scorm_option2text($scorm) {
 748      $scormpopoupoptions = scorm_get_popup_options_array();
 749  
 750      if (isset($scorm->popup)) {
 751          if ($scorm->popup == 1) {
 752              $optionlist = array();
 753              foreach ($scormpopoupoptions as $name => $option) {
 754                  if (isset($scorm->$name)) {
 755                      $optionlist[] = $name.'='.$scorm->$name;
 756                  } else {
 757                      $optionlist[] = $name.'=0';
 758                  }
 759              }
 760              $scorm->options = implode(',', $optionlist);
 761          } else {
 762              $scorm->options = '';
 763          }
 764      } else {
 765          $scorm->popup = 0;
 766          $scorm->options = '';
 767      }
 768      return $scorm;
 769  }
 770  
 771  /**
 772   * Implementation of the function for printing the form elements that control
 773   * whether the course reset functionality affects the scorm.
 774   *
 775   * @param object $mform form passed by reference
 776   */
 777  function scorm_reset_course_form_definition(&$mform) {
 778      $mform->addElement('header', 'scormheader', get_string('modulenameplural', 'scorm'));
 779      $mform->addElement('advcheckbox', 'reset_scorm', get_string('deleteallattempts', 'scorm'));
 780  }
 781  
 782  /**
 783   * Course reset form defaults.
 784   *
 785   * @return array
 786   */
 787  function scorm_reset_course_form_defaults($course) {
 788      return array('reset_scorm' => 1);
 789  }
 790  
 791  /**
 792   * Removes all grades from gradebook
 793   *
 794   * @global stdClass
 795   * @global object
 796   * @param int $courseid
 797   * @param string optional type
 798   */
 799  function scorm_reset_gradebook($courseid, $type='') {
 800      global $CFG, $DB;
 801  
 802      $sql = "SELECT s.*, cm.idnumber as cmidnumber, s.course as courseid
 803                FROM {scorm} s, {course_modules} cm, {modules} m
 804               WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id AND s.course=?";
 805  
 806      if ($scorms = $DB->get_records_sql($sql, array($courseid))) {
 807          foreach ($scorms as $scorm) {
 808              scorm_grade_item_update($scorm, 'reset');
 809          }
 810      }
 811  }
 812  
 813  /**
 814   * Actual implementation of the reset course functionality, delete all the
 815   * scorm attempts for course $data->courseid.
 816   *
 817   * @global stdClass
 818   * @global object
 819   * @param object $data the data submitted from the reset course.
 820   * @return array status array
 821   */
 822  function scorm_reset_userdata($data) {
 823      global $CFG, $DB;
 824  
 825      $componentstr = get_string('modulenameplural', 'scorm');
 826      $status = array();
 827  
 828      if (!empty($data->reset_scorm)) {
 829          $scormssql = "SELECT s.id
 830                           FROM {scorm} s
 831                          WHERE s.course=?";
 832  
 833          $DB->delete_records_select('scorm_scoes_track', "scormid IN ($scormssql)", array($data->courseid));
 834  
 835          // Remove all grades from gradebook.
 836          if (empty($data->reset_gradebook_grades)) {
 837              scorm_reset_gradebook($data->courseid);
 838          }
 839  
 840          $status[] = array('component' => $componentstr, 'item' => get_string('deleteallattempts', 'scorm'), 'error' => false);
 841      }
 842  
 843      // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
 844      // See MDL-9367.
 845      shift_course_mod_dates('scorm', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
 846      $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
 847  
 848      return $status;
 849  }
 850  
 851  /**
 852   * Lists all file areas current user may browse
 853   *
 854   * @param object $course
 855   * @param object $cm
 856   * @param object $context
 857   * @return array
 858   */
 859  function scorm_get_file_areas($course, $cm, $context) {
 860      $areas = array();
 861      $areas['content'] = get_string('areacontent', 'scorm');
 862      $areas['package'] = get_string('areapackage', 'scorm');
 863      return $areas;
 864  }
 865  
 866  /**
 867   * File browsing support for SCORM file areas
 868   *
 869   * @package  mod_scorm
 870   * @category files
 871   * @param file_browser $browser file browser instance
 872   * @param array $areas file areas
 873   * @param stdClass $course course object
 874   * @param stdClass $cm course module object
 875   * @param stdClass $context context object
 876   * @param string $filearea file area
 877   * @param int $itemid item ID
 878   * @param string $filepath file path
 879   * @param string $filename file name
 880   * @return file_info instance or null if not found
 881   */
 882  function scorm_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
 883      global $CFG;
 884  
 885      if (!has_capability('moodle/course:managefiles', $context)) {
 886          return null;
 887      }
 888  
 889      // No writing for now!
 890  
 891      $fs = get_file_storage();
 892  
 893      if ($filearea === 'content') {
 894  
 895          $filepath = is_null($filepath) ? '/' : $filepath;
 896          $filename = is_null($filename) ? '.' : $filename;
 897  
 898          $urlbase = $CFG->wwwroot.'/pluginfile.php';
 899          if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'content', 0, $filepath, $filename)) {
 900              if ($filepath === '/' and $filename === '.') {
 901                  $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'content', 0);
 902              } else {
 903                  // Not found.
 904                  return null;
 905              }
 906          }
 907          require_once("$CFG->dirroot/mod/scorm/locallib.php");
 908          return new scorm_package_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, false, false);
 909  
 910      } else if ($filearea === 'package') {
 911          $filepath = is_null($filepath) ? '/' : $filepath;
 912          $filename = is_null($filename) ? '.' : $filename;
 913  
 914          $urlbase = $CFG->wwwroot.'/pluginfile.php';
 915          if (!$storedfile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, $filepath, $filename)) {
 916              if ($filepath === '/' and $filename === '.') {
 917                  $storedfile = new virtual_root_file($context->id, 'mod_scorm', 'package', 0);
 918              } else {
 919                  // Not found.
 920                  return null;
 921              }
 922          }
 923          return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, false, false);
 924      }
 925  
 926      // Scorm_intro handled in file_browser.
 927  
 928      return false;
 929  }
 930  
 931  /**
 932   * Serves scorm content, introduction images and packages. Implements needed access control ;-)
 933   *
 934   * @package  mod_scorm
 935   * @category files
 936   * @param stdClass $course course object
 937   * @param stdClass $cm course module object
 938   * @param stdClass $context context object
 939   * @param string $filearea file area
 940   * @param array $args extra arguments
 941   * @param bool $forcedownload whether or not force download
 942   * @param array $options additional options affecting the file serving
 943   * @return bool false if file not found, does not return if found - just send the file
 944   */
 945  function scorm_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
 946      global $CFG, $DB;
 947  
 948      if ($context->contextlevel != CONTEXT_MODULE) {
 949          return false;
 950      }
 951  
 952      require_login($course, true, $cm);
 953  
 954      $canmanageactivity = has_capability('moodle/course:manageactivities', $context);
 955      $lifetime = null;
 956  
 957      // Check SCORM availability.
 958      if (!$canmanageactivity) {
 959          require_once($CFG->dirroot.'/mod/scorm/locallib.php');
 960  
 961          $scorm = $DB->get_record('scorm', array('id' => $cm->instance), 'id, timeopen, timeclose', MUST_EXIST);
 962          list($available, $warnings) = scorm_get_availability_status($scorm);
 963          if (!$available) {
 964              return false;
 965          }
 966      }
 967  
 968      if ($filearea === 'content') {
 969          $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
 970          $relativepath = implode('/', $args);
 971          $fullpath = "/$context->id/mod_scorm/content/0/$relativepath";
 972          $options['immutable'] = true; // Add immutable option, $relativepath changes on file update.
 973  
 974      } else if ($filearea === 'package') {
 975          // Check if the global setting for disabling package downloads is enabled.
 976          $protectpackagedownloads = get_config('scorm', 'protectpackagedownloads');
 977          if ($protectpackagedownloads and !$canmanageactivity) {
 978              return false;
 979          }
 980          $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
 981          $relativepath = implode('/', $args);
 982          $fullpath = "/$context->id/mod_scorm/package/0/$relativepath";
 983          $lifetime = 0; // No caching here.
 984  
 985      } else if ($filearea === 'imsmanifest') { // This isn't a real filearea, it's a url parameter for this type of package.
 986          $revision = (int)array_shift($args); // Prevents caching problems - ignored here.
 987          $relativepath = implode('/', $args);
 988  
 989          // Get imsmanifest file.
 990          $fs = get_file_storage();
 991          $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, '', false);
 992          $file = reset($files);
 993  
 994          // Check that the package file is an imsmanifest.xml file - if not then this method is not allowed.
 995          $packagefilename = $file->get_filename();
 996          if (strtolower($packagefilename) !== 'imsmanifest.xml') {
 997              return false;
 998          }
 999  
1000          $file->send_relative_file($relativepath);
1001      } else {
1002          return false;
1003      }
1004  
1005      $fs = get_file_storage();
1006      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1007          if ($filearea === 'content') { // Return file not found straight away to improve performance.
1008              send_header_404();
1009              die;
1010          }
1011          return false;
1012      }
1013  
1014      // Allow SVG files to be loaded within SCORM content, instead of forcing download.
1015      $options['dontforcesvgdownload'] = true;
1016  
1017      // Finally send the file.
1018      send_stored_file($file, $lifetime, 0, false, $options);
1019  }
1020  
1021  /**
1022   * @uses FEATURE_GROUPS
1023   * @uses FEATURE_GROUPINGS
1024   * @uses FEATURE_MOD_INTRO
1025   * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1026   * @uses FEATURE_COMPLETION_HAS_RULES
1027   * @uses FEATURE_GRADE_HAS_GRADE
1028   * @uses FEATURE_GRADE_OUTCOMES
1029   * @param string $feature FEATURE_xx constant for requested feature
1030   * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1031   */
1032  function scorm_supports($feature) {
1033      switch($feature) {
1034          case FEATURE_GROUPS:                  return true;
1035          case FEATURE_GROUPINGS:               return true;
1036          case FEATURE_MOD_INTRO:               return true;
1037          case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1038          case FEATURE_COMPLETION_HAS_RULES:    return true;
1039          case FEATURE_GRADE_HAS_GRADE:         return true;
1040          case FEATURE_GRADE_OUTCOMES:          return true;
1041          case FEATURE_BACKUP_MOODLE2:          return true;
1042          case FEATURE_SHOW_DESCRIPTION:        return true;
1043          case FEATURE_MOD_PURPOSE:             return MOD_PURPOSE_CONTENT;
1044  
1045          default: return null;
1046      }
1047  }
1048  
1049  /**
1050   * Get the filename for a temp log file
1051   *
1052   * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1053   * @param integer $scoid - scoid of object this log entry is for
1054   * @return string The filename as an absolute path
1055   */
1056  function scorm_debug_log_filename($type, $scoid) {
1057      global $CFG, $USER;
1058  
1059      $logpath = $CFG->tempdir.'/scormlogs';
1060      $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1061      return $logfile;
1062  }
1063  
1064  /**
1065   * writes log output to a temp log file
1066   *
1067   * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1068   * @param string $text - text to be written to file.
1069   * @param integer $scoid - scoid of object this log entry is for.
1070   */
1071  function scorm_debug_log_write($type, $text, $scoid) {
1072      global $CFG;
1073  
1074      $debugenablelog = get_config('scorm', 'allowapidebug');
1075      if (!$debugenablelog || empty($text)) {
1076          return;
1077      }
1078      if (make_temp_directory('scormlogs/')) {
1079          $logfile = scorm_debug_log_filename($type, $scoid);
1080          @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1081          @chmod($logfile, $CFG->filepermissions);
1082      }
1083  }
1084  
1085  /**
1086   * Remove debug log file
1087   *
1088   * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1089   * @param integer $scoid - scoid of object this log entry is for
1090   * @return boolean True if the file is successfully deleted, false otherwise
1091   */
1092  function scorm_debug_log_remove($type, $scoid) {
1093  
1094      $debugenablelog = get_config('scorm', 'allowapidebug');
1095      $logfile = scorm_debug_log_filename($type, $scoid);
1096      if (!$debugenablelog || !file_exists($logfile)) {
1097          return false;
1098      }
1099  
1100      return @unlink($logfile);
1101  }
1102  
1103  /**
1104   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
1105   */
1106  function scorm_print_overview() {
1107      throw new coding_exception('scorm_print_overview() can not be used any more and is obsolete.');
1108  }
1109  
1110  /**
1111   * Return a list of page types
1112   * @param string $pagetype current page type
1113   * @param stdClass $parentcontext Block's parent context
1114   * @param stdClass $currentcontext Current context of block
1115   */
1116  function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1117      $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1118      return $modulepagetype;
1119  }
1120  
1121  /**
1122   * Returns the SCORM version used.
1123   * @param string $scormversion comes from $scorm->version
1124   * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1125   * @return Scorm version.
1126   */
1127  function scorm_version_check($scormversion, $version='') {
1128      $scormversion = trim(strtolower($scormversion));
1129      if (empty($version) || $version == SCORM_12) {
1130          if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1131              return SCORM_12;
1132          }
1133          if (!empty($version)) {
1134              return false;
1135          }
1136      }
1137      if (empty($version) || $version == SCORM_13) {
1138          if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1139              return SCORM_13;
1140          }
1141          if (!empty($version)) {
1142              return false;
1143          }
1144      }
1145      if (empty($version) || $version == SCORM_AICC) {
1146          if (strpos($scormversion, 'aicc')) {
1147              return SCORM_AICC;
1148          }
1149          if (!empty($version)) {
1150              return false;
1151          }
1152      }
1153      return false;
1154  }
1155  
1156  /**
1157   * Register the ability to handle drag and drop file uploads
1158   * @return array containing details of the files / types the mod can handle
1159   */
1160  function scorm_dndupload_register() {
1161      return array('files' => array(
1162          array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1163      ));
1164  }
1165  
1166  /**
1167   * Handle a file that has been uploaded
1168   * @param object $uploadinfo details of the file / content that has been uploaded
1169   * @return int instance id of the newly created mod
1170   */
1171  function scorm_dndupload_handle($uploadinfo) {
1172  
1173      $context = context_module::instance($uploadinfo->coursemodule);
1174      file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1175      $fs = get_file_storage();
1176      $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1177      $file = reset($files);
1178  
1179      // Validate the file, make sure it's a valid SCORM package!
1180      $errors = scorm_validate_package($file);
1181      if (!empty($errors)) {
1182          return false;
1183      }
1184      // Create a default scorm object to pass to scorm_add_instance()!
1185      $scorm = get_config('scorm');
1186      $scorm->course = $uploadinfo->course->id;
1187      $scorm->coursemodule = $uploadinfo->coursemodule;
1188      $scorm->cmidnumber = '';
1189      $scorm->name = $uploadinfo->displayname;
1190      $scorm->scormtype = SCORM_TYPE_LOCAL;
1191      $scorm->reference = $file->get_filename();
1192      $scorm->intro = '';
1193      $scorm->width = $scorm->framewidth;
1194      $scorm->height = $scorm->frameheight;
1195  
1196      return scorm_add_instance($scorm, null);
1197  }
1198  
1199  /**
1200   * Sets activity completion state
1201   *
1202   * @param object $scorm object
1203   * @param int $userid User ID
1204   * @param int $completionstate Completion state
1205   * @param array $grades grades array of users with grades - used when $userid = 0
1206   */
1207  function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1208      $course = new stdClass();
1209      $course->id = $scorm->course;
1210      $completion = new completion_info($course);
1211  
1212      // Check if completion is enabled site-wide, or for the course.
1213      if (!$completion->is_enabled()) {
1214          return;
1215      }
1216  
1217      $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1218      if (empty($cm) || !$completion->is_enabled($cm)) {
1219              return;
1220      }
1221  
1222      if (empty($userid)) { // We need to get all the relevant users from $grades param.
1223          foreach ($grades as $grade) {
1224              $completion->update_state($cm, $completionstate, $grade->userid);
1225          }
1226      } else {
1227          $completion->update_state($cm, $completionstate, $userid);
1228      }
1229  }
1230  
1231  /**
1232   * Check that a Zip file contains a valid SCORM package
1233   *
1234   * @param $file stored_file a Zip file.
1235   * @return array empty if no issue is found. Array of error message otherwise
1236   */
1237  function scorm_validate_package($file) {
1238      $packer = get_file_packer('application/zip');
1239      $errors = array();
1240      if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1241          $file->import_external_file_contents();
1242      }
1243      $filelist = $file->list_files($packer);
1244  
1245      if (!is_array($filelist)) {
1246          $errors['packagefile'] = get_string('badarchive', 'scorm');
1247      } else {
1248          $aiccfound = false;
1249          $badmanifestpresent = false;
1250          foreach ($filelist as $info) {
1251              if ($info->pathname == 'imsmanifest.xml') {
1252                  return array();
1253              } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1254                  // This package has an imsmanifest file inside a folder of the package.
1255                  $badmanifestpresent = true;
1256              }
1257              if (preg_match('/\.cst$/', $info->pathname)) {
1258                  return array();
1259              }
1260          }
1261          if (!$aiccfound) {
1262              if ($badmanifestpresent) {
1263                  $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1264              } else {
1265                  $errors['packagefile'] = get_string('nomanifest', 'scorm');
1266              }
1267          }
1268      }
1269      return $errors;
1270  }
1271  
1272  /**
1273   * Check and set the correct mode and attempt when entering a SCORM package.
1274   *
1275   * @param object $scorm object
1276   * @param string $newattempt should a new attempt be generated here.
1277   * @param int $attempt the attempt number this is for.
1278   * @param int $userid the userid of the user.
1279   * @param string $mode the current mode that has been selected.
1280   */
1281  function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1282      global $DB;
1283  
1284      if (($mode == 'browse')) {
1285          if ($scorm->hidebrowse == 1) {
1286              // Prevent Browse mode if hidebrowse is set.
1287              $mode = 'normal';
1288          } else {
1289              // We don't need to check attempts as browse mode is set.
1290              return;
1291          }
1292      }
1293  
1294      if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS) {
1295          // This SCORM is configured to force a new attempt on every re-entry.
1296          $newattempt = 'on';
1297          $mode = 'normal';
1298          if ($attempt == 1) {
1299              // Check if the user has any existing data or if this is really the first attempt.
1300              $exists = $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id));
1301              if (!$exists) {
1302                  // No records yet - Attempt should == 1.
1303                  return;
1304              }
1305          }
1306          $attempt++;
1307  
1308          return;
1309      }
1310      // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1311      $incomplete = true;
1312  
1313      // Note - in SCORM_13 the cmi-core.lesson_status field was split into
1314      // 'cmi.completion_status' and 'cmi.success_status'.
1315      // 'cmi.completion_status' can only contain values 'completed', 'incomplete', 'not attempted' or 'unknown'.
1316      // This means the values 'passed' or 'failed' will never be reported for a track in SCORM_13 and
1317      // the only status that will be treated as complete is 'completed'.
1318  
1319      $completionelements = array(
1320          SCORM_12 => 'cmi.core.lesson_status',
1321          SCORM_13 => 'cmi.completion_status',
1322          SCORM_AICC => 'cmi.core.lesson_status'
1323      );
1324      $scormversion = scorm_version_check($scorm->version);
1325      if($scormversion===false) {
1326          $scormversion = SCORM_12;
1327      }
1328      $completionelement = $completionelements[$scormversion];
1329  
1330      $sql = "SELECT sc.id, t.value
1331                FROM {scorm_scoes} sc
1332           LEFT JOIN {scorm_scoes_track} t ON sc.scorm = t.scormid AND sc.id = t.scoid
1333                     AND t.element = ? AND t.userid = ? AND t.attempt = ?
1334               WHERE sc.scormtype = 'sco' AND sc.scorm = ?";
1335      $tracks = $DB->get_recordset_sql($sql, array($completionelement, $userid, $attempt, $scorm->id));
1336  
1337      foreach ($tracks as $track) {
1338          if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1339              $incomplete = false;
1340          } else {
1341              $incomplete = true;
1342              break; // Found an incomplete sco, so the result as a whole is incomplete.
1343          }
1344      }
1345      $tracks->close();
1346  
1347      // Validate user request to start a new attempt.
1348      if ($incomplete === true) {
1349          // The option to start a new attempt should never have been presented. Force false.
1350          $newattempt = 'off';
1351      } else if (!empty($scorm->forcenewattempt)) {
1352          // A new attempt should be forced for already completed attempts.
1353          $newattempt = 'on';
1354      }
1355  
1356      if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1357          $attempt++;
1358          $mode = 'normal';
1359      } else { // Check if review mode should be set.
1360          if ($incomplete === true) {
1361              $mode = 'normal';
1362          } else {
1363              $mode = 'review';
1364          }
1365      }
1366  }
1367  
1368  /**
1369   * Trigger the course_module_viewed event.
1370   *
1371   * @param  stdClass $scorm        scorm object
1372   * @param  stdClass $course     course object
1373   * @param  stdClass $cm         course module object
1374   * @param  stdClass $context    context object
1375   * @since Moodle 3.0
1376   */
1377  function scorm_view($scorm, $course, $cm, $context) {
1378  
1379      // Trigger course_module_viewed event.
1380      $params = array(
1381          'context' => $context,
1382          'objectid' => $scorm->id
1383      );
1384  
1385      $event = \mod_scorm\event\course_module_viewed::create($params);
1386      $event->add_record_snapshot('course_modules', $cm);
1387      $event->add_record_snapshot('course', $course);
1388      $event->add_record_snapshot('scorm', $scorm);
1389      $event->trigger();
1390  }
1391  
1392  /**
1393   * Check if the module has any update that affects the current user since a given time.
1394   *
1395   * @param  cm_info $cm course module data
1396   * @param  int $from the time to check updates from
1397   * @param  array $filter  if we need to check only specific updates
1398   * @return stdClass an object with the different type of areas indicating if they were updated or not
1399   * @since Moodle 3.2
1400   */
1401  function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1402      global $DB, $USER, $CFG;
1403      require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1404  
1405      $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1406      $updates = new stdClass();
1407      list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1408      if (!$available) {
1409          return $updates;
1410      }
1411      $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1412  
1413      $updates->tracks = (object) array('updated' => false);
1414      $select = 'scormid = ? AND userid = ? AND timemodified > ?';
1415      $params = array($scorm->id, $USER->id, $from);
1416      $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1417      if (!empty($tracks)) {
1418          $updates->tracks->updated = true;
1419          $updates->tracks->itemids = array_keys($tracks);
1420      }
1421  
1422      // Now, teachers should see other students updates.
1423      if (has_capability('mod/scorm:viewreport', $cm->context)) {
1424          $select = 'scormid = ? AND timemodified > ?';
1425          $params = array($scorm->id, $from);
1426  
1427          if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1428              $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1429              if (empty($groupusers)) {
1430                  return $updates;
1431              }
1432              list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1433              $select .= ' AND userid ' . $insql;
1434              $params = array_merge($params, $inparams);
1435          }
1436  
1437          $updates->usertracks = (object) array('updated' => false);
1438          $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1439          if (!empty($tracks)) {
1440              $updates->usertracks->updated = true;
1441              $updates->usertracks->itemids = array_keys($tracks);
1442          }
1443      }
1444      return $updates;
1445  }
1446  
1447  /**
1448   * Get icon mapping for font-awesome.
1449   */
1450  function mod_scorm_get_fontawesome_icon_map() {
1451      return [
1452          'mod_scorm:assetc' => 'fa-file-archive-o',
1453          'mod_scorm:asset' => 'fa-file-archive-o',
1454          'mod_scorm:browsed' => 'fa-book',
1455          'mod_scorm:completed' => 'fa-check-square-o',
1456          'mod_scorm:failed' => 'fa-times',
1457          'mod_scorm:incomplete' => 'fa-pencil-square-o',
1458          'mod_scorm:minus' => 'fa-minus',
1459          'mod_scorm:notattempted' => 'fa-square-o',
1460          'mod_scorm:passed' => 'fa-check',
1461          'mod_scorm:plus' => 'fa-plus',
1462          'mod_scorm:popdown' => 'fa-window-close-o',
1463          'mod_scorm:popup' => 'fa-window-restore',
1464          'mod_scorm:suspend' => 'fa-pause',
1465          'mod_scorm:wait' => 'fa-clock-o',
1466      ];
1467  }
1468  
1469  /**
1470   * This standard function will check all instances of this module
1471   * and make sure there are up-to-date events created for each of them.
1472   * If courseid = 0, then every scorm event in the site is checked, else
1473   * only scorm events belonging to the course specified are checked.
1474   *
1475   * @param int $courseid
1476   * @param int|stdClass $instance scorm module instance or ID.
1477   * @param int|stdClass $cm Course module object or ID.
1478   * @return bool
1479   */
1480  function scorm_refresh_events($courseid = 0, $instance = null, $cm = null) {
1481      global $CFG, $DB;
1482  
1483      require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1484  
1485      // If we have instance information then we can just update the one event instead of updating all events.
1486      if (isset($instance)) {
1487          if (!is_object($instance)) {
1488              $instance = $DB->get_record('scorm', array('id' => $instance), '*', MUST_EXIST);
1489          }
1490          if (isset($cm)) {
1491              if (!is_object($cm)) {
1492                  $cm = (object)array('id' => $cm);
1493              }
1494          } else {
1495              $cm = get_coursemodule_from_instance('scorm', $instance->id);
1496          }
1497          scorm_update_calendar($instance, $cm->id);
1498          return true;
1499      }
1500  
1501      if ($courseid) {
1502          // Make sure that the course id is numeric.
1503          if (!is_numeric($courseid)) {
1504              return false;
1505          }
1506          if (!$scorms = $DB->get_records('scorm', array('course' => $courseid))) {
1507              return false;
1508          }
1509      } else {
1510          if (!$scorms = $DB->get_records('scorm')) {
1511              return false;
1512          }
1513      }
1514  
1515      foreach ($scorms as $scorm) {
1516          $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1517          scorm_update_calendar($scorm, $cm->id);
1518      }
1519  
1520      return true;
1521  }
1522  
1523  /**
1524   * This function receives a calendar event and returns the action associated with it, or null if there is none.
1525   *
1526   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1527   * is not displayed on the block.
1528   *
1529   * @param calendar_event $event
1530   * @param \core_calendar\action_factory $factory
1531   * @param int $userid User id override
1532   * @return \core_calendar\local\event\entities\action_interface|null
1533   */
1534  function mod_scorm_core_calendar_provide_event_action(calendar_event $event,
1535                                                        \core_calendar\action_factory $factory, $userid = null) {
1536      global $CFG, $USER;
1537  
1538      require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1539  
1540      if (empty($userid)) {
1541          $userid = $USER->id;
1542      }
1543  
1544      $cm = get_fast_modinfo($event->courseid, $userid)->instances['scorm'][$event->instance];
1545  
1546      if (has_capability('mod/scorm:viewreport', $cm->context, $userid)) {
1547          // Teachers do not need to be reminded to complete a scorm.
1548          return null;
1549      }
1550  
1551      $completion = new \completion_info($cm->get_course());
1552  
1553      $completiondata = $completion->get_data($cm, false, $userid);
1554  
1555      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1556          return null;
1557      }
1558  
1559      if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
1560          // The scorm has closed so the user can no longer submit anything.
1561          return null;
1562      }
1563  
1564      // Restore scorm object from cached values in $cm, we only need id, timeclose and timeopen.
1565      $customdata = $cm->customdata ?: [];
1566      $customdata['id'] = $cm->instance;
1567      $scorm = (object)($customdata + ['timeclose' => 0, 'timeopen' => 0]);
1568  
1569      // Check that the SCORM activity is open.
1570      list($actionable, $warnings) = scorm_get_availability_status($scorm, false, null, $userid);
1571  
1572      return $factory->create_instance(
1573          get_string('enter', 'scorm'),
1574          new \moodle_url('/mod/scorm/view.php', array('id' => $cm->id)),
1575          1,
1576          $actionable
1577      );
1578  }
1579  
1580  /**
1581   * Add a get_coursemodule_info function in case any SCORM type wants to add 'extra' information
1582   * for the course (see resource).
1583   *
1584   * Given a course_module object, this function returns any "extra" information that may be needed
1585   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1586   *
1587   * @param stdClass $coursemodule The coursemodule object (record).
1588   * @return cached_cm_info An object on information that the courses
1589   *                        will know about (most noticeably, an icon).
1590   */
1591  function scorm_get_coursemodule_info($coursemodule) {
1592      global $DB;
1593  
1594      $dbparams = ['id' => $coursemodule->instance];
1595      $fields = 'id, name, intro, introformat, completionstatusrequired, completionscorerequired, completionstatusallscos, '.
1596          'timeopen, timeclose';
1597      if (!$scorm = $DB->get_record('scorm', $dbparams, $fields)) {
1598          return false;
1599      }
1600  
1601      $result = new cached_cm_info();
1602      $result->name = $scorm->name;
1603  
1604      if ($coursemodule->showdescription) {
1605          // Convert intro to html. Do not filter cached version, filters run at display time.
1606          $result->content = format_module_intro('scorm', $scorm, $coursemodule->id, false);
1607      }
1608  
1609      // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1610      if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1611          $result->customdata['customcompletionrules']['completionstatusrequired'] = $scorm->completionstatusrequired;
1612          $result->customdata['customcompletionrules']['completionscorerequired'] = $scorm->completionscorerequired;
1613          $result->customdata['customcompletionrules']['completionstatusallscos'] = $scorm->completionstatusallscos;
1614      }
1615      // Populate some other values that can be used in calendar or on dashboard.
1616      if ($scorm->timeopen) {
1617          $result->customdata['timeopen'] = $scorm->timeopen;
1618      }
1619      if ($scorm->timeclose) {
1620          $result->customdata['timeclose'] = $scorm->timeclose;
1621      }
1622  
1623      return $result;
1624  }
1625  
1626  /**
1627   * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1628   *
1629   * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1630   * @return array $descriptions the array of descriptions for the custom rules.
1631   */
1632  function mod_scorm_get_completion_active_rule_descriptions($cm) {
1633      // Values will be present in cm_info, and we assume these are up to date.
1634      if (empty($cm->customdata['customcompletionrules'])
1635          || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1636          return [];
1637      }
1638  
1639      $descriptions = [];
1640      foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1641          switch ($key) {
1642              case 'completionstatusrequired':
1643                  if (!is_null($val)) {
1644                      // Determine the selected statuses using a bitwise operation.
1645                      $cvalues = array();
1646                      foreach (scorm_status_options(true) as $bit => $string) {
1647                          if (($val & $bit) == $bit) {
1648                              $cvalues[] = $string;
1649                          }
1650                      }
1651                      $statusstring = implode(', ', $cvalues);
1652                      $descriptions[] = get_string('completionstatusrequireddesc', 'scorm', $statusstring);
1653                  }
1654                  break;
1655              case 'completionscorerequired':
1656                  if (!is_null($val)) {
1657                      $descriptions[] = get_string('completionscorerequireddesc', 'scorm', $val);
1658                  }
1659                  break;
1660              case 'completionstatusallscos':
1661                  if (!empty($val)) {
1662                      $descriptions[] = get_string('completionstatusallscos', 'scorm');
1663                  }
1664                  break;
1665              default:
1666                  break;
1667          }
1668      }
1669      return $descriptions;
1670  }
1671  
1672  /**
1673   * This function will update the scorm module according to the
1674   * event that has been modified.
1675   *
1676   * It will set the timeopen or timeclose value of the scorm instance
1677   * according to the type of event provided.
1678   *
1679   * @throws \moodle_exception
1680   * @param \calendar_event $event
1681   * @param stdClass $scorm The module instance to get the range from
1682   */
1683  function mod_scorm_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $scorm) {
1684      global $DB;
1685  
1686      if (empty($event->instance) || $event->modulename != 'scorm') {
1687          return;
1688      }
1689  
1690      if ($event->instance != $scorm->id) {
1691          return;
1692      }
1693  
1694      if (!in_array($event->eventtype, [SCORM_EVENT_TYPE_OPEN, SCORM_EVENT_TYPE_CLOSE])) {
1695          return;
1696      }
1697  
1698      $courseid = $event->courseid;
1699      $modulename = $event->modulename;
1700      $instanceid = $event->instance;
1701      $modified = false;
1702  
1703      $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1704      $context = context_module::instance($coursemodule->id);
1705  
1706      // The user does not have the capability to modify this activity.
1707      if (!has_capability('moodle/course:manageactivities', $context)) {
1708          return;
1709      }
1710  
1711      if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1712          // If the event is for the scorm activity opening then we should
1713          // set the start time of the scorm activity to be the new start
1714          // time of the event.
1715          if ($scorm->timeopen != $event->timestart) {
1716              $scorm->timeopen = $event->timestart;
1717              $scorm->timemodified = time();
1718              $modified = true;
1719          }
1720      } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1721          // If the event is for the scorm activity closing then we should
1722          // set the end time of the scorm activity to be the new start
1723          // time of the event.
1724          if ($scorm->timeclose != $event->timestart) {
1725              $scorm->timeclose = $event->timestart;
1726              $modified = true;
1727          }
1728      }
1729  
1730      if ($modified) {
1731          $scorm->timemodified = time();
1732          $DB->update_record('scorm', $scorm);
1733          $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1734          $event->trigger();
1735      }
1736  }
1737  
1738  /**
1739   * This function calculates the minimum and maximum cutoff values for the timestart of
1740   * the given event.
1741   *
1742   * It will return an array with two values, the first being the minimum cutoff value and
1743   * the second being the maximum cutoff value. Either or both values can be null, which
1744   * indicates there is no minimum or maximum, respectively.
1745   *
1746   * If a cutoff is required then the function must return an array containing the cutoff
1747   * timestamp and error string to display to the user if the cutoff value is violated.
1748   *
1749   * A minimum and maximum cutoff return value will look like:
1750   * [
1751   *     [1505704373, 'The date must be after this date'],
1752   *     [1506741172, 'The date must be before this date']
1753   * ]
1754   *
1755   * @param \calendar_event $event The calendar event to get the time range for
1756   * @param \stdClass $instance The module instance to get the range from
1757   * @return array Returns an array with min and max date.
1758   */
1759  function mod_scorm_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1760      $mindate = null;
1761      $maxdate = null;
1762  
1763      if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1764          // The start time of the open event can't be equal to or after the
1765          // close time of the scorm activity.
1766          if (!empty($instance->timeclose)) {
1767              $maxdate = [
1768                  $instance->timeclose,
1769                  get_string('openafterclose', 'scorm')
1770              ];
1771          }
1772      } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1773          // The start time of the close event can't be equal to or earlier than the
1774          // open time of the scorm activity.
1775          if (!empty($instance->timeopen)) {
1776              $mindate = [
1777                  $instance->timeopen,
1778                  get_string('closebeforeopen', 'scorm')
1779              ];
1780          }
1781      }
1782  
1783      return [$mindate, $maxdate];
1784  }
1785  
1786  /**
1787   * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
1788   *
1789   * @param  string $filearea The filearea.
1790   * @param  array  $args The path (the part after the filearea and before the filename).
1791   * @return array The itemid and the filepath inside the $args path, for the defined filearea.
1792   */
1793  function mod_scorm_get_path_from_pluginfile(string $filearea, array $args) : array {
1794      // SCORM never has an itemid (the number represents the revision but it's not stored in database).
1795      array_shift($args);
1796  
1797      // Get the filepath.
1798      if (empty($args)) {
1799          $filepath = '/';
1800      } else {
1801          $filepath = '/' . implode('/', $args) . '/';
1802      }
1803  
1804      return [
1805          'itemid' => 0,
1806          'filepath' => $filepath,
1807      ];
1808  }
1809  
1810  /**
1811   * Callback to fetch the activity event type lang string.
1812   *
1813   * @param string $eventtype The event type.
1814   * @return lang_string The event type lang string.
1815   */
1816  function mod_scorm_core_calendar_get_event_action_string(string $eventtype): string {
1817      $modulename = get_string('modulename', 'scorm');
1818  
1819      switch ($eventtype) {
1820          case SCORM_EVENT_TYPE_OPEN:
1821              $identifier = 'calendarstart';
1822              break;
1823          case SCORM_EVENT_TYPE_CLOSE:
1824              $identifier = 'calendarend';
1825              break;
1826          default:
1827              return get_string('requiresaction', 'calendar', $modulename);
1828      }
1829  
1830      return get_string($identifier, 'scorm', $modulename);
1831  }
1832  
1833  /**
1834   * This function extends the settings navigation block for the site.
1835   *
1836   * It is safe to rely on PAGE here as we will only ever be within the module
1837   * context when this is called
1838   *
1839   * @param settings_navigation $settings navigation_node object.
1840   * @param navigation_node $scormnode navigation_node object.
1841   * @return void
1842   */
1843  function scorm_extend_settings_navigation(settings_navigation $settings, navigation_node $scormnode): void {
1844      if (has_capability('mod/scorm:viewreport', $settings->get_page()->cm->context)) {
1845          $url = new moodle_url('/mod/scorm/report.php', ['id' => $settings->get_page()->cm->id]);
1846          $scormnode->add(get_string("reports", "scorm"), $url, navigation_node::TYPE_CUSTOM, null, 'scormreport');
1847      }
1848  }