MDL-29483: advanced grading methods support on assignment module, grading form elemen...
[moodle.git] / grade / grading / form / rubric / lib.php
CommitLineData
9b8550f8
DM
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 * Grading method controller for the Rubric plugin
20 *
21 * @package gradingform
22 * @subpackage rubric
23 * @copyright 2011 David Mudrak <david@moodle.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
fe817d87 29require_once($CFG->dirroot.'/grade/grading/form/lib.php');
9b8550f8
DM
30
31/**
32 * This controller encapsulates the rubric grading logic
33 */
21d37aa6 34class gradingform_rubric_controller extends gradingform_controller {
ab156741
MG
35 // Modes of displaying the rubric (used in gradingform_rubric_renderer)
36 const DISPLAY_EDIT_FULL = 1; // For editing (moderator or teacher creates a rubric)
37 const DISPLAY_EDIT_FROZEN = 2; // Preview the rubric design with hidden fields
38 const DISPLAY_PREVIEW = 3; // Preview the rubric design
39 const DISPLAY_EVAL = 4; // For evaluation, enabled (teacher grades a student)
40 const DISPLAY_EVAL_FROZEN = 5; // For evaluation, with hidden fields
41 const DISPLAY_REVIEW = 6; // Dispaly filled rubric (i.e. students see their grades)
9b8550f8
DM
42
43 /**
44 * Extends the module settings navigation with the rubric grading settings
45 *
46 * This function is called when the context for the page is an activity module with the
47 * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
48 * and there is an area with the active grading method set to 'rubric'.
49 *
50 * @param settings_navigation $settingsnav {@link settings_navigation}
51 * @param navigation_node $node {@link navigation_node}
52 */
53 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
54 $node->add(get_string('definerubric', 'gradingform_rubric'),
6832a102 55 $this->get_editor_url(), settings_navigation::TYPE_CUSTOM,
9b8550f8
DM
56 null, null, new pix_icon('icon', '', 'gradingform_rubric'));
57 }
21d37aa6 58
c586d2bf 59 /**
fe817d87 60 * Saves the rubric definition into the database
c586d2bf 61 *
fe817d87
DM
62 * @see parent::update_definition()
63 * @param stdClass $newdefinition rubric definition data as coming from {@link self::postupdate_definition_data()}
64 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
c586d2bf 65 */
fe817d87 66 public function update_definition(stdClass $newdefinition, $usermodified = null) {
c586d2bf 67 global $DB;
c586d2bf 68
fe817d87
DM
69 // firstly update the common definition data in the {grading_definition} table
70 parent::update_definition($newdefinition, $usermodified);
71 // reload the definition from the database
72 $this->load_definition();
73 $currentdefinition = $this->get_definition();
74
75 // update current data
76 $haschanges = false;
77 if (empty($newdefinition->rubric_criteria)) {
78 $newcriteria = array();
c586d2bf 79 } else {
fe817d87 80 $newcriteria = $newdefinition->rubric_criteria; // new ones to be saved
c586d2bf 81 }
fe817d87
DM
82 $currentcriteria = $currentdefinition->rubric_criteria;
83 $criteriafields = array('sortorder', 'description', 'descriptionformat');
84 $levelfields = array('score', 'definition', 'definitionformat');
85 foreach ($newcriteria as $id => $criterion) {
86 // get list of submitted levels
87 $levelsdata = array();
88 if (array_key_exists('levels', $criterion)) {
89 $levelsdata = $criterion['levels'];
90 }
91 if (preg_match('/^NEWID\d+$/', $id)) {
92 // insert criterion into DB
93 $data = array('formid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE); // TODO format is not supported yet
94 foreach ($criteriafields as $key) {
95 if (array_key_exists($key, $criterion)) {
96 $data[$key] = $criterion[$key];
97 }
98 }
99 $id = $DB->insert_record('gradingform_rubric_criteria', $data);
100 $haschanges = true;
101 } else {
102 // update criterion in DB
103 $data = array();
104 foreach ($criteriafields as $key) {
105 if (array_key_exists($key, $criterion) && $criterion[$key] != $currentcriteria[$id][$key]) {
106 $data[$key] = $criterion[$key];
107 }
108 }
109 if (!empty($data)) {
110 // update only if something is changed
111 $data['id'] = $id;
112 $DB->update_record('gradingform_rubric_criteria', $data);
113 $haschanges = true;
c586d2bf 114 }
fe817d87
DM
115 // remove deleted levels from DB
116 foreach (array_keys($currentcriteria[$id]['levels']) as $levelid) {
117 if (!array_key_exists($levelid, $levelsdata)) {
118 $DB->delete_records('gradingform_rubric_levels', array('id' => $levelid));
119 $haschanges = true;
120 }
121 }
122 }
123 foreach ($levelsdata as $levelid => $level) {
124 if (preg_match('/^NEWID\d+$/', $levelid)) {
125 // insert level into DB
126 $data = array('criterionid' => $id, 'definitionformat' => FORMAT_MOODLE); // TODO format is not supported yet
127 foreach ($levelfields as $key) {
128 if (array_key_exists($key, $level)) {
129 $data[$key] = $level[$key];
c586d2bf
MG
130 }
131 }
fe817d87 132 $levelid = $DB->insert_record('gradingform_rubric_levels', $data);
c586d2bf
MG
133 $haschanges = true;
134 } else {
fe817d87 135 // update level in DB
c586d2bf 136 $data = array();
fe817d87
DM
137 foreach ($levelfields as $key) {
138 if (array_key_exists($key, $level) && $level[$key] != $currentcriteria[$id]['levels'][$levelid][$key]) {
139 $data[$key] = $level[$key];
c586d2bf
MG
140 }
141 }
142 if (!empty($data)) {
143 // update only if something is changed
fe817d87
DM
144 $data['id'] = $levelid;
145 $DB->update_record('gradingform_rubric_levels', $data);
c586d2bf 146 $haschanges = true;
c586d2bf
MG
147 }
148 }
149 }
c586d2bf 150 }
fe817d87
DM
151 // remove deleted criteria from DB
152 foreach (array_keys($currentcriteria) as $id) {
153 if (!array_key_exists($id, $newcriteria)) {
154 $DB->delete_records('gradingform_rubric_criteria', array('id' => $id));
155 $DB->delete_records('gradingform_rubric_levels', array('criterionid' => $id));
156 $haschanges = true;
157 }
c586d2bf 158 }
fe817d87 159 $this->load_definition();
c586d2bf
MG
160 }
161
162 /**
fe817d87 163 * Loads the rubric form definition if it exists
c586d2bf 164 *
fe817d87 165 * There is a new array called 'rubric_criteria' appended to the list of parent's definition properties.
c586d2bf 166 */
fe817d87 167 protected function load_definition() {
c586d2bf 168 global $DB;
fe817d87
DM
169
170 $sql = "SELECT gd.*,
171 rc.id AS rcid, rc.sortorder AS rcsortorder, rc.description AS rcdescription, rc.descriptionformat AS rcdescriptionformat,
172 rl.id AS rlid, rl.score AS rlscore, rl.definition AS rldefinition, rl.definitionformat AS rldefinitionformat
173 FROM {grading_definitions} gd
174 LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.formid = gd.id)
175 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)
176 WHERE gd.areaid = :areaid AND gd.method = :method
177 ORDER BY rc.sortorder,rl.score";
178 $params = array('areaid' => $this->areaid, 'method' => $this->get_method_name());
179
180 $rs = $DB->get_recordset_sql($sql, $params);
181 $this->definition = false;
182 foreach ($rs as $record) {
183 // pick the common definition data
184 if (empty($this->definition)) {
185 $this->definition = new stdClass();
186 foreach (array('id', 'name', 'description', 'descriptionformat', 'status', 'copiedfromid',
187 'timecreated', 'usercreated', 'timemodified', 'usermodified', 'options') as $fieldname) {
188 $this->definition->$fieldname = $record->$fieldname;
189 }
190 $this->definition->rubric_criteria = array();
191 }
192 // pick the criterion data
193 if (!empty($record->rcid) and empty($this->definition->rubric_criteria[$record->rcid])) {
194 foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
195 $this->definition->rubric_criteria[$record->rcid][$fieldname] = $record->{'rc'.$fieldname};
196 }
197 $this->definition->rubric_criteria[$record->rcid]['levels'] = array();
c586d2bf 198 }
fe817d87
DM
199 // pick the level data
200 if (!empty($record->rlid)) {
201 foreach (array('id', 'score', 'definition', 'definitionformat') as $fieldname) {
202 $this->definition->rubric_criteria[$record->rcid]['levels'][$record->rlid][$fieldname] = $record->{'rl'.$fieldname};
c586d2bf
MG
203 }
204 }
205 }
fe817d87 206 $rs->close();
c586d2bf
MG
207 }
208
209 /**
fe817d87 210 * Converts the current definition into an object suitable for the editor form's set_data()
c586d2bf 211 *
fe817d87 212 * @return stdClass
c586d2bf 213 */
fe817d87
DM
214 public function get_definition_for_editing() {
215
216 $definition = $this->get_definition();
c586d2bf 217 $properties = new stdClass();
fe817d87
DM
218 $properties->areaid = $this->areaid;
219 if ($definition) {
c586d2bf 220 foreach (array('id', 'name', 'description', 'descriptionformat', 'options', 'status') as $key) {
fe817d87 221 $properties->$key = $definition->$key;
c586d2bf 222 }
c586d2bf 223 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
224 $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
225 'gradingform_rubric', 'definition_description', $definition->id);
226 }
227 if (!empty($definition->rubric_criteria)) {
228 $properties->rubric_criteria = $definition->rubric_criteria;
229 } else {
230 $properties->rubric_criteria = array();
c586d2bf 231 }
c586d2bf 232
c586d2bf
MG
233 return $properties;
234 }
235
fde33804
DM
236 /**
237 * Returns the form definition suitable for cloning into another area
238 *
239 * @see parent::get_definition_copy()
240 * @param gradingform_controller $target the controller of the new copy
241 * @return stdClass definition structure to pass to the target's {@link update_definition()}
242 */
243 public function get_definition_copy(gradingform_controller $target) {
244
245 $new = parent::get_definition_copy($target);
246 $old = $this->get_definition();
247 $new->rubric_criteria = array();
248 $newcritid = 1;
249 $newlevid = 1;
250 foreach ($old->rubric_criteria as $oldcritid => $oldcrit) {
251 unset($oldcrit['id']);
252 if (isset($oldcrit['levels'])) {
253 foreach ($oldcrit['levels'] as $oldlevid => $oldlev) {
254 unset($oldlev['id']);
255 $oldcrit['levels']['NEWID'.$newlevid] = $oldlev;
256 unset($oldcrit['levels'][$oldlevid]);
257 $newlevid++;
258 }
259 } else {
260 $oldcrit['levels'] = array();
261 }
262 $new->rubric_criteria['NEWID'.$newcritid] = $oldcrit;
263 $newcritid++;
264 }
265
266 return $new;
267 }
268
c586d2bf
MG
269 // TODO the following functions may be moved to parent:
270
fe817d87
DM
271 /**
272 * @return array options for the form description field
273 */
c586d2bf
MG
274 public static function description_form_field_options($context) {
275 global $CFG;
276 return array(
277 'maxfiles' => -1,
278 'maxbytes' => get_max_upload_file_size($CFG->maxbytes),
fe817d87 279 'context' => $context,
c586d2bf
MG
280 );
281 }
282
283 public function get_formatted_description() {
284 if (!$this->definition) {
285 return null;
286 }
287 $context = $this->get_context();
288
289 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
290 $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
291 'gradingform_rubric', 'definition_description', $this->definition->id, $options);
c586d2bf
MG
292
293 $formatoptions = array(
294 'noclean' => false,
295 'trusted' => false,
296 'filter' => true,
297 'context' => $context
298 );
299 return format_text($description, $this->definition->descriptionformat, $formatoptions);
300 }
301
fe817d87
DM
302 /**
303 * Converts the rubric definition data from the submitted form back to the form
304 * suitable for storing in database
305 */
306 public function postupdate_definition_data($data) {
c586d2bf
MG
307 if (!$this->definition) {
308 return $data;
309 }
310 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
311 $data = file_postupdate_standard_editor($data, 'description', $options, $this->get_context(),
312 'gradingform_rubric', 'definition_description', $this->definition->id);
c586d2bf
MG
313 // TODO change filearea for embedded files in grading_definition.description
314 return $data;
315 }
18e6298c
MG
316
317 public function is_form_available($foruserid = null) {
318 return true;
319 // TODO this is temporary for testing!
320 }
6798c63e 321
6832a102
DM
322 /**
323 * Returns the rubric plugin renderer
324 *
325 * @param moodle_page $page the target page
326 * @return renderer_base
327 */
328 public function get_renderer(moodle_page $page) {
329 return $page->get_renderer('gradingform_'. $this->get_method_name());
330 }
331
332 /**
333 * Returns the HTML code displaying the preview of the grading form
334 *
335 * @param moodle_page $page the target page
336 * @return string
337 */
338 public function render_preview(moodle_page $page) {
339
340 // use the parent's method to render the common information about the form
341 $header = parent::render_preview($page);
342
343 // append the rubric itself, using own renderer
344 $output = $this->get_renderer($page);
36937f02
MG
345 $criteria = $this->definition->rubric_criteria;
346 $rubric = $output->display_rubric($criteria, self::DISPLAY_PREVIEW, 'rubric');
6832a102
DM
347
348 return $header . $rubric;
349 }
671ec8f5
DM
350
351 /**
352 * Deletes the rubric definition and all the associated information
353 */
354 protected function delete_plugin_definition() {
355 global $DB;
356
357 // get the list of instances
358 $instances = array_keys($DB->get_records('grading_instances', array('formid' => $this->definition->id), '', 'id'));
359 // delete all fillings
360 $DB->delete_records_list('gradingform_rubric_fillings', 'forminstanceid', $instances);
361 // delete instances
362 $DB->delete_records_list('grading_instances', 'id', $instances);
363 // get the list of criteria records
364 $criteria = array_keys($DB->get_records('gradingform_rubric_criteria', array('formid' => $this->definition->id), '', 'id'));
365 // delete levels
366 $DB->delete_records_list('gradingform_rubric_levels', 'criterionid', $criteria);
367 // delete critera
368 $DB->delete_records_list('gradingform_rubric_criteria', 'id', $criteria);
369 }
36937f02
MG
370
371 /**
372 * Returns html code to be included in student's feedback.
373 *
374 * @param moodle_page $page
375 * @param int $itemid
376 * @param string $defaultcontent default string to be returned if no active grading is found
377 * @return string
378 */
379 public function render_grade($page, $itemid, $defaultcontent) {
380 $instances = $this->get_current_instances($itemid);
381 return $this->get_renderer($page)->display_instances($this->get_current_instances($itemid), $defaultcontent);
382 }
9b8550f8 383}
36937f02
MG
384
385/**
386 * Class to manage one rubric grading instance. Stores information and performs actions like
387 * update, copy, validate, submit, etc.
388 *
389 * @copyright 2011 Marina Glancy
390 */
391class gradingform_rubric_instance extends gradingform_instance {
392
393 /**
394 * Deletes this (INCOMPLETE) instance from database.
395 */
396 public function cancel() {
397 global $DB;
398 parent::cancel();
399 $DB->delete_records('gradingform_rubric_fillings', array('forminstanceid' => $this->get_id()));
400 }
401
402 /**
403 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
404 * the specified values)
405 *
406 * @param int $raterid value for raterid in the duplicate
407 * @param int $itemid value for itemid in the duplicate
408 * @return int id of the new instance
409 */
410 public function copy($raterid, $itemid) {
411 global $DB;
412 $instanceid = parent::copy($raterid, $itemid);
413 $currentgrade = $this->get_rubric_filling();
414 foreach ($currentgrade as $criterionid => $levelid) {
415 $params = array('forminstanceid' => $instanceid, 'criterionid' => $criterionid, 'levelid' => $levelid);
416 $DB->insert_record('gradingform_rubric_fillings', $params);
417 }
418 // TODO remarks
419 return $instanceid;
420 }
421
422 /**
423 * Validates that rubric is fully completed and contains valid grade on each criterion
424 * @return boolean true if the form data is validated and contains no errors
425 */
426 public function validate_grading_element($elementvalue) {
427 // TODO: if there is nothing selected in rubric, we don't enter this function at all :(
428 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
429 if (!is_array($elementvalue) || sizeof($elementvalue) < sizeof($criteria)) {
430 return false;
431 }
432 foreach ($criteria as $id => $criterion) {
433 if (!array_key_exists($id, $elementvalue) || !array_key_exists($elementvalue[$id], $criterion['levels'])) {
434 return false;
435 }
436 }
437 return true;
438 }
439
440 /**
441 * Retrieves from DB and returns the data how this rubric was filled
442 *
443 * @return array
444 */
445 public function get_rubric_filling() {
446 // TODO cache
447 global $DB;
448 $rs = $DB->get_records('gradingform_rubric_fillings', array('forminstanceid' => $this->get_id()));
449 $grading = array();
450 foreach ($rs as $record) {
451 if ($record->levelid) {
452 $grading[$record->criterionid] = $record->levelid;
453 }
454 // TODO: remarks
455 }
456 return $grading;
457 }
458
459 /**
460 * Updates the instance with the data received from grading form. This function may be
461 * called via AJAX when grading is not yet completed, so it does not change the
462 * status of the instance.
463 */
464 public function update($data) {
465 global $DB;
466 $currentgrade = $this->get_rubric_filling();
467 parent::update($data); // TODO ? +timemodified
468 foreach ($data as $criterionid => $levelid) {
469 $params = array('forminstanceid' => $this->get_id(), 'criterionid' => $criterionid);
470 if (!array_key_exists($criterionid, $currentgrade)) {
471 $DB->insert_record('gradingform_rubric_fillings', $params + array('levelid' => $levelid));
472 } else if ($currentgrade[$criterionid] != $levelid) {
473 $DB->set_field('gradingform_rubric_fillings', 'levelid', $levelid, $params);
474 }
475 }
476 foreach ($currentgrade as $criterionid => $levelid) {
477 if (!array_key_exists($criterionid, $data)) {
478 $params = array('forminstanceid' => $this->get_id(), 'criterionid' => $criterionid);
479 $DB->delete_records('gradingform_rubric_fillings', $params);
480 }
481 }
482 // TODO: remarks
483 }
484
485 /**
486 * Calculates the grade to be pushed to the gradebook
487 * @return int the grade on 0-100 scale
488 */
489 public function get_grade() {
490 global $DB, $USER;
491 $grade = $this->get_rubric_filling();
492
493 $minscore = 0;
494 $maxscore = 0;
495 foreach ($this->get_controller()->get_definition()->rubric_criteria as $id => $criterion) {
496 $keys = array_keys($criterion['levels']);
497 // TODO array_reverse($keys) if levels are sorted DESC
498 $minscore += $criterion['levels'][$keys[0]]['score'];
499 $maxscore += $criterion['levels'][$keys[sizeof($keys)-1]]['score'];
500 }
501
502 if ($maxscore == 0) {
503 return -1;
504 }
505
506 $curscore = 0;
507 foreach ($grade as $id => $levelid) {
508 $curscore += $this->get_controller()->get_definition()->rubric_criteria[$id]['levels'][$levelid]['score'];
509 }
510 return $curscore/$maxscore*100; // TODO mapping
511 }
512
513 /**
514 * Returns the error message displayed in case of validation failed
515 *
516 * @return string
517 */
518 public function default_validation_error_message() {
519 return 'The rubric is incomplete'; //TODO string
520 }
521
522 /**
523 * Returns html for form element of type 'grading'.
524 *
525 * @param moodle_page $page
526 * @param MoodleQuickForm_grading $formelement
527 * @return string
528 */
529 public function render_grading_element($page, $gradingformelement) {
530 global $USER;
531 if (!$gradingformelement->_flagFrozen) {
532 $module = array('name'=>'gradingform_rubric', 'fullpath'=>'/grade/grading/form/rubric/js/rubric.js');
533 $page->requires->js_init_call('M.gradingform_rubric.init', array(array('name' => $gradingformelement->getName())), true, $module);
534 $mode = gradingform_rubric_controller::DISPLAY_EVAL;
535 } else {
536 if ($gradingformelement->_persistantFreeze) {
537 $mode = gradingform_rubric_controller::DISPLAY_EVAL_FROZEN;
538 } else {
539 $mode = gradingform_rubric_controller::DISPLAY_REVIEW;
540 }
541 }
542 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
543 $value = $gradingformelement->getValue();
544 if ($value === null) {
545 $value = $this->get_rubric_filling();
546 }
547 return $this->get_controller()->get_renderer($page)->display_rubric($criteria, $mode, $gradingformelement->getName(), $value);
548 }
549}