Search moodle.org's
Developer Documentation

See Release Notes

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

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