Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
/mod/quiz/ -> lib.php (source)

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [Versions 402 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   * Library of functions for the quiz module.
  19   *
  20   * This contains functions that are called also from outside the quiz module
  21   * Functions that are only called by the quiz module itself are in {@link locallib.php}
  22   *
  23   * @package    mod_quiz
  24   * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
  25   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  
  29  use qbank_managecategories\helper;
  30  
  31  defined('MOODLE_INTERNAL') || die();
  32  
  33  use mod_quiz\access_manager;
  34  use mod_quiz\grade_calculator;
  35  use mod_quiz\question\bank\custom_view;
  36  use mod_quiz\question\bank\qbank_helper;
  37  use mod_quiz\question\display_options;
  38  use mod_quiz\question\qubaids_for_quiz;
  39  use mod_quiz\question\qubaids_for_users_attempts;
  40  use core_question\statistics\questions\all_calculated_for_qubaid_condition;
  41  use mod_quiz\quiz_attempt;
  42  use mod_quiz\quiz_settings;
  43  
  44  require_once($CFG->dirroot . '/calendar/lib.php');
  45  require_once($CFG->dirroot . '/question/editlib.php');
  46  
  47  /**#@+
  48   * Option controlling what options are offered on the quiz settings form.
  49   */
  50  define('QUIZ_MAX_ATTEMPT_OPTION', 10);
  51  define('QUIZ_MAX_QPP_OPTION', 50);
  52  define('QUIZ_MAX_DECIMAL_OPTION', 5);
  53  define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
  54  /**#@-*/
  55  
  56  /**#@+
  57   * Options determining how the grades from individual attempts are combined to give
  58   * the overall grade for a user
  59   */
  60  define('QUIZ_GRADEHIGHEST', '1');
  61  define('QUIZ_GRADEAVERAGE', '2');
  62  define('QUIZ_ATTEMPTFIRST', '3');
  63  define('QUIZ_ATTEMPTLAST',  '4');
  64  /**#@-*/
  65  
  66  /**
  67   * @var int If start and end date for the quiz are more than this many seconds apart
  68   * they will be represented by two separate events in the calendar
  69   */
  70  define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
  71  
  72  /**#@+
  73   * Options for navigation method within quizzes.
  74   */
  75  define('QUIZ_NAVMETHOD_FREE', 'free');
  76  define('QUIZ_NAVMETHOD_SEQ',  'sequential');
  77  /**#@-*/
  78  
  79  /**
  80   * Event types.
  81   */
  82  define('QUIZ_EVENT_TYPE_OPEN', 'open');
  83  define('QUIZ_EVENT_TYPE_CLOSE', 'close');
  84  
  85  require_once (__DIR__ . '/deprecatedlib.php');
  86  
  87  /**
  88   * Given an object containing all the necessary data,
  89   * (defined by the form in mod_form.php) this function
  90   * will create a new instance and return the id number
  91   * of the new instance.
  92   *
  93   * @param stdClass $quiz the data that came from the form.
  94   * @return mixed the id of the new instance on success,
  95   *          false or a string error message on failure.
  96   */
  97  function quiz_add_instance($quiz) {
  98      global $DB;
  99      $cmid = $quiz->coursemodule;
 100  
 101      // Process the options from the form.
 102      $quiz->timecreated = time();
 103      $result = quiz_process_options($quiz);
 104      if ($result && is_string($result)) {
 105          return $result;
 106      }
 107  
 108      // Try to store it in the database.
 109      $quiz->id = $DB->insert_record('quiz', $quiz);
 110  
 111      // Create the first section for this quiz.
 112      $DB->insert_record('quiz_sections', ['quizid' => $quiz->id,
 113              'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0]);
 114  
 115      // Do the processing required after an add or an update.
 116      quiz_after_add_or_update($quiz);
 117  
 118      return $quiz->id;
 119  }
 120  
 121  /**
 122   * Given an object containing all the necessary data,
 123   * (defined by the form in mod_form.php) this function
 124   * will update an existing instance with new data.
 125   *
 126   * @param stdClass $quiz the data that came from the form.
 127   * @param stdClass $mform no longer used.
 128   * @return mixed true on success, false or a string error message on failure.
 129   */
 130  function quiz_update_instance($quiz, $mform) {
 131      global $CFG, $DB;
 132      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
 133  
 134      // Process the options from the form.
 135      $result = quiz_process_options($quiz);
 136      if ($result && is_string($result)) {
 137          return $result;
 138      }
 139  
 140      // Get the current value, so we can see what changed.
 141      $oldquiz = $DB->get_record('quiz', ['id' => $quiz->instance]);
 142  
 143      // We need two values from the existing DB record that are not in the form,
 144      // in some of the function calls below.
 145      $quiz->sumgrades = $oldquiz->sumgrades;
 146      $quiz->grade     = $oldquiz->grade;
 147  
 148      // Update the database.
 149      $quiz->id = $quiz->instance;
 150      $DB->update_record('quiz', $quiz);
 151  
 152      // Do the processing required after an add or an update.
 153      quiz_after_add_or_update($quiz);
 154  
 155      if ($oldquiz->grademethod != $quiz->grademethod) {
 156          $gradecalculator = quiz_settings::create($quiz->id)->get_grade_calculator();
 157          $gradecalculator->recompute_all_final_grades();
 158          quiz_update_grades($quiz);
 159      }
 160  
 161      $quizdateschanged = $oldquiz->timelimit   != $quiz->timelimit
 162                       || $oldquiz->timeclose   != $quiz->timeclose
 163                       || $oldquiz->graceperiod != $quiz->graceperiod;
 164      if ($quizdateschanged) {
 165          quiz_update_open_attempts(['quizid' => $quiz->id]);
 166      }
 167  
 168      // Delete any previous preview attempts.
 169      quiz_delete_previews($quiz);
 170  
 171      // Repaginate, if asked to.
 172      if (!empty($quiz->repaginatenow) && !quiz_has_attempts($quiz->id)) {
 173          quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
 174      }
 175  
 176      return true;
 177  }
 178  
 179  /**
 180   * Given an ID of an instance of this module,
 181   * this function will permanently delete the instance
 182   * and any data that depends on it.
 183   *
 184   * @param int $id the id of the quiz to delete.
 185   * @return bool success or failure.
 186   */
 187  function quiz_delete_instance($id) {
 188      global $DB;
 189  
 190      $quiz = $DB->get_record('quiz', ['id' => $id], '*', MUST_EXIST);
 191  
 192      quiz_delete_all_attempts($quiz);
 193      quiz_delete_all_overrides($quiz);
 194      quiz_delete_references($quiz->id);
 195  
 196      // We need to do the following deletes before we try and delete randoms, otherwise they would still be 'in use'.
 197      $DB->delete_records('quiz_slots', ['quizid' => $quiz->id]);
 198      $DB->delete_records('quiz_sections', ['quizid' => $quiz->id]);
 199  
 200      $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]);
 201  
 202      access_manager::delete_settings($quiz);
 203  
 204      $events = $DB->get_records('event', ['modulename' => 'quiz', 'instance' => $quiz->id]);
 205      foreach ($events as $event) {
 206          $event = calendar_event::load($event);
 207          $event->delete();
 208      }
 209  
 210      quiz_grade_item_delete($quiz);
 211      // We must delete the module record after we delete the grade item.
 212      $DB->delete_records('quiz', ['id' => $quiz->id]);
 213  
 214      return true;
 215  }
 216  
 217  /**
 218   * Deletes a quiz override from the database and clears any corresponding calendar events
 219   *
 220   * @param stdClass $quiz The quiz object.
 221   * @param int $overrideid The id of the override being deleted
 222   * @param bool $log Whether to trigger logs.
 223   * @return bool true on success
 224   */
 225  function quiz_delete_override($quiz, $overrideid, $log = true) {
 226      global $DB;
 227  
 228      if (!isset($quiz->cmid)) {
 229          $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
 230          $quiz->cmid = $cm->id;
 231      }
 232  
 233      $override = $DB->get_record('quiz_overrides', ['id' => $overrideid], '*', MUST_EXIST);
 234  
 235      // Delete the events.
 236      if (isset($override->groupid)) {
 237          // Create the search array for a group override.
 238          $eventsearcharray = ['modulename' => 'quiz',
 239              'instance' => $quiz->id, 'groupid' => (int)$override->groupid];
 240          $cachekey = "{$quiz->id}_g_{$override->groupid}";
 241      } else {
 242          // Create the search array for a user override.
 243          $eventsearcharray = ['modulename' => 'quiz',
 244              'instance' => $quiz->id, 'userid' => (int)$override->userid];
 245          $cachekey = "{$quiz->id}_u_{$override->userid}";
 246      }
 247      $events = $DB->get_records('event', $eventsearcharray);
 248      foreach ($events as $event) {
 249          $eventold = calendar_event::load($event);
 250          $eventold->delete();
 251      }
 252  
 253      $DB->delete_records('quiz_overrides', ['id' => $overrideid]);
 254      cache::make('mod_quiz', 'overrides')->delete($cachekey);
 255  
 256      if ($log) {
 257          // Set the common parameters for one of the events we will be triggering.
 258          $params = [
 259              'objectid' => $override->id,
 260              'context' => context_module::instance($quiz->cmid),
 261              'other' => [
 262                  'quizid' => $override->quiz
 263              ]
 264          ];
 265          // Determine which override deleted event to fire.
 266          if (!empty($override->userid)) {
 267              $params['relateduserid'] = $override->userid;
 268              $event = \mod_quiz\event\user_override_deleted::create($params);
 269          } else {
 270              $params['other']['groupid'] = $override->groupid;
 271              $event = \mod_quiz\event\group_override_deleted::create($params);
 272          }
 273  
 274          // Trigger the override deleted event.
 275          $event->add_record_snapshot('quiz_overrides', $override);
 276          $event->trigger();
 277      }
 278  
 279      return true;
 280  }
 281  
 282  /**
 283   * Deletes all quiz overrides from the database and clears any corresponding calendar events
 284   *
 285   * @param stdClass $quiz The quiz object.
 286   * @param bool $log Whether to trigger logs.
 287   */
 288  function quiz_delete_all_overrides($quiz, $log = true) {
 289      global $DB;
 290  
 291      $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id');
 292      foreach ($overrides as $override) {
 293          quiz_delete_override($quiz, $override->id, $log);
 294      }
 295  }
 296  
 297  /**
 298   * Updates a quiz object with override information for a user.
 299   *
 300   * Algorithm:  For each quiz setting, if there is a matching user-specific override,
 301   *   then use that otherwise, if there are group-specific overrides, return the most
 302   *   lenient combination of them.  If neither applies, leave the quiz setting unchanged.
 303   *
 304   *   Special case: if there is more than one password that applies to the user, then
 305   *   quiz->extrapasswords will contain an array of strings giving the remaining
 306   *   passwords.
 307   *
 308   * @param stdClass $quiz The quiz object.
 309   * @param int $userid The userid.
 310   * @return stdClass $quiz The updated quiz object.
 311   */
 312  function quiz_update_effective_access($quiz, $userid) {
 313      global $DB;
 314  
 315      // Check for user override.
 316      $override = $DB->get_record('quiz_overrides', ['quiz' => $quiz->id, 'userid' => $userid]);
 317  
 318      if (!$override) {
 319          $override = new stdClass();
 320          $override->timeopen = null;
 321          $override->timeclose = null;
 322          $override->timelimit = null;
 323          $override->attempts = null;
 324          $override->password = null;
 325      }
 326  
 327      // Check for group overrides.
 328      $groupings = groups_get_user_groups($quiz->course, $userid);
 329  
 330      if (!empty($groupings[0])) {
 331          // Select all overrides that apply to the User's groups.
 332          list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
 333          $sql = "SELECT * FROM {quiz_overrides}
 334                  WHERE groupid $extra AND quiz = ?";
 335          $params[] = $quiz->id;
 336          $records = $DB->get_records_sql($sql, $params);
 337  
 338          // Combine the overrides.
 339          $opens = [];
 340          $closes = [];
 341          $limits = [];
 342          $attempts = [];
 343          $passwords = [];
 344  
 345          foreach ($records as $gpoverride) {
 346              if (isset($gpoverride->timeopen)) {
 347                  $opens[] = $gpoverride->timeopen;
 348              }
 349              if (isset($gpoverride->timeclose)) {
 350                  $closes[] = $gpoverride->timeclose;
 351              }
 352              if (isset($gpoverride->timelimit)) {
 353                  $limits[] = $gpoverride->timelimit;
 354              }
 355              if (isset($gpoverride->attempts)) {
 356                  $attempts[] = $gpoverride->attempts;
 357              }
 358              if (isset($gpoverride->password)) {
 359                  $passwords[] = $gpoverride->password;
 360              }
 361          }
 362          // If there is a user override for a setting, ignore the group override.
 363          if (is_null($override->timeopen) && count($opens)) {
 364              $override->timeopen = min($opens);
 365          }
 366          if (is_null($override->timeclose) && count($closes)) {
 367              if (in_array(0, $closes)) {
 368                  $override->timeclose = 0;
 369              } else {
 370                  $override->timeclose = max($closes);
 371              }
 372          }
 373          if (is_null($override->timelimit) && count($limits)) {
 374              if (in_array(0, $limits)) {
 375                  $override->timelimit = 0;
 376              } else {
 377                  $override->timelimit = max($limits);
 378              }
 379          }
 380          if (is_null($override->attempts) && count($attempts)) {
 381              if (in_array(0, $attempts)) {
 382                  $override->attempts = 0;
 383              } else {
 384                  $override->attempts = max($attempts);
 385              }
 386          }
 387          if (is_null($override->password) && count($passwords)) {
 388              $override->password = array_shift($passwords);
 389              if (count($passwords)) {
 390                  $override->extrapasswords = $passwords;
 391              }
 392          }
 393  
 394      }
 395  
 396      // Merge with quiz defaults.
 397      $keys = ['timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords'];
 398      foreach ($keys as $key) {
 399          if (isset($override->{$key})) {
 400              $quiz->{$key} = $override->{$key};
 401          }
 402      }
 403  
 404      return $quiz;
 405  }
 406  
 407  /**
 408   * Delete all the attempts belonging to a quiz.
 409   *
 410   * @param stdClass $quiz The quiz object.
 411   */
 412  function quiz_delete_all_attempts($quiz) {
 413      global $CFG, $DB;
 414      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
 415      question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
 416      $DB->delete_records('quiz_attempts', ['quiz' => $quiz->id]);
 417      $DB->delete_records('quiz_grades', ['quiz' => $quiz->id]);
 418  }
 419  
 420  /**
 421   * Delete all the attempts belonging to a user in a particular quiz.
 422   *
 423   * @param \mod_quiz\quiz_settings $quiz The quiz object.
 424   * @param stdClass $user The user object.
 425   */
 426  function quiz_delete_user_attempts($quiz, $user) {
 427      global $CFG, $DB;
 428      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
 429      question_engine::delete_questions_usage_by_activities(new qubaids_for_users_attempts(
 430              $quiz->get_quizid(), $user->id, 'all'));
 431      $params = [
 432          'quiz' => $quiz->get_quizid(),
 433          'userid' => $user->id,
 434      ];
 435      $DB->delete_records('quiz_attempts', $params);
 436      $DB->delete_records('quiz_grades', $params);
 437  }
 438  
 439  /**
 440   * Get the best current grade for a particular user in a quiz.
 441   *
 442   * @param stdClass $quiz the quiz settings.
 443   * @param int $userid the id of the user.
 444   * @return float the user's current grade for this quiz, or null if this user does
 445   * not have a grade on this quiz.
 446   */
 447  function quiz_get_best_grade($quiz, $userid) {
 448      global $DB;
 449      $grade = $DB->get_field('quiz_grades', 'grade',
 450              ['quiz' => $quiz->id, 'userid' => $userid]);
 451  
 452      // Need to detect errors/no result, without catching 0 grades.
 453      if ($grade === false) {
 454          return null;
 455      }
 456  
 457      return $grade + 0; // Convert to number.
 458  }
 459  
 460  /**
 461   * Is this a graded quiz? If this method returns true, you can assume that
 462   * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
 463   * divide by them).
 464   *
 465   * @param stdClass $quiz a row from the quiz table.
 466   * @return bool whether this is a graded quiz.
 467   */
 468  function quiz_has_grades($quiz) {
 469      return $quiz->grade >= grade_calculator::ALMOST_ZERO && $quiz->sumgrades >= grade_calculator::ALMOST_ZERO;
 470  }
 471  
 472  /**
 473   * Does this quiz allow multiple tries?
 474   *
 475   * @return bool
 476   */
 477  function quiz_allows_multiple_tries($quiz) {
 478      $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
 479      return $bt->allows_multiple_submitted_responses();
 480  }
 481  
 482  /**
 483   * Return a small object with summary information about what a
 484   * user has done with a given particular instance of this module
 485   * Used for user activity reports.
 486   * $return->time = the time they did it
 487   * $return->info = a short text description
 488   *
 489   * @param stdClass $course
 490   * @param stdClass $user
 491   * @param stdClass $mod
 492   * @param stdClass $quiz
 493   * @return stdClass|null
 494   */
 495  function quiz_user_outline($course, $user, $mod, $quiz) {
 496      global $DB, $CFG;
 497      require_once($CFG->libdir . '/gradelib.php');
 498      $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
 499  
 500      if (empty($grades->items[0]->grades)) {
 501          return null;
 502      } else {
 503          $grade = reset($grades->items[0]->grades);
 504      }
 505  
 506      $result = new stdClass();
 507      // If the user can't see hidden grades, don't return that information.
 508      $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
 509      if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 510          $result->info = get_string('gradenoun') . ': ' . $grade->str_long_grade;
 511      } else {
 512          $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
 513      }
 514  
 515      $result->time = grade_get_date_for_user_grade($grade, $user);
 516  
 517      return $result;
 518  }
 519  
 520  /**
 521   * Print a detailed representation of what a  user has done with
 522   * a given particular instance of this module, for user activity reports.
 523   *
 524   * @param stdClass $course
 525   * @param stdClass $user
 526   * @param stdClass $mod
 527   * @param stdClass $quiz
 528   * @return bool
 529   */
 530  function quiz_user_complete($course, $user, $mod, $quiz) {
 531      global $DB, $CFG, $OUTPUT;
 532      require_once($CFG->libdir . '/gradelib.php');
 533      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
 534  
 535      $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
 536      if (!empty($grades->items[0]->grades)) {
 537          $grade = reset($grades->items[0]->grades);
 538          // If the user can't see hidden grades, don't return that information.
 539          $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
 540          if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 541              echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade);
 542              if ($grade->str_feedback) {
 543                  echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
 544              }
 545          } else {
 546              echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
 547              if ($grade->str_feedback) {
 548                  echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
 549              }
 550          }
 551      }
 552  
 553      if ($attempts = $DB->get_records('quiz_attempts',
 554              ['userid' => $user->id, 'quiz' => $quiz->id], 'attempt')) {
 555          foreach ($attempts as $attempt) {
 556              echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
 557              if ($attempt->state != quiz_attempt::FINISHED) {
 558                  echo quiz_attempt_state_name($attempt->state);
 559              } else {
 560                  if (!isset($gitem)) {
 561                      if (!empty($grades->items[0]->grades)) {
 562                          $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
 563                      } else {
 564                          $gitem = new stdClass();
 565                          $gitem->hidden = true;
 566                      }
 567                  }
 568                  if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 569                      echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
 570                  } else {
 571                      echo get_string('hidden', 'grades');
 572                  }
 573                  echo ' - '.userdate($attempt->timefinish).'<br />';
 574              }
 575          }
 576      } else {
 577          print_string('noattempts', 'quiz');
 578      }
 579  
 580      return true;
 581  }
 582  
 583  
 584  /**
 585   * @param int|array $quizids A quiz ID, or an array of quiz IDs.
 586   * @param int $userid the userid.
 587   * @param string $status 'all', 'finished' or 'unfinished' to control
 588   * @param bool $includepreviews
 589   * @return array of all the user's attempts at this quiz. Returns an empty
 590   *      array if there are none.
 591   */
 592  function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
 593      global $DB;
 594  
 595      $params = [];
 596      switch ($status) {
 597          case 'all':
 598              $statuscondition = '';
 599              break;
 600  
 601          case 'finished':
 602              $statuscondition = ' AND state IN (:state1, :state2)';
 603              $params['state1'] = quiz_attempt::FINISHED;
 604              $params['state2'] = quiz_attempt::ABANDONED;
 605              break;
 606  
 607          case 'unfinished':
 608              $statuscondition = ' AND state IN (:state1, :state2)';
 609              $params['state1'] = quiz_attempt::IN_PROGRESS;
 610              $params['state2'] = quiz_attempt::OVERDUE;
 611              break;
 612      }
 613  
 614      $quizids = (array) $quizids;
 615      list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
 616      $params += $inparams;
 617      $params['userid'] = $userid;
 618  
 619      $previewclause = '';
 620      if (!$includepreviews) {
 621          $previewclause = ' AND preview = 0';
 622      }
 623  
 624      return $DB->get_records_select('quiz_attempts',
 625              "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
 626              $params, 'quiz, attempt ASC');
 627  }
 628  
 629  /**
 630   * Return grade for given user or all users.
 631   *
 632   * @param int $quizid id of quiz
 633   * @param int $userid optional user id, 0 means all users
 634   * @return array array of grades, false if none. These are raw grades. They should
 635   * be processed with quiz_format_grade for display.
 636   */
 637  function quiz_get_user_grades($quiz, $userid = 0) {
 638      global $CFG, $DB;
 639  
 640      $params = [$quiz->id];
 641      $usertest = '';
 642      if ($userid) {
 643          $params[] = $userid;
 644          $usertest = 'AND u.id = ?';
 645      }
 646      return $DB->get_records_sql("
 647              SELECT
 648                  u.id,
 649                  u.id AS userid,
 650                  qg.grade AS rawgrade,
 651                  qg.timemodified AS dategraded,
 652                  MAX(qa.timefinish) AS datesubmitted
 653  
 654              FROM {user} u
 655              JOIN {quiz_grades} qg ON u.id = qg.userid
 656              JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
 657  
 658              WHERE qg.quiz = ?
 659              $usertest
 660              GROUP BY u.id, qg.grade, qg.timemodified", $params);
 661  }
 662  
 663  /**
 664   * Round a grade to the correct number of decimal places, and format it for display.
 665   *
 666   * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
 667   * @param float $grade The grade to round.
 668   * @return string
 669   */
 670  function quiz_format_grade($quiz, $grade) {
 671      if (is_null($grade)) {
 672          return get_string('notyetgraded', 'quiz');
 673      }
 674      return format_float($grade, $quiz->decimalpoints);
 675  }
 676  
 677  /**
 678   * Determine the correct number of decimal places required to format a grade.
 679   *
 680   * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints and
 681   *      ->questiondecimalpoints are used.
 682   * @return integer
 683   */
 684  function quiz_get_grade_format($quiz) {
 685      if (empty($quiz->questiondecimalpoints)) {
 686          $quiz->questiondecimalpoints = -1;
 687      }
 688  
 689      if ($quiz->questiondecimalpoints == -1) {
 690          return $quiz->decimalpoints;
 691      }
 692  
 693      return $quiz->questiondecimalpoints;
 694  }
 695  
 696  /**
 697   * Round a grade to the correct number of decimal places, and format it for display.
 698   *
 699   * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
 700   * @param float $grade The grade to round.
 701   * @return string
 702   */
 703  function quiz_format_question_grade($quiz, $grade) {
 704      return format_float($grade, quiz_get_grade_format($quiz));
 705  }
 706  
 707  /**
 708   * Update grades in central gradebook
 709   *
 710   * @category grade
 711   * @param stdClass $quiz the quiz settings.
 712   * @param int $userid specific user only, 0 means all users.
 713   * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
 714   */
 715  function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
 716      global $CFG, $DB;
 717      require_once($CFG->libdir . '/gradelib.php');
 718  
 719      if ($quiz->grade == 0) {
 720          quiz_grade_item_update($quiz);
 721  
 722      } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
 723          quiz_grade_item_update($quiz, $grades);
 724  
 725      } else if ($userid && $nullifnone) {
 726          $grade = new stdClass();
 727          $grade->userid = $userid;
 728          $grade->rawgrade = null;
 729          quiz_grade_item_update($quiz, $grade);
 730  
 731      } else {
 732          quiz_grade_item_update($quiz);
 733      }
 734  }
 735  
 736  /**
 737   * Create or update the grade item for given quiz
 738   *
 739   * @category grade
 740   * @param stdClass $quiz object with extra cmidnumber
 741   * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
 742   * @return int 0 if ok, error code otherwise
 743   */
 744  function quiz_grade_item_update($quiz, $grades = null) {
 745      global $CFG, $OUTPUT;
 746      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
 747      require_once($CFG->libdir . '/gradelib.php');
 748  
 749      if (property_exists($quiz, 'cmidnumber')) { // May not be always present.
 750          $params = ['itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber];
 751      } else {
 752          $params = ['itemname' => $quiz->name];
 753      }
 754  
 755      if ($quiz->grade > 0) {
 756          $params['gradetype'] = GRADE_TYPE_VALUE;
 757          $params['grademax']  = $quiz->grade;
 758          $params['grademin']  = 0;
 759  
 760      } else {
 761          $params['gradetype'] = GRADE_TYPE_NONE;
 762      }
 763  
 764      // What this is trying to do:
 765      // 1. If the quiz is set to not show grades while the quiz is still open,
 766      //    and is set to show grades after the quiz is closed, then create the
 767      //    grade_item with a show-after date that is the quiz close date.
 768      // 2. If the quiz is set to not show grades at either of those times,
 769      //    create the grade_item as hidden.
 770      // 3. If the quiz is set to show grades, create the grade_item visible.
 771      $openreviewoptions = display_options::make_from_quiz($quiz,
 772              display_options::LATER_WHILE_OPEN);
 773      $closedreviewoptions = display_options::make_from_quiz($quiz,
 774              display_options::AFTER_CLOSE);
 775      if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
 776              $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
 777          $params['hidden'] = 1;
 778  
 779      } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
 780              $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
 781          if ($quiz->timeclose) {
 782              $params['hidden'] = $quiz->timeclose;
 783          } else {
 784              $params['hidden'] = 1;
 785          }
 786  
 787      } else {
 788          // Either
 789          // a) both open and closed enabled
 790          // b) open enabled, closed disabled - we can not "hide after",
 791          //    grades are kept visible even after closing.
 792          $params['hidden'] = 0;
 793      }
 794  
 795      if (!$params['hidden']) {
 796          // If the grade item is not hidden by the quiz logic, then we need to
 797          // hide it if the quiz is hidden from students.
 798          if (property_exists($quiz, 'visible')) {
 799              // Saving the quiz form, and cm not yet updated in the database.
 800              $params['hidden'] = !$quiz->visible;
 801          } else {
 802              $cm = get_coursemodule_from_instance('quiz', $quiz->id);
 803              $params['hidden'] = !$cm->visible;
 804          }
 805      }
 806  
 807      if ($grades  === 'reset') {
 808          $params['reset'] = true;
 809          $grades = null;
 810      }
 811  
 812      $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
 813      if (!empty($gradebook_grades->items)) {
 814          $grade_item = $gradebook_grades->items[0];
 815          if ($grade_item->locked) {
 816              // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
 817              $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
 818              if (!$confirm_regrade) {
 819                  if (!AJAX_SCRIPT) {
 820                      $message = get_string('gradeitemislocked', 'grades');
 821                      $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
 822                              '&amp;mode=overview';
 823                      $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
 824                      echo $OUTPUT->box_start('generalbox', 'notice');
 825                      echo '<p>'. $message .'</p>';
 826                      echo $OUTPUT->container_start('buttons');
 827                      echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
 828                      echo $OUTPUT->single_button($back_link,  get_string('cancel'));
 829                      echo $OUTPUT->container_end();
 830                      echo $OUTPUT->box_end();
 831                  }
 832                  return GRADE_UPDATE_ITEM_LOCKED;
 833              }
 834          }
 835      }
 836  
 837      return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
 838  }
 839  
 840  /**
 841   * Delete grade item for given quiz
 842   *
 843   * @category grade
 844   * @param stdClass $quiz object
 845   * @return int
 846   */
 847  function quiz_grade_item_delete($quiz) {
 848      global $CFG;
 849      require_once($CFG->libdir . '/gradelib.php');
 850  
 851      return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
 852              null, ['deleted' => 1]);
 853  }
 854  
 855  /**
 856   * This standard function will check all instances of this module
 857   * and make sure there are up-to-date events created for each of them.
 858   * If courseid = 0, then every quiz event in the site is checked, else
 859   * only quiz events belonging to the course specified are checked.
 860   * This function is used, in its new format, by restore_refresh_events()
 861   *
 862   * @param int $courseid
 863   * @param int|stdClass $instance Quiz module instance or ID.
 864   * @param int|stdClass $cm Course module object or ID (not used in this module).
 865   * @return bool
 866   */
 867  function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
 868      global $DB;
 869  
 870      // If we have instance information then we can just update the one event instead of updating all events.
 871      if (isset($instance)) {
 872          if (!is_object($instance)) {
 873              $instance = $DB->get_record('quiz', ['id' => $instance], '*', MUST_EXIST);
 874          }
 875          quiz_update_events($instance);
 876          return true;
 877      }
 878  
 879      if ($courseid == 0) {
 880          if (!$quizzes = $DB->get_records('quiz')) {
 881              return true;
 882          }
 883      } else {
 884          if (!$quizzes = $DB->get_records('quiz', ['course' => $courseid])) {
 885              return true;
 886          }
 887      }
 888  
 889      foreach ($quizzes as $quiz) {
 890          quiz_update_events($quiz);
 891      }
 892  
 893      return true;
 894  }
 895  
 896  /**
 897   * Returns all quiz graded users since a given time for specified quiz
 898   */
 899  function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
 900          $courseid, $cmid, $userid = 0, $groupid = 0) {
 901      global $CFG, $USER, $DB;
 902      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
 903  
 904      $course = get_course($courseid);
 905      $modinfo = get_fast_modinfo($course);
 906  
 907      $cm = $modinfo->cms[$cmid];
 908      $quiz = $DB->get_record('quiz', ['id' => $cm->instance]);
 909  
 910      if ($userid) {
 911          $userselect = "AND u.id = :userid";
 912          $params['userid'] = $userid;
 913      } else {
 914          $userselect = '';
 915      }
 916  
 917      if ($groupid) {
 918          $groupselect = 'AND gm.groupid = :groupid';
 919          $groupjoin   = 'JOIN {groups_members} gm ON  gm.userid=u.id';
 920          $params['groupid'] = $groupid;
 921      } else {
 922          $groupselect = '';
 923          $groupjoin   = '';
 924      }
 925  
 926      $params['timestart'] = $timestart;
 927      $params['quizid'] = $quiz->id;
 928  
 929      $userfieldsapi = \core_user\fields::for_userpic();
 930      $ufields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects;
 931      if (!$attempts = $DB->get_records_sql("
 932                SELECT qa.*,
 933                       {$ufields}
 934                  FROM {quiz_attempts} qa
 935                       JOIN {user} u ON u.id = qa.userid
 936                       $groupjoin
 937                 WHERE qa.timefinish > :timestart
 938                   AND qa.quiz = :quizid
 939                   AND qa.preview = 0
 940                       $userselect
 941                       $groupselect
 942              ORDER BY qa.timefinish ASC", $params)) {
 943          return;
 944      }
 945  
 946      $context         = context_module::instance($cm->id);
 947      $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
 948      $viewfullnames   = has_capability('moodle/site:viewfullnames', $context);
 949      $grader          = has_capability('mod/quiz:viewreports', $context);
 950      $groupmode       = groups_get_activity_groupmode($cm, $course);
 951  
 952      $usersgroups = null;
 953      $aname = format_string($cm->name, true);
 954      foreach ($attempts as $attempt) {
 955          if ($attempt->userid != $USER->id) {
 956              if (!$grader) {
 957                  // Grade permission required.
 958                  continue;
 959              }
 960  
 961              if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
 962                  $usersgroups = groups_get_all_groups($course->id,
 963                          $attempt->userid, $cm->groupingid);
 964                  $usersgroups = array_keys($usersgroups);
 965                  if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
 966                      continue;
 967                  }
 968              }
 969          }
 970  
 971          $options = quiz_get_review_options($quiz, $attempt, $context);
 972  
 973          $tmpactivity = new stdClass();
 974  
 975          $tmpactivity->type       = 'quiz';
 976          $tmpactivity->cmid       = $cm->id;
 977          $tmpactivity->name       = $aname;
 978          $tmpactivity->sectionnum = $cm->sectionnum;
 979          $tmpactivity->timestamp  = $attempt->timefinish;
 980  
 981          $tmpactivity->content = new stdClass();
 982          $tmpactivity->content->attemptid = $attempt->id;
 983          $tmpactivity->content->attempt   = $attempt->attempt;
 984          if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
 985              $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
 986              $tmpactivity->content->maxgrade  = quiz_format_grade($quiz, $quiz->sumgrades);
 987          } else {
 988              $tmpactivity->content->sumgrades = null;
 989              $tmpactivity->content->maxgrade  = null;
 990          }
 991  
 992          $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
 993          $tmpactivity->user->fullname  = fullname($tmpactivity->user, $viewfullnames);
 994  
 995          $activities[$index++] = $tmpactivity;
 996      }
 997  }
 998  
 999  function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
1000      global $CFG, $OUTPUT;
1001  
1002      echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
1003  
1004      echo '<tr><td class="userpicture" valign="top">';
1005      echo $OUTPUT->user_picture($activity->user, ['courseid' => $courseid]);
1006      echo '</td><td>';
1007  
1008      if ($detail) {
1009          $modname = $modnames[$activity->type];
1010          echo '<div class="title">';
1011          echo $OUTPUT->image_icon('monologo', $modname, $activity->type);
1012          echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1013                  $activity->cmid . '">' . $activity->name . '</a>';
1014          echo '</div>';
1015      }
1016  
1017      echo '<div class="grade">';
1018      echo  get_string('attempt', 'quiz', $activity->content->attempt);
1019      if (isset($activity->content->maxgrade)) {
1020          $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1021          echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1022                  $activity->content->attemptid . '">' . $grades . '</a>)';
1023      }
1024      echo '</div>';
1025  
1026      echo '<div class="user">';
1027      echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1028              '&amp;course=' . $courseid . '">' . $activity->user->fullname .
1029              '</a> - ' . userdate($activity->timestamp);
1030      echo '</div>';
1031  
1032      echo '</td></tr></table>';
1033  
1034      return;
1035  }
1036  
1037  /**
1038   * Pre-process the quiz options form data, making any necessary adjustments.
1039   * Called by add/update instance in this file.
1040   *
1041   * @param stdClass $quiz The variables set on the form.
1042   */
1043  function quiz_process_options($quiz) {
1044      global $CFG;
1045      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1046      require_once($CFG->libdir . '/questionlib.php');
1047  
1048      $quiz->timemodified = time();
1049  
1050      // Quiz name.
1051      if (!empty($quiz->name)) {
1052          $quiz->name = trim($quiz->name);
1053      }
1054  
1055      // Password field - different in form to stop browsers that remember passwords
1056      // getting confused.
1057      $quiz->password = $quiz->quizpassword;
1058      unset($quiz->quizpassword);
1059  
1060      // Quiz feedback.
1061      if (isset($quiz->feedbacktext)) {
1062          // Clean up the boundary text.
1063          for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1064              if (empty($quiz->feedbacktext[$i]['text'])) {
1065                  $quiz->feedbacktext[$i]['text'] = '';
1066              } else {
1067                  $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1068              }
1069          }
1070  
1071          // Check the boundary value is a number or a percentage, and in range.
1072          $i = 0;
1073          while (!empty($quiz->feedbackboundaries[$i])) {
1074              $boundary = trim($quiz->feedbackboundaries[$i]);
1075              if (!is_numeric($boundary)) {
1076                  if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1077                      $boundary = trim(substr($boundary, 0, -1));
1078                      if (is_numeric($boundary)) {
1079                          $boundary = $boundary * $quiz->grade / 100.0;
1080                      } else {
1081                          return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1082                      }
1083                  }
1084              }
1085              if ($boundary <= 0 || $boundary >= $quiz->grade) {
1086                  return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1087              }
1088              if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1089                  return get_string('feedbackerrororder', 'quiz', $i + 1);
1090              }
1091              $quiz->feedbackboundaries[$i] = $boundary;
1092              $i += 1;
1093          }
1094          $numboundaries = $i;
1095  
1096          // Check there is nothing in the remaining unused fields.
1097          if (!empty($quiz->feedbackboundaries)) {
1098              for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1099                  if (!empty($quiz->feedbackboundaries[$i]) &&
1100                          trim($quiz->feedbackboundaries[$i]) != '') {
1101                      return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1102                  }
1103              }
1104          }
1105          for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1106              if (!empty($quiz->feedbacktext[$i]['text']) &&
1107                      trim($quiz->feedbacktext[$i]['text']) != '') {
1108                  return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1109              }
1110          }
1111          // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1112          $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1113          $quiz->feedbackboundaries[$numboundaries] = 0;
1114          $quiz->feedbackboundarycount = $numboundaries;
1115      } else {
1116          $quiz->feedbackboundarycount = -1;
1117      }
1118  
1119      // Combing the individual settings into the review columns.
1120      $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1121      $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1122      $quiz->reviewmaxmarks = quiz_review_option_form_to_db($quiz, 'maxmarks');
1123      $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1124      $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1125      $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1126      $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1127      $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1128      $quiz->reviewattempt |= display_options::DURING;
1129      $quiz->reviewoverallfeedback &= ~display_options::DURING;
1130  
1131      // Ensure that disabled checkboxes in completion settings are set to 0.
1132      // But only if the completion settinsg are unlocked.
1133      if (!empty($quiz->completionunlocked)) {
1134          if (empty($quiz->completionusegrade)) {
1135              $quiz->completionpassgrade = 0;
1136          }
1137          if (empty($quiz->completionpassgrade)) {
1138              $quiz->completionattemptsexhausted = 0;
1139          }
1140          if (empty($quiz->completionminattemptsenabled)) {
1141              $quiz->completionminattempts = 0;
1142          }
1143      }
1144  }
1145  
1146  /**
1147   * Helper function for {@link quiz_process_options()}.
1148   * @param stdClass $fromform the sumbitted form date.
1149   * @param string $field one of the review option field names.
1150   */
1151  function quiz_review_option_form_to_db($fromform, $field) {
1152      static $times = [
1153          'during' => display_options::DURING,
1154          'immediately' => display_options::IMMEDIATELY_AFTER,
1155          'open' => display_options::LATER_WHILE_OPEN,
1156          'closed' => display_options::AFTER_CLOSE,
1157      ];
1158  
1159      $review = 0;
1160      foreach ($times as $whenname => $when) {
1161          $fieldname = $field . $whenname;
1162          if (!empty($fromform->$fieldname)) {
1163              $review |= $when;
1164              unset($fromform->$fieldname);
1165          }
1166      }
1167  
1168      return $review;
1169  }
1170  
1171  /**
1172   * In place editable callback for slot displaynumber.
1173   *
1174   * @param string $itemtype slotdisplarnumber
1175   * @param int $itemid the id of the slot in the quiz_slots table
1176   * @param string $newvalue the new value for displaynumber field for a given slot in the quiz_slots table
1177   * @return \core\output\inplace_editable|void
1178   */
1179  function mod_quiz_inplace_editable(string $itemtype, int $itemid, string $newvalue): \core\output\inplace_editable {
1180      global $DB;
1181  
1182      if ($itemtype === 'slotdisplaynumber') {
1183          // Work out which quiz and slot this is.
1184          $slot = $DB->get_record('quiz_slots', ['id' => $itemid], '*', MUST_EXIST);
1185          $quizobj = quiz_settings::create($slot->quizid);
1186  
1187          // Validate the context, and check the required capability.
1188          $context = $quizobj->get_context();
1189          \core_external\external_api::validate_context($context);
1190          require_capability('mod/quiz:manage', $context);
1191  
1192          // Update the value - truncating the size of the DB column.
1193          $structure = $quizobj->get_structure();
1194          $structure->update_slot_display_number($itemid, core_text::substr($newvalue, 0, 16));
1195  
1196          // Prepare the element for the output.
1197          return $structure->make_slot_display_number_in_place_editable($itemid, $context);
1198      }
1199  }
1200  
1201  /**
1202   * This function is called at the end of quiz_add_instance
1203   * and quiz_update_instance, to do the common processing.
1204   *
1205   * @param stdClass $quiz the quiz object.
1206   */
1207  function quiz_after_add_or_update($quiz) {
1208      global $DB;
1209      $cmid = $quiz->coursemodule;
1210  
1211      // We need to use context now, so we need to make sure all needed info is already in db.
1212      $DB->set_field('course_modules', 'instance', $quiz->id, ['id' => $cmid]);
1213      $context = context_module::instance($cmid);
1214  
1215      // Save the feedback.
1216      $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]);
1217  
1218      for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1219          $feedback = new stdClass();
1220          $feedback->quizid = $quiz->id;
1221          $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1222          $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1223          $feedback->mingrade = $quiz->feedbackboundaries[$i];
1224          $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1225          $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1226          $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1227                  $context->id, 'mod_quiz', 'feedback', $feedback->id,
1228                  ['subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0],
1229                  $quiz->feedbacktext[$i]['text']);
1230          $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1231                  ['id' => $feedback->id]);
1232      }
1233  
1234      // Store any settings belonging to the access rules.
1235      access_manager::save_settings($quiz);
1236  
1237      // Update the events relating to this quiz.
1238      quiz_update_events($quiz);
1239      $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null;
1240      \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected);
1241  
1242      // Update related grade item.
1243      quiz_grade_item_update($quiz);
1244  }
1245  
1246  /**
1247   * This function updates the events associated to the quiz.
1248   * If $override is non-zero, then it updates only the events
1249   * associated with the specified override.
1250   *
1251   * @param stdClass $quiz the quiz object.
1252   * @param stdClass|null $override limit to a specific override
1253   */
1254  function quiz_update_events($quiz, $override = null) {
1255      global $DB;
1256  
1257      // Load the old events relating to this quiz.
1258      $conds = ['modulename' => 'quiz',
1259                     'instance' => $quiz->id];
1260      if (!empty($override)) {
1261          // Only load events for this override.
1262          if (isset($override->userid)) {
1263              $conds['userid'] = $override->userid;
1264          } else {
1265              $conds['groupid'] = $override->groupid;
1266          }
1267      }
1268      $oldevents = $DB->get_records('event', $conds, 'id ASC');
1269  
1270      // Now make a to-do list of all that needs to be updated.
1271      if (empty($override)) {
1272          // We are updating the primary settings for the quiz, so we need to add all the overrides.
1273          $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id ASC');
1274          // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1275          // list contains the original (non-override) event for the module. If this is not included
1276          // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1277          // list against the $oldevents list.
1278          array_unshift($overrides, new stdClass());
1279      } else {
1280          // Just do the one override.
1281          $overrides = [$override];
1282      }
1283  
1284      // Get group override priorities.
1285      $grouppriorities = quiz_get_group_override_priorities($quiz->id);
1286  
1287      foreach ($overrides as $current) {
1288          $groupid   = isset($current->groupid)?  $current->groupid : 0;
1289          $userid    = isset($current->userid)? $current->userid : 0;
1290          $timeopen  = isset($current->timeopen)?  $current->timeopen : $quiz->timeopen;
1291          $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1292  
1293          // Only add open/close events for an override if they differ from the quiz default.
1294          $addopen  = empty($current->id) || !empty($current->timeopen);
1295          $addclose = empty($current->id) || !empty($current->timeclose);
1296  
1297          if (!empty($quiz->coursemodule)) {
1298              $cmid = $quiz->coursemodule;
1299          } else {
1300              $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1301          }
1302  
1303          $event = new stdClass();
1304          $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
1305          $event->description = format_module_intro('quiz', $quiz, $cmid, false);
1306          $event->format = FORMAT_HTML;
1307          // Events module won't show user events when the courseid is nonzero.
1308          $event->courseid    = ($userid) ? 0 : $quiz->course;
1309          $event->groupid     = $groupid;
1310          $event->userid      = $userid;
1311          $event->modulename  = 'quiz';
1312          $event->instance    = $quiz->id;
1313          $event->timestart   = $timeopen;
1314          $event->timeduration = max($timeclose - $timeopen, 0);
1315          $event->timesort    = $timeopen;
1316          $event->visible     = instance_is_visible('quiz', $quiz);
1317          $event->eventtype   = QUIZ_EVENT_TYPE_OPEN;
1318          $event->priority    = null;
1319  
1320          // Determine the event name and priority.
1321          if ($groupid) {
1322              // Group override event.
1323              $params = new stdClass();
1324              $params->quiz = $quiz->name;
1325              $params->group = groups_get_group_name($groupid);
1326              if ($params->group === false) {
1327                  // Group doesn't exist, just skip it.
1328                  continue;
1329              }
1330              $eventname = get_string('overridegroupeventname', 'quiz', $params);
1331              // Set group override priority.
1332              if ($grouppriorities !== null) {
1333                  $openpriorities = $grouppriorities['open'];
1334                  if (isset($openpriorities[$timeopen])) {
1335                      $event->priority = $openpriorities[$timeopen];
1336                  }
1337              }
1338          } else if ($userid) {
1339              // User override event.
1340              $params = new stdClass();
1341              $params->quiz = $quiz->name;
1342              $eventname = get_string('overrideusereventname', 'quiz', $params);
1343              // Set user override priority.
1344              $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
1345          } else {
1346              // The parent event.
1347              $eventname = $quiz->name;
1348          }
1349  
1350          if ($addopen or $addclose) {
1351              // Separate start and end events.
1352              $event->timeduration  = 0;
1353              if ($timeopen && $addopen) {
1354                  if ($oldevent = array_shift($oldevents)) {
1355                      $event->id = $oldevent->id;
1356                  } else {
1357                      unset($event->id);
1358                  }
1359                  $event->name = get_string('quizeventopens', 'quiz', $eventname);
1360                  // The method calendar_event::create will reuse a db record if the id field is set.
1361                  calendar_event::create($event, false);
1362              }
1363              if ($timeclose && $addclose) {
1364                  if ($oldevent = array_shift($oldevents)) {
1365                      $event->id = $oldevent->id;
1366                  } else {
1367                      unset($event->id);
1368                  }
1369                  $event->type      = CALENDAR_EVENT_TYPE_ACTION;
1370                  $event->name      = get_string('quizeventcloses', 'quiz', $eventname);
1371                  $event->timestart = $timeclose;
1372                  $event->timesort  = $timeclose;
1373                  $event->eventtype = QUIZ_EVENT_TYPE_CLOSE;
1374                  if ($groupid && $grouppriorities !== null) {
1375                      $closepriorities = $grouppriorities['close'];
1376                      if (isset($closepriorities[$timeclose])) {
1377                          $event->priority = $closepriorities[$timeclose];
1378                      }
1379                  }
1380                  calendar_event::create($event, false);
1381              }
1382          }
1383      }
1384  
1385      // Delete any leftover events.
1386      foreach ($oldevents as $badevent) {
1387          $badevent = calendar_event::load($badevent);
1388          $badevent->delete();
1389      }
1390  }
1391  
1392  /**
1393   * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1394   *
1395   * @param int $quizid The quiz ID.
1396   * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1397   */
1398  function quiz_get_group_override_priorities($quizid) {
1399      global $DB;
1400  
1401      // Fetch group overrides.
1402      $where = 'quiz = :quiz AND groupid IS NOT NULL';
1403      $params = ['quiz' => $quizid];
1404      $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1405      if (!$overrides) {
1406          return null;
1407      }
1408  
1409      $grouptimeopen = [];
1410      $grouptimeclose = [];
1411      foreach ($overrides as $override) {
1412          if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1413              $grouptimeopen[] = $override->timeopen;
1414          }
1415          if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1416              $grouptimeclose[] = $override->timeclose;
1417          }
1418      }
1419  
1420      // Sort open times in ascending manner. The earlier open time gets higher priority.
1421      sort($grouptimeopen);
1422      // Set priorities.
1423      $opengrouppriorities = [];
1424      $openpriority = 1;
1425      foreach ($grouptimeopen as $timeopen) {
1426          $opengrouppriorities[$timeopen] = $openpriority++;
1427      }
1428  
1429      // Sort close times in descending manner. The later close time gets higher priority.
1430      rsort($grouptimeclose);
1431      // Set priorities.
1432      $closegrouppriorities = [];
1433      $closepriority = 1;
1434      foreach ($grouptimeclose as $timeclose) {
1435          $closegrouppriorities[$timeclose] = $closepriority++;
1436      }
1437  
1438      return [
1439          'open' => $opengrouppriorities,
1440          'close' => $closegrouppriorities
1441      ];
1442  }
1443  
1444  /**
1445   * List the actions that correspond to a view of this module.
1446   * This is used by the participation report.
1447   *
1448   * Note: This is not used by new logging system. Event with
1449   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1450   *       be considered as view action.
1451   *
1452   * @return array
1453   */
1454  function quiz_get_view_actions() {
1455      return ['view', 'view all', 'report', 'review'];
1456  }
1457  
1458  /**
1459   * List the actions that correspond to a post of this module.
1460   * This is used by the participation report.
1461   *
1462   * Note: This is not used by new logging system. Event with
1463   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1464   *       will be considered as post action.
1465   *
1466   * @return array
1467   */
1468  function quiz_get_post_actions() {
1469      return ['attempt', 'close attempt', 'preview', 'editquestions',
1470              'delete attempt', 'manualgrade'];
1471  }
1472  
1473  /**
1474   * Standard callback used by questions_in_use.
1475   *
1476   * @param array $questionids of question ids.
1477   * @return bool whether any of these questions are used by any instance of this module.
1478   */
1479  function quiz_questions_in_use($questionids) {
1480      return question_engine::questions_in_use($questionids,
1481              new qubaid_join('{quiz_attempts} quiza', 'quiza.uniqueid',
1482                  'quiza.preview = 0'));
1483  }
1484  
1485  /**
1486   * Implementation of the function for printing the form elements that control
1487   * whether the course reset functionality affects the quiz.
1488   *
1489   * @param MoodleQuickForm $mform the course reset form that is being built.
1490   */
1491  function quiz_reset_course_form_definition($mform) {
1492      $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1493      $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1494              get_string('removeallquizattempts', 'quiz'));
1495      $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1496              get_string('removealluseroverrides', 'quiz'));
1497      $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1498              get_string('removeallgroupoverrides', 'quiz'));
1499  }
1500  
1501  /**
1502   * Course reset form defaults.
1503   * @return array the defaults.
1504   */
1505  function quiz_reset_course_form_defaults($course) {
1506      return ['reset_quiz_attempts' => 1,
1507                   'reset_quiz_group_overrides' => 1,
1508                   'reset_quiz_user_overrides' => 1];
1509  }
1510  
1511  /**
1512   * Removes all grades from gradebook
1513   *
1514   * @param int $courseid
1515   * @param string optional type
1516   */
1517  function quiz_reset_gradebook($courseid, $type='') {
1518      global $CFG, $DB;
1519  
1520      $quizzes = $DB->get_records_sql("
1521              SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1522              FROM {modules} m
1523              JOIN {course_modules} cm ON m.id = cm.module
1524              JOIN {quiz} q ON cm.instance = q.id
1525              WHERE m.name = 'quiz' AND cm.course = ?", [$courseid]);
1526  
1527      foreach ($quizzes as $quiz) {
1528          quiz_grade_item_update($quiz, 'reset');
1529      }
1530  }
1531  
1532  /**
1533   * Actual implementation of the reset course functionality, delete all the
1534   * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1535   * set and true.
1536   *
1537   * Also, move the quiz open and close dates, if the course start date is changing.
1538   *
1539   * @param stdClass $data the data submitted from the reset course.
1540   * @return array status array
1541   */
1542  function quiz_reset_userdata($data) {
1543      global $CFG, $DB;
1544      require_once($CFG->libdir . '/questionlib.php');
1545  
1546      $componentstr = get_string('modulenameplural', 'quiz');
1547      $status = [];
1548  
1549      // Delete attempts.
1550      if (!empty($data->reset_quiz_attempts)) {
1551          question_engine::delete_questions_usage_by_activities(new qubaid_join(
1552                  '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1553                  'quiza.uniqueid', 'quiz.course = :quizcourseid',
1554                  ['quizcourseid' => $data->courseid]));
1555  
1556          $DB->delete_records_select('quiz_attempts',
1557                  'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]);
1558          $status[] = [
1559              'component' => $componentstr,
1560              'item' => get_string('attemptsdeleted', 'quiz'),
1561              'error' => false];
1562  
1563          // Remove all grades from gradebook.
1564          $DB->delete_records_select('quiz_grades',
1565                  'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]);
1566          if (empty($data->reset_gradebook_grades)) {
1567              quiz_reset_gradebook($data->courseid);
1568          }
1569          $status[] = [
1570              'component' => $componentstr,
1571              'item' => get_string('gradesdeleted', 'quiz'),
1572              'error' => false];
1573      }
1574  
1575      $purgeoverrides = false;
1576  
1577      // Remove user overrides.
1578      if (!empty($data->reset_quiz_user_overrides)) {
1579          $DB->delete_records_select('quiz_overrides',
1580                  'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid]);
1581          $status[] = [
1582              'component' => $componentstr,
1583              'item' => get_string('useroverridesdeleted', 'quiz'),
1584              'error' => false];
1585          $purgeoverrides = true;
1586      }
1587      // Remove group overrides.
1588      if (!empty($data->reset_quiz_group_overrides)) {
1589          $DB->delete_records_select('quiz_overrides',
1590                  'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid]);
1591          $status[] = [
1592              'component' => $componentstr,
1593              'item' => get_string('groupoverridesdeleted', 'quiz'),
1594              'error' => false];
1595          $purgeoverrides = true;
1596      }
1597  
1598      // Updating dates - shift may be negative too.
1599      if ($data->timeshift) {
1600          $DB->execute("UPDATE {quiz_overrides}
1601                           SET timeopen = timeopen + ?
1602                         WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1603                           AND timeopen <> 0", [$data->timeshift, $data->courseid]);
1604          $DB->execute("UPDATE {quiz_overrides}
1605                           SET timeclose = timeclose + ?
1606                         WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1607                           AND timeclose <> 0", [$data->timeshift, $data->courseid]);
1608  
1609          $purgeoverrides = true;
1610  
1611          // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1612          // See MDL-9367.
1613          shift_course_mod_dates('quiz', ['timeopen', 'timeclose'],
1614                  $data->timeshift, $data->courseid);
1615  
1616          $status[] = [
1617              'component' => $componentstr,
1618              'item' => get_string('openclosedatesupdated', 'quiz'),
1619              'error' => false];
1620      }
1621  
1622      if ($purgeoverrides) {
1623          cache::make('mod_quiz', 'overrides')->purge();
1624      }
1625  
1626      return $status;
1627  }
1628  
1629  /**
1630   * Return a textual summary of the number of attempts that have been made at a particular quiz,
1631   * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1632   *
1633   * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1634   * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1635   *      $cm->groupingid fields are used at the moment.
1636   * @param bool $returnzero if false (default), when no attempts have been
1637   *      made '' is returned instead of 'Attempts: 0'.
1638   * @param int $currentgroup if there is a concept of current group where this method is being called
1639   *         (e.g. a report) pass it in here. Default 0 which means no current group.
1640   * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1641   *          "Attemtps 123 (45 from this group)".
1642   */
1643  function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1644      global $DB, $USER;
1645      $numattempts = $DB->count_records('quiz_attempts', ['quiz' => $quiz->id, 'preview' => 0]);
1646      if ($numattempts || $returnzero) {
1647          if (groups_get_activity_groupmode($cm)) {
1648              $a = new stdClass();
1649              $a->total = $numattempts;
1650              if ($currentgroup) {
1651                  $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1652                          '{quiz_attempts} qa JOIN ' .
1653                          '{groups_members} gm ON qa.userid = gm.userid ' .
1654                          'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1655                          [$quiz->id, $currentgroup]);
1656                  return get_string('attemptsnumthisgroup', 'quiz', $a);
1657              } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1658                  list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1659                  $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1660                          '{quiz_attempts} qa JOIN ' .
1661                          '{groups_members} gm ON qa.userid = gm.userid ' .
1662                          'WHERE quiz = ? AND preview = 0 AND ' .
1663                          "groupid $usql", array_merge([$quiz->id], $params));
1664                  return get_string('attemptsnumyourgroups', 'quiz', $a);
1665              }
1666          }
1667          return get_string('attemptsnum', 'quiz', $numattempts);
1668      }
1669      return '';
1670  }
1671  
1672  /**
1673   * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1674   * to the quiz reports.
1675   *
1676   * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1677   * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1678   *      $cm->groupingid fields are used at the moment.
1679   * @param stdClass $context the quiz context.
1680   * @param bool $returnzero if false (default), when no attempts have been made
1681   *      '' is returned instead of 'Attempts: 0'.
1682   * @param int $currentgroup if there is a concept of current group where this method is being called
1683   *         (e.g. a report) pass it in here. Default 0 which means no current group.
1684   * @return string HTML fragment for the link.
1685   */
1686  function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1687          $currentgroup = 0) {
1688      global $PAGE;
1689  
1690      return $PAGE->get_renderer('mod_quiz')->quiz_attempt_summary_link_to_reports(
1691              $quiz, $cm, $context, $returnzero, $currentgroup);
1692  }
1693  
1694  /**
1695   * @param string $feature FEATURE_xx constant for requested feature
1696   * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1697   */
1698  function quiz_supports($feature) {
1699      switch($feature) {
1700          case FEATURE_GROUPS:                    return true;
1701          case FEATURE_GROUPINGS:                 return true;
1702          case FEATURE_MOD_INTRO:                 return true;
1703          case FEATURE_COMPLETION_TRACKS_VIEWS:   return true;
1704          case FEATURE_COMPLETION_HAS_RULES:      return true;
1705          case FEATURE_GRADE_HAS_GRADE:           return true;
1706          case FEATURE_GRADE_OUTCOMES:            return true;
1707          case FEATURE_BACKUP_MOODLE2:            return true;
1708          case FEATURE_SHOW_DESCRIPTION:          return true;
1709          case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1710          case FEATURE_USES_QUESTIONS:            return true;
1711          case FEATURE_PLAGIARISM:                return true;
1712          case FEATURE_MOD_PURPOSE:               return MOD_PURPOSE_ASSESSMENT;
1713  
1714          default: return null;
1715      }
1716  }
1717  
1718  /**
1719   * @return array all other caps used in module
1720   */
1721  function quiz_get_extra_capabilities() {
1722      global $CFG;
1723      require_once($CFG->libdir . '/questionlib.php');
1724      return question_get_all_capabilities();
1725  }
1726  
1727  /**
1728   * This function extends the settings navigation block for the site.
1729   *
1730   * It is safe to rely on PAGE here as we will only ever be within the module
1731   * context when this is called
1732   *
1733   * @param settings_navigation $settings
1734   * @param navigation_node $quiznode
1735   * @return void
1736   */
1737  function quiz_extend_settings_navigation(settings_navigation $settings, navigation_node $quiznode) {
1738      global $CFG;
1739  
1740      // Require {@link questionlib.php}
1741      // Included here as we only ever want to include this file if we really need to.
1742      require_once($CFG->libdir . '/questionlib.php');
1743  
1744      // We want to add these new nodes after the Edit settings node, and before the
1745      // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1746      $keys = $quiznode->get_children_key_list();
1747      $beforekey = null;
1748      $i = array_search('modedit', $keys);
1749      if ($i === false and array_key_exists(0, $keys)) {
1750          $beforekey = $keys[0];
1751      } else if (array_key_exists($i + 1, $keys)) {
1752          $beforekey = $keys[$i + 1];
1753      }
1754  
1755      if (has_any_capability(['mod/quiz:manageoverrides', 'mod/quiz:viewoverrides'], $settings->get_page()->cm->context)) {
1756          $url = new moodle_url('/mod/quiz/overrides.php', ['cmid' => $settings->get_page()->cm->id, 'mode' => 'user']);
1757          $node = navigation_node::create(get_string('overrides', 'quiz'),
1758                      $url, navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1759          $settingsoverride = $quiznode->add_node($node, $beforekey);
1760      }
1761  
1762      if (has_capability('mod/quiz:manage', $settings->get_page()->cm->context)) {
1763          $node = navigation_node::create(get_string('questions', 'quiz'),
1764              new moodle_url('/mod/quiz/edit.php', ['cmid' => $settings->get_page()->cm->id]),
1765              navigation_node::TYPE_SETTING, null, 'mod_quiz_edit', new pix_icon('t/edit', ''));
1766          $quiznode->add_node($node, $beforekey);
1767      }
1768  
1769      if (has_capability('mod/quiz:preview', $settings->get_page()->cm->context)) {
1770          $url = new moodle_url('/mod/quiz/startattempt.php',
1771                  ['cmid' => $settings->get_page()->cm->id, 'sesskey' => sesskey()]);
1772          $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1773                  navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1774                  new pix_icon('i/preview', ''));
1775          $previewnode = $quiznode->add_node($node, $beforekey);
1776          $previewnode->set_show_in_secondary_navigation(false);
1777      }
1778  
1779      question_extend_settings_navigation($quiznode, $settings->get_page()->cm->context)->trim_if_empty();
1780  
1781      if (has_any_capability(['mod/quiz:viewreports', 'mod/quiz:grade'], $settings->get_page()->cm->context)) {
1782          require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1783          $reportlist = quiz_report_list($settings->get_page()->cm->context);
1784  
1785          $url = new moodle_url('/mod/quiz/report.php',
1786                  ['id' => $settings->get_page()->cm->id, 'mode' => reset($reportlist)]);
1787          $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1788                  navigation_node::TYPE_SETTING,
1789                  null, 'quiz_report', new pix_icon('i/report', '')));
1790  
1791          foreach ($reportlist as $report) {
1792              $url = new moodle_url('/mod/quiz/report.php', ['id' => $settings->get_page()->cm->id, 'mode' => $report]);
1793              $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1794                      navigation_node::TYPE_SETTING,
1795                      null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1796          }
1797      }
1798  }
1799  
1800  /**
1801   * Serves the quiz files.
1802   *
1803   * @package  mod_quiz
1804   * @category files
1805   * @param stdClass $course course object
1806   * @param stdClass $cm course module object
1807   * @param stdClass $context context object
1808   * @param string $filearea file area
1809   * @param array $args extra arguments
1810   * @param bool $forcedownload whether or not force download
1811   * @param array $options additional options affecting the file serving
1812   * @return bool false if file not found, does not return if found - justsend the file
1813   */
1814  function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options= []) {
1815      global $CFG, $DB;
1816  
1817      if ($context->contextlevel != CONTEXT_MODULE) {
1818          return false;
1819      }
1820  
1821      require_login($course, false, $cm);
1822  
1823      if (!$quiz = $DB->get_record('quiz', ['id' => $cm->instance])) {
1824          return false;
1825      }
1826  
1827      // The 'intro' area is served by pluginfile.php.
1828      $fileareas = ['feedback'];
1829      if (!in_array($filearea, $fileareas)) {
1830          return false;
1831      }
1832  
1833      $feedbackid = (int)array_shift($args);
1834      if (!$feedback = $DB->get_record('quiz_feedback', ['id' => $feedbackid])) {
1835          return false;
1836      }
1837  
1838      $fs = get_file_storage();
1839      $relativepath = implode('/', $args);
1840      $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1841      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1842          return false;
1843      }
1844      send_stored_file($file, 0, 0, true, $options);
1845  }
1846  
1847  /**
1848   * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1849   * a question in a question_attempt when that attempt is a quiz attempt.
1850   *
1851   * @package  mod_quiz
1852   * @category files
1853   * @param stdClass $course course settings object
1854   * @param stdClass $context context object
1855   * @param string $component the name of the component we are serving files for.
1856   * @param string $filearea the name of the file area.
1857   * @param int $qubaid the attempt usage id.
1858   * @param int $slot the id of a question in this quiz attempt.
1859   * @param array $args the remaining bits of the file path.
1860   * @param bool $forcedownload whether the user must be forced to download the file.
1861   * @param array $options additional options affecting the file serving
1862   * @return bool false if file not found, does not return if found - justsend the file
1863   */
1864  function quiz_question_pluginfile($course, $context, $component,
1865          $filearea, $qubaid, $slot, $args, $forcedownload, array $options= []) {
1866      global $CFG;
1867      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1868  
1869      $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1870      require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1871  
1872      if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1873          // In the middle of an attempt.
1874          if (!$attemptobj->is_preview_user()) {
1875              $attemptobj->require_capability('mod/quiz:attempt');
1876          }
1877          $isreviewing = false;
1878  
1879      } else {
1880          // Reviewing an attempt.
1881          $attemptobj->check_review_capability();
1882          $isreviewing = true;
1883      }
1884  
1885      if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1886              $component, $filearea, $args, $forcedownload)) {
1887          send_file_not_found();
1888      }
1889  
1890      $fs = get_file_storage();
1891      $relativepath = implode('/', $args);
1892      $fullpath = "/$context->id/$component/$filearea/$relativepath";
1893      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1894          send_file_not_found();
1895      }
1896  
1897      send_stored_file($file, 0, 0, $forcedownload, $options);
1898  }
1899  
1900  /**
1901   * Return a list of page types
1902   * @param string $pagetype current page type
1903   * @param stdClass $parentcontext Block's parent context
1904   * @param stdClass $currentcontext Current context of block
1905   */
1906  function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1907      $modulepagetype = [
1908          'mod-quiz-*'       => get_string('page-mod-quiz-x', 'quiz'),
1909          'mod-quiz-view'    => get_string('page-mod-quiz-view', 'quiz'),
1910          'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1911          'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1912          'mod-quiz-review'  => get_string('page-mod-quiz-review', 'quiz'),
1913          'mod-quiz-edit'    => get_string('page-mod-quiz-edit', 'quiz'),
1914          'mod-quiz-report'  => get_string('page-mod-quiz-report', 'quiz'),
1915      ];
1916      return $modulepagetype;
1917  }
1918  
1919  /**
1920   * @return the options for quiz navigation.
1921   */
1922  function quiz_get_navigation_options() {
1923      return [
1924          QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1925          QUIZ_NAVMETHOD_SEQ  => get_string('navmethod_seq', 'quiz')
1926      ];
1927  }
1928  
1929  /**
1930   * Check if the module has any update that affects the current user since a given time.
1931   *
1932   * @param  cm_info $cm course module data
1933   * @param  int $from the time to check updates from
1934   * @param  array $filter  if we need to check only specific updates
1935   * @return stdClass an object with the different type of areas indicating if they were updated or not
1936   * @since Moodle 3.2
1937   */
1938  function quiz_check_updates_since(cm_info $cm, $from, $filter = []) {
1939      global $DB, $USER, $CFG;
1940      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1941  
1942      $updates = course_check_module_updates_since($cm, $from, [], $filter);
1943  
1944      // Check if questions were updated.
1945      $updates->questions = (object) ['updated' => false];
1946      $quizobj = quiz_settings::create($cm->instance, $USER->id);
1947      $quizobj->preload_questions();
1948      $questionids = array_keys($quizobj->get_questions(null, false));
1949      if (!empty($questionids)) {
1950          list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
1951          $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
1952          $params['time1'] = $from;
1953          $params['time2'] = $from;
1954          $questions = $DB->get_records_select('question', $select, $params, '', 'id');
1955          if (!empty($questions)) {
1956              $updates->questions->updated = true;
1957              $updates->questions->itemids = array_keys($questions);
1958          }
1959      }
1960  
1961      // Check for new attempts or grades.
1962      $updates->attempts = (object) ['updated' => false];
1963      $updates->grades = (object) ['updated' => false];
1964      $select = 'quiz = ? AND userid = ? AND timemodified > ?';
1965      $params = [$cm->instance, $USER->id, $from];
1966  
1967      $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1968      if (!empty($attempts)) {
1969          $updates->attempts->updated = true;
1970          $updates->attempts->itemids = array_keys($attempts);
1971      }
1972      $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
1973      if (!empty($grades)) {
1974          $updates->grades->updated = true;
1975          $updates->grades->itemids = array_keys($grades);
1976      }
1977  
1978      // Now, teachers should see other students updates.
1979      if (has_capability('mod/quiz:viewreports', $cm->context)) {
1980          $select = 'quiz = ? AND timemodified > ?';
1981          $params = [$cm->instance, $from];
1982  
1983          if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1984              $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1985              if (empty($groupusers)) {
1986                  return $updates;
1987              }
1988              list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1989              $select .= ' AND userid ' . $insql;
1990              $params = array_merge($params, $inparams);
1991          }
1992  
1993          $updates->userattempts = (object) ['updated' => false];
1994          $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1995          if (!empty($attempts)) {
1996              $updates->userattempts->updated = true;
1997              $updates->userattempts->itemids = array_keys($attempts);
1998          }
1999  
2000          $updates->usergrades = (object) ['updated' => false];
2001          $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2002          if (!empty($grades)) {
2003              $updates->usergrades->updated = true;
2004              $updates->usergrades->itemids = array_keys($grades);
2005          }
2006      }
2007      return $updates;
2008  }
2009  
2010  /**
2011   * Get icon mapping for font-awesome.
2012   */
2013  function mod_quiz_get_fontawesome_icon_map() {
2014      return [
2015          'mod_quiz:navflagged' => 'fa-flag',
2016      ];
2017  }
2018  
2019  /**
2020   * This function receives a calendar event and returns the action associated with it, or null if there is none.
2021   *
2022   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
2023   * is not displayed on the block.
2024   *
2025   * @param calendar_event $event
2026   * @param \core_calendar\action_factory $factory
2027   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
2028   * @return \core_calendar\local\event\entities\action_interface|null
2029   */
2030  function mod_quiz_core_calendar_provide_event_action(calendar_event $event,
2031                                                       \core_calendar\action_factory $factory,
2032                                                       int $userid = 0) {
2033      global $CFG, $USER;
2034  
2035      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2036  
2037      if (empty($userid)) {
2038          $userid = $USER->id;
2039      }
2040  
2041      $cm = get_fast_modinfo($event->courseid, $userid)->instances['quiz'][$event->instance];
2042      $quizobj = quiz_settings::create($cm->instance, $userid);
2043      $quiz = $quizobj->get_quiz();
2044  
2045      // Check they have capabilities allowing them to view the quiz.
2046      if (!has_any_capability(['mod/quiz:reviewmyattempts', 'mod/quiz:attempt'], $quizobj->get_context(), $userid)) {
2047          return null;
2048      }
2049  
2050      $completion = new \completion_info($cm->get_course());
2051  
2052      $completiondata = $completion->get_data($cm, false, $userid);
2053  
2054      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
2055          return null;
2056      }
2057  
2058      quiz_update_effective_access($quiz, $userid);
2059  
2060      // Check if quiz is closed, if so don't display it.
2061      if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) {
2062          return null;
2063      }
2064  
2065      if (!$quizobj->is_participant($userid)) {
2066          // If the user is not a participant then they have
2067          // no action to take. This will filter out the events for teachers.
2068          return null;
2069      }
2070  
2071      $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $userid);
2072      if (!empty($attempts)) {
2073          // The student's last attempt is finished.
2074          return null;
2075      }
2076  
2077      $name = get_string('attemptquiznow', 'quiz');
2078      $url = new \moodle_url('/mod/quiz/view.php', [
2079          'id' => $cm->id
2080      ]);
2081      $itemcount = 1;
2082      $actionable = true;
2083  
2084      // Check if the quiz is not currently actionable.
2085      if (!empty($quiz->timeopen) && $quiz->timeopen > time()) {
2086          $actionable = false;
2087      }
2088  
2089      return $factory->create_instance(
2090          $name,
2091          $url,
2092          $itemcount,
2093          $actionable
2094      );
2095  }
2096  
2097  /**
2098   * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2099   * for the course (see resource).
2100   *
2101   * Given a course_module object, this function returns any "extra" information that may be needed
2102   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2103   *
2104   * @param stdClass $coursemodule The coursemodule object (record).
2105   * @return cached_cm_info|false An object on information that the courses
2106   *                        will know about (most noticeably, an icon).
2107   */
2108  function quiz_get_coursemodule_info($coursemodule) {
2109      global $DB;
2110  
2111      $dbparams = ['id' => $coursemodule->instance];
2112      $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionminattempts,
2113          timeopen, timeclose';
2114      if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2115          return false;
2116      }
2117  
2118      $result = new cached_cm_info();
2119      $result->name = $quiz->name;
2120  
2121      if ($coursemodule->showdescription) {
2122          // Convert intro to html. Do not filter cached version, filters run at display time.
2123          $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false);
2124      }
2125  
2126      // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2127      if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
2128          if ($quiz->completionattemptsexhausted) {
2129              $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [
2130                  'completionpassgrade' => $coursemodule->completionpassgrade,
2131                  'completionattemptsexhausted' => $quiz->completionattemptsexhausted,
2132              ];
2133          } else {
2134              $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [];
2135          }
2136  
2137          $result->customdata['customcompletionrules']['completionminattempts'] = $quiz->completionminattempts;
2138      }
2139  
2140      // Populate some other values that can be used in calendar or on dashboard.
2141      if ($quiz->timeopen) {
2142          $result->customdata['timeopen'] = $quiz->timeopen;
2143      }
2144      if ($quiz->timeclose) {
2145          $result->customdata['timeclose'] = $quiz->timeclose;
2146      }
2147  
2148      return $result;
2149  }
2150  
2151  /**
2152   * Sets dynamic information about a course module
2153   *
2154   * This function is called from cm_info when displaying the module
2155   *
2156   * @param cm_info $cm
2157   */
2158  function mod_quiz_cm_info_dynamic(cm_info $cm) {
2159      global $USER;
2160  
2161      $cache = cache::make('mod_quiz', 'overrides');
2162      $override = $cache->get("{$cm->instance}_u_{$USER->id}");
2163  
2164      if (!$override) {
2165          $override = (object) [
2166              'timeopen' => null,
2167              'timeclose' => null,
2168          ];
2169      }
2170  
2171      // No need to look for group overrides if there are user overrides for both timeopen and timeclose.
2172      if (is_null($override->timeopen) || is_null($override->timeclose)) {
2173          $opens = [];
2174          $closes = [];
2175          $groupings = groups_get_user_groups($cm->course, $USER->id);
2176          foreach ($groupings[0] as $groupid) {
2177              $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}");
2178              if (isset($groupoverride->timeopen)) {
2179                  $opens[] = $groupoverride->timeopen;
2180              }
2181              if (isset($groupoverride->timeclose)) {
2182                  $closes[] = $groupoverride->timeclose;
2183              }
2184          }
2185          // If there is a user override for a setting, ignore the group override.
2186          if (is_null($override->timeopen) && count($opens)) {
2187              $override->timeopen = min($opens);
2188          }
2189          if (is_null($override->timeclose) && count($closes)) {
2190              if (in_array(0, $closes)) {
2191                  $override->timeclose = 0;
2192              } else {
2193                  $override->timeclose = max($closes);
2194              }
2195          }
2196      }
2197  
2198      // Populate some other values that can be used in calendar or on dashboard.
2199      if (!is_null($override->timeopen)) {
2200          $cm->override_customdata('timeopen', $override->timeopen);
2201      }
2202      if (!is_null($override->timeclose)) {
2203          $cm->override_customdata('timeclose', $override->timeclose);
2204      }
2205  }
2206  
2207  /**
2208   * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2209   *
2210   * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
2211   * @return array $descriptions the array of descriptions for the custom rules.
2212   */
2213  function mod_quiz_get_completion_active_rule_descriptions($cm) {
2214      // Values will be present in cm_info, and we assume these are up to date.
2215      if (empty($cm->customdata['customcompletionrules'])
2216          || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
2217          return [];
2218      }
2219  
2220      $descriptions = [];
2221      $rules = $cm->customdata['customcompletionrules'];
2222  
2223      if (!empty($rules['completionpassorattemptsexhausted'])) {
2224          if (!empty($rules['completionpassorattemptsexhausted']['completionattemptsexhausted'])) {
2225              $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2226          }
2227      } else {
2228          // Fallback.
2229          if (!empty($rules['completionattemptsexhausted'])) {
2230              $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2231          }
2232      }
2233  
2234      if (!empty($rules['completionminattempts'])) {
2235          $descriptions[] = get_string('completionminattemptsdesc', 'quiz', $rules['completionminattempts']);
2236      }
2237  
2238      return $descriptions;
2239  }
2240  
2241  /**
2242   * Returns the min and max values for the timestart property of a quiz
2243   * activity event.
2244   *
2245   * The min and max values will be the timeopen and timeclose properties
2246   * of the quiz, respectively, if they are set.
2247   *
2248   * If either value isn't set then null will be returned instead to
2249   * indicate that there is no cutoff for that value.
2250   *
2251   * If the vent has no valid timestart range then [false, false] will
2252   * be returned. This is the case for overriden events.
2253   *
2254   * A minimum and maximum cutoff return value will look like:
2255   * [
2256   *     [1505704373, 'The date must be after this date'],
2257   *     [1506741172, 'The date must be before this date']
2258   * ]
2259   *
2260   * @throws \moodle_exception
2261   * @param \calendar_event $event The calendar event to get the time range for
2262   * @param stdClass $quiz The module instance to get the range from
2263   * @return array
2264   */
2265  function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz) {
2266      global $CFG, $DB;
2267      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2268  
2269      // Overrides do not have a valid timestart range.
2270      if (quiz_is_overriden_calendar_event($event)) {
2271          return [false, false];
2272      }
2273  
2274      $mindate = null;
2275      $maxdate = null;
2276  
2277      if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2278          if (!empty($quiz->timeclose)) {
2279              $maxdate = [
2280                  $quiz->timeclose,
2281                  get_string('openafterclose', 'quiz')
2282              ];
2283          }
2284      } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2285          if (!empty($quiz->timeopen)) {
2286              $mindate = [
2287                  $quiz->timeopen,
2288                  get_string('closebeforeopen', 'quiz')
2289              ];
2290          }
2291      }
2292  
2293      return [$mindate, $maxdate];
2294  }
2295  
2296  /**
2297   * This function will update the quiz module according to the
2298   * event that has been modified.
2299   *
2300   * It will set the timeopen or timeclose value of the quiz instance
2301   * according to the type of event provided.
2302   *
2303   * @throws \moodle_exception
2304   * @param \calendar_event $event A quiz activity calendar event
2305   * @param \stdClass $quiz A quiz activity instance
2306   */
2307  function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz) {
2308      global $CFG, $DB;
2309      require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2310  
2311      if (!in_array($event->eventtype, [QUIZ_EVENT_TYPE_OPEN, QUIZ_EVENT_TYPE_CLOSE])) {
2312          // This isn't an event that we care about so we can ignore it.
2313          return;
2314      }
2315  
2316      $courseid = $event->courseid;
2317      $modulename = $event->modulename;
2318      $instanceid = $event->instance;
2319      $modified = false;
2320      $closedatechanged = false;
2321  
2322      // Something weird going on. The event is for a different module so
2323      // we should ignore it.
2324      if ($modulename != 'quiz') {
2325          return;
2326      }
2327  
2328      if ($quiz->id != $instanceid) {
2329          // The provided quiz instance doesn't match the event so
2330          // there is nothing to do here.
2331          return;
2332      }
2333  
2334      // We don't update the activity if it's an override event that has
2335      // been modified.
2336      if (quiz_is_overriden_calendar_event($event)) {
2337          return;
2338      }
2339  
2340      $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2341      $context = context_module::instance($coursemodule->id);
2342  
2343      // The user does not have the capability to modify this activity.
2344      if (!has_capability('moodle/course:manageactivities', $context)) {
2345          return;
2346      }
2347  
2348      if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2349          // If the event is for the quiz activity opening then we should
2350          // set the start time of the quiz activity to be the new start
2351          // time of the event.
2352          if ($quiz->timeopen != $event->timestart) {
2353              $quiz->timeopen = $event->timestart;
2354              $modified = true;
2355          }
2356      } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2357          // If the event is for the quiz activity closing then we should
2358          // set the end time of the quiz activity to be the new start
2359          // time of the event.
2360          if ($quiz->timeclose != $event->timestart) {
2361              $quiz->timeclose = $event->timestart;
2362              $modified = true;
2363              $closedatechanged = true;
2364          }
2365      }
2366  
2367      if ($modified) {
2368          $quiz->timemodified = time();
2369          $DB->update_record('quiz', $quiz);
2370  
2371          if ($closedatechanged) {
2372              quiz_update_open_attempts(['quizid' => $quiz->id]);
2373          }
2374  
2375          // Delete any previous preview attempts.
2376          quiz_delete_previews($quiz);
2377          quiz_update_events($quiz);
2378          $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2379          $event->trigger();
2380      }
2381  }
2382  
2383  /**
2384   * Generates the question bank in a fragment output. This allows
2385   * the question bank to be displayed in a modal.
2386   *
2387   * The only expected argument provided in the $args array is
2388   * 'querystring'. The value should be the list of parameters
2389   * URL encoded and used to build the question bank page.
2390   *
2391   * The individual list of parameters expected can be found in
2392   * question_build_edit_resources.
2393   *
2394   * @param array $args The fragment arguments.
2395   * @return string The rendered mform fragment.
2396   */
2397  function mod_quiz_output_fragment_quiz_question_bank($args): string {
2398      global $PAGE;
2399  
2400      // Retrieve params.
2401      $params = [];
2402      $extraparams = [];
2403      $querystring = parse_url($args['querystring'], PHP_URL_QUERY);
2404      parse_str($querystring, $params);
2405  
2406      $viewclass = \mod_quiz\question\bank\custom_view::class;
2407      $extraparams['view'] = $viewclass;
2408  
2409      // Build required parameters.
2410      [$contexts, $thispageurl, $cm, $pagevars, $extraparams] =
2411              build_required_parameters_for_custom_view($params, $extraparams);
2412  
2413      $course = get_course($cm->course);
2414      require_capability('mod/quiz:manage', $contexts->lowest());
2415  
2416      // Custom View.
2417      $questionbank = new $viewclass($contexts, $thispageurl, $course, $cm, $pagevars, $extraparams);
2418  
2419      // Output.
2420      $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2421      return $renderer->question_bank_contents($questionbank, $pagevars);
2422  }
2423  
2424  /**
2425   * Generates the add random question in a fragment output. This allows the
2426   * form to be rendered in javascript, for example inside a modal.
2427   *
2428   * The required arguments as keys in the $args array are:
2429   *      cat {string} The category and category context ids comma separated.
2430   *      addonpage {int} The page id to add this question to.
2431   *      returnurl {string} URL to return to after form submission.
2432   *      cmid {int} The course module id the questions are being added to.
2433   *
2434   * @param array $args The fragment arguments.
2435   * @return string The rendered mform fragment.
2436   */
2437  function mod_quiz_output_fragment_add_random_question_form($args) {
2438      global $PAGE, $OUTPUT;
2439  
2440      $extraparams = [];
2441  
2442      // Build required parameters.
2443      [$contexts, $thispageurl, $cm, $pagevars, $extraparams] =
2444              build_required_parameters_for_custom_view($args, $extraparams);
2445  
2446      // Additional param to differentiate with other question bank view.
2447      $extraparams['view'] = mod_quiz\question\bank\random_question_view::class;
2448  
2449      $course = get_course($cm->course);
2450      require_capability('mod/quiz:manage', $contexts->lowest());
2451  
2452      // Custom View.
2453      $questionbank = new mod_quiz\question\bank\random_question_view($contexts, $thispageurl, $course, $cm, $pagevars, $extraparams);
2454  
2455      $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2456      $questionbankoutput = $renderer->question_bank_contents($questionbank, $pagevars);
2457  
2458      $maxrand = 100;
2459      for ($i = 1; $i <= min(100, $maxrand); $i++) {
2460          $randomcount[] = ['value' => $i, 'name' => $i];
2461      }
2462  
2463      // Parent category select.
2464      $usablecontexts = $contexts->having_cap('moodle/question:useall');
2465      $categoriesarray = helper::question_category_options($usablecontexts);
2466      $catoptions = [];
2467      foreach ($categoriesarray as $group => $opts) {
2468          // Options for each category group.
2469          $categories = [];
2470          foreach ($opts as $context => $name) {
2471              $categories[] = ['value' => $context, 'name' => $name];
2472          }
2473          $catoptions[] = ['label' => $group, 'options' => $categories];
2474      }
2475  
2476      // Template data.
2477      $data = [
2478          'questionbank' => $questionbankoutput,
2479          'randomoptions' => $randomcount,
2480          'questioncategoryoptions' => $catoptions,
2481      ];
2482  
2483      $result = $OUTPUT->render_from_template('mod_quiz/add_random_question_form', $data);
2484  
2485      return $result;
2486  }
2487  
2488  /**
2489   * Callback to fetch the activity event type lang string.
2490   *
2491   * @param string $eventtype The event type.
2492   * @return lang_string The event type lang string.
2493   */
2494  function mod_quiz_core_calendar_get_event_action_string(string $eventtype): string {
2495      $modulename = get_string('modulename', 'quiz');
2496  
2497      switch ($eventtype) {
2498          case QUIZ_EVENT_TYPE_OPEN:
2499              $identifier = 'quizeventopens';
2500              break;
2501          case QUIZ_EVENT_TYPE_CLOSE:
2502              $identifier = 'quizeventcloses';
2503              break;
2504          default:
2505              return get_string('requiresaction', 'calendar', $modulename);
2506      }
2507  
2508      return get_string($identifier, 'quiz', $modulename);
2509  }
2510  
2511  /**
2512   * Delete question reference data.
2513   *
2514   * @param int $quizid The id of quiz.
2515   */
2516  function quiz_delete_references($quizid): void {
2517      global $DB;
2518      $slots = $DB->get_records('quiz_slots', ['quizid' => $quizid]);
2519      foreach ($slots as $slot) {
2520          $params = [
2521              'itemid' => $slot->id,
2522              'component' => 'mod_quiz',
2523              'questionarea' => 'slot'
2524          ];
2525          // Delete any set references.
2526          $DB->delete_records('question_set_references', $params);
2527          // Delete any references.
2528          $DB->delete_records('question_references', $params);
2529      }
2530  }
2531  
2532  /**
2533   * Question data fragment to get the question html via ajax call.
2534   *
2535   * @param array $args
2536   * @return string
2537   */
2538  function mod_quiz_output_fragment_question_data(array $args): string {
2539      // Return if there is no args.
2540      if (empty($args)) {
2541          return '';
2542      }
2543  
2544      // Retrieve params from query string.
2545      [$params, $extraparams] = \core_question\local\bank\filter_condition_manager::extract_parameters_from_fragment_args($args);
2546  
2547      // Build required parameters.
2548      $cmid = clean_param($args['cmid'], PARAM_INT);
2549      $thispageurl = new \moodle_url('/mod/quiz/edit.php', ['cmid' => $cmid]);
2550      $thiscontext = \context_module::instance($cmid);
2551      $contexts = new \core_question\local\bank\question_edit_contexts($thiscontext);
2552      $defaultcategory = question_make_default_categories($contexts->all());
2553      $params['cat'] = implode(',', [$defaultcategory->id, $defaultcategory->contextid]);
2554  
2555      $course = get_course($params['courseid']);
2556      [, $cm] = get_module_from_cmid($cmid);
2557      $params['tabname'] = 'questions';
2558  
2559      // Custom question bank View.
2560      $viewclass = clean_param($args['view'], PARAM_NOTAGS);
2561      $questionbank = new $viewclass($contexts, $thispageurl, $course, $cm, $params, $extraparams);
2562  
2563      // Question table.
2564      $questionbank->add_standard_search_conditions();
2565      ob_start();
2566      $questionbank->display_question_list();
2567      return ob_get_clean();
2568  }
2569  
2570  /**
2571   * Build required parameters for question bank custom view
2572   *
2573   * @param array $params the page parameters
2574   * @param array $extraparams additional parameters
2575   * @return array
2576   */
2577  function build_required_parameters_for_custom_view(array $params, array $extraparams): array {
2578      // Retrieve questions per page.
2579      $viewclass = $extraparams['view'] ?? null;
2580      $defaultpagesize = $viewclass ? $viewclass::DEFAULT_PAGE_SIZE : DEFAULT_QUESTIONS_PER_PAGE;
2581      // Build the required params.
2582      [$thispageurl, $contexts, $cmid, $cm, , $pagevars] = question_build_edit_resources(
2583              'editq',
2584              '/mod/quiz/edit.php',
2585              array_merge($params, $extraparams),
2586              $defaultpagesize);
2587  
2588      // Add cmid so we can retrieve later in extra params.
2589      $extraparams['cmid'] = $cmid;
2590  
2591      return [$contexts, $thispageurl, $cm, $pagevars, $extraparams];
2592  }
2593  
2594  /**
2595   * Implement the calculate_question_stats callback.
2596   *
2597   * This enables quiz statistics to be shown in statistics columns in the database.
2598   *
2599   * @param context $context return the statistics related to this context (which will be a quiz context).
2600   * @return all_calculated_for_qubaid_condition|null The statistics for this quiz, if available, else null.
2601   */
2602  function mod_quiz_calculate_question_stats(context $context): ?all_calculated_for_qubaid_condition {
2603      global $CFG;
2604      require_once($CFG->dirroot . '/mod/quiz/report/statistics/report.php');
2605      $cm = get_coursemodule_from_id('quiz', $context->instanceid);
2606      $report = new quiz_statistics_report();
2607      return $report->calculate_questions_stats_for_question_bank($cm->instance, false, false);
2608  }