MDL-61837 core_question: replace tag fields on tag modal
[moodle.git] / question / type / edit_question_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  * A base class for question editing forms.
19  *
20  * @package    moodlecore
21  * @subpackage questiontypes
22  * @copyright  2006 The Open University
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License
24  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
30 require_once($CFG->libdir.'/formslib.php');
33 abstract class question_wizard_form extends moodleform {
34     /**
35      * Add all the hidden form fields used by question/question.php.
36      */
37     protected function add_hidden_fields() {
38         $mform = $this->_form;
40         $mform->addElement('hidden', 'id');
41         $mform->setType('id', PARAM_INT);
43         $mform->addElement('hidden', 'inpopup');
44         $mform->setType('inpopup', PARAM_INT);
46         $mform->addElement('hidden', 'cmid');
47         $mform->setType('cmid', PARAM_INT);
49         $mform->addElement('hidden', 'courseid');
50         $mform->setType('courseid', PARAM_INT);
52         $mform->addElement('hidden', 'returnurl');
53         $mform->setType('returnurl', PARAM_LOCALURL);
55         $mform->addElement('hidden', 'scrollpos');
56         $mform->setType('scrollpos', PARAM_INT);
58         $mform->addElement('hidden', 'appendqnumstring');
59         $mform->setType('appendqnumstring', PARAM_ALPHA);
60     }
61 }
63 /**
64  * Form definition base class. This defines the common fields that
65  * all question types need. Question types should define their own
66  * class that inherits from this one, and implements the definition_inner()
67  * method.
68  *
69  * @copyright  2006 The Open University
70  * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License
71  */
72 abstract class question_edit_form extends question_wizard_form {
73     const DEFAULT_NUM_HINTS = 2;
75     /**
76      * Question object with options and answers already loaded by get_question_options
77      * Be careful how you use this it is needed sometimes to set up the structure of the
78      * form in definition_inner but data is always loaded into the form with set_data.
79      * @var object
80      */
81     protected $question;
83     protected $contexts;
84     protected $category;
85     protected $categorycontext;
87     /** @var object current context */
88     public $context;
89     /** @var array html editor options */
90     public $editoroptions;
91     /** @var array options to preapre draft area */
92     public $fileoptions;
93     /** @var object instance of question type */
94     public $instance;
96     public function __construct($submiturl, $question, $category, $contexts, $formeditable = true) {
97         global $DB;
99         $this->question = $question;
100         $this->contexts = $contexts;
102         $record = $DB->get_record('question_categories',
103                 array('id' => $question->category), 'contextid');
104         $this->context = context::instance_by_id($record->contextid);
106         $this->editoroptions = array('subdirs' => 1, 'maxfiles' => EDITOR_UNLIMITED_FILES,
107                 'context' => $this->context);
108         $this->fileoptions = array('subdirs' => 1, 'maxfiles' => -1, 'maxbytes' => -1);
110         $this->category = $category;
111         $this->categorycontext = context::instance_by_id($category->contextid);
113         parent::__construct($submiturl, null, 'post', '', null, $formeditable);
114     }
116     /**
117      * Build the form definition.
118      *
119      * This adds all the form fields that the default question type supports.
120      * If your question type does not support all these fields, then you can
121      * override this method and remove the ones you don't want with $mform->removeElement().
122      */
123     protected function definition() {
124         global $COURSE, $CFG, $DB, $PAGE;
126         $qtype = $this->qtype();
127         $langfile = "qtype_{$qtype}";
129         $mform = $this->_form;
131         // Standard fields at the start of the form.
132         $mform->addElement('header', 'generalheader', get_string("general", 'form'));
134         if (!isset($this->question->id)) {
135             if (!empty($this->question->formoptions->mustbeusable)) {
136                 $contexts = $this->contexts->having_add_and_use();
137             } else {
138                 $contexts = $this->contexts->having_cap('moodle/question:add');
139             }
141             // Adding question.
142             $mform->addElement('questioncategory', 'category', get_string('category', 'question'),
143                     array('contexts' => $contexts));
144         } else if (!($this->question->formoptions->canmove ||
145                 $this->question->formoptions->cansaveasnew)) {
146             // Editing question with no permission to move from category.
147             $mform->addElement('questioncategory', 'category', get_string('category', 'question'),
148                     array('contexts' => array($this->categorycontext)));
149             $mform->addElement('hidden', 'usecurrentcat', 1);
150             $mform->setType('usecurrentcat', PARAM_BOOL);
151             $mform->setConstant('usecurrentcat', 1);
152         } else {
153             // Editing question with permission to move from category or save as new q.
154             $currentgrp = array();
155             $currentgrp[0] = $mform->createElement('questioncategory', 'category',
156                     get_string('categorycurrent', 'question'),
157                     array('contexts' => array($this->categorycontext)));
158             if ($this->question->formoptions->canedit ||
159                     $this->question->formoptions->cansaveasnew) {
160                 // Not move only form.
161                 $currentgrp[1] = $mform->createElement('checkbox', 'usecurrentcat', '',
162                         get_string('categorycurrentuse', 'question'));
163                 $mform->setDefault('usecurrentcat', 1);
164             }
165             $currentgrp[0]->freeze();
166             $currentgrp[0]->setPersistantFreeze(false);
167             $mform->addGroup($currentgrp, 'currentgrp',
168                     get_string('categorycurrent', 'question'), null, false);
170             $mform->addElement('questioncategory', 'categorymoveto',
171                     get_string('categorymoveto', 'question'),
172                     array('contexts' => array($this->categorycontext)));
173             if ($this->question->formoptions->canedit ||
174                     $this->question->formoptions->cansaveasnew) {
175                 // Not move only form.
176                 $mform->disabledIf('categorymoveto', 'usecurrentcat', 'checked');
177             }
178         }
180         $mform->addElement('text', 'name', get_string('questionname', 'question'),
181                 array('size' => 50, 'maxlength' => 255));
182         $mform->setType('name', PARAM_TEXT);
183         $mform->addRule('name', null, 'required', null, 'client');
185         $mform->addElement('editor', 'questiontext', get_string('questiontext', 'question'),
186                 array('rows' => 15), $this->editoroptions);
187         $mform->setType('questiontext', PARAM_RAW);
188         $mform->addRule('questiontext', null, 'required', null, 'client');
190         $mform->addElement('text', 'defaultmark', get_string('defaultmark', 'question'),
191                 array('size' => 7));
192         $mform->setType('defaultmark', PARAM_FLOAT);
193         $mform->setDefault('defaultmark', 1);
194         $mform->addRule('defaultmark', null, 'required', null, 'client');
196         $mform->addElement('editor', 'generalfeedback', get_string('generalfeedback', 'question'),
197                 array('rows' => 10), $this->editoroptions);
198         $mform->setType('generalfeedback', PARAM_RAW);
199         $mform->addHelpButton('generalfeedback', 'generalfeedback', 'question');
201         // Any questiontype specific fields.
202         $this->definition_inner($mform);
204         if (core_tag_tag::is_enabled('core_question', 'question')) {
205             $this->add_tag_fields($mform);
206         }
208         if (!empty($this->question->id)) {
209             $mform->addElement('header', 'createdmodifiedheader',
210                     get_string('createdmodifiedheader', 'question'));
211             $a = new stdClass();
212             if (!empty($this->question->createdby)) {
213                 $a->time = userdate($this->question->timecreated);
214                 $a->user = fullname($DB->get_record(
215                         'user', array('id' => $this->question->createdby)));
216             } else {
217                 $a->time = get_string('unknown', 'question');
218                 $a->user = get_string('unknown', 'question');
219             }
220             $mform->addElement('static', 'created', get_string('created', 'question'),
221                      get_string('byandon', 'question', $a));
222             if (!empty($this->question->modifiedby)) {
223                 $a = new stdClass();
224                 $a->time = userdate($this->question->timemodified);
225                 $a->user = fullname($DB->get_record(
226                         'user', array('id' => $this->question->modifiedby)));
227                 $mform->addElement('static', 'modified', get_string('modified', 'question'),
228                         get_string('byandon', 'question', $a));
229             }
230         }
232         $this->add_hidden_fields();
234         $mform->addElement('hidden', 'qtype');
235         $mform->setType('qtype', PARAM_ALPHA);
237         $mform->addElement('hidden', 'makecopy');
238         $mform->setType('makecopy', PARAM_INT);
240         $buttonarray = array();
241         $buttonarray[] = $mform->createElement('submit', 'updatebutton',
242                              get_string('savechangesandcontinueediting', 'question'));
243         if ($this->can_preview()) {
244             $previewlink = $PAGE->get_renderer('core_question')->question_preview_link(
245                     $this->question->id, $this->context, true);
246             $buttonarray[] = $mform->createElement('static', 'previewlink', '', $previewlink);
247         }
249         $mform->addGroup($buttonarray, 'updatebuttonar', '', array(' '), false);
250         $mform->closeHeaderBefore('updatebuttonar');
252         $this->add_action_buttons(true, get_string('savechanges'));
254         if ((!empty($this->question->id)) && (!($this->question->formoptions->canedit ||
255                 $this->question->formoptions->cansaveasnew))) {
256             $mform->hardFreezeAllVisibleExcept(array('categorymoveto', 'buttonar', 'currentgrp'));
257         }
258     }
260     /**
261      * Add any question-type specific form fields.
262      *
263      * @param object $mform the form being built.
264      */
265     protected function definition_inner($mform) {
266         // By default, do nothing.
267     }
269     /**
270      * Is the question being edited in a state where it can be previewed?
271      * @return bool whether to show the preview link.
272      */
273     protected function can_preview() {
274         return empty($this->question->beingcopied) && !empty($this->question->id) &&
275                 $this->question->formoptions->canedit;
276     }
278     /**
279      * Get the list of form elements to repeat, one for each answer.
280      * @param object $mform the form being built.
281      * @param $label the label to use for each option.
282      * @param $gradeoptions the possible grades for each answer.
283      * @param $repeatedoptions reference to array of repeated options to fill
284      * @param $answersoption reference to return the name of $question->options
285      *      field holding an array of answers
286      * @return array of form fields.
287      */
288     protected function get_per_answer_fields($mform, $label, $gradeoptions,
289             &$repeatedoptions, &$answersoption) {
290         $repeated = array();
291         $answeroptions = array();
292         $answeroptions[] = $mform->createElement('text', 'answer',
293                 $label, array('size' => 40));
294         $answeroptions[] = $mform->createElement('select', 'fraction',
295                 get_string('grade'), $gradeoptions);
296         $repeated[] = $mform->createElement('group', 'answeroptions',
297                  $label, $answeroptions, null, false);
298         $repeated[] = $mform->createElement('editor', 'feedback',
299                 get_string('feedback', 'question'), array('rows' => 5), $this->editoroptions);
300         $repeatedoptions['answer']['type'] = PARAM_RAW;
301         $repeatedoptions['fraction']['default'] = 0;
302         $answersoption = 'answers';
303         return $repeated;
304     }
306     /**
307      * Add the tag and course tag fields to the mform.
308      *
309      * If the form is being built in a course context then add the field
310      * for course tags.
311      *
312      * If the question category doesn't belong to a course context or we
313      * aren't editing in a course context then add the tags element to allow
314      * tags to be added to the question category context.
315      *
316      * @param object $mform The form being built
317      */
318     protected function add_tag_fields($mform) {
319         $hastagcapability = question_has_capability_on($this->question, 'tag');
320         // Is the question category in a course context?
321         $qcontext = $this->categorycontext;
322         $qcoursecontext = $qcontext->get_course_context(false);
323         $iscourseoractivityquestion = !empty($qcoursecontext);
324         // Is the current context we're editing in a course context?
325         $editingcontext = $this->contexts->lowest();
326         $editingcoursecontext = $editingcontext->get_course_context(false);
327         $iseditingcontextcourseoractivity = !empty($editingcoursecontext);
329         $mform->addElement('header', 'tagsheader', get_string('tags'));
330         $mform->addElement('tags', 'tags', get_string('tags'),
331                 array('itemtype' => 'question', 'component' => 'core_question'));
333         if (!$hastagcapability) {
334             $mform->hardFreeze('tags');
335         }
337         if ($iseditingcontextcourseoractivity && !$iscourseoractivityquestion) {
338             // If the question is being edited in a course or activity context
339             // and the question isn't a course or activity level question then
340             // allow course tags to be added to the course.
341             $coursetagheader = get_string('questionformtagheader', 'core_question',
342                 $editingcoursecontext->get_context_name(true));
343             $mform->addElement('header', 'coursetagsheader', $coursetagheader);
344             $mform->addElement('tags', 'coursetags', get_string('tags'),
345                     array('itemtype' => 'question', 'component' => 'core_question'));
347             if (!$hastagcapability) {
348                 $mform->hardFreeze('coursetags');
349             }
350         }
351     }
353     /**
354      * Add a set of form fields, obtained from get_per_answer_fields, to the form,
355      * one for each existing answer, with some blanks for some new ones.
356      * @param object $mform the form being built.
357      * @param $label the label to use for each option.
358      * @param $gradeoptions the possible grades for each answer.
359      * @param $minoptions the minimum number of answer blanks to display.
360      *      Default QUESTION_NUMANS_START.
361      * @param $addoptions the number of answer blanks to add. Default QUESTION_NUMANS_ADD.
362      */
363     protected function add_per_answer_fields(&$mform, $label, $gradeoptions,
364             $minoptions = QUESTION_NUMANS_START, $addoptions = QUESTION_NUMANS_ADD) {
365         $mform->addElement('header', 'answerhdr',
366                     get_string('answers', 'question'), '');
367         $mform->setExpanded('answerhdr', 1);
368         $answersoption = '';
369         $repeatedoptions = array();
370         $repeated = $this->get_per_answer_fields($mform, $label, $gradeoptions,
371                 $repeatedoptions, $answersoption);
373         if (isset($this->question->options)) {
374             $repeatsatstart = count($this->question->options->$answersoption);
375         } else {
376             $repeatsatstart = $minoptions;
377         }
379         $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions,
380                 'noanswers', 'addanswers', $addoptions,
381                 $this->get_more_choices_string(), true);
382     }
384     /**
385      * Language string to use for 'Add {no} more {whatever we call answers}'.
386      */
387     protected function get_more_choices_string() {
388         return get_string('addmorechoiceblanks', 'question');
389     }
391     protected function add_combined_feedback_fields($withshownumpartscorrect = false) {
392         $mform = $this->_form;
394         $mform->addElement('header', 'combinedfeedbackhdr',
395                 get_string('combinedfeedback', 'question'));
397         $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
398         foreach ($fields as $feedbackname) {
399             $element = $mform->addElement('editor', $feedbackname,
400                                 get_string($feedbackname, 'question'),
401                                 array('rows' => 5), $this->editoroptions);
402             $mform->setType($feedbackname, PARAM_RAW);
403             // Using setValue() as setDefault() does not work for the editor class.
404             $element->setValue(array('text' => get_string($feedbackname.'default', 'question')));
406             if ($withshownumpartscorrect && $feedbackname == 'partiallycorrectfeedback') {
407                 $mform->addElement('advcheckbox', 'shownumcorrect',
408                         get_string('options', 'question'),
409                         get_string('shownumpartscorrectwhenfinished', 'question'));
410                 $mform->setDefault('shownumcorrect', true);
411             }
412         }
413     }
415     /**
416      * Create the form elements required by one hint.
417      * @param string $withclearwrong whether this quesiton type uses the 'Clear wrong' option on hints.
418      * @param string $withshownumpartscorrect whether this quesiton type uses the 'Show num parts correct' option on hints.
419      * @return array form field elements for one hint.
420      */
421     protected function get_hint_fields($withclearwrong = false, $withshownumpartscorrect = false) {
422         $mform = $this->_form;
424         $repeatedoptions = array();
425         $repeated = array();
426         $repeated[] = $mform->createElement('editor', 'hint', get_string('hintn', 'question'),
427                 array('rows' => 5), $this->editoroptions);
428         $repeatedoptions['hint']['type'] = PARAM_RAW;
430         $optionelements = array();
431         if ($withclearwrong) {
432             $optionelements[] = $mform->createElement('advcheckbox', 'hintclearwrong',
433                     get_string('options', 'question'), get_string('clearwrongparts', 'question'));
434         }
435         if ($withshownumpartscorrect) {
436             $optionelements[] = $mform->createElement('advcheckbox', 'hintshownumcorrect', '',
437                     get_string('shownumpartscorrect', 'question'));
438         }
440         if (count($optionelements)) {
441             $repeated[] = $mform->createElement('group', 'hintoptions',
442                  get_string('hintnoptions', 'question'), $optionelements, null, false);
443         }
445         return array($repeated, $repeatedoptions);
446     }
448     protected function add_interactive_settings($withclearwrong = false,
449             $withshownumpartscorrect = false) {
450         $mform = $this->_form;
452         $mform->addElement('header', 'multitriesheader',
453                 get_string('settingsformultipletries', 'question'));
455         $penalties = array(
456             1.0000000,
457             0.5000000,
458             0.3333333,
459             0.2500000,
460             0.2000000,
461             0.1000000,
462             0.0000000
463         );
464         if (!empty($this->question->penalty) && !in_array($this->question->penalty, $penalties)) {
465             $penalties[] = $this->question->penalty;
466             sort($penalties);
467         }
468         $penaltyoptions = array();
469         foreach ($penalties as $penalty) {
470             $penaltyoptions["{$penalty}"] = (100 * $penalty) . '%';
471         }
472         $mform->addElement('select', 'penalty',
473                 get_string('penaltyforeachincorrecttry', 'question'), $penaltyoptions);
474         $mform->addHelpButton('penalty', 'penaltyforeachincorrecttry', 'question');
475         $mform->setDefault('penalty', 0.3333333);
477         if (isset($this->question->hints)) {
478             $counthints = count($this->question->hints);
479         } else {
480             $counthints = 0;
481         }
483         if ($this->question->formoptions->repeatelements) {
484             $repeatsatstart = max(self::DEFAULT_NUM_HINTS, $counthints);
485         } else {
486             $repeatsatstart = $counthints;
487         }
489         list($repeated, $repeatedoptions) = $this->get_hint_fields(
490                 $withclearwrong, $withshownumpartscorrect);
491         $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions,
492                 'numhints', 'addhint', 1, get_string('addanotherhint', 'question'), true);
493     }
495     public function set_data($question) {
496         question_bank::get_qtype($question->qtype)->set_default_options($question);
498         // Prepare question text.
499         $draftid = file_get_submitted_draft_itemid('questiontext');
501         if (!empty($question->questiontext)) {
502             $questiontext = $question->questiontext;
503         } else {
504             $questiontext = $this->_form->getElement('questiontext')->getValue();
505             $questiontext = $questiontext['text'];
506         }
507         $questiontext = file_prepare_draft_area($draftid, $this->context->id,
508                 'question', 'questiontext', empty($question->id) ? null : (int) $question->id,
509                 $this->fileoptions, $questiontext);
511         $question->questiontext = array();
512         $question->questiontext['text'] = $questiontext;
513         $question->questiontext['format'] = empty($question->questiontextformat) ?
514                 editors_get_preferred_format() : $question->questiontextformat;
515         $question->questiontext['itemid'] = $draftid;
517         // Prepare general feedback.
518         $draftid = file_get_submitted_draft_itemid('generalfeedback');
520         if (empty($question->generalfeedback)) {
521             $generalfeedback = $this->_form->getElement('generalfeedback')->getValue();
522             $question->generalfeedback = $generalfeedback['text'];
523         }
525         $feedback = file_prepare_draft_area($draftid, $this->context->id,
526                 'question', 'generalfeedback', empty($question->id) ? null : (int) $question->id,
527                 $this->fileoptions, $question->generalfeedback);
528         $question->generalfeedback = array();
529         $question->generalfeedback['text'] = $feedback;
530         $question->generalfeedback['format'] = empty($question->generalfeedbackformat) ?
531                 editors_get_preferred_format() : $question->generalfeedbackformat;
532         $question->generalfeedback['itemid'] = $draftid;
534         // Remove unnecessary trailing 0s form grade fields.
535         if (isset($question->defaultgrade)) {
536             $question->defaultgrade = 0 + $question->defaultgrade;
537         }
538         if (isset($question->penalty)) {
539             $question->penalty = 0 + $question->penalty;
540         }
542         // Set any options.
543         $extraquestionfields = question_bank::get_qtype($question->qtype)->extra_question_fields();
544         if (is_array($extraquestionfields) && !empty($question->options)) {
545             array_shift($extraquestionfields);
546             foreach ($extraquestionfields as $field) {
547                 if (property_exists($question->options, $field)) {
548                     $question->$field = $question->options->$field;
549                 }
550             }
551         }
553         // Subclass adds data_preprocessing code here.
554         $question = $this->data_preprocessing($question);
556         parent::set_data($question);
557     }
559     /**
560      * Perform an preprocessing needed on the data passed to {@link set_data()}
561      * before it is used to initialise the form.
562      * @param object $question the data being passed to the form.
563      * @return object $question the modified data.
564      */
565     protected function data_preprocessing($question) {
566         return $question;
567     }
569     /**
570      * Perform the necessary preprocessing for the fields added by
571      * {@link add_per_answer_fields()}.
572      * @param object $question the data being passed to the form.
573      * @return object $question the modified data.
574      */
575     protected function data_preprocessing_answers($question, $withanswerfiles = false) {
576         if (empty($question->options->answers)) {
577             return $question;
578         }
580         $key = 0;
581         foreach ($question->options->answers as $answer) {
582             if ($withanswerfiles) {
583                 // Prepare the feedback editor to display files in draft area.
584                 $draftitemid = file_get_submitted_draft_itemid('answer['.$key.']');
585                 $question->answer[$key]['text'] = file_prepare_draft_area(
586                     $draftitemid,          // Draftid
587                     $this->context->id,    // context
588                     'question',            // component
589                     'answer',              // filarea
590                     !empty($answer->id) ? (int) $answer->id : null, // itemid
591                     $this->fileoptions,    // options
592                     $answer->answer        // text.
593                 );
594                 $question->answer[$key]['itemid'] = $draftitemid;
595                 $question->answer[$key]['format'] = $answer->answerformat;
596             } else {
597                 $question->answer[$key] = $answer->answer;
598             }
600             $question->fraction[$key] = 0 + $answer->fraction;
601             $question->feedback[$key] = array();
603             // Evil hack alert. Formslib can store defaults in two ways for
604             // repeat elements:
605             //   ->_defaultValues['fraction[0]'] and
606             //   ->_defaultValues['fraction'][0].
607             // The $repeatedoptions['fraction']['default'] = 0 bit above means
608             // that ->_defaultValues['fraction[0]'] has already been set, but we
609             // are using object notation here, so we will be setting
610             // ->_defaultValues['fraction'][0]. That does not work, so we have
611             // to unset ->_defaultValues['fraction[0]'].
612             unset($this->_form->_defaultValues["fraction[{$key}]"]);
614             // Prepare the feedback editor to display files in draft area.
615             $draftitemid = file_get_submitted_draft_itemid('feedback['.$key.']');
616             $question->feedback[$key]['text'] = file_prepare_draft_area(
617                 $draftitemid,          // Draftid
618                 $this->context->id,    // context
619                 'question',            // component
620                 'answerfeedback',      // filarea
621                 !empty($answer->id) ? (int) $answer->id : null, // itemid
622                 $this->fileoptions,    // options
623                 $answer->feedback      // text.
624             );
625             $question->feedback[$key]['itemid'] = $draftitemid;
626             $question->feedback[$key]['format'] = $answer->feedbackformat;
627             $key++;
628         }
630         // Now process extra answer fields.
631         $extraanswerfields = question_bank::get_qtype($question->qtype)->extra_answer_fields();
632         if (is_array($extraanswerfields)) {
633             // Omit table name.
634             array_shift($extraanswerfields);
635             $question = $this->data_preprocessing_extra_answer_fields($question, $extraanswerfields);
636         }
638         return $question;
639     }
641     /**
642      * Perform the necessary preprocessing for the extra answer fields.
643      *
644      * Questions that do something not trivial when editing extra answer fields
645      * will want to override this.
646      * @param object $question the data being passed to the form.
647      * @param array $extraanswerfields extra answer fields (without table name).
648      * @return object $question the modified data.
649      */
650     protected function data_preprocessing_extra_answer_fields($question, $extraanswerfields) {
651         // Setting $question->$field[$key] won't work in PHP, so we need set an array of answer values to $question->$field.
652         // As we may have several extra fields with data for several answers in each, we use an array of arrays.
653         // Index in $extrafieldsdata is an extra answer field name, value - array of it's data for each answer.
654         $extrafieldsdata = array();
655         // First, prepare an array if empty arrays for each extra answer fields data.
656         foreach ($extraanswerfields as $field) {
657             $extrafieldsdata[$field] = array();
658         }
660         // Fill arrays with data from $question->options->answers.
661         $key = 0;
662         foreach ($question->options->answers as $answer) {
663             foreach ($extraanswerfields as $field) {
664                 // See hack comment in {@link data_preprocessing_answers()}.
665                 unset($this->_form->_defaultValues["{$field}[{$key}]"]);
666                 $extrafieldsdata[$field][$key] = $this->data_preprocessing_extra_answer_field($answer, $field);
667             }
668             $key++;
669         }
671         // Set this data in the $question object.
672         foreach ($extraanswerfields as $field) {
673             $question->$field = $extrafieldsdata[$field];
674         }
675         return $question;
676     }
678     /**
679      * Perfmorm preprocessing for particular extra answer field.
680      *
681      * Questions with non-trivial DB - form element relationship will
682      * want to override this.
683      * @param object $answer an answer object to get extra field from.
684      * @param string $field extra answer field name.
685      * @return field value to be set to the form.
686      */
687     protected function data_preprocessing_extra_answer_field($answer, $field) {
688         return $answer->$field;
689     }
691     /**
692      * Perform the necessary preprocessing for the fields added by
693      * {@link add_combined_feedback_fields()}.
694      * @param object $question the data being passed to the form.
695      * @return object $question the modified data.
696      */
697     protected function data_preprocessing_combined_feedback($question,
698             $withshownumcorrect = false) {
699         if (empty($question->options)) {
700             return $question;
701         }
703         $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
704         foreach ($fields as $feedbackname) {
705             $draftid = file_get_submitted_draft_itemid($feedbackname);
706             $feedback = array();
707             $feedback['text'] = file_prepare_draft_area(
708                 $draftid,              // Draftid
709                 $this->context->id,    // context
710                 'question',            // component
711                 $feedbackname,         // filarea
712                 !empty($question->id) ? (int) $question->id : null, // itemid
713                 $this->fileoptions,    // options
714                 $question->options->$feedbackname // text.
715             );
716             $feedbackformat = $feedbackname . 'format';
717             $feedback['format'] = $question->options->$feedbackformat;
718             $feedback['itemid'] = $draftid;
720             $question->$feedbackname = $feedback;
721         }
723         if ($withshownumcorrect) {
724             $question->shownumcorrect = $question->options->shownumcorrect;
725         }
727         return $question;
728     }
730     /**
731      * Perform the necessary preprocessing for the hint fields.
732      * @param object $question the data being passed to the form.
733      * @return object $question the modified data.
734      */
735     protected function data_preprocessing_hints($question, $withclearwrong = false,
736             $withshownumpartscorrect = false) {
737         if (empty($question->hints)) {
738             return $question;
739         }
741         $key = 0;
742         foreach ($question->hints as $hint) {
743             $question->hint[$key] = array();
745             // Prepare feedback editor to display files in draft area.
746             $draftitemid = file_get_submitted_draft_itemid('hint['.$key.']');
747             $question->hint[$key]['text'] = file_prepare_draft_area(
748                 $draftitemid,          // Draftid
749                 $this->context->id,    // context
750                 'question',            // component
751                 'hint',                // filarea
752                 !empty($hint->id) ? (int) $hint->id : null, // itemid
753                 $this->fileoptions,    // options
754                 $hint->hint            // text.
755             );
756             $question->hint[$key]['itemid'] = $draftitemid;
757             $question->hint[$key]['format'] = $hint->hintformat;
758             $key++;
760             if ($withclearwrong) {
761                 $question->hintclearwrong[] = $hint->clearwrong;
762             }
763             if ($withshownumpartscorrect) {
764                 $question->hintshownumcorrect[] = $hint->shownumcorrect;
765             }
766         }
768         return $question;
769     }
771     public function validation($fromform, $files) {
772         $errors = parent::validation($fromform, $files);
773         if (empty($fromform['makecopy']) && isset($this->question->id)
774                 && ($this->question->formoptions->canedit ||
775                         $this->question->formoptions->cansaveasnew)
776                 && empty($fromform['usecurrentcat']) && !$this->question->formoptions->canmove) {
777             $errors['currentgrp'] = get_string('nopermissionmove', 'question');
778         }
780         // Category.
781         if (empty($fromform['category'])) {
782             // User has provided an invalid category.
783             $errors['category'] = get_string('required');
784         }
786         // Default mark.
787         if (array_key_exists('defaultmark', $fromform) && $fromform['defaultmark'] < 0) {
788             $errors['defaultmark'] = get_string('defaultmarkmustbepositive', 'question');
789         }
791         return $errors;
792     }
794     /**
795      * Override this in the subclass to question type name.
796      * @return the question type name, should be the same as the name() method
797      *      in the question type class.
798      */
799     public abstract function qtype();
801     /**
802      * Returns an array of editor options with collapsed options turned off.
803      * @deprecated since 2.6
804      * @return array
805      */
806     protected function get_non_collabsible_editor_options() {
807         debugging('get_non_collabsible_editor_options() is deprecated, use $this->editoroptions instead.', DEBUG_DEVELOPER);
808         return $this->editoroptions;
809     }