Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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