Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

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