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 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Settings form for overrides in the quiz module.
  19   *
  20   * @package    mod_quiz
  21   * @copyright  2010 Matt Petro
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  require_once($CFG->libdir . '/formslib.php');
  29  require_once($CFG->dirroot . '/mod/quiz/mod_form.php');
  30  
  31  
  32  /**
  33   * Form for editing settings overrides.
  34   *
  35   * @copyright  2010 Matt Petro
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class quiz_override_form extends moodleform {
  39  
  40      /** @var cm_info course module object. */
  41      protected $cm;
  42  
  43      /** @var stdClass the quiz settings object. */
  44      protected $quiz;
  45  
  46      /** @var context the quiz context. */
  47      protected $context;
  48  
  49      /** @var bool editing group override (true) or user override (false). */
  50      protected $groupmode;
  51  
  52      /** @var int groupid, if provided. */
  53      protected $groupid;
  54  
  55      /** @var int userid, if provided. */
  56      protected $userid;
  57  
  58      /**
  59       * Constructor.
  60       * @param moodle_url $submiturl the form action URL.
  61       * @param object course module object.
  62       * @param object the quiz settings object.
  63       * @param context the quiz context.
  64       * @param bool editing group override (true) or user override (false).
  65       * @param object $override the override being edited, if it already exists.
  66       */
  67      public function __construct($submiturl, $cm, $quiz, $context, $groupmode, $override) {
  68  
  69          $this->cm = $cm;
  70          $this->quiz = $quiz;
  71          $this->context = $context;
  72          $this->groupmode = $groupmode;
  73          $this->groupid = empty($override->groupid) ? 0 : $override->groupid;
  74          $this->userid = empty($override->userid) ? 0 : $override->userid;
  75  
  76          parent::__construct($submiturl);
  77      }
  78  
  79      protected function definition() {
  80          global $DB;
  81  
  82          $cm = $this->cm;
  83          $mform = $this->_form;
  84  
  85          $mform->addElement('header', 'override', get_string('override', 'quiz'));
  86  
  87          $quizgroupmode = groups_get_activity_groupmode($cm);
  88          $accessallgroups = ($quizgroupmode == NOGROUPS) || has_capability('moodle/site:accessallgroups', $this->context);
  89  
  90          if ($this->groupmode) {
  91              // Group override.
  92              if ($this->groupid) {
  93                  // There is already a groupid, so freeze the selector.
  94                  $groupchoices = [
  95                      $this->groupid => format_string(groups_get_group_name($this->groupid), true, [
  96                          'context' => $this->context,
  97                      ]),
  98                  ];
  99                  $mform->addElement('select', 'groupid',
 100                          get_string('overridegroup', 'quiz'), $groupchoices);
 101                  $mform->freeze('groupid');
 102              } else {
 103                  // Prepare the list of groups.
 104                  // Only include the groups the current can access.
 105                  $groups = $accessallgroups ? groups_get_all_groups($cm->course) : groups_get_activity_allowed_groups($cm);
 106                  if (empty($groups)) {
 107                      // Generate an error.
 108                      $link = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$cm->id));
 109                      throw new \moodle_exception('groupsnone', 'quiz', $link);
 110                  }
 111  
 112                  $groupchoices = array();
 113                  foreach ($groups as $group) {
 114                      $groupchoices[$group->id] = format_string($group->name, true, [
 115                          'context' => $this->context,
 116                      ]);
 117                  }
 118                  unset($groups);
 119  
 120                  if (count($groupchoices) == 0) {
 121                      $groupchoices[0] = get_string('none');
 122                  }
 123  
 124                  $mform->addElement('select', 'groupid',
 125                          get_string('overridegroup', 'quiz'), $groupchoices);
 126                  $mform->addRule('groupid', get_string('required'), 'required', null, 'client');
 127              }
 128          } else {
 129              // User override.
 130              $userfieldsapi = \core_user\fields::for_identity($this->context)->with_userpic()->with_name();
 131              $extrauserfields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);
 132              if ($this->userid) {
 133                  // There is already a userid, so freeze the selector.
 134                  $user = $DB->get_record('user', ['id' => $this->userid]);
 135                  profile_load_custom_fields($user);
 136                  $userchoices = array();
 137                  $userchoices[$this->userid] = self::display_user_name($user, $extrauserfields);
 138                  $mform->addElement('select', 'userid',
 139                          get_string('overrideuser', 'quiz'), $userchoices);
 140                  $mform->freeze('userid');
 141              } else {
 142                  // Prepare the list of users.
 143  
 144                  // Get the list of appropriate users, depending on whether and how groups are used.
 145                  $userfieldsql = $userfieldsapi->get_sql('u', true, '', '', false);
 146                  $capabilityjoin = get_with_capability_join($this->context, 'mod/quiz:attempt', 'u.id');
 147                  list($sort, $sortparams) = users_order_by_sql('u', null,
 148                          $this->context, $userfieldsql->mappings);
 149  
 150                  $groupjoin = '';
 151                  $groupparams = [];
 152                  if (!$accessallgroups) {
 153                      $groups = groups_get_activity_allowed_groups($cm);
 154                      list($grouptest, $groupparams) = $DB->get_in_or_equal(
 155                              array_keys($groups), SQL_PARAMS_NAMED, 'grp');
 156                      $groupjoin = "JOIN (SELECT DISTINCT userid
 157                                    FROM {groups_members}
 158                                   WHERE groupid $grouptest
 159                                         ) gm ON gm.userid = u.id";
 160                  }
 161  
 162                  $capabilitywhere = '';
 163                  if ($capabilityjoin->wheres) {
 164                      $capabilitywhere = 'AND ' . $capabilityjoin->wheres;
 165                  }
 166  
 167                  $users = $DB->get_records_sql("
 168                          SELECT $userfieldsql->selects
 169                            FROM {user} u
 170                            LEFT JOIN {quiz_overrides} existingoverride ON
 171                                        existingoverride.userid = u.id AND existingoverride.quiz = :quizid
 172                            $capabilityjoin->joins
 173                            $groupjoin
 174                            $userfieldsql->joins
 175                           WHERE existingoverride.id IS NULL
 176                             $capabilitywhere
 177                        ORDER BY $sort
 178                          ", array_merge(['quizid' => $this->quiz->id], $capabilityjoin->params,
 179                          $groupparams, $userfieldsql->params, $sortparams));
 180  
 181                  // Filter users based on any fixed restrictions (groups, profile).
 182                  $info = new \core_availability\info_module($cm);
 183                  $users = $info->filter_user_list($users);
 184  
 185                  if (empty($users)) {
 186                      // Generate an error.
 187                      $link = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$cm->id));
 188                      throw new \moodle_exception('usersnone', 'quiz', $link);
 189                  }
 190  
 191                  $userchoices = [];
 192                  foreach ($users as $id => $user) {
 193                      $userchoices[$id] = self::display_user_name($user, $extrauserfields);
 194                  }
 195                  unset($users);
 196  
 197                  $mform->addElement('searchableselector', 'userid',
 198                          get_string('overrideuser', 'quiz'), $userchoices);
 199                  $mform->addRule('userid', get_string('required'), 'required', null, 'client');
 200              }
 201          }
 202  
 203          // Password.
 204          // This field has to be above the date and timelimit fields,
 205          // otherwise browsers will clear it when those fields are changed.
 206          $mform->addElement('passwordunmask', 'password', get_string('requirepassword', 'quiz'));
 207          $mform->setType('password', PARAM_TEXT);
 208          $mform->addHelpButton('password', 'requirepassword', 'quiz');
 209          $mform->setDefault('password', $this->quiz->password);
 210  
 211          // Open and close dates.
 212          $mform->addElement('date_time_selector', 'timeopen',
 213                  get_string('quizopen', 'quiz'), mod_quiz_mod_form::$datefieldoptions);
 214          $mform->setDefault('timeopen', $this->quiz->timeopen);
 215  
 216          $mform->addElement('date_time_selector', 'timeclose',
 217                  get_string('quizclose', 'quiz'), mod_quiz_mod_form::$datefieldoptions);
 218          $mform->setDefault('timeclose', $this->quiz->timeclose);
 219  
 220          // Time limit.
 221          $mform->addElement('duration', 'timelimit',
 222                  get_string('timelimit', 'quiz'), array('optional' => true));
 223          $mform->addHelpButton('timelimit', 'timelimit', 'quiz');
 224          $mform->setDefault('timelimit', $this->quiz->timelimit);
 225  
 226          // Number of attempts.
 227          $attemptoptions = array('0' => get_string('unlimited'));
 228          for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) {
 229              $attemptoptions[$i] = $i;
 230          }
 231          $mform->addElement('select', 'attempts',
 232                  get_string('attemptsallowed', 'quiz'), $attemptoptions);
 233          $mform->addHelpButton('attempts', 'attempts', 'quiz');
 234          $mform->setDefault('attempts', $this->quiz->attempts);
 235  
 236          // Submit buttons.
 237          $mform->addElement('submit', 'resetbutton',
 238                  get_string('reverttodefaults', 'quiz'));
 239  
 240          $buttonarray = array();
 241          $buttonarray[] = $mform->createElement('submit', 'submitbutton',
 242                  get_string('save', 'quiz'));
 243          $buttonarray[] = $mform->createElement('submit', 'againbutton',
 244                  get_string('saveoverrideandstay', 'quiz'));
 245          $buttonarray[] = $mform->createElement('cancel');
 246  
 247          $mform->addGroup($buttonarray, 'buttonbar', '', array(' '), false);
 248          $mform->closeHeaderBefore('buttonbar');
 249      }
 250  
 251      /**
 252       * Get a user's name and identity ready to display.
 253       *
 254       * @param stdClass $user a user object.
 255       * @param array $extrauserfields (identity fields in user table only from the user_fields API)
 256       * @return string User's name, with extra info, for display.
 257       */
 258      public static function display_user_name(stdClass $user, array $extrauserfields): string {
 259          $username = fullname($user);
 260          $namefields = [];
 261          foreach ($extrauserfields as $field) {
 262              if (isset($user->$field) && $user->$field !== '') {
 263                  $namefields[] = s($user->$field);
 264              } else if (strpos($field, 'profile_field_') === 0) {
 265                  $field = substr($field, 14);
 266                  if (isset($user->profile[$field]) && $user->profile[$field] !== '') {
 267                      $namefields[] = s($user->profile[$field]);
 268                  }
 269              }
 270          }
 271          if ($namefields) {
 272              $username .= ' (' . implode(', ', $namefields) . ')';
 273          }
 274          return $username;
 275      }
 276  
 277      public function validation($data, $files): array {
 278          $errors = parent::validation($data, $files);
 279  
 280          $mform =& $this->_form;
 281          $quiz = $this->quiz;
 282  
 283          if ($mform->elementExists('userid')) {
 284              if (empty($data['userid'])) {
 285                  $errors['userid'] = get_string('required');
 286              }
 287          }
 288  
 289          if ($mform->elementExists('groupid')) {
 290              if (empty($data['groupid'])) {
 291                  $errors['groupid'] = get_string('required');
 292              }
 293          }
 294  
 295          // Ensure that the dates make sense.
 296          if (!empty($data['timeopen']) && !empty($data['timeclose'])) {
 297              if ($data['timeclose'] < $data['timeopen'] ) {
 298                  $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
 299              }
 300          }
 301  
 302          // Ensure that at least one quiz setting was changed.
 303          $changed = false;
 304          $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password');
 305          foreach ($keys as $key) {
 306              if ($data[$key] != $quiz->{$key}) {
 307                  $changed = true;
 308                  break;
 309              }
 310          }
 311          if (!$changed) {
 312              $errors['timeopen'] = get_string('nooverridedata', 'quiz');
 313          }
 314  
 315          return $errors;
 316      }
 317  }