Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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, $this->context),
  96                  ];
  97                  $mform->addElement('select', 'groupid',
  98                          get_string('overridegroup', 'quiz'), $groupchoices);
  99                  $mform->freeze('groupid');
 100              } else {
 101                  // Prepare the list of groups.
 102                  // Only include the groups the current can access.
 103                  $groups = $accessallgroups ? groups_get_all_groups($cm->course) : groups_get_activity_allowed_groups($cm);
 104                  if (empty($groups)) {
 105                      // Generate an error.
 106                      $link = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$cm->id));
 107                      print_error('groupsnone', 'quiz', $link);
 108                  }
 109  
 110                  $groupchoices = array();
 111                  foreach ($groups as $group) {
 112                      $groupchoices[$group->id] = format_string($group->name, true, $this->context);
 113                  }
 114                  unset($groups);
 115  
 116                  if (count($groupchoices) == 0) {
 117                      $groupchoices[0] = get_string('none');
 118                  }
 119  
 120                  $mform->addElement('select', 'groupid',
 121                          get_string('overridegroup', 'quiz'), $groupchoices);
 122                  $mform->addRule('groupid', get_string('required'), 'required', null, 'client');
 123              }
 124          } else {
 125              // User override.
 126              $userfieldsapi = \core_user\fields::for_identity($this->context)->with_userpic()->with_name();
 127              $extrauserfields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);
 128              if ($this->userid) {
 129                  // There is already a userid, so freeze the selector.
 130                  $user = $DB->get_record('user', ['id' => $this->userid]);
 131                  profile_load_custom_fields($user);
 132                  $userchoices = array();
 133                  $userchoices[$this->userid] = self::display_user_name($user, $extrauserfields);
 134                  $mform->addElement('select', 'userid',
 135                          get_string('overrideuser', 'quiz'), $userchoices);
 136                  $mform->freeze('userid');
 137              } else {
 138                  // Prepare the list of users.
 139  
 140                  // Get the list of appropriate users, depending on whether and how groups are used.
 141                  $userfieldsql = $userfieldsapi->get_sql('u', true, '', '', false);
 142                  $capabilityjoin = get_with_capability_join($this->context, 'mod/quiz:attempt', 'u.id');
 143                  list($sort, $sortparams) = users_order_by_sql('u', null,
 144                          $this->context, $userfieldsql->mappings);
 145  
 146                  $groupjoin = '';
 147                  $groupparams = [];
 148                  if (!$accessallgroups) {
 149                      $groups = groups_get_activity_allowed_groups($cm);
 150                      list($grouptest, $groupparams) = $DB->get_in_or_equal(
 151                              array_keys($groups), SQL_PARAMS_NAMED, 'grp');
 152                      $groupjoin = "JOIN (SELECT DISTINCT userid
 153                                    FROM {groups_members}
 154                                   WHERE groupid $grouptest
 155                                         ) gm ON gm.userid = u.id";
 156                  }
 157  
 158                  $capabilitywhere = '';
 159                  if ($capabilityjoin->wheres) {
 160                      $capabilitywhere = 'AND ' . $capabilityjoin->wheres;
 161                  }
 162  
 163                  $users = $DB->get_records_sql("
 164                          SELECT $userfieldsql->selects
 165                            FROM {user} u
 166                            LEFT JOIN {quiz_overrides} existingoverride ON
 167                                        existingoverride.userid = u.id AND existingoverride.quiz = :quizid
 168                            $capabilityjoin->joins
 169                            $groupjoin
 170                            $userfieldsql->joins
 171                           WHERE existingoverride.id IS NULL
 172                             $capabilitywhere
 173                        ORDER BY $sort
 174                          ", array_merge(['quizid' => $this->quiz->id], $capabilityjoin->params,
 175                          $groupparams, $userfieldsql->params, $sortparams));
 176  
 177                  // Filter users based on any fixed restrictions (groups, profile).
 178                  $info = new \core_availability\info_module($cm);
 179                  $users = $info->filter_user_list($users);
 180  
 181                  if (empty($users)) {
 182                      // Generate an error.
 183                      $link = new moodle_url('/mod/quiz/overrides.php', array('cmid'=>$cm->id));
 184                      print_error('usersnone', 'quiz', $link);
 185                  }
 186  
 187                  $userchoices = [];
 188                  foreach ($users as $id => $user) {
 189                      $userchoices[$id] = self::display_user_name($user, $extrauserfields);
 190                  }
 191                  unset($users);
 192  
 193                  $mform->addElement('searchableselector', 'userid',
 194                          get_string('overrideuser', 'quiz'), $userchoices);
 195                  $mform->addRule('userid', get_string('required'), 'required', null, 'client');
 196              }
 197          }
 198  
 199          // Password.
 200          // This field has to be above the date and timelimit fields,
 201          // otherwise browsers will clear it when those fields are changed.
 202          $mform->addElement('passwordunmask', 'password', get_string('requirepassword', 'quiz'));
 203          $mform->setType('password', PARAM_TEXT);
 204          $mform->addHelpButton('password', 'requirepassword', 'quiz');
 205          $mform->setDefault('password', $this->quiz->password);
 206  
 207          // Open and close dates.
 208          $mform->addElement('date_time_selector', 'timeopen',
 209                  get_string('quizopen', 'quiz'), mod_quiz_mod_form::$datefieldoptions);
 210          $mform->setDefault('timeopen', $this->quiz->timeopen);
 211  
 212          $mform->addElement('date_time_selector', 'timeclose',
 213                  get_string('quizclose', 'quiz'), mod_quiz_mod_form::$datefieldoptions);
 214          $mform->setDefault('timeclose', $this->quiz->timeclose);
 215  
 216          // Time limit.
 217          $mform->addElement('duration', 'timelimit',
 218                  get_string('timelimit', 'quiz'), array('optional' => true));
 219          $mform->addHelpButton('timelimit', 'timelimit', 'quiz');
 220          $mform->setDefault('timelimit', $this->quiz->timelimit);
 221  
 222          // Number of attempts.
 223          $attemptoptions = array('0' => get_string('unlimited'));
 224          for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) {
 225              $attemptoptions[$i] = $i;
 226          }
 227          $mform->addElement('select', 'attempts',
 228                  get_string('attemptsallowed', 'quiz'), $attemptoptions);
 229          $mform->addHelpButton('attempts', 'attempts', 'quiz');
 230          $mform->setDefault('attempts', $this->quiz->attempts);
 231  
 232          // Submit buttons.
 233          $mform->addElement('submit', 'resetbutton',
 234                  get_string('reverttodefaults', 'quiz'));
 235  
 236          $buttonarray = array();
 237          $buttonarray[] = $mform->createElement('submit', 'submitbutton',
 238                  get_string('save', 'quiz'));
 239          $buttonarray[] = $mform->createElement('submit', 'againbutton',
 240                  get_string('saveoverrideandstay', 'quiz'));
 241          $buttonarray[] = $mform->createElement('cancel');
 242  
 243          $mform->addGroup($buttonarray, 'buttonbar', '', array(' '), false);
 244          $mform->closeHeaderBefore('buttonbar');
 245      }
 246  
 247      /**
 248       * Get a user's name and identity ready to display.
 249       *
 250       * @param stdClass $user a user object.
 251       * @param array $extrauserfields (identity fields in user table only from the user_fields API)
 252       * @return string User's name, with extra info, for display.
 253       */
 254      public static function display_user_name(stdClass $user, array $extrauserfields): string {
 255          $username = fullname($user);
 256          $namefields = [];
 257          foreach ($extrauserfields as $field) {
 258              if (isset($user->$field) && $user->$field !== '') {
 259                  $namefields[] = s($user->$field);
 260              } else if (strpos($field, 'profile_field_') === 0) {
 261                  $field = substr($field, 14);
 262                  if (isset($user->profile[$field]) && $user->profile[$field] !== '') {
 263                      $namefields[] = s($user->profile[$field]);
 264                  }
 265              }
 266          }
 267          if ($namefields) {
 268              $username .= ' (' . implode(', ', $namefields) . ')';
 269          }
 270          return $username;
 271      }
 272  
 273      public function validation($data, $files): array {
 274          $errors = parent::validation($data, $files);
 275  
 276          $mform =& $this->_form;
 277          $quiz = $this->quiz;
 278  
 279          if ($mform->elementExists('userid')) {
 280              if (empty($data['userid'])) {
 281                  $errors['userid'] = get_string('required');
 282              }
 283          }
 284  
 285          if ($mform->elementExists('groupid')) {
 286              if (empty($data['groupid'])) {
 287                  $errors['groupid'] = get_string('required');
 288              }
 289          }
 290  
 291          // Ensure that the dates make sense.
 292          if (!empty($data['timeopen']) && !empty($data['timeclose'])) {
 293              if ($data['timeclose'] < $data['timeopen'] ) {
 294                  $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
 295              }
 296          }
 297  
 298          // Ensure that at least one quiz setting was changed.
 299          $changed = false;
 300          $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password');
 301          foreach ($keys as $key) {
 302              if ($data[$key] != $quiz->{$key}) {
 303                  $changed = true;
 304                  break;
 305              }
 306          }
 307          if (!$changed) {
 308              $errors['timeopen'] = get_string('nooverridedata', 'quiz');
 309          }
 310  
 311          return $errors;
 312      }
 313  }