Search moodle.org's
Developer Documentation

See Release Notes

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

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

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