MDL-30998: updated docblocks for advanced grading
[moodle.git] / grade / grading / form / rubric / rubriceditor.php
CommitLineData
c586d2bf 1<?php
c586d2bf
MG
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/>.
16
17/**
d22e9e32
MG
18 * File contains definition of class MoodleQuickForm_rubriceditor
19 *
20 * @package gradingform_rubric
c586d2bf
MG
21 * @copyright 2011 Marina Glancy
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25defined('MOODLE_INTERNAL') || die();
26
27require_once("HTML/QuickForm/input.php");
28
d22e9e32
MG
29/**
30 * Form element for handling rubric editor
31 *
32 * The rubric editor is defined as a separate form element. This allows us to render
33 * criteria, levels and buttons using the rubric's own renderer. Also, the required
34 * Javascript library is included, which processes, on the client, buttons needed
35 * for reordering, adding and deleting criteria.
36 *
37 * If Javascript is disabled when one of those special buttons is pressed, the form
38 * element is not validated and, instead of submitting the form, we process button presses.
39 *
40 * @copyright 2011 Marina Glancy
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 */
c586d2bf 43class MoodleQuickForm_rubriceditor extends HTML_QuickForm_input {
d22e9e32 44 /** @var string help message */
c586d2bf 45 public $_helpbutton = '';
d22e9e32 46 /** @var string|bool stores the result of the last validation: null - undefined, false - no errors, string - error(s) text */
3c2b3cb3 47 protected $validationerrors = null;
d22e9e32 48 /** @var bool if element has already been validated **/
3c2b3cb3 49 protected $wasvalidated = false;
d22e9e32 50 /** @var bool If non-submit (JS) button was pressed: null - unknown, true/false - button was/wasn't pressed */
3c2b3cb3 51 protected $nonjsbuttonpressed = false;
d22e9e32 52 /** @var bool Message to display in front of the editor (that there exist grades on this rubric being edited) */
3c2b3cb3 53 protected $regradeconfirmation = false;
c586d2bf 54
d22e9e32
MG
55 /**
56 * Constructor for rubric editor
57 *
58 * @param string $elementName
59 * @param string $elementLabel
60 * @param array $attributes
61 */
c586d2bf
MG
62 function MoodleQuickForm_rubriceditor($elementName=null, $elementLabel=null, $attributes=null) {
63 parent::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
64 }
65
3c2b3cb3
MG
66 /**
67 * get html for help button
68 *
d22e9e32 69 * @return string html for help button
3c2b3cb3
MG
70 */
71 public function getHelpButton() {
c586d2bf
MG
72 return $this->_helpbutton;
73 }
74
3c2b3cb3
MG
75 /**
76 * The renderer will take care itself about different display in normal and frozen states
77 *
78 * @return string
79 */
80 public function getElementTemplateType() {
c586d2bf
MG
81 return 'default';
82 }
83
0136124e
MG
84 /**
85 * Specifies that confirmation about re-grading needs to be added to this rubric editor.
86 * $changelevel is saved in $this->regradeconfirmation and retrieved in toHtml()
87 *
88 * @see gradingform_rubric_controller::update_or_check_rubric()
89 * @param int $changelevel
90 */
3c2b3cb3 91 public function add_regrade_confirmation($changelevel) {
0136124e
MG
92 $this->regradeconfirmation = $changelevel;
93 }
94
95 /**
96 * Returns html string to display this element
97 *
98 * @return string
99 */
3c2b3cb3 100 public function toHtml() {
c586d2bf
MG
101 global $PAGE;
102 $html = $this->_getTabs();
ab156741 103 $renderer = $PAGE->get_renderer('gradingform_rubric');
2ae7faf1 104 $data = $this->prepare_data(null, $this->wasvalidated);
c586d2bf 105 if (!$this->_flagFrozen) {
ab156741
MG
106 $mode = gradingform_rubric_controller::DISPLAY_EDIT_FULL;
107 $module = array('name'=>'gradingform_rubriceditor', 'fullpath'=>'/grade/grading/form/rubric/js/rubriceditor.js',
108 'strings' => array(array('confirmdeletecriterion', 'gradingform_rubric'), array('confirmdeletelevel', 'gradingform_rubric'),
109 array('criterionempty', 'gradingform_rubric'), array('levelempty', 'gradingform_rubric')
110 ));
111 $PAGE->requires->js_init_call('M.gradingform_rubriceditor.init', array(
112 array('name' => $this->getName(),
39c6f4b6
MG
113 'criteriontemplate' => $renderer->criterion_template($mode, $data['options'], $this->getName()),
114 'leveltemplate' => $renderer->level_template($mode, $data['options'], $this->getName())
ab156741
MG
115 )),
116 true, $module);
c586d2bf 117 } else {
39c6f4b6 118 // Rubric is frozen, no javascript needed
c586d2bf 119 if ($this->_persistantFreeze) {
ab156741
MG
120 $mode = gradingform_rubric_controller::DISPLAY_EDIT_FROZEN;
121 } else {
122 $mode = gradingform_rubric_controller::DISPLAY_PREVIEW;
c586d2bf 123 }
c586d2bf 124 }
0136124e
MG
125 if ($this->regradeconfirmation) {
126 if (!isset($data['regrade'])) {
127 $data['regrade'] = 1;
128 }
129 $html .= $renderer->display_regrade_confirmation($this->getName(), $this->regradeconfirmation, $data['regrade']);
130 }
2ae7faf1
MG
131 if ($this->validationerrors) {
132 $html .= $renderer->notification($this->validationerrors, 'error');
133 }
39c6f4b6 134 $html .= $renderer->display_rubric($data['criteria'], $data['options'], $mode, $this->getName());
c586d2bf
MG
135 return $html;
136 }
137
39c6f4b6
MG
138 /**
139 * Prepares the data passed in $_POST:
140 * - processes the pressed buttons 'addlevel', 'addcriterion', 'moveup', 'movedown', 'delete' (when JavaScript is disabled)
2ae7faf1 141 * sets $this->nonjsbuttonpressed to true/false if such button was pressed
39c6f4b6
MG
142 * - if options not passed (i.e. we create a new rubric) fills the options array with the default values
143 * - if options are passed completes the options array with unchecked checkboxes
2ae7faf1
MG
144 * - if $withvalidation is set, adds 'error_xxx' attributes to elements that contain errors and creates an error string
145 * and stores it in $this->validationerrors
39c6f4b6
MG
146 *
147 * @param array $value
2ae7faf1 148 * @param boolean $withvalidation whether to enable data validation
39c6f4b6
MG
149 * @return array
150 */
3c2b3cb3 151 protected function prepare_data($value = null, $withvalidation = false) {
39c6f4b6
MG
152 if (null === $value) {
153 $value = $this->getValue();
154 }
2ae7faf1
MG
155 if ($this->nonjsbuttonpressed === null) {
156 $this->nonjsbuttonpressed = false;
157 }
158 $totalscore = 0;
159 $errors = array();
39c6f4b6
MG
160 $return = array('criteria' => array(), 'options' => gradingform_rubric_controller::get_default_options());
161 if (!isset($value['criteria'])) {
162 $value['criteria'] = array();
2ae7faf1 163 $errors['err_nocriteria'] = 1;
39c6f4b6 164 }
2ae7faf1 165 // If options are present in $value, replace default values with submitted values
39c6f4b6
MG
166 if (!empty($value['options'])) {
167 foreach (array_keys($return['options']) as $option) {
168 // special treatment for checkboxes
169 if (!empty($value['options'][$option])) {
170 $return['options'][$option] = $value['options'][$option];
171 } else {
172 $return['options'][$option] = null;
173 }
174 }
c586d2bf 175 }
0136124e
MG
176 if (is_array($value)) {
177 // for other array keys of $value no special treatmeant neeeded, copy them to return value as is
178 foreach (array_keys($value) as $key) {
179 if ($key != 'options' && $key != 'criteria') {
180 $return[$key] = $value[$key];
181 }
182 }
183 }
2ae7faf1
MG
184
185 // iterate through criteria
c586d2bf
MG
186 $lastaction = null;
187 $lastid = null;
39c6f4b6 188 foreach ($value['criteria'] as $id => $criterion) {
c586d2bf 189 if ($id == 'addcriterion') {
39c6f4b6 190 $id = $this->get_next_id(array_keys($value['criteria']));
ffbf4370
MG
191 $criterion = array('description' => '', 'levels' => array());
192 $i = 0;
193 // when adding new criterion copy the number of levels and their scores from the last criterion
194 if (!empty($value['criteria'][$lastid]['levels'])) {
195 foreach ($value['criteria'][$lastid]['levels'] as $lastlevel) {
a19d1057 196 $criterion['levels']['NEWID'.($i++)]['score'] = $lastlevel['score'];
ffbf4370
MG
197 }
198 } else {
a19d1057 199 $criterion['levels']['NEWID'.($i++)]['score'] = 0;
ffbf4370
MG
200 }
201 // add more levels so there are at least 3 in the new criterion. Increment by 1 the score for each next one
a19d1057
MG
202 for ($i=$i; $i<3; $i++) {
203 $criterion['levels']['NEWID'.$i]['score'] = $criterion['levels']['NEWID'.($i-1)]['score'] + 1;
ffbf4370
MG
204 }
205 // set other necessary fields (definition) for the levels in the new criterion
206 foreach (array_keys($criterion['levels']) as $i) {
207 $criterion['levels'][$i]['definition'] = '';
208 }
2ae7faf1 209 $this->nonjsbuttonpressed = true;
c586d2bf
MG
210 }
211 $levels = array();
2ae7faf1 212 $maxscore = null;
c586d2bf
MG
213 if (array_key_exists('levels', $criterion)) {
214 foreach ($criterion['levels'] as $levelid => $level) {
215 if ($levelid == 'addlevel') {
216 $levelid = $this->get_next_id(array_keys($criterion['levels']));
217 $level = array(
218 'definition' => '',
219 'score' => 0,
220 );
ffbf4370
MG
221 foreach ($criterion['levels'] as $lastlevel) {
222 if ($level['score'] < $lastlevel['score'] + 1) {
223 $level['score'] = $lastlevel['score'] + 1;
224 }
225 }
2ae7faf1 226 $this->nonjsbuttonpressed = true;
c586d2bf
MG
227 }
228 if (!array_key_exists('delete', $level)) {
2ae7faf1 229 if ($withvalidation) {
3c2b3cb3 230 if (!strlen(trim($level['definition']))) {
2ae7faf1
MG
231 $errors['err_nodefinition'] = 1;
232 $level['error_definition'] = true;
233 }
234 if (!preg_match('#^[\+]?\d*$#', trim($level['score'])) && !preg_match('#^[\+]?\d*[\.,]\d+$#', trim($level['score']))) {
2ae7faf1
MG
235 $errors['err_scoreformat'] = 1;
236 $level['error_score'] = true;
237 }
238 }
c586d2bf 239 $levels[$levelid] = $level;
2ae7faf1
MG
240 if ($maxscore === null || (float)$level['score'] > $maxscore) {
241 $maxscore = (float)$level['score'];
242 }
243 } else {
244 $this->nonjsbuttonpressed = true;
c586d2bf
MG
245 }
246 }
247 }
2ae7faf1 248 $totalscore += (float)$maxscore;
c586d2bf 249 $criterion['levels'] = $levels;
2ae7faf1
MG
250 if ($withvalidation && !array_key_exists('delete', $criterion)) {
251 if (count($levels)<2) {
252 $errors['err_mintwolevels'] = 1;
253 $criterion['error_levels'] = true;
254 }
3c2b3cb3 255 if (!strlen(trim($criterion['description']))) {
2ae7faf1
MG
256 $errors['err_nodescription'] = 1;
257 $criterion['error_description'] = true;
258 }
259 }
c586d2bf
MG
260 if (array_key_exists('moveup', $criterion) || $lastaction == 'movedown') {
261 unset($criterion['moveup']);
262 if ($lastid !== null) {
39c6f4b6
MG
263 $lastcriterion = $return['criteria'][$lastid];
264 unset($return['criteria'][$lastid]);
265 $return['criteria'][$id] = $criterion;
266 $return['criteria'][$lastid] = $lastcriterion;
c586d2bf 267 } else {
39c6f4b6 268 $return['criteria'][$id] = $criterion;
c586d2bf
MG
269 }
270 $lastaction = null;
271 $lastid = $id;
2ae7faf1 272 $this->nonjsbuttonpressed = true;
c586d2bf 273 } else if (array_key_exists('delete', $criterion)) {
2ae7faf1 274 $this->nonjsbuttonpressed = true;
c586d2bf
MG
275 } else {
276 if (array_key_exists('movedown', $criterion)) {
277 unset($criterion['movedown']);
278 $lastaction = 'movedown';
2ae7faf1 279 $this->nonjsbuttonpressed = true;
c586d2bf 280 }
39c6f4b6 281 $return['criteria'][$id] = $criterion;
c586d2bf
MG
282 $lastid = $id;
283 }
284 }
2ae7faf1
MG
285
286 if ($totalscore <= 0) {
287 $errors['err_totalscore'] = 1;
288 }
289
290 // add sort order field to criteria
c586d2bf 291 $csortorder = 1;
39c6f4b6
MG
292 foreach (array_keys($return['criteria']) as $id) {
293 $return['criteria'][$id]['sortorder'] = $csortorder++;
c586d2bf 294 }
2ae7faf1
MG
295
296 // create validation error string (if needed)
297 if ($withvalidation) {
298 if (count($errors)) {
299 $rv = array();
300 foreach ($errors as $error => $v) {
301 $rv[] = get_string($error, 'gradingform_rubric');
302 }
303 $this->validationerrors = join('<br/ >', $rv);
304 } else {
305 $this->validationerrors = false;
306 }
307 $this->wasvalidated = true;
308 }
c586d2bf
MG
309 return $return;
310 }
311
3c2b3cb3
MG
312 /**
313 * Scans array $ids to find the biggest element ! NEWID*, increments it by 1 and returns
314 *
315 * @param array $ids
316 * @return string
317 */
318 protected function get_next_id($ids) {
c586d2bf
MG
319 $maxid = 0;
320 foreach ($ids as $id) {
321 if (preg_match('/^NEWID(\d+)$/', $id, $matches) && ((int)$matches[1]) > $maxid) {
322 $maxid = (int)$matches[1];
323 }
324 }
325 return 'NEWID'.($maxid+1);
326 }
327
2ae7faf1
MG
328 /**
329 * Checks if a submit button was pressed which is supposed to be processed on client side by JS
330 * but user seem to have disabled JS in the browser.
331 * (buttons 'add criteria', 'add level', 'move up', 'move down', etc.)
332 * In this case the form containing this element is prevented from being submitted
333 *
334 * @param array $value
335 * @return boolean true if non-submit button was pressed and not processed by JS
336 */
3c2b3cb3 337 public function non_js_button_pressed($value) {
2ae7faf1
MG
338 if ($this->nonjsbuttonpressed === null) {
339 $this->prepare_data($value);
c586d2bf 340 }
2ae7faf1 341 return $this->nonjsbuttonpressed;
c586d2bf
MG
342 }
343
2ae7faf1
MG
344 /**
345 * Validates that rubric has at least one criterion, at least two levels within one criterion,
346 * each level has a valid score, all levels have filled definitions and all criteria
347 * have filled descriptions
348 *
349 * @param array $value
350 * @return string|false error text or false if no errors found
351 */
3c2b3cb3 352 public function validate($value) {
2ae7faf1
MG
353 if (!$this->wasvalidated) {
354 $this->prepare_data($value, true);
c586d2bf 355 }
2ae7faf1 356 return $this->validationerrors;
c586d2bf
MG
357 }
358
39c6f4b6
MG
359 /**
360 * Prepares the data for saving
39c6f4b6 361 *
d22e9e32 362 * @see prepare_data()
39c6f4b6
MG
363 * @param array $submitValues
364 * @param boolean $assoc
365 * @return array
366 */
3c2b3cb3 367 public function exportValue(&$submitValues, $assoc = false) {
2ae7faf1 368 $value = $this->prepare_data($this->_findValue($submitValues));
39c6f4b6
MG
369 return $this->_prepareValue($value, $assoc);
370 }
c586d2bf 371}