MDL-49813 quiz: add sections in the right place after page changes
[moodle.git] / mod / quiz / mod_form.php
blob40581cc7946578836e766a2656b048968765807b
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->standard_intro_elements(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 $pagegroup = array();
155 $pagegroup[] = $mform->createElement('select', 'questionsperpage',
156 get_string('newpage', 'quiz'), quiz_questions_per_page_options(), array('id' => 'id_questionsperpage'));
157 $mform->setDefault('questionsperpage', $quizconfig->questionsperpage);
159 if (!empty($this->_cm)) {
160 $pagegroup[] = $mform->createElement('checkbox', 'repaginatenow', '',
161 get_string('repaginatenow', 'quiz'), array('id' => 'id_repaginatenow'));
164 $mform->addGroup($pagegroup, 'questionsperpagegrp',
165 get_string('newpage', 'quiz'), null, false);
166 $mform->addHelpButton('questionsperpagegrp', 'newpage', 'quiz');
167 $mform->setAdvanced('questionsperpagegrp', $quizconfig->questionsperpage_adv);
169 // Navigation method.
170 $mform->addElement('select', 'navmethod', get_string('navmethod', 'quiz'),
171 quiz_get_navigation_options());
172 $mform->addHelpButton('navmethod', 'navmethod', 'quiz');
173 $mform->setAdvanced('navmethod', $quizconfig->navmethod_adv);
174 $mform->setDefault('navmethod', $quizconfig->navmethod);
176 // -------------------------------------------------------------------------------
177 $mform->addElement('header', 'interactionhdr', get_string('questionbehaviour', 'quiz'));
179 // Shuffle within questions.
180 $mform->addElement('selectyesno', 'shuffleanswers', get_string('shufflewithin', 'quiz'));
181 $mform->addHelpButton('shuffleanswers', 'shufflewithin', 'quiz');
182 $mform->setAdvanced('shuffleanswers', $quizconfig->shuffleanswers_adv);
183 $mform->setDefault('shuffleanswers', $quizconfig->shuffleanswers);
185 // How questions behave (question behaviour).
186 if (!empty($this->current->preferredbehaviour)) {
187 $currentbehaviour = $this->current->preferredbehaviour;
188 } else {
189 $currentbehaviour = '';
191 $behaviours = question_engine::get_behaviour_options($currentbehaviour);
192 $mform->addElement('select', 'preferredbehaviour',
193 get_string('howquestionsbehave', 'question'), $behaviours);
194 $mform->addHelpButton('preferredbehaviour', 'howquestionsbehave', 'question');
195 $mform->setDefault('preferredbehaviour', $quizconfig->preferredbehaviour);
197 // Can redo completed questions.
198 $redochoices = array(0 => get_string('no'), 1 => get_string('canredoquestionsyes', 'quiz'));
199 $mform->addElement('select', 'canredoquestions', get_string('canredoquestions', 'quiz'), $redochoices);
200 $mform->addHelpButton('canredoquestions', 'canredoquestions', 'quiz');
201 $mform->setAdvanced('canredoquestions', $quizconfig->canredoquestions_adv);
202 $mform->setDefault('canredoquestions', $quizconfig->canredoquestions);
203 foreach ($behaviours as $behaviour => $notused) {
204 if (!question_engine::can_questions_finish_during_the_attempt($behaviour)) {
205 $mform->disabledIf('canredoquestions', 'preferredbehaviour', 'eq', $behaviour);
209 // Each attempt builds on last.
210 $mform->addElement('selectyesno', 'attemptonlast',
211 get_string('eachattemptbuildsonthelast', 'quiz'));
212 $mform->addHelpButton('attemptonlast', 'eachattemptbuildsonthelast', 'quiz');
213 $mform->setAdvanced('attemptonlast', $quizconfig->attemptonlast_adv);
214 $mform->setDefault('attemptonlast', $quizconfig->attemptonlast);
215 if ($this->get_max_attempts_for_any_override() < 2) {
216 $mform->disabledIf('attemptonlast', 'attempts', 'eq', 1);
219 // -------------------------------------------------------------------------------
220 $mform->addElement('header', 'reviewoptionshdr',
221 get_string('reviewoptionsheading', 'quiz'));
222 $mform->addHelpButton('reviewoptionshdr', 'reviewoptionsheading', 'quiz');
224 // Review options.
225 $this->add_review_options_group($mform, $quizconfig, 'during',
226 mod_quiz_display_options::DURING, true);
227 $this->add_review_options_group($mform, $quizconfig, 'immediately',
228 mod_quiz_display_options::IMMEDIATELY_AFTER);
229 $this->add_review_options_group($mform, $quizconfig, 'open',
230 mod_quiz_display_options::LATER_WHILE_OPEN);
231 $this->add_review_options_group($mform, $quizconfig, 'closed',
232 mod_quiz_display_options::AFTER_CLOSE);
234 foreach ($behaviours as $behaviour => $notused) {
235 $unusedoptions = question_engine::get_behaviour_unused_display_options($behaviour);
236 foreach ($unusedoptions as $unusedoption) {
237 $mform->disabledIf($unusedoption . 'during', 'preferredbehaviour',
238 'eq', $behaviour);
241 $mform->disabledIf('attemptduring', 'preferredbehaviour',
242 'neq', 'wontmatch');
243 $mform->disabledIf('overallfeedbackduring', 'preferredbehaviour',
244 'neq', 'wontmatch');
246 // -------------------------------------------------------------------------------
247 $mform->addElement('header', 'display', get_string('appearance'));
249 // Show user picture.
250 $mform->addElement('select', 'showuserpicture', get_string('showuserpicture', 'quiz'),
251 quiz_get_user_image_options());
252 $mform->addHelpButton('showuserpicture', 'showuserpicture', 'quiz');
253 $mform->setAdvanced('showuserpicture', $quizconfig->showuserpicture_adv);
254 $mform->setDefault('showuserpicture', $quizconfig->showuserpicture);
256 // Overall decimal points.
257 $options = array();
258 for ($i = 0; $i <= QUIZ_MAX_DECIMAL_OPTION; $i++) {
259 $options[$i] = $i;
261 $mform->addElement('select', 'decimalpoints', get_string('decimalplaces', 'quiz'),
262 $options);
263 $mform->addHelpButton('decimalpoints', 'decimalplaces', 'quiz');
264 $mform->setAdvanced('decimalpoints', $quizconfig->decimalpoints_adv);
265 $mform->setDefault('decimalpoints', $quizconfig->decimalpoints);
267 // Question decimal points.
268 $options = array(-1 => get_string('sameasoverall', 'quiz'));
269 for ($i = 0; $i <= QUIZ_MAX_Q_DECIMAL_OPTION; $i++) {
270 $options[$i] = $i;
272 $mform->addElement('select', 'questiondecimalpoints',
273 get_string('decimalplacesquestion', 'quiz'), $options);
274 $mform->addHelpButton('questiondecimalpoints', 'decimalplacesquestion', 'quiz');
275 $mform->setAdvanced('questiondecimalpoints', $quizconfig->questiondecimalpoints_adv);
276 $mform->setDefault('questiondecimalpoints', $quizconfig->questiondecimalpoints);
278 // Show blocks during quiz attempt.
279 $mform->addElement('selectyesno', 'showblocks', get_string('showblocks', 'quiz'));
280 $mform->addHelpButton('showblocks', 'showblocks', 'quiz');
281 $mform->setAdvanced('showblocks', $quizconfig->showblocks_adv);
282 $mform->setDefault('showblocks', $quizconfig->showblocks);
284 // -------------------------------------------------------------------------------
285 $mform->addElement('header', 'security', get_string('extraattemptrestrictions', 'quiz'));
287 // Require password to begin quiz attempt.
288 $mform->addElement('passwordunmask', 'quizpassword', get_string('requirepassword', 'quiz'));
289 $mform->setType('quizpassword', PARAM_TEXT);
290 $mform->addHelpButton('quizpassword', 'requirepassword', 'quiz');
291 $mform->setAdvanced('quizpassword', $quizconfig->password_adv);
292 $mform->setDefault('quizpassword', $quizconfig->password);
294 // IP address.
295 $mform->addElement('text', 'subnet', get_string('requiresubnet', 'quiz'));
296 $mform->setType('subnet', PARAM_TEXT);
297 $mform->addHelpButton('subnet', 'requiresubnet', 'quiz');
298 $mform->setAdvanced('subnet', $quizconfig->subnet_adv);
299 $mform->setDefault('subnet', $quizconfig->subnet);
301 // Enforced time delay between quiz attempts.
302 $mform->addElement('duration', 'delay1', get_string('delay1st2nd', 'quiz'),
303 array('optional' => true));
304 $mform->addHelpButton('delay1', 'delay1st2nd', 'quiz');
305 $mform->setAdvanced('delay1', $quizconfig->delay1_adv);
306 $mform->setDefault('delay1', $quizconfig->delay1);
307 if ($this->get_max_attempts_for_any_override() < 2) {
308 $mform->disabledIf('delay1', 'attempts', 'eq', 1);
311 $mform->addElement('duration', 'delay2', get_string('delaylater', 'quiz'),
312 array('optional' => true));
313 $mform->addHelpButton('delay2', 'delaylater', 'quiz');
314 $mform->setAdvanced('delay2', $quizconfig->delay2_adv);
315 $mform->setDefault('delay2', $quizconfig->delay2);
316 if ($this->get_max_attempts_for_any_override() < 3) {
317 $mform->disabledIf('delay2', 'attempts', 'eq', 1);
318 $mform->disabledIf('delay2', 'attempts', 'eq', 2);
321 // Browser security choices.
322 $mform->addElement('select', 'browsersecurity', get_string('browsersecurity', 'quiz'),
323 quiz_access_manager::get_browser_security_choices());
324 $mform->addHelpButton('browsersecurity', 'browsersecurity', 'quiz');
325 $mform->setAdvanced('browsersecurity', $quizconfig->browsersecurity_adv);
326 $mform->setDefault('browsersecurity', $quizconfig->browsersecurity);
328 // Any other rule plugins.
329 quiz_access_manager::add_settings_form_fields($this, $mform);
331 // -------------------------------------------------------------------------------
332 $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'quiz'));
333 $mform->addHelpButton('overallfeedbackhdr', 'overallfeedback', 'quiz');
335 if (isset($this->current->grade)) {
336 $needwarning = $this->current->grade === 0;
337 } else {
338 $needwarning = $quizconfig->maximumgrade == 0;
340 if ($needwarning) {
341 $mform->addElement('static', 'nogradewarning', '',
342 get_string('nogradewarning', 'quiz'));
345 $mform->addElement('static', 'gradeboundarystatic1',
346 get_string('gradeboundary', 'quiz'), '100%');
348 $repeatarray = array();
349 $repeatedoptions = array();
350 $repeatarray[] = $mform->createElement('editor', 'feedbacktext',
351 get_string('feedback', 'quiz'), array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES,
352 'noclean' => true, 'context' => $this->context));
353 $repeatarray[] = $mform->createElement('text', 'feedbackboundaries',
354 get_string('gradeboundary', 'quiz'), array('size' => 10));
355 $repeatedoptions['feedbacktext']['type'] = PARAM_RAW;
356 $repeatedoptions['feedbackboundaries']['type'] = PARAM_RAW;
358 if (!empty($this->_instance)) {
359 $this->_feedbacks = $DB->get_records('quiz_feedback',
360 array('quizid' => $this->_instance), 'mingrade DESC');
361 } else {
362 $this->_feedbacks = array();
364 $numfeedbacks = max(count($this->_feedbacks) * 1.5, 5);
366 $nextel = $this->repeat_elements($repeatarray, $numfeedbacks - 1,
367 $repeatedoptions, 'boundary_repeats', 'boundary_add_fields', 3,
368 get_string('addmoreoverallfeedbacks', 'quiz'), true);
370 // Put some extra elements in before the button.
371 $mform->insertElementBefore($mform->createElement('editor',
372 "feedbacktext[$nextel]", get_string('feedback', 'quiz'), array('rows' => 3),
373 array('maxfiles' => EDITOR_UNLIMITED_FILES, 'noclean' => true,
374 'context' => $this->context)),
375 'boundary_add_fields');
376 $mform->insertElementBefore($mform->createElement('static',
377 'gradeboundarystatic2', get_string('gradeboundary', 'quiz'), '0%'),
378 'boundary_add_fields');
380 // Add the disabledif rules. We cannot do this using the $repeatoptions parameter to
381 // repeat_elements because we don't want to dissable the first feedbacktext.
382 for ($i = 0; $i < $nextel; $i++) {
383 $mform->disabledIf('feedbackboundaries[' . $i . ']', 'grade', 'eq', 0);
384 $mform->disabledIf('feedbacktext[' . ($i + 1) . ']', 'grade', 'eq', 0);
387 // -------------------------------------------------------------------------------
388 $this->standard_coursemodule_elements();
390 // Check and act on whether setting outcomes is considered an advanced setting.
391 $mform->setAdvanced('modoutcomes', !empty($quizconfig->outcomes_adv));
393 // The standard_coursemodule_elements method sets this to 100, but the
394 // quiz has its own setting, so use that.
395 $mform->setDefault('grade', $quizconfig->maximumgrade);
397 // -------------------------------------------------------------------------------
398 $this->add_action_buttons();
400 $PAGE->requires->yui_module('moodle-mod_quiz-modform', 'M.mod_quiz.modform.init');
403 protected function add_review_options_group($mform, $quizconfig, $whenname,
404 $when, $withhelp = false) {
405 global $OUTPUT;
407 $group = array();
408 foreach (self::$reviewfields as $field => $string) {
409 list($identifier, $component) = $string;
411 $label = get_string($identifier, $component);
412 if ($withhelp) {
413 $label .= ' ' . $OUTPUT->help_icon($identifier, $component);
416 $group[] = $mform->createElement('checkbox', $field . $whenname, '', $label);
418 $mform->addGroup($group, $whenname . 'optionsgrp',
419 get_string('review' . $whenname, 'quiz'), null, false);
421 foreach (self::$reviewfields as $field => $notused) {
422 $cfgfield = 'review' . $field;
423 if ($quizconfig->$cfgfield & $when) {
424 $mform->setDefault($field . $whenname, 1);
425 } else {
426 $mform->setDefault($field . $whenname, 0);
430 if ($whenname != 'during') {
431 $mform->disabledIf('correctness' . $whenname, 'attempt' . $whenname);
432 $mform->disabledIf('specificfeedback' . $whenname, 'attempt' . $whenname);
433 $mform->disabledIf('generalfeedback' . $whenname, 'attempt' . $whenname);
434 $mform->disabledIf('rightanswer' . $whenname, 'attempt' . $whenname);
438 protected function preprocessing_review_settings(&$toform, $whenname, $when) {
439 foreach (self::$reviewfields as $field => $notused) {
440 $fieldname = 'review' . $field;
441 if (array_key_exists($fieldname, $toform)) {
442 $toform[$field . $whenname] = $toform[$fieldname] & $when;
447 public function data_preprocessing(&$toform) {
448 if (isset($toform['grade'])) {
449 // Convert to a real number, so we don't get 0.0000.
450 $toform['grade'] = $toform['grade'] + 0;
453 if (count($this->_feedbacks)) {
454 $key = 0;
455 foreach ($this->_feedbacks as $feedback) {
456 $draftid = file_get_submitted_draft_itemid('feedbacktext['.$key.']');
457 $toform['feedbacktext['.$key.']']['text'] = file_prepare_draft_area(
458 $draftid, // Draftid.
459 $this->context->id, // Context.
460 'mod_quiz', // Component.
461 'feedback', // Filarea.
462 !empty($feedback->id) ? (int) $feedback->id : null, // Itemid.
463 null,
464 $feedback->feedbacktext // Text.
466 $toform['feedbacktext['.$key.']']['format'] = $feedback->feedbacktextformat;
467 $toform['feedbacktext['.$key.']']['itemid'] = $draftid;
469 if ($toform['grade'] == 0) {
470 // When a quiz is un-graded, there can only be one lot of
471 // feedback. If the quiz previously had a maximum grade and
472 // several lots of feedback, we must now avoid putting text
473 // into input boxes that are disabled, but which the
474 // validation will insist are blank.
475 break;
478 if ($feedback->mingrade > 0) {
479 $toform['feedbackboundaries['.$key.']'] =
480 round(100.0 * $feedback->mingrade / $toform['grade'], 6) . '%';
482 $key++;
486 if (isset($toform['timelimit'])) {
487 $toform['timelimitenable'] = $toform['timelimit'] > 0;
490 $this->preprocessing_review_settings($toform, 'during',
491 mod_quiz_display_options::DURING);
492 $this->preprocessing_review_settings($toform, 'immediately',
493 mod_quiz_display_options::IMMEDIATELY_AFTER);
494 $this->preprocessing_review_settings($toform, 'open',
495 mod_quiz_display_options::LATER_WHILE_OPEN);
496 $this->preprocessing_review_settings($toform, 'closed',
497 mod_quiz_display_options::AFTER_CLOSE);
498 $toform['attemptduring'] = true;
499 $toform['overallfeedbackduring'] = false;
501 // Password field - different in form to stop browsers that remember
502 // passwords from getting confused.
503 if (isset($toform['password'])) {
504 $toform['quizpassword'] = $toform['password'];
505 unset($toform['password']);
508 // Load any settings belonging to the access rules.
509 if (!empty($toform['instance'])) {
510 $accesssettings = quiz_access_manager::load_settings($toform['instance']);
511 foreach ($accesssettings as $name => $value) {
512 $toform[$name] = $value;
517 public function validation($data, $files) {
518 $errors = parent::validation($data, $files);
520 // Check open and close times are consistent.
521 if ($data['timeopen'] != 0 && $data['timeclose'] != 0 &&
522 $data['timeclose'] < $data['timeopen']) {
523 $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
526 // Check that the grace period is not too short.
527 if ($data['overduehandling'] == 'graceperiod') {
528 $graceperiodmin = get_config('quiz', 'graceperiodmin');
529 if ($data['graceperiod'] <= $graceperiodmin) {
530 $errors['graceperiod'] = get_string('graceperiodtoosmall', 'quiz', format_time($graceperiodmin));
534 // Check the boundary value is a number or a percentage, and in range.
535 $i = 0;
536 while (!empty($data['feedbackboundaries'][$i] )) {
537 $boundary = trim($data['feedbackboundaries'][$i]);
538 if (strlen($boundary) > 0) {
539 if ($boundary[strlen($boundary) - 1] == '%') {
540 $boundary = trim(substr($boundary, 0, -1));
541 if (is_numeric($boundary)) {
542 $boundary = $boundary * $data['grade'] / 100.0;
543 } else {
544 $errors["feedbackboundaries[$i]"] =
545 get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
547 } else if (!is_numeric($boundary)) {
548 $errors["feedbackboundaries[$i]"] =
549 get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
552 if (is_numeric($boundary) && $boundary <= 0 || $boundary >= $data['grade'] ) {
553 $errors["feedbackboundaries[$i]"] =
554 get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
556 if (is_numeric($boundary) && $i > 0 &&
557 $boundary >= $data['feedbackboundaries'][$i - 1]) {
558 $errors["feedbackboundaries[$i]"] =
559 get_string('feedbackerrororder', 'quiz', $i + 1);
561 $data['feedbackboundaries'][$i] = $boundary;
562 $i += 1;
564 $numboundaries = $i;
566 // Check there is nothing in the remaining unused fields.
567 if (!empty($data['feedbackboundaries'])) {
568 for ($i = $numboundaries; $i < count($data['feedbackboundaries']); $i += 1) {
569 if (!empty($data['feedbackboundaries'][$i] ) &&
570 trim($data['feedbackboundaries'][$i] ) != '') {
571 $errors["feedbackboundaries[$i]"] =
572 get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
576 for ($i = $numboundaries + 1; $i < count($data['feedbacktext']); $i += 1) {
577 if (!empty($data['feedbacktext'][$i]['text']) &&
578 trim($data['feedbacktext'][$i]['text'] ) != '') {
579 $errors["feedbacktext[$i]"] =
580 get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
584 // Any other rule plugins.
585 $errors = quiz_access_manager::validate_settings_form_fields($errors, $data, $files, $this);
587 return $errors;
591 * Display module-specific activity completion rules.
592 * Part of the API defined by moodleform_mod
593 * @return array Array of string IDs of added items, empty array if none
595 public function add_completion_rules() {
596 $mform = $this->_form;
597 $items = array();
599 $group = array();
600 $group[] = $mform->createElement('advcheckbox', 'completionpass', null, get_string('completionpass', 'quiz'),
601 array('group' => 'cpass'));
603 $group[] = $mform->createElement('advcheckbox', 'completionattemptsexhausted', null,
604 get_string('completionattemptsexhausted', 'quiz'),
605 array('group' => 'cattempts'));
606 $mform->disabledIf('completionattemptsexhausted', 'completionpass', 'notchecked');
607 $mform->addGroup($group, 'completionpassgroup', get_string('completionpass', 'quiz'), ' &nbsp; ', false);
608 $mform->addHelpButton('completionpassgroup', 'completionpass', 'quiz');
609 $items[] = 'completionpassgroup';
610 return $items;
614 * Called during validation. Indicates whether a module-specific completion rule is selected.
616 * @param array $data Input data (not yet validated)
617 * @return bool True if one or more rules is enabled, false if none are.
619 public function completion_rule_enabled($data) {
620 return !empty($data['completionattemptsexhausted']) || !empty($data['completionpass']);
624 * Get the maximum number of attempts that anyone might have due to a user
625 * or group override. Used to decide whether disabledIf rules should be applied.
626 * @return int the number of attempts allowed. For the purpose of this method,
627 * unlimited is returned as 1000, not 0.
629 public function get_max_attempts_for_any_override() {
630 global $DB;
632 if (empty($this->_instance)) {
633 // Quiz not created yet, so no overrides.
634 return 1;
637 if ($this->maxattemptsanyoverride === null) {
638 $this->maxattemptsanyoverride = $DB->get_field_sql("
639 SELECT MAX(CASE WHEN attempts = 0 THEN 1000 ELSE attempts END)
640 FROM {quiz_overrides}
641 WHERE quiz = ?",
642 array($this->_instance));
643 if ($this->maxattemptsanyoverride < 1) {
644 // This happens when no override alters the number of attempts.
645 $this->maxattemptsanyoverride = 1;
649 return $this->maxattemptsanyoverride;