Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/mod/scorm/ -> lib.php (source)

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

   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
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  
1044          default: return null;
1045      }
1046  }
1047  
1048  /**
1049   * Get the filename for a temp log file
1050   *
1051   * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1052   * @param integer $scoid - scoid of object this log entry is for
1053   * @return string The filename as an absolute path
1054   */
1055  function scorm_debug_log_filename($type, $scoid) {
1056      global $CFG, $USER;
1057  
1058      $logpath = $CFG->tempdir.'/scormlogs';
1059      $logfile = $logpath.'/'.$type.'debug_'.$USER->id.'_'.$scoid.'.log';
1060      return $logfile;
1061  }
1062  
1063  /**
1064   * writes log output to a temp log file
1065   *
1066   * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1067   * @param string $text - text to be written to file.
1068   * @param integer $scoid - scoid of object this log entry is for.
1069   */
1070  function scorm_debug_log_write($type, $text, $scoid) {
1071      global $CFG;
1072  
1073      $debugenablelog = get_config('scorm', 'allowapidebug');
1074      if (!$debugenablelog || empty($text)) {
1075          return;
1076      }
1077      if (make_temp_directory('scormlogs/')) {
1078          $logfile = scorm_debug_log_filename($type, $scoid);
1079          @file_put_contents($logfile, date('Y/m/d H:i:s O')." DEBUG $text\r\n", FILE_APPEND);
1080          @chmod($logfile, $CFG->filepermissions);
1081      }
1082  }
1083  
1084  /**
1085   * Remove debug log file
1086   *
1087   * @param string $type - type of log(aicc,scorm12,scorm13) used as prefix for filename
1088   * @param integer $scoid - scoid of object this log entry is for
1089   * @return boolean True if the file is successfully deleted, false otherwise
1090   */
1091  function scorm_debug_log_remove($type, $scoid) {
1092  
1093      $debugenablelog = get_config('scorm', 'allowapidebug');
1094      $logfile = scorm_debug_log_filename($type, $scoid);
1095      if (!$debugenablelog || !file_exists($logfile)) {
1096          return false;
1097      }
1098  
1099      return @unlink($logfile);
1100  }
1101  
1102  /**
1103   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
1104   */
1105  function scorm_print_overview() {
1106      throw new coding_exception('scorm_print_overview() can not be used any more and is obsolete.');
1107  }
1108  
1109  /**
1110   * Return a list of page types
1111   * @param string $pagetype current page type
1112   * @param stdClass $parentcontext Block's parent context
1113   * @param stdClass $currentcontext Current context of block
1114   */
1115  function scorm_page_type_list($pagetype, $parentcontext, $currentcontext) {
1116      $modulepagetype = array('mod-scorm-*' => get_string('page-mod-scorm-x', 'scorm'));
1117      return $modulepagetype;
1118  }
1119  
1120  /**
1121   * Returns the SCORM version used.
1122   * @param string $scormversion comes from $scorm->version
1123   * @param string $version one of the defined vars SCORM_12, SCORM_13, SCORM_AICC (or empty)
1124   * @return Scorm version.
1125   */
1126  function scorm_version_check($scormversion, $version='') {
1127      $scormversion = trim(strtolower($scormversion));
1128      if (empty($version) || $version == SCORM_12) {
1129          if ($scormversion == 'scorm_12' || $scormversion == 'scorm_1.2') {
1130              return SCORM_12;
1131          }
1132          if (!empty($version)) {
1133              return false;
1134          }
1135      }
1136      if (empty($version) || $version == SCORM_13) {
1137          if ($scormversion == 'scorm_13' || $scormversion == 'scorm_1.3') {
1138              return SCORM_13;
1139          }
1140          if (!empty($version)) {
1141              return false;
1142          }
1143      }
1144      if (empty($version) || $version == SCORM_AICC) {
1145          if (strpos($scormversion, 'aicc')) {
1146              return SCORM_AICC;
1147          }
1148          if (!empty($version)) {
1149              return false;
1150          }
1151      }
1152      return false;
1153  }
1154  
1155  /**
1156   * Register the ability to handle drag and drop file uploads
1157   * @return array containing details of the files / types the mod can handle
1158   */
1159  function scorm_dndupload_register() {
1160      return array('files' => array(
1161          array('extension' => 'zip', 'message' => get_string('dnduploadscorm', 'scorm'))
1162      ));
1163  }
1164  
1165  /**
1166   * Handle a file that has been uploaded
1167   * @param object $uploadinfo details of the file / content that has been uploaded
1168   * @return int instance id of the newly created mod
1169   */
1170  function scorm_dndupload_handle($uploadinfo) {
1171  
1172      $context = context_module::instance($uploadinfo->coursemodule);
1173      file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0);
1174      $fs = get_file_storage();
1175      $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false);
1176      $file = reset($files);
1177  
1178      // Validate the file, make sure it's a valid SCORM package!
1179      $errors = scorm_validate_package($file);
1180      if (!empty($errors)) {
1181          return false;
1182      }
1183      // Create a default scorm object to pass to scorm_add_instance()!
1184      $scorm = get_config('scorm');
1185      $scorm->course = $uploadinfo->course->id;
1186      $scorm->coursemodule = $uploadinfo->coursemodule;
1187      $scorm->cmidnumber = '';
1188      $scorm->name = $uploadinfo->displayname;
1189      $scorm->scormtype = SCORM_TYPE_LOCAL;
1190      $scorm->reference = $file->get_filename();
1191      $scorm->intro = '';
1192      $scorm->width = $scorm->framewidth;
1193      $scorm->height = $scorm->frameheight;
1194  
1195      return scorm_add_instance($scorm, null);
1196  }
1197  
1198  /**
1199   * Sets activity completion state
1200   *
1201   * @param object $scorm object
1202   * @param int $userid User ID
1203   * @param int $completionstate Completion state
1204   * @param array $grades grades array of users with grades - used when $userid = 0
1205   */
1206  function scorm_set_completion($scorm, $userid, $completionstate = COMPLETION_COMPLETE, $grades = array()) {
1207      $course = new stdClass();
1208      $course->id = $scorm->course;
1209      $completion = new completion_info($course);
1210  
1211      // Check if completion is enabled site-wide, or for the course.
1212      if (!$completion->is_enabled()) {
1213          return;
1214      }
1215  
1216      $cm = get_coursemodule_from_instance('scorm', $scorm->id, $scorm->course);
1217      if (empty($cm) || !$completion->is_enabled($cm)) {
1218              return;
1219      }
1220  
1221      if (empty($userid)) { // We need to get all the relevant users from $grades param.
1222          foreach ($grades as $grade) {
1223              $completion->update_state($cm, $completionstate, $grade->userid);
1224          }
1225      } else {
1226          $completion->update_state($cm, $completionstate, $userid);
1227      }
1228  }
1229  
1230  /**
1231   * Check that a Zip file contains a valid SCORM package
1232   *
1233   * @param $file stored_file a Zip file.
1234   * @return array empty if no issue is found. Array of error message otherwise
1235   */
1236  function scorm_validate_package($file) {
1237      $packer = get_file_packer('application/zip');
1238      $errors = array();
1239      if ($file->is_external_file()) { // Get zip file so we can check it is correct.
1240          $file->import_external_file_contents();
1241      }
1242      $filelist = $file->list_files($packer);
1243  
1244      if (!is_array($filelist)) {
1245          $errors['packagefile'] = get_string('badarchive', 'scorm');
1246      } else {
1247          $aiccfound = false;
1248          $badmanifestpresent = false;
1249          foreach ($filelist as $info) {
1250              if ($info->pathname == 'imsmanifest.xml') {
1251                  return array();
1252              } else if (strpos($info->pathname, 'imsmanifest.xml') !== false) {
1253                  // This package has an imsmanifest file inside a folder of the package.
1254                  $badmanifestpresent = true;
1255              }
1256              if (preg_match('/\.cst$/', $info->pathname)) {
1257                  return array();
1258              }
1259          }
1260          if (!$aiccfound) {
1261              if ($badmanifestpresent) {
1262                  $errors['packagefile'] = get_string('badimsmanifestlocation', 'scorm');
1263              } else {
1264                  $errors['packagefile'] = get_string('nomanifest', 'scorm');
1265              }
1266          }
1267      }
1268      return $errors;
1269  }
1270  
1271  /**
1272   * Check and set the correct mode and attempt when entering a SCORM package.
1273   *
1274   * @param object $scorm object
1275   * @param string $newattempt should a new attempt be generated here.
1276   * @param int $attempt the attempt number this is for.
1277   * @param int $userid the userid of the user.
1278   * @param string $mode the current mode that has been selected.
1279   */
1280  function scorm_check_mode($scorm, &$newattempt, &$attempt, $userid, &$mode) {
1281      global $DB;
1282  
1283      if (($mode == 'browse')) {
1284          if ($scorm->hidebrowse == 1) {
1285              // Prevent Browse mode if hidebrowse is set.
1286              $mode = 'normal';
1287          } else {
1288              // We don't need to check attempts as browse mode is set.
1289              return;
1290          }
1291      }
1292  
1293      if ($scorm->forcenewattempt == SCORM_FORCEATTEMPT_ALWAYS) {
1294          // This SCORM is configured to force a new attempt on every re-entry.
1295          $newattempt = 'on';
1296          $mode = 'normal';
1297          if ($attempt == 1) {
1298              // Check if the user has any existing data or if this is really the first attempt.
1299              $exists = $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id));
1300              if (!$exists) {
1301                  // No records yet - Attempt should == 1.
1302                  return;
1303              }
1304          }
1305          $attempt++;
1306  
1307          return;
1308      }
1309      // Check if the scorm module is incomplete (used to validate user request to start a new attempt).
1310      $incomplete = true;
1311  
1312      // Note - in SCORM_13 the cmi-core.lesson_status field was split into
1313      // 'cmi.completion_status' and 'cmi.success_status'.
1314      // 'cmi.completion_status' can only contain values 'completed', 'incomplete', 'not attempted' or 'unknown'.
1315      // This means the values 'passed' or 'failed' will never be reported for a track in SCORM_13 and
1316      // the only status that will be treated as complete is 'completed'.
1317  
1318      $completionelements = array(
1319          SCORM_12 => 'cmi.core.lesson_status',
1320          SCORM_13 => 'cmi.completion_status',
1321          SCORM_AICC => 'cmi.core.lesson_status'
1322      );
1323      $scormversion = scorm_version_check($scorm->version);
1324      if($scormversion===false) {
1325          $scormversion = SCORM_12;
1326      }
1327      $completionelement = $completionelements[$scormversion];
1328  
1329      $sql = "SELECT sc.id, t.value
1330                FROM {scorm_scoes} sc
1331           LEFT JOIN {scorm_scoes_track} t ON sc.scorm = t.scormid AND sc.id = t.scoid
1332                     AND t.element = ? AND t.userid = ? AND t.attempt = ?
1333               WHERE sc.scormtype = 'sco' AND sc.scorm = ?";
1334      $tracks = $DB->get_recordset_sql($sql, array($completionelement, $userid, $attempt, $scorm->id));
1335  
1336      foreach ($tracks as $track) {
1337          if (($track->value == 'completed') || ($track->value == 'passed') || ($track->value == 'failed')) {
1338              $incomplete = false;
1339          } else {
1340              $incomplete = true;
1341              break; // Found an incomplete sco, so the result as a whole is incomplete.
1342          }
1343      }
1344      $tracks->close();
1345  
1346      // Validate user request to start a new attempt.
1347      if ($incomplete === true) {
1348          // The option to start a new attempt should never have been presented. Force false.
1349          $newattempt = 'off';
1350      } else if (!empty($scorm->forcenewattempt)) {
1351          // A new attempt should be forced for already completed attempts.
1352          $newattempt = 'on';
1353      }
1354  
1355      if (($newattempt == 'on') && (($attempt < $scorm->maxattempt) || ($scorm->maxattempt == 0))) {
1356          $attempt++;
1357          $mode = 'normal';
1358      } else { // Check if review mode should be set.
1359          if ($incomplete === true) {
1360              $mode = 'normal';
1361          } else {
1362              $mode = 'review';
1363          }
1364      }
1365  }
1366  
1367  /**
1368   * Trigger the course_module_viewed event.
1369   *
1370   * @param  stdClass $scorm        scorm object
1371   * @param  stdClass $course     course object
1372   * @param  stdClass $cm         course module object
1373   * @param  stdClass $context    context object
1374   * @since Moodle 3.0
1375   */
1376  function scorm_view($scorm, $course, $cm, $context) {
1377  
1378      // Trigger course_module_viewed event.
1379      $params = array(
1380          'context' => $context,
1381          'objectid' => $scorm->id
1382      );
1383  
1384      $event = \mod_scorm\event\course_module_viewed::create($params);
1385      $event->add_record_snapshot('course_modules', $cm);
1386      $event->add_record_snapshot('course', $course);
1387      $event->add_record_snapshot('scorm', $scorm);
1388      $event->trigger();
1389  }
1390  
1391  /**
1392   * Check if the module has any update that affects the current user since a given time.
1393   *
1394   * @param  cm_info $cm course module data
1395   * @param  int $from the time to check updates from
1396   * @param  array $filter  if we need to check only specific updates
1397   * @return stdClass an object with the different type of areas indicating if they were updated or not
1398   * @since Moodle 3.2
1399   */
1400  function scorm_check_updates_since(cm_info $cm, $from, $filter = array()) {
1401      global $DB, $USER, $CFG;
1402      require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1403  
1404      $scorm = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1405      $updates = new stdClass();
1406      list($available, $warnings) = scorm_get_availability_status($scorm, true, $cm->context);
1407      if (!$available) {
1408          return $updates;
1409      }
1410      $updates = course_check_module_updates_since($cm, $from, array('package'), $filter);
1411  
1412      $updates->tracks = (object) array('updated' => false);
1413      $select = 'scormid = ? AND userid = ? AND timemodified > ?';
1414      $params = array($scorm->id, $USER->id, $from);
1415      $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1416      if (!empty($tracks)) {
1417          $updates->tracks->updated = true;
1418          $updates->tracks->itemids = array_keys($tracks);
1419      }
1420  
1421      // Now, teachers should see other students updates.
1422      if (has_capability('mod/scorm:viewreport', $cm->context)) {
1423          $select = 'scormid = ? AND timemodified > ?';
1424          $params = array($scorm->id, $from);
1425  
1426          if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1427              $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1428              if (empty($groupusers)) {
1429                  return $updates;
1430              }
1431              list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1432              $select .= ' AND userid ' . $insql;
1433              $params = array_merge($params, $inparams);
1434          }
1435  
1436          $updates->usertracks = (object) array('updated' => false);
1437          $tracks = $DB->get_records_select('scorm_scoes_track', $select, $params, '', 'id');
1438          if (!empty($tracks)) {
1439              $updates->usertracks->updated = true;
1440              $updates->usertracks->itemids = array_keys($tracks);
1441          }
1442      }
1443      return $updates;
1444  }
1445  
1446  /**
1447   * Get icon mapping for font-awesome.
1448   */
1449  function mod_scorm_get_fontawesome_icon_map() {
1450      return [
1451          'mod_scorm:assetc' => 'fa-file-archive-o',
1452          'mod_scorm:asset' => 'fa-file-archive-o',
1453          'mod_scorm:browsed' => 'fa-book',
1454          'mod_scorm:completed' => 'fa-check-square-o',
1455          'mod_scorm:failed' => 'fa-times',
1456          'mod_scorm:incomplete' => 'fa-pencil-square-o',
1457          'mod_scorm:minus' => 'fa-minus',
1458          'mod_scorm:notattempted' => 'fa-square-o',
1459          'mod_scorm:passed' => 'fa-check',
1460          'mod_scorm:plus' => 'fa-plus',
1461          'mod_scorm:popdown' => 'fa-window-close-o',
1462          'mod_scorm:popup' => 'fa-window-restore',
1463          'mod_scorm:suspend' => 'fa-pause',
1464          'mod_scorm:wait' => 'fa-clock-o',
1465      ];
1466  }
1467  
1468  /**
1469   * This standard function will check all instances of this module
1470   * and make sure there are up-to-date events created for each of them.
1471   * If courseid = 0, then every scorm event in the site is checked, else
1472   * only scorm events belonging to the course specified are checked.
1473   *
1474   * @param int $courseid
1475   * @param int|stdClass $instance scorm module instance or ID.
1476   * @param int|stdClass $cm Course module object or ID.
1477   * @return bool
1478   */
1479  function scorm_refresh_events($courseid = 0, $instance = null, $cm = null) {
1480      global $CFG, $DB;
1481  
1482      require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1483  
1484      // If we have instance information then we can just update the one event instead of updating all events.
1485      if (isset($instance)) {
1486          if (!is_object($instance)) {
1487              $instance = $DB->get_record('scorm', array('id' => $instance), '*', MUST_EXIST);
1488          }
1489          if (isset($cm)) {
1490              if (!is_object($cm)) {
1491                  $cm = (object)array('id' => $cm);
1492              }
1493          } else {
1494              $cm = get_coursemodule_from_instance('scorm', $instance->id);
1495          }
1496          scorm_update_calendar($instance, $cm->id);
1497          return true;
1498      }
1499  
1500      if ($courseid) {
1501          // Make sure that the course id is numeric.
1502          if (!is_numeric($courseid)) {
1503              return false;
1504          }
1505          if (!$scorms = $DB->get_records('scorm', array('course' => $courseid))) {
1506              return false;
1507          }
1508      } else {
1509          if (!$scorms = $DB->get_records('scorm')) {
1510              return false;
1511          }
1512      }
1513  
1514      foreach ($scorms as $scorm) {
1515          $cm = get_coursemodule_from_instance('scorm', $scorm->id);
1516          scorm_update_calendar($scorm, $cm->id);
1517      }
1518  
1519      return true;
1520  }
1521  
1522  /**
1523   * This function receives a calendar event and returns the action associated with it, or null if there is none.
1524   *
1525   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1526   * is not displayed on the block.
1527   *
1528   * @param calendar_event $event
1529   * @param \core_calendar\action_factory $factory
1530   * @param int $userid User id override
1531   * @return \core_calendar\local\event\entities\action_interface|null
1532   */
1533  function mod_scorm_core_calendar_provide_event_action(calendar_event $event,
1534                                                        \core_calendar\action_factory $factory, $userid = null) {
1535      global $CFG, $USER;
1536  
1537      require_once($CFG->dirroot . '/mod/scorm/locallib.php');
1538  
1539      if (empty($userid)) {
1540          $userid = $USER->id;
1541      }
1542  
1543      $cm = get_fast_modinfo($event->courseid, $userid)->instances['scorm'][$event->instance];
1544  
1545      if (has_capability('mod/scorm:viewreport', $cm->context, $userid)) {
1546          // Teachers do not need to be reminded to complete a scorm.
1547          return null;
1548      }
1549  
1550      $completion = new \completion_info($cm->get_course());
1551  
1552      $completiondata = $completion->get_data($cm, false, $userid);
1553  
1554      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1555          return null;
1556      }
1557  
1558      if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
1559          // The scorm has closed so the user can no longer submit anything.
1560          return null;
1561      }
1562  
1563      // Restore scorm object from cached values in $cm, we only need id, timeclose and timeopen.
1564      $customdata = $cm->customdata ?: [];
1565      $customdata['id'] = $cm->instance;
1566      $scorm = (object)($customdata + ['timeclose' => 0, 'timeopen' => 0]);
1567  
1568      // Check that the SCORM activity is open.
1569      list($actionable, $warnings) = scorm_get_availability_status($scorm, false, null, $userid);
1570  
1571      return $factory->create_instance(
1572          get_string('enter', 'scorm'),
1573          new \moodle_url('/mod/scorm/view.php', array('id' => $cm->id)),
1574          1,
1575          $actionable
1576      );
1577  }
1578  
1579  /**
1580   * Add a get_coursemodule_info function in case any SCORM type wants to add 'extra' information
1581   * for the course (see resource).
1582   *
1583   * Given a course_module object, this function returns any "extra" information that may be needed
1584   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1585   *
1586   * @param stdClass $coursemodule The coursemodule object (record).
1587   * @return cached_cm_info An object on information that the courses
1588   *                        will know about (most noticeably, an icon).
1589   */
1590  function scorm_get_coursemodule_info($coursemodule) {
1591      global $DB;
1592  
1593      $dbparams = ['id' => $coursemodule->instance];
1594      $fields = 'id, name, intro, introformat, completionstatusrequired, completionscorerequired, completionstatusallscos, '.
1595          'timeopen, timeclose';
1596      if (!$scorm = $DB->get_record('scorm', $dbparams, $fields)) {
1597          return false;
1598      }
1599  
1600      $result = new cached_cm_info();
1601      $result->name = $scorm->name;
1602  
1603      if ($coursemodule->showdescription) {
1604          // Convert intro to html. Do not filter cached version, filters run at display time.
1605          $result->content = format_module_intro('scorm', $scorm, $coursemodule->id, false);
1606      }
1607  
1608      // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1609      if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1610          $result->customdata['customcompletionrules']['completionstatusrequired'] = $scorm->completionstatusrequired;
1611          $result->customdata['customcompletionrules']['completionscorerequired'] = $scorm->completionscorerequired;
1612          $result->customdata['customcompletionrules']['completionstatusallscos'] = $scorm->completionstatusallscos;
1613      }
1614      // Populate some other values that can be used in calendar or on dashboard.
1615      if ($scorm->timeopen) {
1616          $result->customdata['timeopen'] = $scorm->timeopen;
1617      }
1618      if ($scorm->timeclose) {
1619          $result->customdata['timeclose'] = $scorm->timeclose;
1620      }
1621  
1622      return $result;
1623  }
1624  
1625  /**
1626   * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1627   *
1628   * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1629   * @return array $descriptions the array of descriptions for the custom rules.
1630   */
1631  function mod_scorm_get_completion_active_rule_descriptions($cm) {
1632      // Values will be present in cm_info, and we assume these are up to date.
1633      if (empty($cm->customdata['customcompletionrules'])
1634          || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1635          return [];
1636      }
1637  
1638      $descriptions = [];
1639      foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1640          switch ($key) {
1641              case 'completionstatusrequired':
1642                  if (!is_null($val)) {
1643                      // Determine the selected statuses using a bitwise operation.
1644                      $cvalues = array();
1645                      foreach (scorm_status_options(true) as $bit => $string) {
1646                          if (($val & $bit) == $bit) {
1647                              $cvalues[] = $string;
1648                          }
1649                      }
1650                      $statusstring = implode(', ', $cvalues);
1651                      $descriptions[] = get_string('completionstatusrequireddesc', 'scorm', $statusstring);
1652                  }
1653                  break;
1654              case 'completionscorerequired':
1655                  if (!is_null($val)) {
1656                      $descriptions[] = get_string('completionscorerequireddesc', 'scorm', $val);
1657                  }
1658                  break;
1659              case 'completionstatusallscos':
1660                  if (!empty($val)) {
1661                      $descriptions[] = get_string('completionstatusallscos', 'scorm');
1662                  }
1663                  break;
1664              default:
1665                  break;
1666          }
1667      }
1668      return $descriptions;
1669  }
1670  
1671  /**
1672   * This function will update the scorm module according to the
1673   * event that has been modified.
1674   *
1675   * It will set the timeopen or timeclose value of the scorm instance
1676   * according to the type of event provided.
1677   *
1678   * @throws \moodle_exception
1679   * @param \calendar_event $event
1680   * @param stdClass $scorm The module instance to get the range from
1681   */
1682  function mod_scorm_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $scorm) {
1683      global $DB;
1684  
1685      if (empty($event->instance) || $event->modulename != 'scorm') {
1686          return;
1687      }
1688  
1689      if ($event->instance != $scorm->id) {
1690          return;
1691      }
1692  
1693      if (!in_array($event->eventtype, [SCORM_EVENT_TYPE_OPEN, SCORM_EVENT_TYPE_CLOSE])) {
1694          return;
1695      }
1696  
1697      $courseid = $event->courseid;
1698      $modulename = $event->modulename;
1699      $instanceid = $event->instance;
1700      $modified = false;
1701  
1702      $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1703      $context = context_module::instance($coursemodule->id);
1704  
1705      // The user does not have the capability to modify this activity.
1706      if (!has_capability('moodle/course:manageactivities', $context)) {
1707          return;
1708      }
1709  
1710      if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1711          // If the event is for the scorm activity opening then we should
1712          // set the start time of the scorm activity to be the new start
1713          // time of the event.
1714          if ($scorm->timeopen != $event->timestart) {
1715              $scorm->timeopen = $event->timestart;
1716              $scorm->timemodified = time();
1717              $modified = true;
1718          }
1719      } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1720          // If the event is for the scorm activity closing then we should
1721          // set the end time of the scorm activity to be the new start
1722          // time of the event.
1723          if ($scorm->timeclose != $event->timestart) {
1724              $scorm->timeclose = $event->timestart;
1725              $modified = true;
1726          }
1727      }
1728  
1729      if ($modified) {
1730          $scorm->timemodified = time();
1731          $DB->update_record('scorm', $scorm);
1732          $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1733          $event->trigger();
1734      }
1735  }
1736  
1737  /**
1738   * This function calculates the minimum and maximum cutoff values for the timestart of
1739   * the given event.
1740   *
1741   * It will return an array with two values, the first being the minimum cutoff value and
1742   * the second being the maximum cutoff value. Either or both values can be null, which
1743   * indicates there is no minimum or maximum, respectively.
1744   *
1745   * If a cutoff is required then the function must return an array containing the cutoff
1746   * timestamp and error string to display to the user if the cutoff value is violated.
1747   *
1748   * A minimum and maximum cutoff return value will look like:
1749   * [
1750   *     [1505704373, 'The date must be after this date'],
1751   *     [1506741172, 'The date must be before this date']
1752   * ]
1753   *
1754   * @param \calendar_event $event The calendar event to get the time range for
1755   * @param \stdClass $instance The module instance to get the range from
1756   * @return array Returns an array with min and max date.
1757   */
1758  function mod_scorm_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1759      $mindate = null;
1760      $maxdate = null;
1761  
1762      if ($event->eventtype == SCORM_EVENT_TYPE_OPEN) {
1763          // The start time of the open event can't be equal to or after the
1764          // close time of the scorm activity.
1765          if (!empty($instance->timeclose)) {
1766              $maxdate = [
1767                  $instance->timeclose,
1768                  get_string('openafterclose', 'scorm')
1769              ];
1770          }
1771      } else if ($event->eventtype == SCORM_EVENT_TYPE_CLOSE) {
1772          // The start time of the close event can't be equal to or earlier than the
1773          // open time of the scorm activity.
1774          if (!empty($instance->timeopen)) {
1775              $mindate = [
1776                  $instance->timeopen,
1777                  get_string('closebeforeopen', 'scorm')
1778              ];
1779          }
1780      }
1781  
1782      return [$mindate, $maxdate];
1783  }
1784  
1785  /**
1786   * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
1787   *
1788   * @param  string $filearea The filearea.
1789   * @param  array  $args The path (the part after the filearea and before the filename).
1790   * @return array The itemid and the filepath inside the $args path, for the defined filearea.
1791   */
1792  function mod_scorm_get_path_from_pluginfile(string $filearea, array $args) : array {
1793      // SCORM never has an itemid (the number represents the revision but it's not stored in database).
1794      array_shift($args);
1795  
1796      // Get the filepath.
1797      if (empty($args)) {
1798          $filepath = '/';
1799      } else {
1800          $filepath = '/' . implode('/', $args) . '/';
1801      }
1802  
1803      return [
1804          'itemid' => 0,
1805          'filepath' => $filepath,
1806      ];
1807  }