MDL-37998 quiz settings: disableif rules should account for overrides.
[moodle.git] / mod / quiz / mod_form.php
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/>.
17 /**
18  * Defines the quiz module ettings form.
19  *
20  * @package    mod_quiz
21  * @copyright  2006 Jamie Pratt
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
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.
34  *
35  * @copyright  2006 Jamie Pratt
36  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37  */
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'),
57         );
58         parent::__construct($current, $section, $cm, $course);
59     }
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);
75         }
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         $mform->addElement('hidden', 'grade', $quizconfig->maximumgrade);
124         $mform->setType('grade', PARAM_FLOAT);
126         // Number of attempts.
127         $attemptoptions = array('0' => get_string('unlimited'));
128         for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) {
129             $attemptoptions[$i] = $i;
130         }
131         $mform->addElement('select', 'attempts', get_string('attemptsallowed', 'quiz'),
132                 $attemptoptions);
133         $mform->setAdvanced('attempts', $quizconfig->attempts_adv);
134         $mform->setDefault('attempts', $quizconfig->attempts);
136         // Grading method.
137         $mform->addElement('select', 'grademethod', get_string('grademethod', 'quiz'),
138                 quiz_get_grading_options());
139         $mform->addHelpButton('grademethod', 'grademethod', 'quiz');
140         $mform->setAdvanced('grademethod', $quizconfig->grademethod_adv);
141         $mform->setDefault('grademethod', $quizconfig->grademethod);
142         if ($this->get_max_attempts_for_any_override() < 2) {
143             $mform->disabledIf('grademethod', 'attempts', 'eq', 1);
144         }
146         // -------------------------------------------------------------------------------
147         $mform->addElement('header', 'layouthdr', get_string('layout', 'quiz'));
149         // Shuffle questions.
150         $shuffleoptions = array(
151             0 => get_string('asshownoneditscreen', 'quiz'),
152             1 => get_string('shuffledrandomly', 'quiz')
153         );
154         $mform->addElement('select', 'shufflequestions', get_string('questionorder', 'quiz'),
155                 $shuffleoptions, array('id' => 'id_shufflequestions'));
156         $mform->setAdvanced('shufflequestions', $quizconfig->shufflequestions_adv);
157         $mform->setDefault('shufflequestions', $quizconfig->shufflequestions);
159         // Questions per page.
160         $pageoptions = array();
161         $pageoptions[0] = get_string('neverallononepage', 'quiz');
162         $pageoptions[1] = get_string('everyquestion', 'quiz');
163         for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
164             $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
165         }
167         $pagegroup = array();
168         $pagegroup[] = $mform->createElement('select', 'questionsperpage',
169                 get_string('newpage', 'quiz'), $pageoptions, array('id' => 'id_questionsperpage'));
170         $mform->setDefault('questionsperpage', $quizconfig->questionsperpage);
172         if (!empty($this->_cm)) {
173             $pagegroup[] = $mform->createElement('checkbox', 'repaginatenow', '',
174                     get_string('repaginatenow', 'quiz'), array('id' => 'id_repaginatenow'));
175             $mform->disabledIf('repaginatenow', 'shufflequestions', 'eq', 1);
177             $PAGE->requires->js('/question/qengine.js');
178             $module = array(
179                 'name'      => 'mod_quiz_edit',
180                 'fullpath'  => '/mod/quiz/edit.js',
181                 'requires'  => array('yui2-dom', 'yui2-event', 'yui2-container'),
182                 'strings'   => array(),
183                 'async'     => false,
184             );
185             $PAGE->requires->js_init_call('quiz_settings_init', null, false, $module);
186         }
188         $mform->addGroup($pagegroup, 'questionsperpagegrp',
189                 get_string('newpage', 'quiz'), null, false);
190         $mform->addHelpButton('questionsperpagegrp', 'newpage', 'quiz');
191         $mform->setAdvanced('questionsperpagegrp', $quizconfig->questionsperpage_adv);
193         // Navigation method.
194         $mform->addElement('select', 'navmethod', get_string('navmethod', 'quiz'),
195                 quiz_get_navigation_options());
196         $mform->addHelpButton('navmethod', 'navmethod', 'quiz');
197         $mform->setAdvanced('navmethod', $quizconfig->navmethod_adv);
198         $mform->setDefault('navmethod', $quizconfig->navmethod);
200         // -------------------------------------------------------------------------------
201         $mform->addElement('header', 'interactionhdr', get_string('questionbehaviour', 'quiz'));
203         // Shuffle within questions.
204         $mform->addElement('selectyesno', 'shuffleanswers', get_string('shufflewithin', 'quiz'));
205         $mform->addHelpButton('shuffleanswers', 'shufflewithin', 'quiz');
206         $mform->setAdvanced('shuffleanswers', $quizconfig->shuffleanswers_adv);
207         $mform->setDefault('shuffleanswers', $quizconfig->shuffleanswers);
209         // How questions behave (question behaviour).
210         if (!empty($this->current->preferredbehaviour)) {
211             $currentbehaviour = $this->current->preferredbehaviour;
212         } else {
213             $currentbehaviour = '';
214         }
215         $behaviours = question_engine::get_behaviour_options($currentbehaviour);
216         $mform->addElement('select', 'preferredbehaviour',
217                 get_string('howquestionsbehave', 'question'), $behaviours);
218         $mform->addHelpButton('preferredbehaviour', 'howquestionsbehave', 'question');
219         $mform->setDefault('preferredbehaviour', $quizconfig->preferredbehaviour);
221         // Each attempt builds on last.
222         $mform->addElement('selectyesno', 'attemptonlast',
223                 get_string('eachattemptbuildsonthelast', 'quiz'));
224         $mform->addHelpButton('attemptonlast', 'eachattemptbuildsonthelast', 'quiz');
225         $mform->setAdvanced('attemptonlast', $quizconfig->attemptonlast_adv);
226         $mform->setDefault('attemptonlast', $quizconfig->attemptonlast);
227         if ($this->get_max_attempts_for_any_override() < 2) {
228             $mform->disabledIf('attemptonlast', 'attempts', 'eq', 1);
229         }
231         // -------------------------------------------------------------------------------
232         $mform->addElement('header', 'reviewoptionshdr',
233                 get_string('reviewoptionsheading', 'quiz'));
234         $mform->addHelpButton('reviewoptionshdr', 'reviewoptionsheading', 'quiz');
236         // Review options.
237         $this->add_review_options_group($mform, $quizconfig, 'during',
238                 mod_quiz_display_options::DURING, true);
239         $this->add_review_options_group($mform, $quizconfig, 'immediately',
240                 mod_quiz_display_options::IMMEDIATELY_AFTER);
241         $this->add_review_options_group($mform, $quizconfig, 'open',
242                 mod_quiz_display_options::LATER_WHILE_OPEN);
243         $this->add_review_options_group($mform, $quizconfig, 'closed',
244                 mod_quiz_display_options::AFTER_CLOSE);
246         foreach ($behaviours as $behaviour => $notused) {
247             $unusedoptions = question_engine::get_behaviour_unused_display_options($behaviour);
248             foreach ($unusedoptions as $unusedoption) {
249                 $mform->disabledIf($unusedoption . 'during', 'preferredbehaviour',
250                         'eq', $behaviour);
251             }
252         }
253         $mform->disabledIf('attemptduring', 'preferredbehaviour',
254                 'neq', 'wontmatch');
255         $mform->disabledIf('overallfeedbackduring', 'preferredbehaviour',
256                 'neq', 'wontmatch');
258         // -------------------------------------------------------------------------------
259         $mform->addElement('header', 'display', get_string('appearance'));
261         // Show user picture.
262         $mform->addElement('select', 'showuserpicture', get_string('showuserpicture', 'quiz'),
263                 quiz_get_user_image_options());
264         $mform->addHelpButton('showuserpicture', 'showuserpicture', 'quiz');
265         $mform->setAdvanced('showuserpicture', $quizconfig->showuserpicture_adv);
266         $mform->setDefault('showuserpicture', $quizconfig->showuserpicture);
268         // Overall decimal points.
269         $options = array();
270         for ($i = 0; $i <= QUIZ_MAX_DECIMAL_OPTION; $i++) {
271             $options[$i] = $i;
272         }
273         $mform->addElement('select', 'decimalpoints', get_string('decimalplaces', 'quiz'),
274                 $options);
275         $mform->addHelpButton('decimalpoints', 'decimalplaces', 'quiz');
276         $mform->setAdvanced('decimalpoints', $quizconfig->decimalpoints_adv);
277         $mform->setDefault('decimalpoints', $quizconfig->decimalpoints);
279         // Question decimal points.
280         $options = array(-1 => get_string('sameasoverall', 'quiz'));
281         for ($i = 0; $i <= QUIZ_MAX_Q_DECIMAL_OPTION; $i++) {
282             $options[$i] = $i;
283         }
284         $mform->addElement('select', 'questiondecimalpoints',
285                 get_string('decimalplacesquestion', 'quiz'), $options);
286         $mform->addHelpButton('questiondecimalpoints', 'decimalplacesquestion', 'quiz');
287         $mform->setAdvanced('questiondecimalpoints', $quizconfig->questiondecimalpoints_adv);
288         $mform->setDefault('questiondecimalpoints', $quizconfig->questiondecimalpoints);
290         // Show blocks during quiz attempt.
291         $mform->addElement('selectyesno', 'showblocks', get_string('showblocks', 'quiz'));
292         $mform->addHelpButton('showblocks', 'showblocks', 'quiz');
293         $mform->setAdvanced('showblocks', $quizconfig->showblocks_adv);
294         $mform->setDefault('showblocks', $quizconfig->showblocks);
296         // -------------------------------------------------------------------------------
297         $mform->addElement('header', 'security', get_string('extraattemptrestrictions', 'quiz'));
299         // Require password to begin quiz attempt.
300         $mform->addElement('passwordunmask', 'quizpassword', get_string('requirepassword', 'quiz'));
301         $mform->setType('quizpassword', PARAM_TEXT);
302         $mform->addHelpButton('quizpassword', 'requirepassword', 'quiz');
303         $mform->setAdvanced('quizpassword', $quizconfig->password_adv);
304         $mform->setDefault('quizpassword', $quizconfig->password);
306         // IP address.
307         $mform->addElement('text', 'subnet', get_string('requiresubnet', 'quiz'));
308         $mform->setType('subnet', PARAM_TEXT);
309         $mform->addHelpButton('subnet', 'requiresubnet', 'quiz');
310         $mform->setAdvanced('subnet', $quizconfig->subnet_adv);
311         $mform->setDefault('subnet', $quizconfig->subnet);
313         // Enforced time delay between quiz attempts.
314         $mform->addElement('duration', 'delay1', get_string('delay1st2nd', 'quiz'),
315                 array('optional' => true));
316         $mform->addHelpButton('delay1', 'delay1st2nd', 'quiz');
317         $mform->setAdvanced('delay1', $quizconfig->delay1_adv);
318         $mform->setDefault('delay1', $quizconfig->delay1);
319         if ($this->get_max_attempts_for_any_override() < 2) {
320             $mform->disabledIf('delay1', 'attempts', 'eq', 1);
321         }
323         $mform->addElement('duration', 'delay2', get_string('delaylater', 'quiz'),
324                 array('optional' => true));
325         $mform->addHelpButton('delay2', 'delaylater', 'quiz');
326         $mform->setAdvanced('delay2', $quizconfig->delay2_adv);
327         $mform->setDefault('delay2', $quizconfig->delay2);
328         if ($this->get_max_attempts_for_any_override() < 3) {
329             $mform->disabledIf('delay2', 'attempts', 'eq', 1);
330             $mform->disabledIf('delay2', 'attempts', 'eq', 2);
331         }
333         // Browser security choices.
334         $mform->addElement('select', 'browsersecurity', get_string('browsersecurity', 'quiz'),
335                 quiz_access_manager::get_browser_security_choices());
336         $mform->addHelpButton('browsersecurity', 'browsersecurity', 'quiz');
337         $mform->setAdvanced('browsersecurity', $quizconfig->browsersecurity_adv);
338         $mform->setDefault('browsersecurity', $quizconfig->browsersecurity);
340         // Any other rule plugins.
341         quiz_access_manager::add_settings_form_fields($this, $mform);
343         // -------------------------------------------------------------------------------
344         $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'quiz'));
345         $mform->addHelpButton('overallfeedbackhdr', 'overallfeedback', 'quiz');
347         if (isset($this->current->grade)) {
348             $needwarning = $this->current->grade === 0;
349         } else {
350             $needwarning = $quizconfig->maximumgrade == 0;
351         }
352         if ($needwarning) {
353             $mform->addElement('static', 'nogradewarning', '',
354                     get_string('nogradewarning', 'quiz'));
355         }
357         $mform->addElement('static', 'gradeboundarystatic1',
358                 get_string('gradeboundary', 'quiz'), '100%');
360         $repeatarray = array();
361         $repeatedoptions = array();
362         $repeatarray[] = $mform->createElement('editor', 'feedbacktext',
363                 get_string('feedback', 'quiz'), array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES,
364                         'noclean' => true, 'context' => $this->context));
365         $repeatarray[] = $mform->createElement('text', 'feedbackboundaries',
366                 get_string('gradeboundary', 'quiz'), array('size' => 10));
367         $repeatedoptions['feedbacktext']['type'] = PARAM_RAW;
368         $repeatedoptions['feedbackboundaries']['type'] = PARAM_RAW;
370         if (!empty($this->_instance)) {
371             $this->_feedbacks = $DB->get_records('quiz_feedback',
372                     array('quizid' => $this->_instance), 'mingrade DESC');
373         } else {
374             $this->_feedbacks = array();
375         }
376         $numfeedbacks = max(count($this->_feedbacks) * 1.5, 5);
378         $nextel = $this->repeat_elements($repeatarray, $numfeedbacks - 1,
379                 $repeatedoptions, 'boundary_repeats', 'boundary_add_fields', 3,
380                 get_string('addmoreoverallfeedbacks', 'quiz'), true);
382         // Put some extra elements in before the button.
383         $mform->insertElementBefore($mform->createElement('editor',
384                 "feedbacktext[$nextel]", get_string('feedback', 'quiz'), array('rows' => 3),
385                 array('maxfiles' => EDITOR_UNLIMITED_FILES, 'noclean' => true,
386                       'context' => $this->context)),
387                 'boundary_add_fields');
388         $mform->insertElementBefore($mform->createElement('static',
389                 'gradeboundarystatic2', get_string('gradeboundary', 'quiz'), '0%'),
390                 'boundary_add_fields');
392         // Add the disabledif rules. We cannot do this using the $repeatoptions parameter to
393         // repeat_elements because we don't want to dissable the first feedbacktext.
394         for ($i = 0; $i < $nextel; $i++) {
395             $mform->disabledIf('feedbackboundaries[' . $i . ']', 'grade', 'eq', 0);
396             $mform->disabledIf('feedbacktext[' . ($i + 1) . ']', 'grade', 'eq', 0);
397         }
399         // -------------------------------------------------------------------------------
400         $this->standard_coursemodule_elements();
402         // Check and act on whether setting outcomes is considered an advanced setting.
403         $mform->setAdvanced('modoutcomes', !empty($quizconfig->outcomes_adv));
405         // The standard_coursemodule_elements method sets this to 100, but the
406         // quiz has its own setting, so use that.
407         $mform->setDefault('grade', $quizconfig->maximumgrade);
409         // -------------------------------------------------------------------------------
410         $this->add_action_buttons();
411     }
413     protected function add_review_options_group($mform, $quizconfig, $whenname,
414             $when, $withhelp = false) {
415         global $OUTPUT;
417         $group = array();
418         foreach (self::$reviewfields as $field => $string) {
419             list($identifier, $component) = $string;
421             $label = get_string($identifier, $component);
422             if ($withhelp) {
423                 $label .= ' ' . $OUTPUT->help_icon($identifier, $component);
424             }
426             $group[] = $mform->createElement('checkbox', $field . $whenname, '', $label);
427         }
428         $mform->addGroup($group, $whenname . 'optionsgrp',
429                 get_string('review' . $whenname, 'quiz'), null, false);
431         foreach (self::$reviewfields as $field => $notused) {
432             $cfgfield = 'review' . $field;
433             if ($quizconfig->$cfgfield & $when) {
434                 $mform->setDefault($field . $whenname, 1);
435             } else {
436                 $mform->setDefault($field . $whenname, 0);
437             }
438         }
440         if ($whenname != 'during') {
441             $mform->disabledIf('correctness' . $whenname, 'attempt' . $whenname);
442             $mform->disabledIf('specificfeedback' . $whenname, 'attempt' . $whenname);
443             $mform->disabledIf('generalfeedback' . $whenname, 'attempt' . $whenname);
444             $mform->disabledIf('rightanswer' . $whenname, 'attempt' . $whenname);
445         }
446     }
448     protected function preprocessing_review_settings(&$toform, $whenname, $when) {
449         foreach (self::$reviewfields as $field => $notused) {
450             $fieldname = 'review' . $field;
451             if (array_key_exists($fieldname, $toform)) {
452                 $toform[$field . $whenname] = $toform[$fieldname] & $when;
453             }
454         }
455     }
457     public function data_preprocessing(&$toform) {
458         if (isset($toform['grade'])) {
459             // Convert to a real number, so we don't get 0.0000.
460             $toform['grade'] = $toform['grade'] + 0;
461         }
463         if (count($this->_feedbacks)) {
464             $key = 0;
465             foreach ($this->_feedbacks as $feedback) {
466                 $draftid = file_get_submitted_draft_itemid('feedbacktext['.$key.']');
467                 $toform['feedbacktext['.$key.']']['text'] = file_prepare_draft_area(
468                     $draftid,               // Draftid.
469                     $this->context->id,     // Context.
470                     'mod_quiz',             // Component.
471                     'feedback',             // Filarea.
472                     !empty($feedback->id) ? (int) $feedback->id : null, // Itemid.
473                     null,
474                     $feedback->feedbacktext // Text.
475                 );
476                 $toform['feedbacktext['.$key.']']['format'] = $feedback->feedbacktextformat;
477                 $toform['feedbacktext['.$key.']']['itemid'] = $draftid;
479                 if ($toform['grade'] == 0) {
480                     // When a quiz is un-graded, there can only be one lot of
481                     // feedback. If the quiz previously had a maximum grade and
482                     // several lots of feedback, we must now avoid putting text
483                     // into input boxes that are disabled, but which the
484                     // validation will insist are blank.
485                     break;
486                 }
488                 if ($feedback->mingrade > 0) {
489                     $toform['feedbackboundaries['.$key.']'] =
490                             (100.0 * $feedback->mingrade / $toform['grade']) . '%';
491                 }
492                 $key++;
493             }
494         }
496         if (isset($toform['timelimit'])) {
497             $toform['timelimitenable'] = $toform['timelimit'] > 0;
498         }
500         $this->preprocessing_review_settings($toform, 'during',
501                 mod_quiz_display_options::DURING);
502         $this->preprocessing_review_settings($toform, 'immediately',
503                 mod_quiz_display_options::IMMEDIATELY_AFTER);
504         $this->preprocessing_review_settings($toform, 'open',
505                 mod_quiz_display_options::LATER_WHILE_OPEN);
506         $this->preprocessing_review_settings($toform, 'closed',
507                 mod_quiz_display_options::AFTER_CLOSE);
508         $toform['attemptduring'] = true;
509         $toform['overallfeedbackduring'] = false;
511         // Password field - different in form to stop browsers that remember
512         // passwords from getting confused.
513         if (isset($toform['password'])) {
514             $toform['quizpassword'] = $toform['password'];
515             unset($toform['password']);
516         }
518         // Load any settings belonging to the access rules.
519         if (!empty($toform['instance'])) {
520             $accesssettings = quiz_access_manager::load_settings($toform['instance']);
521             foreach ($accesssettings as $name => $value) {
522                 $toform[$name] = $value;
523             }
524         }
525     }
527     public function validation($data, $files) {
528         $errors = parent::validation($data, $files);
530         // Check open and close times are consistent.
531         if ($data['timeopen'] != 0 && $data['timeclose'] != 0 &&
532                 $data['timeclose'] < $data['timeopen']) {
533             $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
534         }
536         // Check that the grace period is not too short.
537         if ($data['overduehandling'] == 'graceperiod') {
538             $graceperiodmin = get_config('quiz', 'graceperiodmin');
539             if ($data['graceperiod'] <= $graceperiodmin) {
540                 $errors['graceperiod'] = get_string('graceperiodtoosmall', 'quiz', format_time($graceperiodmin));
541             }
542         }
544         // Check the boundary value is a number or a percentage, and in range.
545         $i = 0;
546         while (!empty($data['feedbackboundaries'][$i] )) {
547             $boundary = trim($data['feedbackboundaries'][$i]);
548             if (strlen($boundary) > 0) {
549                 if ($boundary[strlen($boundary) - 1] == '%') {
550                     $boundary = trim(substr($boundary, 0, -1));
551                     if (is_numeric($boundary)) {
552                         $boundary = $boundary * $data['grade'] / 100.0;
553                     } else {
554                         $errors["feedbackboundaries[$i]"] =
555                                 get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
556                     }
557                 } else if (!is_numeric($boundary)) {
558                     $errors["feedbackboundaries[$i]"] =
559                             get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
560                 }
561             }
562             if (is_numeric($boundary) && $boundary <= 0 || $boundary >= $data['grade'] ) {
563                 $errors["feedbackboundaries[$i]"] =
564                         get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
565             }
566             if (is_numeric($boundary) && $i > 0 &&
567                     $boundary >= $data['feedbackboundaries'][$i - 1]) {
568                 $errors["feedbackboundaries[$i]"] =
569                         get_string('feedbackerrororder', 'quiz', $i + 1);
570             }
571             $data['feedbackboundaries'][$i] = $boundary;
572             $i += 1;
573         }
574         $numboundaries = $i;
576         // Check there is nothing in the remaining unused fields.
577         if (!empty($data['feedbackboundaries'])) {
578             for ($i = $numboundaries; $i < count($data['feedbackboundaries']); $i += 1) {
579                 if (!empty($data['feedbackboundaries'][$i] ) &&
580                         trim($data['feedbackboundaries'][$i] ) != '') {
581                     $errors["feedbackboundaries[$i]"] =
582                             get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
583                 }
584             }
585         }
586         for ($i = $numboundaries + 1; $i < count($data['feedbacktext']); $i += 1) {
587             if (!empty($data['feedbacktext'][$i]['text']) &&
588                     trim($data['feedbacktext'][$i]['text'] ) != '') {
589                 $errors["feedbacktext[$i]"] =
590                         get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
591             }
592         }
594         // Any other rule plugins.
595         $errors = quiz_access_manager::validate_settings_form_fields($errors, $data, $files, $this);
597         return $errors;
598     }
600     /**
601      * Display module-specific activity completion rules.
602      * Part of the API defined by moodleform_mod
603      * @return array Array of string IDs of added items, empty array if none
604      */
605     public function add_completion_rules() {
606         $mform = $this->_form;
607         $items = array();
609         $group = array();
610         $group[] = $mform->createElement('advcheckbox', 'completionpass', null, get_string('completionpass', 'quiz'),
611                 array('group' => 'cpass'));
613         $group[] = $mform->createElement('advcheckbox', 'completionattemptsexhausted', null,
614                 get_string('completionattemptsexhausted', 'quiz'),
615                 array('group' => 'cattempts'));
616         $mform->disabledIf('completionattemptsexhausted', 'completionpass', 'notchecked');
617         $mform->addGroup($group, 'completionpassgroup', get_string('completionpass', 'quiz'), ' &nbsp; ', false);
618         $mform->addHelpButton('completionpassgroup', 'completionpass', 'quiz');
619         $items[] = 'completionpassgroup';
620         return $items;
621     }
623     /**
624      * Called during validation. Indicates whether a module-specific completion rule is selected.
625      *
626      * @param array $data Input data (not yet validated)
627      * @return bool True if one or more rules is enabled, false if none are.
628      */
629     public function completion_rule_enabled($data) {
630         return !empty($data['completionattemptsexhausted']) || !empty($data['completionpass']);
631     }
633     /**
634      * Get the maximum number of attempts that anyone might have due to a user
635      * or group override. Used to decide whether disabledIf rules should be applied.
636      * @return int the number of attempts allowed. For the purpose of this method,
637      * unlimited is returned as 1000, not 0.
638      */
639     public function get_max_attempts_for_any_override() {
640         global $DB;
642         if (empty($this->_instance)) {
643             // Quiz not created yet, so no overrides.
644             return 1;
645         }
647         if ($this->maxattemptsanyoverride === null) {
648             $this->maxattemptsanyoverride = $DB->get_field_sql("
649                     SELECT MAX(CASE WHEN attempts = 0 THEN 1000 ELSE attempts END)
650                       FROM {quiz_overrides}
651                      WHERE quiz = ?",
652                     array($this->_instance));
653             if ($this->maxattemptsanyoverride < 1) {
654                 // This happens when no override alters the number of attempts.
655                 $this->maxattemptsanyoverride = 1;
656             }
657         }
659         return $this->maxattemptsanyoverride;
660     }