MDL-30241: fixing Javascript to work in IE as well
[moodle.git] / grade / grading / form / rubric / rubriceditor.php
CommitLineData
c586d2bf
MG
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * @package gradingform
20 * @subpackage rubric
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
c586d2bf
MG
29class MoodleQuickForm_rubriceditor extends HTML_QuickForm_input {
30 public $_helpbutton = '';
2ae7faf1
MG
31 protected $validationerrors = null; // null - undefined, false - no errors, string - error(s) text
32 protected $wasvalidated = false; // if element has already been validated
33 protected $nonjsbuttonpressed = false; // null - unknown, true/false - button was/wasn't pressed
c586d2bf
MG
34
35 function MoodleQuickForm_rubriceditor($elementName=null, $elementLabel=null, $attributes=null) {
36 parent::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
37 }
38
39 function getHelpButton() {
40 return $this->_helpbutton;
41 }
42
43 function getElementTemplateType() {
44 return 'default';
45 }
46
0136124e
MG
47 protected $regradeconfirmation = false;
48 /**
49 * Specifies that confirmation about re-grading needs to be added to this rubric editor.
50 * $changelevel is saved in $this->regradeconfirmation and retrieved in toHtml()
51 *
52 * @see gradingform_rubric_controller::update_or_check_rubric()
53 * @param int $changelevel
54 */
55 function add_regrade_confirmation($changelevel) {
56 $this->regradeconfirmation = $changelevel;
57 }
58
59 /**
60 * Returns html string to display this element
61 *
62 * @return string
63 */
c586d2bf
MG
64 function toHtml() {
65 global $PAGE;
66 $html = $this->_getTabs();
ab156741 67 $renderer = $PAGE->get_renderer('gradingform_rubric');
2ae7faf1 68 $data = $this->prepare_data(null, $this->wasvalidated);
c586d2bf 69 if (!$this->_flagFrozen) {
ab156741
MG
70 $mode = gradingform_rubric_controller::DISPLAY_EDIT_FULL;
71 $module = array('name'=>'gradingform_rubriceditor', 'fullpath'=>'/grade/grading/form/rubric/js/rubriceditor.js',
72 'strings' => array(array('confirmdeletecriterion', 'gradingform_rubric'), array('confirmdeletelevel', 'gradingform_rubric'),
73 array('criterionempty', 'gradingform_rubric'), array('levelempty', 'gradingform_rubric')
74 ));
75 $PAGE->requires->js_init_call('M.gradingform_rubriceditor.init', array(
76 array('name' => $this->getName(),
39c6f4b6
MG
77 'criteriontemplate' => $renderer->criterion_template($mode, $data['options'], $this->getName()),
78 'leveltemplate' => $renderer->level_template($mode, $data['options'], $this->getName())
ab156741
MG
79 )),
80 true, $module);
c586d2bf 81 } else {
39c6f4b6 82 // Rubric is frozen, no javascript needed
c586d2bf 83 if ($this->_persistantFreeze) {
ab156741
MG
84 $mode = gradingform_rubric_controller::DISPLAY_EDIT_FROZEN;
85 } else {
86 $mode = gradingform_rubric_controller::DISPLAY_PREVIEW;
c586d2bf 87 }
c586d2bf 88 }
0136124e
MG
89 if ($this->regradeconfirmation) {
90 if (!isset($data['regrade'])) {
91 $data['regrade'] = 1;
92 }
93 $html .= $renderer->display_regrade_confirmation($this->getName(), $this->regradeconfirmation, $data['regrade']);
94 }
2ae7faf1
MG
95 if ($this->validationerrors) {
96 $html .= $renderer->notification($this->validationerrors, 'error');
97 }
39c6f4b6 98 $html .= $renderer->display_rubric($data['criteria'], $data['options'], $mode, $this->getName());
c586d2bf
MG
99 return $html;
100 }
101
39c6f4b6
MG
102 /**
103 * Prepares the data passed in $_POST:
104 * - processes the pressed buttons 'addlevel', 'addcriterion', 'moveup', 'movedown', 'delete' (when JavaScript is disabled)
2ae7faf1 105 * sets $this->nonjsbuttonpressed to true/false if such button was pressed
39c6f4b6
MG
106 * - if options not passed (i.e. we create a new rubric) fills the options array with the default values
107 * - if options are passed completes the options array with unchecked checkboxes
2ae7faf1
MG
108 * - if $withvalidation is set, adds 'error_xxx' attributes to elements that contain errors and creates an error string
109 * and stores it in $this->validationerrors
39c6f4b6
MG
110 *
111 * @param array $value
2ae7faf1 112 * @param boolean $withvalidation whether to enable data validation
39c6f4b6
MG
113 * @return array
114 */
2ae7faf1 115 function prepare_data($value = null, $withvalidation = false) {
39c6f4b6
MG
116 if (null === $value) {
117 $value = $this->getValue();
118 }
2ae7faf1
MG
119 if ($this->nonjsbuttonpressed === null) {
120 $this->nonjsbuttonpressed = false;
121 }
122 $totalscore = 0;
123 $errors = array();
39c6f4b6
MG
124 $return = array('criteria' => array(), 'options' => gradingform_rubric_controller::get_default_options());
125 if (!isset($value['criteria'])) {
126 $value['criteria'] = array();
2ae7faf1 127 $errors['err_nocriteria'] = 1;
39c6f4b6 128 }
2ae7faf1 129 // If options are present in $value, replace default values with submitted values
39c6f4b6
MG
130 if (!empty($value['options'])) {
131 foreach (array_keys($return['options']) as $option) {
132 // special treatment for checkboxes
133 if (!empty($value['options'][$option])) {
134 $return['options'][$option] = $value['options'][$option];
135 } else {
136 $return['options'][$option] = null;
137 }
138 }
c586d2bf 139 }
0136124e
MG
140 if (is_array($value)) {
141 // for other array keys of $value no special treatmeant neeeded, copy them to return value as is
142 foreach (array_keys($value) as $key) {
143 if ($key != 'options' && $key != 'criteria') {
144 $return[$key] = $value[$key];
145 }
146 }
147 }
2ae7faf1
MG
148
149 // iterate through criteria
c586d2bf
MG
150 $lastaction = null;
151 $lastid = null;
39c6f4b6 152 foreach ($value['criteria'] as $id => $criterion) {
c586d2bf 153 if ($id == 'addcriterion') {
39c6f4b6 154 $id = $this->get_next_id(array_keys($value['criteria']));
ffbf4370
MG
155 $criterion = array('description' => '', 'levels' => array());
156 $i = 0;
157 // when adding new criterion copy the number of levels and their scores from the last criterion
158 if (!empty($value['criteria'][$lastid]['levels'])) {
159 foreach ($value['criteria'][$lastid]['levels'] as $lastlevel) {
160 $criterion['levels']['NEWID'+($i++)]['score'] = $lastlevel['score'];
161 }
162 } else {
163 $criterion['levels']['NEWID'+($i++)]['score'] = 0;
164 }
165 // add more levels so there are at least 3 in the new criterion. Increment by 1 the score for each next one
166 for ($i; $i<3; $i++) {
167 $criterion['levels']['NEWID'+$i]['score'] = $criterion['levels']['NEWID'+($i-1)]['score'] + 1;
168 }
169 // set other necessary fields (definition) for the levels in the new criterion
170 foreach (array_keys($criterion['levels']) as $i) {
171 $criterion['levels'][$i]['definition'] = '';
172 }
2ae7faf1 173 $this->nonjsbuttonpressed = true;
c586d2bf
MG
174 }
175 $levels = array();
2ae7faf1 176 $maxscore = null;
c586d2bf
MG
177 if (array_key_exists('levels', $criterion)) {
178 foreach ($criterion['levels'] as $levelid => $level) {
179 if ($levelid == 'addlevel') {
180 $levelid = $this->get_next_id(array_keys($criterion['levels']));
181 $level = array(
182 'definition' => '',
183 'score' => 0,
184 );
ffbf4370
MG
185 foreach ($criterion['levels'] as $lastlevel) {
186 if ($level['score'] < $lastlevel['score'] + 1) {
187 $level['score'] = $lastlevel['score'] + 1;
188 }
189 }
2ae7faf1 190 $this->nonjsbuttonpressed = true;
c586d2bf
MG
191 }
192 if (!array_key_exists('delete', $level)) {
2ae7faf1
MG
193 if ($withvalidation) {
194 if (empty($level['definition'])) {
195 $errors['err_nodefinition'] = 1;
196 $level['error_definition'] = true;
197 }
198 if (!preg_match('#^[\+]?\d*$#', trim($level['score'])) && !preg_match('#^[\+]?\d*[\.,]\d+$#', trim($level['score']))) {
199 // TODO why we can't allow negative score for rubric?
200 $errors['err_scoreformat'] = 1;
201 $level['error_score'] = true;
202 }
203 }
c586d2bf 204 $levels[$levelid] = $level;
2ae7faf1
MG
205 if ($maxscore === null || (float)$level['score'] > $maxscore) {
206 $maxscore = (float)$level['score'];
207 }
208 } else {
209 $this->nonjsbuttonpressed = true;
c586d2bf
MG
210 }
211 }
212 }
2ae7faf1 213 $totalscore += (float)$maxscore;
c586d2bf 214 $criterion['levels'] = $levels;
2ae7faf1
MG
215 if ($withvalidation && !array_key_exists('delete', $criterion)) {
216 if (count($levels)<2) {
217 $errors['err_mintwolevels'] = 1;
218 $criterion['error_levels'] = true;
219 }
220 if (empty($criterion['description'])) {
221 $errors['err_nodescription'] = 1;
222 $criterion['error_description'] = true;
223 }
224 }
c586d2bf
MG
225 if (array_key_exists('moveup', $criterion) || $lastaction == 'movedown') {
226 unset($criterion['moveup']);
227 if ($lastid !== null) {
39c6f4b6
MG
228 $lastcriterion = $return['criteria'][$lastid];
229 unset($return['criteria'][$lastid]);
230 $return['criteria'][$id] = $criterion;
231 $return['criteria'][$lastid] = $lastcriterion;
c586d2bf 232 } else {
39c6f4b6 233 $return['criteria'][$id] = $criterion;
c586d2bf
MG
234 }
235 $lastaction = null;
236 $lastid = $id;
2ae7faf1 237 $this->nonjsbuttonpressed = true;
c586d2bf 238 } else if (array_key_exists('delete', $criterion)) {
2ae7faf1 239 $this->nonjsbuttonpressed = true;
c586d2bf
MG
240 } else {
241 if (array_key_exists('movedown', $criterion)) {
242 unset($criterion['movedown']);
243 $lastaction = 'movedown';
2ae7faf1 244 $this->nonjsbuttonpressed = true;
c586d2bf 245 }
39c6f4b6 246 $return['criteria'][$id] = $criterion;
c586d2bf
MG
247 $lastid = $id;
248 }
249 }
2ae7faf1
MG
250
251 if ($totalscore <= 0) {
252 $errors['err_totalscore'] = 1;
253 }
254
255 // add sort order field to criteria
c586d2bf 256 $csortorder = 1;
39c6f4b6
MG
257 foreach (array_keys($return['criteria']) as $id) {
258 $return['criteria'][$id]['sortorder'] = $csortorder++;
c586d2bf 259 }
2ae7faf1
MG
260
261 // create validation error string (if needed)
262 if ($withvalidation) {
263 if (count($errors)) {
264 $rv = array();
265 foreach ($errors as $error => $v) {
266 $rv[] = get_string($error, 'gradingform_rubric');
267 }
268 $this->validationerrors = join('<br/ >', $rv);
269 } else {
270 $this->validationerrors = false;
271 }
272 $this->wasvalidated = true;
273 }
c586d2bf
MG
274 return $return;
275 }
276
277 function get_next_id($ids) {
278 $maxid = 0;
279 foreach ($ids as $id) {
280 if (preg_match('/^NEWID(\d+)$/', $id, $matches) && ((int)$matches[1]) > $maxid) {
281 $maxid = (int)$matches[1];
282 }
283 }
284 return 'NEWID'.($maxid+1);
285 }
286
2ae7faf1
MG
287 /**
288 * Checks if a submit button was pressed which is supposed to be processed on client side by JS
289 * but user seem to have disabled JS in the browser.
290 * (buttons 'add criteria', 'add level', 'move up', 'move down', etc.)
291 * In this case the form containing this element is prevented from being submitted
292 *
293 * @param array $value
294 * @return boolean true if non-submit button was pressed and not processed by JS
295 */
296 function non_js_button_pressed($value) {
297 if ($this->nonjsbuttonpressed === null) {
298 $this->prepare_data($value);
c586d2bf 299 }
2ae7faf1 300 return $this->nonjsbuttonpressed;
c586d2bf
MG
301 }
302
2ae7faf1
MG
303 /**
304 * Validates that rubric has at least one criterion, at least two levels within one criterion,
305 * each level has a valid score, all levels have filled definitions and all criteria
306 * have filled descriptions
307 *
308 * @param array $value
309 * @return string|false error text or false if no errors found
310 */
311 function validate($value) {
312 if (!$this->wasvalidated) {
313 $this->prepare_data($value, true);
c586d2bf 314 }
2ae7faf1 315 return $this->validationerrors;
c586d2bf
MG
316 }
317
39c6f4b6
MG
318 /**
319 * Prepares the data for saving
2ae7faf1 320 * @see prepare_data()
39c6f4b6
MG
321 *
322 * @param array $submitValues
323 * @param boolean $assoc
324 * @return array
325 */
326 function exportValue(&$submitValues, $assoc = false) {
2ae7faf1 327 $value = $this->prepare_data($this->_findValue($submitValues));
39c6f4b6
MG
328 return $this->_prepareValue($value, $assoc);
329 }
c586d2bf 330}