Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  defined('MOODLE_INTERNAL') || die();
  18  
  19  /**
  20   * Quiz module test data generator class
  21   *
  22   * @package mod_quiz
  23   * @copyright 2012 The Open University
  24   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  class mod_quiz_generator extends testing_module_generator {
  27  
  28      public function create_instance($record = null, array $options = null) {
  29          global $CFG;
  30  
  31          require_once($CFG->dirroot.'/mod/quiz/locallib.php');
  32          $record = (object)(array)$record;
  33  
  34          $defaultquizsettings = array(
  35              'timeopen'               => 0,
  36              'timeclose'              => 0,
  37              'preferredbehaviour'     => 'deferredfeedback',
  38              'attempts'               => 0,
  39              'attemptonlast'          => 0,
  40              'grademethod'            => QUIZ_GRADEHIGHEST,
  41              'decimalpoints'          => 2,
  42              'questiondecimalpoints'  => -1,
  43              'attemptduring'          => 1,
  44              'correctnessduring'      => 1,
  45              'marksduring'            => 1,
  46              'specificfeedbackduring' => 1,
  47              'generalfeedbackduring'  => 1,
  48              'rightanswerduring'      => 1,
  49              'overallfeedbackduring'  => 0,
  50              'attemptimmediately'          => 1,
  51              'correctnessimmediately'      => 1,
  52              'marksimmediately'            => 1,
  53              'specificfeedbackimmediately' => 1,
  54              'generalfeedbackimmediately'  => 1,
  55              'rightanswerimmediately'      => 1,
  56              'overallfeedbackimmediately'  => 1,
  57              'attemptopen'            => 1,
  58              'correctnessopen'        => 1,
  59              'marksopen'              => 1,
  60              'specificfeedbackopen'   => 1,
  61              'generalfeedbackopen'    => 1,
  62              'rightansweropen'        => 1,
  63              'overallfeedbackopen'    => 1,
  64              'attemptclosed'          => 1,
  65              'correctnessclosed'      => 1,
  66              'marksclosed'            => 1,
  67              'specificfeedbackclosed' => 1,
  68              'generalfeedbackclosed'  => 1,
  69              'rightanswerclosed'      => 1,
  70              'overallfeedbackclosed'  => 1,
  71              'questionsperpage'       => 1,
  72              'shuffleanswers'         => 1,
  73              'sumgrades'              => 0,
  74              'grade'                  => 100,
  75              'timecreated'            => time(),
  76              'timemodified'           => time(),
  77              'timelimit'              => 0,
  78              'overduehandling'        => 'autosubmit',
  79              'graceperiod'            => 86400,
  80              'quizpassword'           => '',
  81              'subnet'                 => '',
  82              'browsersecurity'        => '',
  83              'delay1'                 => 0,
  84              'delay2'                 => 0,
  85              'showuserpicture'        => 0,
  86              'showblocks'             => 0,
  87              'navmethod'              => QUIZ_NAVMETHOD_FREE,
  88          );
  89  
  90          foreach ($defaultquizsettings as $name => $value) {
  91              if (!isset($record->{$name})) {
  92                  $record->{$name} = $value;
  93              }
  94          }
  95  
  96          if (isset($record->gradepass)) {
  97              $record->gradepass = unformat_float($record->gradepass);
  98          }
  99  
 100          return parent::create_instance($record, (array)$options);
 101      }
 102  
 103      /**
 104       * Create a quiz attempt for a particular user at a particular course.
 105       *
 106       * @param int $quizid the quiz id (from the mdl_quit table, not cmid).
 107       * @param int $userid the user id.
 108       * @param array $forcedrandomquestions slot => questionid. Optional,
 109       *      used with random questions, to control which one is 'randomly' selected in that slot.
 110       * @param array $forcedvariants slot => variantno. Optional. Optional,
 111       *      used with question where get_num_variants is > 1, to control which
 112       *      variants is 'randomly' selected.
 113       * @return stdClass the new attempt.
 114       */
 115      public function create_attempt($quizid, $userid, array $forcedrandomquestions = [],
 116              array $forcedvariants = []) {
 117          // Build quiz object and load questions.
 118          $quizobj = quiz::create($quizid, $userid);
 119  
 120          $attemptnumber = 1;
 121          $attempt = null;
 122  
 123          if ($attempts = quiz_get_user_attempts($quizid, $userid, 'all', true)) {
 124              // There is/are already an attempt/some attempts.
 125              // Take the last attempt.
 126              $attempt = end($attempts);
 127              // Take the attempt number of the last attempt and increase it.
 128              $attemptnumber = $attempt->attempt + 1;
 129          }
 130  
 131          return quiz_prepare_and_start_new_attempt($quizobj, $attemptnumber, $attempt, false,
 132                  $forcedrandomquestions, $forcedvariants);
 133      }
 134  
 135      /**
 136       * Submit responses to a quiz attempt.
 137       *
 138       * To be realistic, you should ensure that $USER is set to the user whose attempt
 139       * it is before calling this.
 140       *
 141       * @param int $attemptid the id of the attempt which is being
 142       * @param array $responses array responses to submit. See description on
 143       *      {@link core_question_generator::get_simulated_post_data_for_questions_in_usage()}.
 144       * @param bool $checkbutton if simulate a click on the check button for each question, else simulate save.
 145       *      This should only be used with behaviours that have a check button.
 146       * @param bool $finishattempt if true, the attempt will be submitted.
 147       */
 148      public function submit_responses($attemptid, array $responses, $checkbutton, $finishattempt) {
 149          $questiongenerator = $this->datagenerator->get_plugin_generator('core_question');
 150  
 151          $attemptobj = quiz_attempt::create($attemptid);
 152  
 153          $postdata = $questiongenerator->get_simulated_post_data_for_questions_in_usage(
 154                  $attemptobj->get_question_usage(), $responses, $checkbutton);
 155  
 156          $attemptobj->process_submitted_actions(time(), false, $postdata);
 157  
 158          // Bit if a hack for interactive behaviour.
 159          // TODO handle this in a more plugin-friendly way.
 160          if ($checkbutton) {
 161              $postdata = [];
 162              foreach ($responses as $slot => $notused) {
 163                  $qa = $attemptobj->get_question_attempt($slot);
 164                  if ($qa->get_behaviour() instanceof qbehaviour_interactive && $qa->get_behaviour()->is_try_again_state()) {
 165                      $postdata[$qa->get_control_field_name('sequencecheck')] = (string)$qa->get_sequence_check_count();
 166                      $postdata[$qa->get_flag_field_name()] = (string)(int)$qa->is_flagged();
 167                      $postdata[$qa->get_behaviour_field_name('tryagain')] = 1;
 168                  }
 169              }
 170  
 171              if ($postdata) {
 172                  $attemptobj->process_submitted_actions(time(), false, $postdata);
 173              }
 174          }
 175  
 176          if ($finishattempt) {
 177              $attemptobj->process_finish(time(), false);
 178          }
 179      }
 180  
 181      /**
 182       * Create a quiz override (either user or group).
 183       *
 184       * @param array $data must specify quizid, and one of userid or groupid.
 185       */
 186      public function create_override(array $data): void {
 187          global $DB;
 188  
 189          // Validate.
 190          if (!isset($data['quiz'])) {
 191              throw new coding_exception('Must specify quiz (id) when creating a quiz override.');
 192          }
 193  
 194          if (!isset($data['userid']) && !isset($data['groupid'])) {
 195              throw new coding_exception('Must specify one of userid or groupid when creating a quiz override.');
 196          }
 197  
 198          if (isset($data['userid']) && isset($data['groupid'])) {
 199              throw new coding_exception('Cannot specify both userid and groupid when creating a quiz override.');
 200          }
 201  
 202          // Create the override.
 203          $DB->insert_record('quiz_overrides', (object) $data);
 204  
 205          // Update any associated calendar events, if necessary.
 206          quiz_update_events($DB->get_record('quiz', ['id' => $data['quiz']], '*', MUST_EXIST));
 207      }
 208  }