Merge branch 'MDL-48795_27' of https://github.com/apsdehal/moodle into MOODLE_27_STABLE
[moodle.git] / mod / quiz / mod_form.php
blobad98999271372468f1ad0f3952834cd64983aa31
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.
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/>.
17 /**
18 * Defines the quiz module ettings form.
20 * @package mod_quiz
21 * @copyright 2006 Jamie Pratt
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->dirroot . '/course/moodleform_mod.php');
29 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
32 /**
33 * Settings form for the quiz module.
35 * @copyright 2006 Jamie Pratt
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class mod_quiz_mod_form extends moodleform_mod {
39 /** @var array options to be used with date_time_selector fields in the quiz. */
40 public static $datefieldoptions = array('optional' => true, 'step' => 1);
42 protected $_feedbacks;
43 protected static $reviewfields = array(); // Initialised in the constructor.
45 /** @var int the max number of attempts allowed in any user or group override on this quiz. */
46 protected $maxattemptsanyoverride = null;
48 public function __construct($current, $section, $cm, $course) {
49 self::$reviewfields = array(
50 'attempt' => array('theattempt', 'quiz'),
51 'correctness' => array('whethercorrect', 'question'),
52 'marks' => array('marks', 'quiz'),
53 'specificfeedback' => array('specificfeedback', 'question'),
54 'generalfeedback' => array('generalfeedback', 'question'),
55 'rightanswer' => array('rightanswer', 'question'),
56 'overallfeedback' => array('reviewoverallfeedback', 'quiz'),
58 parent::__construct($current, $section, $cm, $course);
61 protected function definition() {
62 global $COURSE, $CFG, $DB, $PAGE;
63 $quizconfig = get_config('quiz');
64 $mform = $this->_form;
66 // -------------------------------------------------------------------------------
67 $mform->addElement('header', 'general', get_string('general', 'form'));
69 // Name.
70 $mform->addElement('text', 'name', get_string('name'), array('size'=>'64'));
71 if (!empty($CFG->formatstringstriptags)) {
72 $mform->setType('name', PARAM_TEXT);
73 } else {
74 $mform->setType('name', PARAM_CLEANHTML);
76 $mform->addRule('name', null, 'required', null, 'client');
77 $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
79 // Introduction.
80 $this->add_intro_editor(false, get_string('introduction', 'quiz'));
82 // -------------------------------------------------------------------------------
83 $mform->addElement('header', 'timing', get_string('timing', 'quiz'));
85 // Open and close dates.
86 $mform->addElement('date_time_selector', 'timeopen', get_string('quizopen', 'quiz'),
87 self::$datefieldoptions);
88 $mform->addHelpButton('timeopen', 'quizopenclose', 'quiz');
90 $mform->addElement('date_time_selector', 'timeclose', get_string('quizclose', 'quiz'),
91 self::$datefieldoptions);
93 // Time limit.
94 $mform->addElement('duration', 'timelimit', get_string('timelimit', 'quiz'),
95 array('optional' => true));
96 $mform->addHelpButton('timelimit', 'timelimit', 'quiz');
97 $mform->setAdvanced('timelimit', $quizconfig->timelimit_adv);
98 $mform->setDefault('timelimit', $quizconfig->timelimit);
100 // What to do with overdue attempts.
101 $mform->addElement('select', 'overduehandling', get_string('overduehandling', 'quiz'),
102 quiz_get_overdue_handling_options());
103 $mform->addHelpButton('overduehandling', 'overduehandling', 'quiz');
104 $mform->setAdvanced('overduehandling', $quizconfig->overduehandling_adv);
105 $mform->setDefault('overduehandling', $quizconfig->overduehandling);
106 // TODO Formslib does OR logic on disableif, and we need AND logic here.
107 // $mform->disabledIf('overduehandling', 'timelimit', 'eq', 0);
108 // $mform->disabledIf('overduehandling', 'timeclose', 'eq', 0);
110 // Grace period time.
111 $mform->addElement('duration', 'graceperiod', get_string('graceperiod', 'quiz'),
112 array('optional' => true));
113 $mform->addHelpButton('graceperiod', 'graceperiod', 'quiz');
114 $mform->setAdvanced('graceperiod', $quizconfig->graceperiod_adv);
115 $mform->setDefault('graceperiod', $quizconfig->graceperiod);
116 $mform->disabledIf('graceperiod', 'overduehandling', 'neq', 'graceperiod');
118 // -------------------------------------------------------------------------------
119 // Grade settings.
120 $this->standard_grading_coursemodule_elements();
122 $mform->removeElement('grade');
123 if (property_exists($this->current, 'grade')) {
124 $currentgrade = $this->current->grade;
125 } else {
126 $currentgrade = $quizconfig->maximumgrade;
128 $mform->addElement('hidden', 'grade', $currentgrade);
129 $mform->setType('grade', PARAM_FLOAT);
131 // Number of attempts.
132 $attemptoptions = array('0' => get_string('unlimited'));
133 for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) {
134 $attemptoptions[$i] = $i;
136 $mform->addElement('select', 'attempts', get_string('attemptsallowed', 'quiz'),
137 $attemptoptions);
138 $mform->setAdvanced('attempts', $quizconfig->attempts_adv);
139 $mform->setDefault('attempts', $quizconfig->attempts);
141 // Grading method.
142 $mform->addElement('select', 'grademethod', get_string('grademethod', 'quiz'),
143 quiz_get_grading_options());
144 $mform->addHelpButton('grademethod', 'grademethod', 'quiz');
145 $mform->setAdvanced('grademethod', $quizconfig->grademethod_adv);
146 $mform->setDefault('grademethod', $quizconfig->grademethod);
147 if ($this->get_max_attempts_for_any_override() < 2) {
148 $mform->disabledIf('grademethod', 'attempts', 'eq', 1);
151 // -------------------------------------------------------------------------------
152 $mform->addElement('header', 'layouthdr', get_string('layout', 'quiz'));
154 // Shuffle questions.
155 $shuffleoptions = array(
156 0 => get_string('asshownoneditscreen', 'quiz'),
157 1 => get_string('shuffledrandomly', 'quiz')
159 $mform->addElement('select', 'shufflequestions', get_string('questionorder', 'quiz'),
160 $shuffleoptions, array('id' => 'id_shufflequestions'));
161 $mform->setAdvanced('shufflequestions', $quizconfig->shufflequestions_adv);
162 $mform->setDefault('shufflequestions', $quizconfig->shufflequestions);
164 // Questions per page.
165 $pageoptions = array();
166 $pageoptions[0] = get_string('neverallononepage', 'quiz');
167 $pageoptions[1] = get_string('everyquestion', 'quiz');
168 for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
169 $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
172 $pagegroup = array();
173 $pagegroup[] = $mform->createElement('select', 'questionsperpage',
174 get_string('newpage', 'quiz'), $pageoptions, array('id' => 'id_questionsperpage'));
175 $mform->setDefault('questionsperpage', $quizconfig->questionsperpage);
177 if (!empty($this->_cm)) {
178 $pagegroup[] = $mform->createElement('checkbox', 'repaginatenow', '',
179 get_string('repaginatenow', 'quiz'), array('id' => 'id_repaginatenow'));
180 $mform->disabledIf('repaginatenow', 'shufflequestions', 'eq', 1);
182 $PAGE->requires->js('/question/qengine.js');
183 $module = array(
184 'name' => 'mod_quiz_edit',
185 'fullpath' => '/mod/quiz/edit.js',
186 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
187 'strings' => array(),
188 'async' => false,
190 $PAGE->requires->js_init_call('quiz_settings_init', null, false, $module);
193 $mform->addGroup($pagegroup, 'questionsperpagegrp',
194 get_string('newpage', 'quiz'), null, false);
195 $mform->addHelpButton('questionsperpagegrp', 'newpage', 'quiz');
196 $mform->setAdvanced('questionsperpagegrp', $quizconfig->questionsperpage_adv);
198 // Navigation method.
199 $mform->addElement('select', 'navmethod', get_string('navmethod', 'quiz'),
200 quiz_get_navigation_options());
201 $mform->addHelpButton('navmethod', 'navmethod', 'quiz');
202 $mform->setAdvanced('navmethod', $quizconfig->navmethod_adv);
203 $mform->setDefault('navmethod', $quizconfig->navmethod);
205 // -------------------------------------------------------------------------------
206 $mform->addElement('header', 'interactionhdr', get_string('questionbehaviour', 'quiz'));
208 // Shuffle within questions.
209 $mform->addElement('selectyesno', 'shuffleanswers', get_string('shufflewithin', 'quiz'));
210 $mform->addHelpButton('shuffleanswers', 'shufflewithin', 'quiz');
211 $mform->setAdvanced('shuffleanswers', $quizconfig->shuffleanswers_adv);
212 $mform->setDefault('shuffleanswers', $quizconfig->shuffleanswers);
214 // How questions behave (question behaviour).
215 if (!empty($this->current->preferredbehaviour)) {
216 $currentbehaviour = $this->current->preferredbehaviour;
217 } else {
218 $currentbehaviour = '';
220 $behaviours = question_engine::get_behaviour_options($currentbehaviour);
221 $mform->addElement('select', 'preferredbehaviour',
222 get_string('howquestionsbehave', 'question'), $behaviours);
223 $mform->addHelpButton('preferredbehaviour', 'howquestionsbehave', 'question');
224 $mform->setDefault('preferredbehaviour', $quizconfig->preferredbehaviour);
226 // Each attempt builds on last.
227 $mform->addElement('selectyesno', 'attemptonlast',
228 get_string('eachattemptbuildsonthelast', 'quiz'));
229 $mform->addHelpButton('attemptonlast', 'eachattemptbuildsonthelast', 'quiz');
230 $mform->setAdvanced('attemptonlast', $quizconfig->attemptonlast_adv);
231 $mform->setDefault('attemptonlast', $quizconfig->attemptonlast);
232 if ($this->get_max_attempts_for_any_override() < 2) {
233 $mform->disabledIf('attemptonlast', 'attempts', 'eq', 1);
236 // -------------------------------------------------------------------------------
237 $mform->addElement('header', 'reviewoptionshdr',
238 get_string('reviewoptionsheading', 'quiz'));
239 $mform->addHelpButton('reviewoptionshdr', 'reviewoptionsheading', 'quiz');
241 // Review options.
242 $this->add_review_options_group($mform, $quizconfig, 'during',
243 mod_quiz_display_options::DURING, true);
244 $this->add_review_options_group($mform, $quizconfig, 'immediately',
245 mod_quiz_display_options::IMMEDIATELY_AFTER);
246 $this->add_review_options_group($mform, $quizconfig, 'open',
247 mod_quiz_display_options::LATER_WHILE_OPEN);
248 $this->add_review_options_group($mform, $quizconfig, 'closed',
249 mod_quiz_display_options::AFTER_CLOSE);
251 foreach ($behaviours as $behaviour => $notused) {
252 $unusedoptions = question_engine::get_behaviour_unused_display_options($behaviour);
253 foreach ($unusedoptions as $unusedoption) {
254 $mform->disabledIf($unusedoption . 'during', 'preferredbehaviour',
255 'eq', $behaviour);
258 $mform->disabledIf('attemptduring', 'preferredbehaviour',
259 'neq', 'wontmatch');
260 $mform->disabledIf('overallfeedbackduring', 'preferredbehaviour',
261 'neq', 'wontmatch');
263 // -------------------------------------------------------------------------------
264 $mform->addElement('header', 'display', get_string('appearance'));
266 // Show user picture.
267 $mform->addElement('select', 'showuserpicture', get_string('showuserpicture', 'quiz'),
268 quiz_get_user_image_options());
269 $mform->addHelpButton('showuserpicture', 'showuserpicture', 'quiz');
270 $mform->setAdvanced('showuserpicture', $quizconfig->showuserpicture_adv);
271 $mform->setDefault('showuserpicture', $quizconfig->showuserpicture);
273 // Overall decimal points.
274 $options = array();
275 for ($i = 0; $i <= QUIZ_MAX_DECIMAL_OPTION; $i++) {
276 $options[$i] = $i;
278 $mform->addElement('select', 'decimalpoints', get_string('decimalplaces', 'quiz'),
279 $options);
280 $mform->addHelpButton('decimalpoints', 'decimalplaces', 'quiz');
281 $mform->setAdvanced('decimalpoints', $quizconfig->decimalpoints_adv);
282 $mform->setDefault('decimalpoints', $quizconfig->decimalpoints);
284 // Question decimal points.
285 $options = array(-1 => get_string('sameasoverall', 'quiz'));
286 for ($i = 0; $i <= QUIZ_MAX_Q_DECIMAL_OPTION; $i++) {
287 $options[$i] = $i;
289 $mform->addElement('select', 'questiondecimalpoints',
290 get_string('decimalplacesquestion', 'quiz'), $options);
291 $mform->addHelpButton('questiondecimalpoints', 'decimalplacesquestion', 'quiz');
292 $mform->setAdvanced('questiondecimalpoints', $quizconfig->questiondecimalpoints_adv);
293 $mform->setDefault('questiondecimalpoints', $quizconfig->questiondecimalpoints);
295 // Show blocks during quiz attempt.
296 $mform->addElement('selectyesno', 'showblocks', get_string('showblocks', 'quiz'));
297 $mform->addHelpButton('showblocks', 'showblocks', 'quiz');
298 $mform->setAdvanced('showblocks', $quizconfig->showblocks_adv);
299 $mform->setDefault('showblocks', $quizconfig->showblocks);
301 // -------------------------------------------------------------------------------
302 $mform->addElement('header', 'security', get_string('extraattemptrestrictions', 'quiz'));
304 // Require password to begin quiz attempt.
305 $mform->addElement('passwordunmask', 'quizpassword', get_string('requirepassword', 'quiz'));
306 $mform->setType('quizpassword', PARAM_TEXT);
307 $mform->addHelpButton('quizpassword', 'requirepassword', 'quiz');
308 $mform->setAdvanced('quizpassword', $quizconfig->password_adv);
309 $mform->setDefault('quizpassword', $quizconfig->password);
311 // IP address.
312 $mform->addElement('text', 'subnet', get_string('requiresubnet', 'quiz'));
313 $mform->setType('subnet', PARAM_TEXT);
314 $mform->addHelpButton('subnet', 'requiresubnet', 'quiz');
315 $mform->setAdvanced('subnet', $quizconfig->subnet_adv);
316 $mform->setDefault('subnet', $quizconfig->subnet);
318 // Enforced time delay between quiz attempts.
319 $mform->addElement('duration', 'delay1', get_string('delay1st2nd', 'quiz'),
320 array('optional' => true));
321 $mform->addHelpButton('delay1', 'delay1st2nd', 'quiz');
322 $mform->setAdvanced('delay1', $quizconfig->delay1_adv);
323 $mform->setDefault('delay1', $quizconfig->delay1);
324 if ($this->get_max_attempts_for_any_override() < 2) {
325 $mform->disabledIf('delay1', 'attempts', 'eq', 1);
328 $mform->addElement('duration', 'delay2', get_string('delaylater', 'quiz'),
329 array('optional' => true));
330 $mform->addHelpButton('delay2', 'delaylater', 'quiz');
331 $mform->setAdvanced('delay2', $quizconfig->delay2_adv);
332 $mform->setDefault('delay2', $quizconfig->delay2);
333 if ($this->get_max_attempts_for_any_override() < 3) {
334 $mform->disabledIf('delay2', 'attempts', 'eq', 1);
335 $mform->disabledIf('delay2', 'attempts', 'eq', 2);
338 // Browser security choices.
339 $mform->addElement('select', 'browsersecurity', get_string('browsersecurity', 'quiz'),
340 quiz_access_manager::get_browser_security_choices());
341 $mform->addHelpButton('browsersecurity', 'browsersecurity', 'quiz');
342 $mform->setAdvanced('browsersecurity', $quizconfig->browsersecurity_adv);
343 $mform->setDefault('browsersecurity', $quizconfig->browsersecurity);
345 // Any other rule plugins.
346 quiz_access_manager::add_settings_form_fields($this, $mform);
348 // -------------------------------------------------------------------------------
349 $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'quiz'));
350 $mform->addHelpButton('overallfeedbackhdr', 'overallfeedback', 'quiz');
352 if (isset($this->current->grade)) {
353 $needwarning = $this->current->grade === 0;
354 } else {
355 $needwarning = $quizconfig->maximumgrade == 0;
357 if ($needwarning) {
358 $mform->addElement('static', 'nogradewarning', '',
359 get_string('nogradewarning', 'quiz'));
362 $mform->addElement('static', 'gradeboundarystatic1',
363 get_string('gradeboundary', 'quiz'), '100%');
365 $repeatarray = array();
366 $repeatedoptions = array();
367 $repeatarray[] = $mform->createElement('editor', 'feedbacktext',
368 get_string('feedback', 'quiz'), array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES,
369 'noclean' => true, 'context' => $this->context));
370 $repeatarray[] = $mform->createElement('text', 'feedbackboundaries',
371 get_string('gradeboundary', 'quiz'), array('size' => 10));
372 $repeatedoptions['feedbacktext']['type'] = PARAM_RAW;
373 $repeatedoptions['feedbackboundaries']['type'] = PARAM_RAW;
375 if (!empty($this->_instance)) {
376 $this->_feedbacks = $DB->get_records('quiz_feedback',
377 array('quizid' => $this->_instance), 'mingrade DESC');
378 } else {
379 $this->_feedbacks = array();
381 $numfeedbacks = max(count($this->_feedbacks) * 1.5, 5);
383 $nextel = $this->repeat_elements($repeatarray, $numfeedbacks - 1,
384 $repeatedoptions, 'boundary_repeats', 'boundary_add_fields', 3,
385 get_string('addmoreoverallfeedbacks', 'quiz'), true);
387 // Put some extra elements in before the button.
388 $mform->insertElementBefore($mform->createElement('editor',
389 "feedbacktext[$nextel]", get_string('feedback', 'quiz'), array('rows' => 3),
390 array('maxfiles' => EDITOR_UNLIMITED_FILES, 'noclean' => true,
391 'context' => $this->context)),
392 'boundary_add_fields');
393 $mform->insertElementBefore($mform->createElement('static',
394 'gradeboundarystatic2', get_string('gradeboundary', 'quiz'), '0%'),
395 'boundary_add_fields');
397 // Add the disabledif rules. We cannot do this using the $repeatoptions parameter to
398 // repeat_elements because we don't want to dissable the first feedbacktext.
399 for ($i = 0; $i < $nextel; $i++) {
400 $mform->disabledIf('feedbackboundaries[' . $i . ']', 'grade', 'eq', 0);
401 $mform->disabledIf('feedbacktext[' . ($i + 1) . ']', 'grade', 'eq', 0);
404 // -------------------------------------------------------------------------------
405 $this->standard_coursemodule_elements();
407 // Check and act on whether setting outcomes is considered an advanced setting.
408 $mform->setAdvanced('modoutcomes', !empty($quizconfig->outcomes_adv));
410 // The standard_coursemodule_elements method sets this to 100, but the
411 // quiz has its own setting, so use that.
412 $mform->setDefault('grade', $quizconfig->maximumgrade);
414 // -------------------------------------------------------------------------------
415 $this->add_action_buttons();
418 protected function add_review_options_group($mform, $quizconfig, $whenname,
419 $when, $withhelp = false) {
420 global $OUTPUT;
422 $group = array();
423 foreach (self::$reviewfields as $field => $string) {
424 list($identifier, $component) = $string;
426 $label = get_string($identifier, $component);
427 if ($withhelp) {
428 $label .= ' ' . $OUTPUT->help_icon($identifier, $component);
431 $group[] = $mform->createElement('checkbox', $field . $whenname, '', $label);
433 $mform->addGroup($group, $whenname . 'optionsgrp',
434 get_string('review' . $whenname, 'quiz'), null, false);
436 foreach (self::$reviewfields as $field => $notused) {
437 $cfgfield = 'review' . $field;
438 if ($quizconfig->$cfgfield & $when) {
439 $mform->setDefault($field . $whenname, 1);
440 } else {
441 $mform->setDefault($field . $whenname, 0);
445 if ($whenname != 'during') {
446 $mform->disabledIf('correctness' . $whenname, 'attempt' . $whenname);
447 $mform->disabledIf('specificfeedback' . $whenname, 'attempt' . $whenname);
448 $mform->disabledIf('generalfeedback' . $whenname, 'attempt' . $whenname);
449 $mform->disabledIf('rightanswer' . $whenname, 'attempt' . $whenname);
453 protected function preprocessing_review_settings(&$toform, $whenname, $when) {
454 foreach (self::$reviewfields as $field => $notused) {
455 $fieldname = 'review' . $field;
456 if (array_key_exists($fieldname, $toform)) {
457 $toform[$field . $whenname] = $toform[$fieldname] & $when;
462 public function data_preprocessing(&$toform) {
463 if (isset($toform['grade'])) {
464 // Convert to a real number, so we don't get 0.0000.
465 $toform['grade'] = $toform['grade'] + 0;
468 if (count($this->_feedbacks)) {
469 $key = 0;
470 foreach ($this->_feedbacks as $feedback) {
471 $draftid = file_get_submitted_draft_itemid('feedbacktext['.$key.']');
472 $toform['feedbacktext['.$key.']']['text'] = file_prepare_draft_area(
473 $draftid, // Draftid.
474 $this->context->id, // Context.
475 'mod_quiz', // Component.
476 'feedback', // Filarea.
477 !empty($feedback->id) ? (int) $feedback->id : null, // Itemid.
478 null,
479 $feedback->feedbacktext // Text.
481 $toform['feedbacktext['.$key.']']['format'] = $feedback->feedbacktextformat;
482 $toform['feedbacktext['.$key.']']['itemid'] = $draftid;
484 if ($toform['grade'] == 0) {
485 // When a quiz is un-graded, there can only be one lot of
486 // feedback. If the quiz previously had a maximum grade and
487 // several lots of feedback, we must now avoid putting text
488 // into input boxes that are disabled, but which the
489 // validation will insist are blank.
490 break;
493 if ($feedback->mingrade > 0) {
494 $toform['feedbackboundaries['.$key.']'] =
495 round(100.0 * $feedback->mingrade / $toform['grade'], 6) . '%';
497 $key++;
501 if (isset($toform['timelimit'])) {
502 $toform['timelimitenable'] = $toform['timelimit'] > 0;
505 $this->preprocessing_review_settings($toform, 'during',
506 mod_quiz_display_options::DURING);
507 $this->preprocessing_review_settings($toform, 'immediately',
508 mod_quiz_display_options::IMMEDIATELY_AFTER);
509 $this->preprocessing_review_settings($toform, 'open',
510 mod_quiz_display_options::LATER_WHILE_OPEN);
511 $this->preprocessing_review_settings($toform, 'closed',
512 mod_quiz_display_options::AFTER_CLOSE);
513 $toform['attemptduring'] = true;
514 $toform['overallfeedbackduring'] = false;
516 // Password field - different in form to stop browsers that remember
517 // passwords from getting confused.
518 if (isset($toform['password'])) {
519 $toform['quizpassword'] = $toform['password'];
520 unset($toform['password']);
523 // Load any settings belonging to the access rules.
524 if (!empty($toform['instance'])) {
525 $accesssettings = quiz_access_manager::load_settings($toform['instance']);
526 foreach ($accesssettings as $name => $value) {
527 $toform[$name] = $value;
532 public function validation($data, $files) {
533 $errors = parent::validation($data, $files);
535 // Check open and close times are consistent.
536 if ($data['timeopen'] != 0 && $data['timeclose'] != 0 &&
537 $data['timeclose'] < $data['timeopen']) {
538 $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
541 // Check that the grace period is not too short.
542 if ($data['overduehandling'] == 'graceperiod') {
543 $graceperiodmin = get_config('quiz', 'graceperiodmin');
544 if ($data['graceperiod'] <= $graceperiodmin) {
545 $errors['graceperiod'] = get_string('graceperiodtoosmall', 'quiz', format_time($graceperiodmin));
549 // Check the boundary value is a number or a percentage, and in range.
550 $i = 0;
551 while (!empty($data['feedbackboundaries'][$i] )) {
552 $boundary = trim($data['feedbackboundaries'][$i]);
553 if (strlen($boundary) > 0) {
554 if ($boundary[strlen($boundary) - 1] == '%') {
555 $boundary = trim(substr($boundary, 0, -1));
556 if (is_numeric($boundary)) {
557 $boundary = $boundary * $data['grade'] / 100.0;
558 } else {
559 $errors["feedbackboundaries[$i]"] =
560 get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
562 } else if (!is_numeric($boundary)) {
563 $errors["feedbackboundaries[$i]"] =
564 get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
567 if (is_numeric($boundary) && $boundary <= 0 || $boundary >= $data['grade'] ) {
568 $errors["feedbackboundaries[$i]"] =
569 get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
571 if (is_numeric($boundary) && $i > 0 &&
572 $boundary >= $data['feedbackboundaries'][$i - 1]) {
573 $errors["feedbackboundaries[$i]"] =
574 get_string('feedbackerrororder', 'quiz', $i + 1);
576 $data['feedbackboundaries'][$i] = $boundary;
577 $i += 1;
579 $numboundaries = $i;
581 // Check there is nothing in the remaining unused fields.
582 if (!empty($data['feedbackboundaries'])) {
583 for ($i = $numboundaries; $i < count($data['feedbackboundaries']); $i += 1) {
584 if (!empty($data['feedbackboundaries'][$i] ) &&
585 trim($data['feedbackboundaries'][$i] ) != '') {
586 $errors["feedbackboundaries[$i]"] =
587 get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
591 for ($i = $numboundaries + 1; $i < count($data['feedbacktext']); $i += 1) {
592 if (!empty($data['feedbacktext'][$i]['text']) &&
593 trim($data['feedbacktext'][$i]['text'] ) != '') {
594 $errors["feedbacktext[$i]"] =
595 get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
599 // Any other rule plugins.
600 $errors = quiz_access_manager::validate_settings_form_fields($errors, $data, $files, $this);
602 return $errors;
606 * Get the maximum number of attempts that anyone might have due to a user
607 * or group override. Used to decide whether disabledIf rules should be applied.
608 * @return int the number of attempts allowed. For the purpose of this method,
609 * unlimited is returned as 1000, not 0.
611 public function get_max_attempts_for_any_override() {
612 global $DB;
614 if (empty($this->_instance)) {
615 // Quiz not created yet, so no overrides.
616 return 1;
619 if ($this->maxattemptsanyoverride === null) {
620 $this->maxattemptsanyoverride = $DB->get_field_sql("
621 SELECT MAX(CASE WHEN attempts = 0 THEN 1000 ELSE attempts END)
622 FROM {quiz_overrides}
623 WHERE quiz = ?",
624 array($this->_instance));
625 if ($this->maxattemptsanyoverride < 1) {
626 // This happens when no override alters the number of attempts.
627 $this->maxattemptsanyoverride = 1;
631 return $this->maxattemptsanyoverride;