Merge branch 'wip-mdl-41266' of https://github.com/rajeshtaneja/moodle
[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
21  * @subpackage quiz
22  * @copyright  2006 Jamie Pratt
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/course/moodleform_mod.php');
30 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
33 /**
34  * Settings form for the quiz module.
35  *
36  * @copyright  2006 Jamie Pratt
37  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38  */
39 class mod_quiz_mod_form extends moodleform_mod {
40     /** @var array options to be used with date_time_selector fields in the quiz. */
41     public static $datefieldoptions = array('optional' => true, 'step' => 1);
43     protected $_feedbacks;
44     protected static $reviewfields = array(); // Initialised in the constructor.
46     public function __construct($current, $section, $cm, $course) {
47         self::$reviewfields = array(
48             'attempt'          => array('theattempt', 'quiz'),
49             'correctness'      => array('whethercorrect', 'question'),
50             'marks'            => array('marks', 'quiz'),
51             'specificfeedback' => array('specificfeedback', 'question'),
52             'generalfeedback'  => array('generalfeedback', 'question'),
53             'rightanswer'      => array('rightanswer', 'question'),
54             'overallfeedback'  => array('reviewoverallfeedback', 'quiz'),
55         );
56         parent::__construct($current, $section, $cm, $course);
57     }
59     protected function definition() {
60         global $COURSE, $CFG, $DB, $PAGE;
61         $quizconfig = get_config('quiz');
62         $mform = $this->_form;
64         // -------------------------------------------------------------------------------
65         $mform->addElement('header', 'general', get_string('general', 'form'));
67         // Name.
68         $mform->addElement('text', 'name', get_string('name'), array('size'=>'64'));
69         if (!empty($CFG->formatstringstriptags)) {
70             $mform->setType('name', PARAM_TEXT);
71         } else {
72             $mform->setType('name', PARAM_CLEANHTML);
73         }
74         $mform->addRule('name', null, 'required', null, 'client');
75         $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
77         // Introduction.
78         $this->add_intro_editor(false, get_string('introduction', 'quiz'));
80         // -------------------------------------------------------------------------------
81         $mform->addElement('header', 'timing', get_string('timing', 'quiz'));
83         // Open and close dates.
84         $mform->addElement('date_time_selector', 'timeopen', get_string('quizopen', 'quiz'),
85                 self::$datefieldoptions);
86         $mform->addHelpButton('timeopen', 'quizopenclose', 'quiz');
88         $mform->addElement('date_time_selector', 'timeclose', get_string('quizclose', 'quiz'),
89                 self::$datefieldoptions);
91         // Time limit.
92         $mform->addElement('duration', 'timelimit', get_string('timelimit', 'quiz'),
93                 array('optional' => true));
94         $mform->addHelpButton('timelimit', 'timelimit', 'quiz');
95         $mform->setAdvanced('timelimit', $quizconfig->timelimit_adv);
96         $mform->setDefault('timelimit', $quizconfig->timelimit);
98         // What to do with overdue attempts.
99         $mform->addElement('select', 'overduehandling', get_string('overduehandling', 'quiz'),
100                 quiz_get_overdue_handling_options());
101         $mform->addHelpButton('overduehandling', 'overduehandling', 'quiz');
102         $mform->setAdvanced('overduehandling', $quizconfig->overduehandling_adv);
103         $mform->setDefault('overduehandling', $quizconfig->overduehandling);
104         // TODO Formslib does OR logic on disableif, and we need AND logic here.
105         // $mform->disabledIf('overduehandling', 'timelimit', 'eq', 0);
106         // $mform->disabledIf('overduehandling', 'timeclose', 'eq', 0);
108         // Grace period time.
109         $mform->addElement('duration', 'graceperiod', get_string('graceperiod', 'quiz'),
110                 array('optional' => true));
111         $mform->addHelpButton('graceperiod', 'graceperiod', 'quiz');
112         $mform->setAdvanced('graceperiod', $quizconfig->graceperiod_adv);
113         $mform->setDefault('graceperiod', $quizconfig->graceperiod);
114         $mform->disabledIf('graceperiod', 'overduehandling', 'neq', 'graceperiod');
116         // -------------------------------------------------------------------------------
117         // Grade settings.
118         $this->standard_grading_coursemodule_elements();
120         $mform->removeElement('grade');
121         $mform->addElement('hidden', 'grade', $quizconfig->maximumgrade);
122         $mform->setType('grade', PARAM_FLOAT);
124         // Number of attempts.
125         $attemptoptions = array('0' => get_string('unlimited'));
126         for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) {
127             $attemptoptions[$i] = $i;
128         }
129         $mform->addElement('select', 'attempts', get_string('attemptsallowed', 'quiz'),
130                 $attemptoptions);
131         $mform->setAdvanced('attempts', $quizconfig->attempts_adv);
132         $mform->setDefault('attempts', $quizconfig->attempts);
134         // Grading method.
135         $mform->addElement('select', 'grademethod', get_string('grademethod', 'quiz'),
136                 quiz_get_grading_options());
137         $mform->addHelpButton('grademethod', 'grademethod', 'quiz');
138         $mform->setAdvanced('grademethod', $quizconfig->grademethod_adv);
139         $mform->setDefault('grademethod', $quizconfig->grademethod);
140         $mform->disabledIf('grademethod', 'attempts', 'eq', 1);
142         // -------------------------------------------------------------------------------
143         $mform->addElement('header', 'layouthdr', get_string('layout', 'quiz'));
145         // Shuffle questions.
146         $shuffleoptions = array(
147             0 => get_string('asshownoneditscreen', 'quiz'),
148             1 => get_string('shuffledrandomly', 'quiz')
149         );
150         $mform->addElement('select', 'shufflequestions', get_string('questionorder', 'quiz'),
151                 $shuffleoptions, array('id' => 'id_shufflequestions'));
152         $mform->setAdvanced('shufflequestions', $quizconfig->shufflequestions_adv);
153         $mform->setDefault('shufflequestions', $quizconfig->shufflequestions);
155         // Questions per page.
156         $pageoptions = array();
157         $pageoptions[0] = get_string('neverallononepage', 'quiz');
158         $pageoptions[1] = get_string('everyquestion', 'quiz');
159         for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
160             $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
161         }
163         $pagegroup = array();
164         $pagegroup[] = $mform->createElement('select', 'questionsperpage',
165                 get_string('newpage', 'quiz'), $pageoptions, array('id' => 'id_questionsperpage'));
166         $mform->setDefault('questionsperpage', $quizconfig->questionsperpage);
168         if (!empty($this->_cm)) {
169             $pagegroup[] = $mform->createElement('checkbox', 'repaginatenow', '',
170                     get_string('repaginatenow', 'quiz'), array('id' => 'id_repaginatenow'));
171             $mform->disabledIf('repaginatenow', 'shufflequestions', 'eq', 1);
173             $PAGE->requires->js('/question/qengine.js');
174             $module = array(
175                 'name'      => 'mod_quiz_edit',
176                 'fullpath'  => '/mod/quiz/edit.js',
177                 'requires'  => array('yui2-dom', 'yui2-event', 'yui2-container'),
178                 'strings'   => array(),
179                 'async'     => false,
180             );
181             $PAGE->requires->js_init_call('quiz_settings_init', null, false, $module);
182         }
184         $mform->addGroup($pagegroup, 'questionsperpagegrp',
185                 get_string('newpage', 'quiz'), null, false);
186         $mform->addHelpButton('questionsperpagegrp', 'newpage', 'quiz');
187         $mform->setAdvanced('questionsperpagegrp', $quizconfig->questionsperpage_adv);
189         // Navigation method.
190         $mform->addElement('select', 'navmethod', get_string('navmethod', 'quiz'),
191                 quiz_get_navigation_options());
192         $mform->addHelpButton('navmethod', 'navmethod', 'quiz');
193         $mform->setAdvanced('navmethod', $quizconfig->navmethod_adv);
194         $mform->setDefault('navmethod', $quizconfig->navmethod);
196         // -------------------------------------------------------------------------------
197         $mform->addElement('header', 'interactionhdr', get_string('questionbehaviour', 'quiz'));
199         // Shuffle within questions.
200         $mform->addElement('selectyesno', 'shuffleanswers', get_string('shufflewithin', 'quiz'));
201         $mform->addHelpButton('shuffleanswers', 'shufflewithin', 'quiz');
202         $mform->setAdvanced('shuffleanswers', $quizconfig->shuffleanswers_adv);
203         $mform->setDefault('shuffleanswers', $quizconfig->shuffleanswers);
205         // How questions behave (question behaviour).
206         if (!empty($this->current->preferredbehaviour)) {
207             $currentbehaviour = $this->current->preferredbehaviour;
208         } else {
209             $currentbehaviour = '';
210         }
211         $behaviours = question_engine::get_behaviour_options($currentbehaviour);
212         $mform->addElement('select', 'preferredbehaviour',
213                 get_string('howquestionsbehave', 'question'), $behaviours);
214         $mform->addHelpButton('preferredbehaviour', 'howquestionsbehave', 'question');
215         $mform->setDefault('preferredbehaviour', $quizconfig->preferredbehaviour);
217         // Each attempt builds on last.
218         $mform->addElement('selectyesno', 'attemptonlast',
219                 get_string('eachattemptbuildsonthelast', 'quiz'));
220         $mform->addHelpButton('attemptonlast', 'eachattemptbuildsonthelast', 'quiz');
221         $mform->setAdvanced('attemptonlast', $quizconfig->attemptonlast_adv);
222         $mform->setDefault('attemptonlast', $quizconfig->attemptonlast);
223         $mform->disabledIf('attemptonlast', 'attempts', 'eq', 1);
225         // -------------------------------------------------------------------------------
226         $mform->addElement('header', 'reviewoptionshdr',
227                 get_string('reviewoptionsheading', 'quiz'));
228         $mform->addHelpButton('reviewoptionshdr', 'reviewoptionsheading', 'quiz');
230         // Review options.
231         $this->add_review_options_group($mform, $quizconfig, 'during',
232                 mod_quiz_display_options::DURING, true);
233         $this->add_review_options_group($mform, $quizconfig, 'immediately',
234                 mod_quiz_display_options::IMMEDIATELY_AFTER);
235         $this->add_review_options_group($mform, $quizconfig, 'open',
236                 mod_quiz_display_options::LATER_WHILE_OPEN);
237         $this->add_review_options_group($mform, $quizconfig, 'closed',
238                 mod_quiz_display_options::AFTER_CLOSE);
240         foreach ($behaviours as $behaviour => $notused) {
241             $unusedoptions = question_engine::get_behaviour_unused_display_options($behaviour);
242             foreach ($unusedoptions as $unusedoption) {
243                 $mform->disabledIf($unusedoption . 'during', 'preferredbehaviour',
244                         'eq', $behaviour);
245             }
246         }
247         $mform->disabledIf('attemptduring', 'preferredbehaviour',
248                 'neq', 'wontmatch');
249         $mform->disabledIf('overallfeedbackduring', 'preferredbehaviour',
250                 'neq', 'wontmatch');
252         // -------------------------------------------------------------------------------
253         $mform->addElement('header', 'display', get_string('display', 'form'));
255         // Show user picture.
256         $mform->addElement('select', 'showuserpicture', get_string('showuserpicture', 'quiz'), array(
257                 QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'),
258                 QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'),
259                 QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz')));
260         $mform->addHelpButton('showuserpicture', 'showuserpicture', 'quiz');
261         $mform->setAdvanced('showuserpicture', $quizconfig->showuserpicture_adv);
262         $mform->setDefault('showuserpicture', $quizconfig->showuserpicture);
264         // Overall decimal points.
265         $options = array();
266         for ($i = 0; $i <= QUIZ_MAX_DECIMAL_OPTION; $i++) {
267             $options[$i] = $i;
268         }
269         $mform->addElement('select', 'decimalpoints', get_string('decimalplaces', 'quiz'),
270                 $options);
271         $mform->addHelpButton('decimalpoints', 'decimalplaces', 'quiz');
272         $mform->setAdvanced('decimalpoints', $quizconfig->decimalpoints_adv);
273         $mform->setDefault('decimalpoints', $quizconfig->decimalpoints);
275         // Question decimal points.
276         $options = array(-1 => get_string('sameasoverall', 'quiz'));
277         for ($i = 0; $i <= QUIZ_MAX_Q_DECIMAL_OPTION; $i++) {
278             $options[$i] = $i;
279         }
280         $mform->addElement('select', 'questiondecimalpoints',
281                 get_string('decimalplacesquestion', 'quiz'), $options);
282         $mform->addHelpButton('questiondecimalpoints', 'decimalplacesquestion', 'quiz');
283         $mform->setAdvanced('questiondecimalpoints', $quizconfig->questiondecimalpoints_adv);
284         $mform->setDefault('questiondecimalpoints', $quizconfig->questiondecimalpoints);
286         // Show blocks during quiz attempt.
287         $mform->addElement('selectyesno', 'showblocks', get_string('showblocks', 'quiz'));
288         $mform->addHelpButton('showblocks', 'showblocks', 'quiz');
289         $mform->setAdvanced('showblocks', $quizconfig->showblocks_adv);
290         $mform->setDefault('showblocks', $quizconfig->showblocks);
292         // -------------------------------------------------------------------------------
293         $mform->addElement('header', 'security', get_string('extraattemptrestrictions', 'quiz'));
295         // Require password to begin quiz attempt.
296         $mform->addElement('passwordunmask', 'quizpassword', get_string('requirepassword', 'quiz'));
297         $mform->setType('quizpassword', PARAM_TEXT);
298         $mform->addHelpButton('quizpassword', 'requirepassword', 'quiz');
299         $mform->setAdvanced('quizpassword', $quizconfig->password_adv);
300         $mform->setDefault('quizpassword', $quizconfig->password);
302         // IP address.
303         $mform->addElement('text', 'subnet', get_string('requiresubnet', 'quiz'));
304         $mform->setType('subnet', PARAM_TEXT);
305         $mform->addHelpButton('subnet', 'requiresubnet', 'quiz');
306         $mform->setAdvanced('subnet', $quizconfig->subnet_adv);
307         $mform->setDefault('subnet', $quizconfig->subnet);
309         // Enforced time delay between quiz attempts.
310         $mform->addElement('duration', 'delay1', get_string('delay1st2nd', 'quiz'),
311                 array('optional' => true));
312         $mform->addHelpButton('delay1', 'delay1st2nd', 'quiz');
313         $mform->setAdvanced('delay1', $quizconfig->delay1_adv);
314         $mform->setDefault('delay1', $quizconfig->delay1);
315         $mform->disabledIf('delay1', 'attempts', 'eq', 1);
317         $mform->addElement('duration', 'delay2', get_string('delaylater', 'quiz'),
318                 array('optional' => true));
319         $mform->addHelpButton('delay2', 'delaylater', 'quiz');
320         $mform->setAdvanced('delay2', $quizconfig->delay2_adv);
321         $mform->setDefault('delay2', $quizconfig->delay2);
322         $mform->disabledIf('delay2', 'attempts', 'eq', 1);
323         $mform->disabledIf('delay2', 'attempts', 'eq', 2);
325         // Browser security choices.
326         $mform->addElement('select', 'browsersecurity', get_string('browsersecurity', 'quiz'),
327                 quiz_access_manager::get_browser_security_choices());
328         $mform->addHelpButton('browsersecurity', 'browsersecurity', 'quiz');
329         $mform->setAdvanced('browsersecurity', $quizconfig->browsersecurity_adv);
330         $mform->setDefault('browsersecurity', $quizconfig->browsersecurity);
332         // Any other rule plugins.
333         quiz_access_manager::add_settings_form_fields($this, $mform);
335         // -------------------------------------------------------------------------------
336         $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'quiz'));
337         $mform->addHelpButton('overallfeedbackhdr', 'overallfeedback', 'quiz');
339         if (isset($this->current->grade)) {
340             $needwarning = $this->current->grade === 0;
341         } else {
342             $needwarning = $quizconfig->maximumgrade == 0;
343         }
344         if ($needwarning) {
345             $mform->addElement('static', 'nogradewarning', '',
346                     get_string('nogradewarning', 'quiz'));
347         }
349         $mform->addElement('static', 'gradeboundarystatic1',
350                 get_string('gradeboundary', 'quiz'), '100%');
352         $repeatarray = array();
353         $repeatedoptions = array();
354         $repeatarray[] = $mform->createElement('editor', 'feedbacktext',
355                 get_string('feedback', 'quiz'), array('rows' => 3), array('maxfiles' => EDITOR_UNLIMITED_FILES,
356                         'noclean' => true, 'context' => $this->context));
357         $repeatarray[] = $mform->createElement('text', 'feedbackboundaries',
358                 get_string('gradeboundary', 'quiz'), array('size' => 10));
359         $repeatedoptions['feedbacktext']['type'] = PARAM_RAW;
360         $repeatedoptions['feedbackboundaries']['type'] = PARAM_RAW;
362         if (!empty($this->_instance)) {
363             $this->_feedbacks = $DB->get_records('quiz_feedback',
364                     array('quizid' => $this->_instance), 'mingrade DESC');
365         } else {
366             $this->_feedbacks = array();
367         }
368         $numfeedbacks = max(count($this->_feedbacks) * 1.5, 5);
370         $nextel = $this->repeat_elements($repeatarray, $numfeedbacks - 1,
371                 $repeatedoptions, 'boundary_repeats', 'boundary_add_fields', 3,
372                 get_string('addmoreoverallfeedbacks', 'quiz'), true);
374         // Put some extra elements in before the button.
375         $mform->insertElementBefore($mform->createElement('editor',
376                 "feedbacktext[$nextel]", get_string('feedback', 'quiz'), array('rows' => 3),
377                 array('maxfiles' => EDITOR_UNLIMITED_FILES, 'noclean' => true,
378                       'context' => $this->context)),
379                 'boundary_add_fields');
380         $mform->insertElementBefore($mform->createElement('static',
381                 'gradeboundarystatic2', get_string('gradeboundary', 'quiz'), '0%'),
382                 'boundary_add_fields');
384         // Add the disabledif rules. We cannot do this using the $repeatoptions parameter to
385         // repeat_elements because we don't want to dissable the first feedbacktext.
386         for ($i = 0; $i < $nextel; $i++) {
387             $mform->disabledIf('feedbackboundaries[' . $i . ']', 'grade', 'eq', 0);
388             $mform->disabledIf('feedbacktext[' . ($i + 1) . ']', 'grade', 'eq', 0);
389         }
391         // -------------------------------------------------------------------------------
392         $this->standard_coursemodule_elements();
394         // Check and act on whether setting outcomes is considered an advanced setting.
395         $mform->setAdvanced('modoutcomes', !empty($quizconfig->outcomes_adv));
397         // The standard_coursemodule_elements method sets this to 100, but the
398         // quiz has its own setting, so use that.
399         $mform->setDefault('grade', $quizconfig->maximumgrade);
401         // -------------------------------------------------------------------------------
402         $this->add_action_buttons();
403     }
405     protected function add_review_options_group($mform, $quizconfig, $whenname,
406             $when, $withhelp = false) {
407         global $OUTPUT;
409         $group = array();
410         foreach (self::$reviewfields as $field => $string) {
411             list($identifier, $component) = $string;
413             $label = get_string($identifier, $component);
414             if ($withhelp) {
415                 $label .= ' ' . $OUTPUT->help_icon($identifier, $component);
416             }
418             $group[] = $mform->createElement('checkbox', $field . $whenname, '', $label);
419         }
420         $mform->addGroup($group, $whenname . 'optionsgrp',
421                 get_string('review' . $whenname, 'quiz'), null, false);
423         foreach (self::$reviewfields as $field => $notused) {
424             $cfgfield = 'review' . $field;
425             if ($quizconfig->$cfgfield & $when) {
426                 $mform->setDefault($field . $whenname, 1);
427             } else {
428                 $mform->setDefault($field . $whenname, 0);
429             }
430         }
432         if ($whenname != 'during') {
433             $mform->disabledIf('correctness' . $whenname, 'attempt' . $whenname);
434             $mform->disabledIf('specificfeedback' . $whenname, 'attempt' . $whenname);
435             $mform->disabledIf('generalfeedback' . $whenname, 'attempt' . $whenname);
436             $mform->disabledIf('rightanswer' . $whenname, 'attempt' . $whenname);
437         }
438     }
440     protected function preprocessing_review_settings(&$toform, $whenname, $when) {
441         foreach (self::$reviewfields as $field => $notused) {
442             $fieldname = 'review' . $field;
443             if (array_key_exists($fieldname, $toform)) {
444                 $toform[$field . $whenname] = $toform[$fieldname] & $when;
445             }
446         }
447     }
449     public function data_preprocessing(&$toform) {
450         if (isset($toform['grade'])) {
451             // Convert to a real number, so we don't get 0.0000.
452             $toform['grade'] = $toform['grade'] + 0;
453         }
455         if (count($this->_feedbacks)) {
456             $key = 0;
457             foreach ($this->_feedbacks as $feedback) {
458                 $draftid = file_get_submitted_draft_itemid('feedbacktext['.$key.']');
459                 $toform['feedbacktext['.$key.']']['text'] = file_prepare_draft_area(
460                     $draftid,               // Draftid.
461                     $this->context->id,     // Context.
462                     'mod_quiz',             // Component.
463                     'feedback',             // Filarea.
464                     !empty($feedback->id) ? (int) $feedback->id : null, // Itemid.
465                     null,
466                     $feedback->feedbacktext // Text.
467                 );
468                 $toform['feedbacktext['.$key.']']['format'] = $feedback->feedbacktextformat;
469                 $toform['feedbacktext['.$key.']']['itemid'] = $draftid;
471                 if ($toform['grade'] == 0) {
472                     // When a quiz is un-graded, there can only be one lot of
473                     // feedback. If the quiz previously had a maximum grade and
474                     // several lots of feedback, we must now avoid putting text
475                     // into input boxes that are disabled, but which the
476                     // validation will insist are blank.
477                     break;
478                 }
480                 if ($feedback->mingrade > 0) {
481                     $toform['feedbackboundaries['.$key.']'] =
482                             (100.0 * $feedback->mingrade / $toform['grade']) . '%';
483                 }
484                 $key++;
485             }
486         }
488         if (isset($toform['timelimit'])) {
489             $toform['timelimitenable'] = $toform['timelimit'] > 0;
490         }
492         $this->preprocessing_review_settings($toform, 'during',
493                 mod_quiz_display_options::DURING);
494         $this->preprocessing_review_settings($toform, 'immediately',
495                 mod_quiz_display_options::IMMEDIATELY_AFTER);
496         $this->preprocessing_review_settings($toform, 'open',
497                 mod_quiz_display_options::LATER_WHILE_OPEN);
498         $this->preprocessing_review_settings($toform, 'closed',
499                 mod_quiz_display_options::AFTER_CLOSE);
500         $toform['attemptduring'] = true;
501         $toform['overallfeedbackduring'] = false;
503         // Password field - different in form to stop browsers that remember
504         // passwords from getting confused.
505         if (isset($toform['password'])) {
506             $toform['quizpassword'] = $toform['password'];
507             unset($toform['password']);
508         }
510         // Load any settings belonging to the access rules.
511         if (!empty($toform['instance'])) {
512             $accesssettings = quiz_access_manager::load_settings($toform['instance']);
513             foreach ($accesssettings as $name => $value) {
514                 $toform[$name] = $value;
515             }
516         }
517     }
519     public function validation($data, $files) {
520         $errors = parent::validation($data, $files);
522         // Check open and close times are consistent.
523         if ($data['timeopen'] != 0 && $data['timeclose'] != 0 &&
524                 $data['timeclose'] < $data['timeopen']) {
525             $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
526         }
528         // Check that the grace period is not too short.
529         if ($data['overduehandling'] == 'graceperiod') {
530             $graceperiodmin = get_config('quiz', 'graceperiodmin');
531             if ($data['graceperiod'] <= $graceperiodmin) {
532                 $errors['graceperiod'] = get_string('graceperiodtoosmall', 'quiz', format_time($graceperiodmin));
533             }
534         }
536         // Check the boundary value is a number or a percentage, and in range.
537         $i = 0;
538         while (!empty($data['feedbackboundaries'][$i] )) {
539             $boundary = trim($data['feedbackboundaries'][$i]);
540             if (strlen($boundary) > 0) {
541                 if ($boundary[strlen($boundary) - 1] == '%') {
542                     $boundary = trim(substr($boundary, 0, -1));
543                     if (is_numeric($boundary)) {
544                         $boundary = $boundary * $data['grade'] / 100.0;
545                     } else {
546                         $errors["feedbackboundaries[$i]"] =
547                                 get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
548                     }
549                 } else if (!is_numeric($boundary)) {
550                     $errors["feedbackboundaries[$i]"] =
551                             get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
552                 }
553             }
554             if (is_numeric($boundary) && $boundary <= 0 || $boundary >= $data['grade'] ) {
555                 $errors["feedbackboundaries[$i]"] =
556                         get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
557             }
558             if (is_numeric($boundary) && $i > 0 &&
559                     $boundary >= $data['feedbackboundaries'][$i - 1]) {
560                 $errors["feedbackboundaries[$i]"] =
561                         get_string('feedbackerrororder', 'quiz', $i + 1);
562             }
563             $data['feedbackboundaries'][$i] = $boundary;
564             $i += 1;
565         }
566         $numboundaries = $i;
568         // Check there is nothing in the remaining unused fields.
569         if (!empty($data['feedbackboundaries'])) {
570             for ($i = $numboundaries; $i < count($data['feedbackboundaries']); $i += 1) {
571                 if (!empty($data['feedbackboundaries'][$i] ) &&
572                         trim($data['feedbackboundaries'][$i] ) != '') {
573                     $errors["feedbackboundaries[$i]"] =
574                             get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
575                 }
576             }
577         }
578         for ($i = $numboundaries + 1; $i < count($data['feedbacktext']); $i += 1) {
579             if (!empty($data['feedbacktext'][$i]['text']) &&
580                     trim($data['feedbacktext'][$i]['text'] ) != '') {
581                 $errors["feedbacktext[$i]"] =
582                         get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
583             }
584         }
586         // Any other rule plugins.
587         $errors = quiz_access_manager::validate_settings_form_fields($errors, $data, $files, $this);
589         return $errors;
590     }