Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

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