MDL-30998: updated docblocks for advanced grading
[moodle.git] / grade / grading / form / rubric / lib.php
CommitLineData
9b8550f8 1<?php
9b8550f8
DM
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/**
18 * Grading method controller for the Rubric plugin
19 *
d22e9e32 20 * @package gradingform_rubric
9b8550f8
DM
21 * @copyright 2011 David Mudrak <david@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25defined('MOODLE_INTERNAL') || die();
26
fe817d87 27require_once($CFG->dirroot.'/grade/grading/form/lib.php');
9b8550f8
DM
28
29/**
30 * This controller encapsulates the rubric grading logic
d22e9e32
MG
31 *
32 * @copyright 2011 David Mudrak <david@moodle.com>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9b8550f8 34 */
21d37aa6 35class gradingform_rubric_controller extends gradingform_controller {
ab156741 36 // Modes of displaying the rubric (used in gradingform_rubric_renderer)
3c2b3cb3
MG
37 /** Rubric display mode: For editing (moderator or teacher creates a rubric) */
38 const DISPLAY_EDIT_FULL = 1;
39 /** Rubric display mode: Preview the rubric design with hidden fields */
40 const DISPLAY_EDIT_FROZEN = 2;
577c8964 41 /** Rubric display mode: Preview the rubric design (for person with manage permission) */
3c2b3cb3 42 const DISPLAY_PREVIEW = 3;
577c8964
MG
43 /** Rubric display mode: Preview the rubric (for people being graded) */
44 const DISPLAY_PREVIEW_GRADED= 8;
3c2b3cb3
MG
45 /** Rubric display mode: For evaluation, enabled (teacher grades a student) */
46 const DISPLAY_EVAL = 4;
47 /** Rubric display mode: For evaluation, with hidden fields */
48 const DISPLAY_EVAL_FROZEN = 5;
49 /** Rubric display mode: Teacher reviews filled rubric */
50 const DISPLAY_REVIEW = 6;
51 /** Rubric display mode: Dispaly filled rubric (i.e. students see their grades) */
52 const DISPLAY_VIEW = 7;
9b8550f8
DM
53
54 /**
55 * Extends the module settings navigation with the rubric grading settings
56 *
57 * This function is called when the context for the page is an activity module with the
58 * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
59 * and there is an area with the active grading method set to 'rubric'.
60 *
61 * @param settings_navigation $settingsnav {@link settings_navigation}
62 * @param navigation_node $node {@link navigation_node}
63 */
64 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
65 $node->add(get_string('definerubric', 'gradingform_rubric'),
6832a102 66 $this->get_editor_url(), settings_navigation::TYPE_CUSTOM,
9b8550f8
DM
67 null, null, new pix_icon('icon', '', 'gradingform_rubric'));
68 }
21d37aa6 69
577c8964
MG
70 /**
71 * Extends the module navigation
72 *
73 * This function is called when the context for the page is an activity module with the
74 * FEATURE_ADVANCED_GRADING and there is an area with the active grading method set to the given plugin.
75 *
76 * @param global_navigation $navigation {@link global_navigation}
77 * @param navigation_node $node {@link navigation_node}
78 */
79 public function extend_navigation(global_navigation $navigation, navigation_node $node=null) {
80 if (has_capability('moodle/grade:managegradingforms', $this->get_context())) {
81 // no need for preview if user can manage forms, he will have link to manage.php in settings instead
82 return;
83 }
84 if ($this->is_form_defined() && ($options = $this->get_options()) && !empty($options['alwaysshowdefinition'])) {
85 $node->add(get_string('gradingof', 'gradingform_rubric', get_grading_manager($this->get_areaid())->get_area_title()),
86 new moodle_url('/grade/grading/form/'.$this->get_method_name().'/preview.php', array('areaid' => $this->get_areaid())),
87 settings_navigation::TYPE_CUSTOM);
88 }
89 }
90
c586d2bf 91 /**
fe817d87 92 * Saves the rubric definition into the database
c586d2bf 93 *
fe817d87 94 * @see parent::update_definition()
9e2eca0f 95 * @param stdClass $newdefinition rubric definition data as coming from gradingform_rubric_editrubric::get_data()
fe817d87 96 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
c586d2bf 97 */
3599b113 98 public function update_definition(stdClass $newdefinition, $usermodified = null) {
0136124e
MG
99 $this->update_or_check_rubric($newdefinition, $usermodified, true);
100 if (isset($newdefinition->rubric['regrade']) && $newdefinition->rubric['regrade']) {
101 $this->mark_for_regrade();
102 }
103 }
104
105 /**
106 * Either saves the rubric definition into the database or check if it has been changed.
107 * Returns the level of changes:
108 * 0 - no changes
109 * 1 - only texts or criteria sortorders are changed, students probably do not require re-grading
110 * 2 - added levels but maximum score on rubric is the same, students still may not require re-grading
111 * 3 - removed criteria or added levels or changed number of points, students require re-grading but may be re-graded automatically
112 * 4 - removed levels - students require re-grading and not all students may be re-graded automatically
113 * 5 - added criteria - all students require manual re-grading
114 *
115 * @param stdClass $newdefinition rubric definition data as coming from gradingform_rubric_editrubric::get_data()
116 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
117 * @param boolean $doupdate if true actually updates DB, otherwise performs a check
118 *
119 */
120 public function update_or_check_rubric(stdClass $newdefinition, $usermodified = null, $doupdate = false) {
c586d2bf 121 global $DB;
c586d2bf 122
fe817d87 123 // firstly update the common definition data in the {grading_definition} table
9e2eca0f 124 if ($this->definition === false) {
0136124e
MG
125 if (!$doupdate) {
126 // if we create the new definition there is no such thing as re-grading anyway
127 return 5;
128 }
7622ae95 129 // if definition does not exist yet, create a blank one
9e2eca0f 130 // (we need id to save files embedded in description)
3599b113 131 parent::update_definition(new stdClass(), $usermodified);
9e2eca0f
MG
132 parent::load_definition();
133 }
39c6f4b6
MG
134 if (!isset($newdefinition->rubric['options'])) {
135 $newdefinition->rubric['options'] = self::get_default_options();
136 }
137 $newdefinition->options = json_encode($newdefinition->rubric['options']);
138 $editoroptions = self::description_form_field_options($this->get_context());
139 $newdefinition = file_postupdate_standard_editor($newdefinition, 'description', $editoroptions, $this->get_context(),
b2c16c6e 140 'grading', 'description', $this->definition->id);
9e2eca0f 141
fe817d87 142 // reload the definition from the database
9e2eca0f 143 $currentdefinition = $this->get_definition(true);
fe817d87 144
9e2eca0f 145 // update rubric data
0136124e 146 $haschanges = array();
39c6f4b6 147 if (empty($newdefinition->rubric['criteria'])) {
fe817d87 148 $newcriteria = array();
c586d2bf 149 } else {
39c6f4b6 150 $newcriteria = $newdefinition->rubric['criteria']; // new ones to be saved
c586d2bf 151 }
fe817d87
DM
152 $currentcriteria = $currentdefinition->rubric_criteria;
153 $criteriafields = array('sortorder', 'description', 'descriptionformat');
154 $levelfields = array('score', 'definition', 'definitionformat');
155 foreach ($newcriteria as $id => $criterion) {
156 // get list of submitted levels
157 $levelsdata = array();
158 if (array_key_exists('levels', $criterion)) {
159 $levelsdata = $criterion['levels'];
160 }
0136124e 161 $criterionmaxscore = null;
fe817d87
DM
162 if (preg_match('/^NEWID\d+$/', $id)) {
163 // insert criterion into DB
d22e9e32 164 $data = array('definitionid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE); // TODO MDL-31235 format is not supported yet
fe817d87
DM
165 foreach ($criteriafields as $key) {
166 if (array_key_exists($key, $criterion)) {
167 $data[$key] = $criterion[$key];
168 }
169 }
0136124e
MG
170 if ($doupdate) {
171 $id = $DB->insert_record('gradingform_rubric_criteria', $data);
172 }
173 $haschanges[5] = true;
fe817d87
DM
174 } else {
175 // update criterion in DB
176 $data = array();
177 foreach ($criteriafields as $key) {
178 if (array_key_exists($key, $criterion) && $criterion[$key] != $currentcriteria[$id][$key]) {
179 $data[$key] = $criterion[$key];
180 }
181 }
182 if (!empty($data)) {
183 // update only if something is changed
184 $data['id'] = $id;
0136124e
MG
185 if ($doupdate) {
186 $DB->update_record('gradingform_rubric_criteria', $data);
187 }
188 $haschanges[1] = true;
c586d2bf 189 }
0136124e
MG
190 // remove deleted levels from DB and calculate the maximum score for this criteria
191 foreach ($currentcriteria[$id]['levels'] as $levelid => $currentlevel) {
192 if ($criterionmaxscore === null || $criterionmaxscore < $currentlevel['score']) {
193 $criterionmaxscore = $currentlevel['score'];
194 }
fe817d87 195 if (!array_key_exists($levelid, $levelsdata)) {
0136124e
MG
196 if ($doupdate) {
197 $DB->delete_records('gradingform_rubric_levels', array('id' => $levelid));
198 }
199 $haschanges[4] = true;
fe817d87
DM
200 }
201 }
202 }
203 foreach ($levelsdata as $levelid => $level) {
2ae7faf1
MG
204 if (isset($level['score'])) {
205 $level['score'] = (float)$level['score'];
206 if ($level['score']<0) {
2ae7faf1
MG
207 $level['score'] = 0;
208 }
209 }
fe817d87
DM
210 if (preg_match('/^NEWID\d+$/', $levelid)) {
211 // insert level into DB
d22e9e32 212 $data = array('criterionid' => $id, 'definitionformat' => FORMAT_MOODLE); // TODO MDL-31235 format is not supported yet
fe817d87
DM
213 foreach ($levelfields as $key) {
214 if (array_key_exists($key, $level)) {
215 $data[$key] = $level[$key];
c586d2bf
MG
216 }
217 }
0136124e
MG
218 if ($doupdate) {
219 $levelid = $DB->insert_record('gradingform_rubric_levels', $data);
220 }
221 if ($criterionmaxscore !== null && $criterionmaxscore >= $level['score']) {
222 // new level is added but the maximum score for this criteria did not change, re-grading may not be necessary
223 $haschanges[2] = true;
224 } else {
225 $haschanges[3] = true;
226 }
c586d2bf 227 } else {
fe817d87 228 // update level in DB
c586d2bf 229 $data = array();
fe817d87
DM
230 foreach ($levelfields as $key) {
231 if (array_key_exists($key, $level) && $level[$key] != $currentcriteria[$id]['levels'][$levelid][$key]) {
232 $data[$key] = $level[$key];
c586d2bf
MG
233 }
234 }
235 if (!empty($data)) {
236 // update only if something is changed
fe817d87 237 $data['id'] = $levelid;
0136124e
MG
238 if ($doupdate) {
239 $DB->update_record('gradingform_rubric_levels', $data);
240 }
241 if (isset($data['score'])) {
242 $haschanges[3] = true;
243 }
244 $haschanges[1] = true;
c586d2bf
MG
245 }
246 }
247 }
c586d2bf 248 }
fe817d87
DM
249 // remove deleted criteria from DB
250 foreach (array_keys($currentcriteria) as $id) {
251 if (!array_key_exists($id, $newcriteria)) {
0136124e
MG
252 if ($doupdate) {
253 $DB->delete_records('gradingform_rubric_criteria', array('id' => $id));
254 $DB->delete_records('gradingform_rubric_levels', array('criterionid' => $id));
255 }
256 $haschanges[3] = true;
fe817d87 257 }
c586d2bf 258 }
0136124e
MG
259 foreach (array('status', 'description', 'descriptionformat', 'name', 'options') as $key) {
260 if (isset($newdefinition->$key) && $newdefinition->$key != $this->definition->$key) {
261 $haschanges[1] = true;
262 }
263 }
264 if ($usermodified && $usermodified != $this->definition->usermodified) {
265 $haschanges[1] = true;
266 }
267 if (!count($haschanges)) {
268 return 0;
269 }
270 if ($doupdate) {
271 parent::update_definition($newdefinition, $usermodified);
272 $this->load_definition();
273 }
274 // return the maximum level of changes
275 $changelevels = array_keys($haschanges);
276 sort($changelevels);
277 return array_pop($changelevels);
278 }
279
3c2b3cb3
MG
280 /**
281 * Marks all instances filled with this rubric with the status INSTANCE_STATUS_NEEDUPDATE
282 */
0136124e
MG
283 public function mark_for_regrade() {
284 global $DB;
285 if ($this->has_active_instances()) {
71ab436a 286 $conditions = array('definitionid' => $this->definition->id,
0136124e
MG
287 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
288 $DB->set_field('grading_instances', 'status', gradingform_instance::INSTANCE_STATUS_NEEDUPDATE, $conditions);
289 }
c586d2bf
MG
290 }
291
292 /**
fe817d87 293 * Loads the rubric form definition if it exists
c586d2bf 294 *
fe817d87 295 * There is a new array called 'rubric_criteria' appended to the list of parent's definition properties.
c586d2bf 296 */
fe817d87 297 protected function load_definition() {
c586d2bf 298 global $DB;
fe817d87
DM
299 $sql = "SELECT gd.*,
300 rc.id AS rcid, rc.sortorder AS rcsortorder, rc.description AS rcdescription, rc.descriptionformat AS rcdescriptionformat,
301 rl.id AS rlid, rl.score AS rlscore, rl.definition AS rldefinition, rl.definitionformat AS rldefinitionformat
302 FROM {grading_definitions} gd
71ab436a 303 LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.definitionid = gd.id)
fe817d87
DM
304 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)
305 WHERE gd.areaid = :areaid AND gd.method = :method
306 ORDER BY rc.sortorder,rl.score";
307 $params = array('areaid' => $this->areaid, 'method' => $this->get_method_name());
308
309 $rs = $DB->get_recordset_sql($sql, $params);
310 $this->definition = false;
311 foreach ($rs as $record) {
312 // pick the common definition data
5060997b 313 if ($this->definition === false) {
fe817d87
DM
314 $this->definition = new stdClass();
315 foreach (array('id', 'name', 'description', 'descriptionformat', 'status', 'copiedfromid',
3f3ee711 316 'timecreated', 'usercreated', 'timemodified', 'usermodified', 'timecopied', 'options') as $fieldname) {
fe817d87
DM
317 $this->definition->$fieldname = $record->$fieldname;
318 }
319 $this->definition->rubric_criteria = array();
320 }
321 // pick the criterion data
322 if (!empty($record->rcid) and empty($this->definition->rubric_criteria[$record->rcid])) {
323 foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
324 $this->definition->rubric_criteria[$record->rcid][$fieldname] = $record->{'rc'.$fieldname};
325 }
326 $this->definition->rubric_criteria[$record->rcid]['levels'] = array();
c586d2bf 327 }
fe817d87
DM
328 // pick the level data
329 if (!empty($record->rlid)) {
330 foreach (array('id', 'score', 'definition', 'definitionformat') as $fieldname) {
2ae7faf1
MG
331 $value = $record->{'rl'.$fieldname};
332 if ($fieldname == 'score') {
333 $value = (float)$value; // To prevent display like 1.00000
334 }
335 $this->definition->rubric_criteria[$record->rcid]['levels'][$record->rlid][$fieldname] = $value;
c586d2bf
MG
336 }
337 }
338 }
fe817d87 339 $rs->close();
39c6f4b6
MG
340 $options = $this->get_options();
341 if (!$options['sortlevelsasc']) {
342 foreach (array_keys($this->definition->rubric_criteria) as $rcid) {
343 $this->definition->rubric_criteria[$rcid]['levels'] = array_reverse($this->definition->rubric_criteria[$rcid]['levels'], true);
344 }
345 }
346 }
347
3c2b3cb3
MG
348 /**
349 * Returns the default options for the rubric display
350 *
351 * @return array
352 */
39c6f4b6
MG
353 public static function get_default_options() {
354 $options = array(
355 'sortlevelsasc' => 1,
577c8964
MG
356 'alwaysshowdefinition' => 1,
357 'showdescriptionteacher' => 1,
358 'showdescriptionstudent' => 1,
39c6f4b6
MG
359 'showscoreteacher' => 1,
360 'showscorestudent' => 1,
361 'enableremarks' => 1,
362 'showremarksstudent' => 1
363 );
39c6f4b6
MG
364 return $options;
365 }
366
3c2b3cb3
MG
367 /**
368 * Gets the options of this rubric definition, fills the missing options with default values
369 *
370 * @return array
371 */
39c6f4b6
MG
372 public function get_options() {
373 $options = self::get_default_options();
374 if (!empty($this->definition->options)) {
375 $thisoptions = json_decode($this->definition->options);
376 foreach ($thisoptions as $option => $value) {
377 $options[$option] = $value;
378 }
379 }
380 return $options;
c586d2bf
MG
381 }
382
383 /**
fe817d87 384 * Converts the current definition into an object suitable for the editor form's set_data()
c586d2bf 385 *
a19d1057 386 * @param boolean $addemptycriterion whether to add an empty criterion if the rubric is completely empty (just being created)
fe817d87 387 * @return stdClass
c586d2bf 388 */
a19d1057 389 public function get_definition_for_editing($addemptycriterion = false) {
fe817d87
DM
390
391 $definition = $this->get_definition();
c586d2bf 392 $properties = new stdClass();
fe817d87
DM
393 $properties->areaid = $this->areaid;
394 if ($definition) {
39c6f4b6 395 foreach (array('id', 'name', 'description', 'descriptionformat', 'status') as $key) {
fe817d87 396 $properties->$key = $definition->$key;
c586d2bf 397 }
c586d2bf 398 $options = self::description_form_field_options($this->get_context());
fe817d87 399 $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
b2c16c6e 400 'grading', 'description', $definition->id);
fe817d87 401 }
39c6f4b6 402 $properties->rubric = array('criteria' => array(), 'options' => $this->get_options());
fe817d87 403 if (!empty($definition->rubric_criteria)) {
39c6f4b6 404 $properties->rubric['criteria'] = $definition->rubric_criteria;
a19d1057
MG
405 } else if (!$definition && $addemptycriterion) {
406 $properties->rubric['criteria'] = array('addcriterion' => 1);
c586d2bf 407 }
c586d2bf 408
c586d2bf
MG
409 return $properties;
410 }
411
fde33804
DM
412 /**
413 * Returns the form definition suitable for cloning into another area
414 *
415 * @see parent::get_definition_copy()
416 * @param gradingform_controller $target the controller of the new copy
417 * @return stdClass definition structure to pass to the target's {@link update_definition()}
418 */
419 public function get_definition_copy(gradingform_controller $target) {
420
421 $new = parent::get_definition_copy($target);
8722a322
MG
422 $old = $this->get_definition_for_editing();
423 $new->description_editor = $old->description_editor;
39c6f4b6 424 $new->rubric = array('criteria' => array(), 'options' => $old->rubric['options']);
fde33804
DM
425 $newcritid = 1;
426 $newlevid = 1;
39c6f4b6 427 foreach ($old->rubric['criteria'] as $oldcritid => $oldcrit) {
fde33804
DM
428 unset($oldcrit['id']);
429 if (isset($oldcrit['levels'])) {
430 foreach ($oldcrit['levels'] as $oldlevid => $oldlev) {
431 unset($oldlev['id']);
432 $oldcrit['levels']['NEWID'.$newlevid] = $oldlev;
433 unset($oldcrit['levels'][$oldlevid]);
434 $newlevid++;
435 }
436 } else {
437 $oldcrit['levels'] = array();
438 }
39c6f4b6 439 $new->rubric['criteria']['NEWID'.$newcritid] = $oldcrit;
fde33804
DM
440 $newcritid++;
441 }
442
443 return $new;
444 }
445
fe817d87 446 /**
3c2b3cb3
MG
447 * Options for displaying the rubric description field in the form
448 *
449 * @param object $context
fe817d87
DM
450 * @return array options for the form description field
451 */
c586d2bf
MG
452 public static function description_form_field_options($context) {
453 global $CFG;
454 return array(
455 'maxfiles' => -1,
1812ea3e 456 'maxbytes' => get_user_max_upload_file_size($context, $CFG->maxbytes),
fe817d87 457 'context' => $context,
c586d2bf
MG
458 );
459 }
460
3599b113
MG
461 /**
462 * Formats the definition description for display on page
463 *
464 * @return string
465 */
c586d2bf 466 public function get_formatted_description() {
3599b113
MG
467 if (!isset($this->definition->description)) {
468 return '';
c586d2bf
MG
469 }
470 $context = $this->get_context();
471
472 $options = self::description_form_field_options($this->get_context());
fe817d87 473 $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
b2c16c6e 474 'grading', 'description', $this->definition->id, $options);
c586d2bf
MG
475
476 $formatoptions = array(
477 'noclean' => false,
478 'trusted' => false,
479 'filter' => true,
480 'context' => $context
481 );
482 return format_text($description, $this->definition->descriptionformat, $formatoptions);
483 }
484
6832a102
DM
485 /**
486 * Returns the rubric plugin renderer
487 *
488 * @param moodle_page $page the target page
3c2b3cb3 489 * @return gradingform_rubric_renderer
6832a102
DM
490 */
491 public function get_renderer(moodle_page $page) {
492 return $page->get_renderer('gradingform_'. $this->get_method_name());
493 }
494
495 /**
496 * Returns the HTML code displaying the preview of the grading form
497 *
498 * @param moodle_page $page the target page
499 * @return string
500 */
501 public function render_preview(moodle_page $page) {
502
20836db9
DM
503 if (!$this->is_form_defined()) {
504 throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
505 }
6832a102 506
6832a102 507 $output = $this->get_renderer($page);
36937f02 508 $criteria = $this->definition->rubric_criteria;
39c6f4b6 509 $options = $this->get_options();
577c8964 510 $rubric = '';
42b18674
MG
511 if (has_capability('moodle/grade:managegradingforms', $page->context)) {
512 $showdescription = true;
513 } else {
514 $showdescription = $options['showdescriptionstudent'];
515 }
516 if ($showdescription) {
517 $rubric .= $output->box($this->get_formatted_description(), 'gradingform_rubric-description');
518 }
577c8964
MG
519 if (has_capability('moodle/grade:managegradingforms', $page->context)) {
520 $rubric .= $output->display_rubric_mapping_explained($this->get_min_max_score());
521 $rubric .= $output->display_rubric($criteria, $options, self::DISPLAY_PREVIEW, 'rubric');
522 } else {
523 $rubric .= $output->display_rubric($criteria, $options, self::DISPLAY_PREVIEW_GRADED, 'rubric');
524 }
6832a102 525
20836db9 526 return $rubric;
6832a102 527 }
671ec8f5
DM
528
529 /**
530 * Deletes the rubric definition and all the associated information
531 */
532 protected function delete_plugin_definition() {
533 global $DB;
534
535 // get the list of instances
71ab436a 536 $instances = array_keys($DB->get_records('grading_instances', array('definitionid' => $this->definition->id), '', 'id'));
671ec8f5 537 // delete all fillings
6f07a6a2 538 $DB->delete_records_list('gradingform_rubric_fillings', 'instanceid', $instances);
671ec8f5
DM
539 // delete instances
540 $DB->delete_records_list('grading_instances', 'id', $instances);
541 // get the list of criteria records
71ab436a 542 $criteria = array_keys($DB->get_records('gradingform_rubric_criteria', array('definitionid' => $this->definition->id), '', 'id'));
671ec8f5
DM
543 // delete levels
544 $DB->delete_records_list('gradingform_rubric_levels', 'criterionid', $criteria);
545 // delete critera
546 $DB->delete_records_list('gradingform_rubric_criteria', 'id', $criteria);
547 }
36937f02 548
188e840b
MG
549 /**
550 * If instanceid is specified and grading instance exists and it is created by this rater for
551 * this item, this instance is returned.
552 * If there exists a draft for this raterid+itemid, take this draft (this is the change from parent)
553 * Otherwise new instance is created for the specified rater and itemid
554 *
555 * @param int $instanceid
556 * @param int $raterid
557 * @param int $itemid
558 * @return gradingform_instance
559 */
560 public function get_or_create_instance($instanceid, $raterid, $itemid) {
561 global $DB;
562 if ($instanceid &&
563 $instance = $DB->get_record('grading_instances', array('id' => $instanceid, 'raterid' => $raterid, 'itemid' => $itemid), '*', IGNORE_MISSING)) {
564 return $this->get_instance($instance);
565 }
566 if ($itemid && $raterid) {
8fea05bf
DM
567 $params = array('definitionid' => $this->definition->id, 'raterid' => $raterid, 'itemid' => $itemid);
568 if ($rs = $DB->get_records('grading_instances', $params, 'timemodified DESC', '*', 0, 1)) {
188e840b
MG
569 $record = reset($rs);
570 $currentinstance = $this->get_current_instance($raterid, $itemid);
050125d4
MG
571 if ($record->status == gradingform_rubric_instance::INSTANCE_STATUS_INCOMPLETE &&
572 (!$currentinstance || $record->timemodified > $currentinstance->get_data('timemodified'))) {
188e840b
MG
573 $record->isrestored = true;
574 return $this->get_instance($record);
575 }
576 }
577 }
578 return $this->create_instance($raterid, $itemid);
579 }
580
36937f02
MG
581 /**
582 * Returns html code to be included in student's feedback.
583 *
584 * @param moodle_page $page
585 * @param int $itemid
3c2b3cb3 586 * @param array $gradinginfo result of function grade_get_grades
36937f02 587 * @param string $defaultcontent default string to be returned if no active grading is found
0136124e 588 * @param boolean $cangrade whether current user has capability to grade in this context
36937f02
MG
589 * @return string
590 */
3c2b3cb3 591 public function render_grade($page, $itemid, $gradinginfo, $defaultcontent, $cangrade) {
0136124e 592 return $this->get_renderer($page)->display_instances($this->get_active_instances($itemid), $defaultcontent, $cangrade);
36937f02 593 }
20836db9 594
d22e9e32 595 // ///// full-text search support /////////////////////////////////////////////
20836db9
DM
596
597 /**
598 * Prepare the part of the search query to append to the FROM statement
599 *
600 * @param string $gdid the alias of grading_definitions.id column used by the caller
601 * @return string
602 */
603 public static function sql_search_from_tables($gdid) {
71ab436a 604 return " LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.definitionid = $gdid)
20836db9
DM
605 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)";
606 }
607
608 /**
609 * Prepare the parts of the SQL WHERE statement to search for the given token
610 *
611 * The returned array cosists of the list of SQL comparions and the list of
612 * respective parameters for the comparisons. The returned chunks will be joined
613 * with other conditions using the OR operator.
614 *
615 * @param string $token token to search for
616 * @return array
617 */
618 public static function sql_search_where($token) {
619 global $DB;
620
621 $subsql = array();
622 $params = array();
623
624 // search in rubric criteria description
625 $subsql[] = $DB->sql_like('rc.description', '?', false, false);
626 $params[] = '%'.$DB->sql_like_escape($token).'%';
627
628 // search in rubric levels definition
629 $subsql[] = $DB->sql_like('rl.definition', '?', false, false);
630 $params[] = '%'.$DB->sql_like_escape($token).'%';
631
632 return array($subsql, $params);
633 }
a19d1057
MG
634
635 /**
636 * Calculates and returns the possible minimum and maximum score (in points) for this rubric
637 *
638 * @return array
639 */
640 public function get_min_max_score() {
641 if (!$this->is_form_available()) {
642 return null;
643 }
644 $returnvalue = array('minscore' => 0, 'maxscore' => 0);
645 foreach ($this->get_definition()->rubric_criteria as $id => $criterion) {
646 $scores = array();
647 foreach ($criterion['levels'] as $level) {
648 $scores[] = $level['score'];
649 }
650 sort($scores);
651 $returnvalue['minscore'] += $scores[0];
652 $returnvalue['maxscore'] += $scores[sizeof($scores)-1];
653 }
654 return $returnvalue;
655 }
9b8550f8 656}
36937f02
MG
657
658/**
d22e9e32
MG
659 * Class to manage one rubric grading instance.
660 *
661 * Stores information and performs actions like update, copy, validate, submit, etc.
36937f02
MG
662 *
663 * @copyright 2011 Marina Glancy
d22e9e32 664 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36937f02
MG
665 */
666class gradingform_rubric_instance extends gradingform_instance {
667
d22e9e32 668 /** @var array stores the rubric, has two keys: 'criteria' and 'options' */
5060997b
MG
669 protected $rubric;
670
36937f02
MG
671 /**
672 * Deletes this (INCOMPLETE) instance from database.
673 */
674 public function cancel() {
675 global $DB;
676 parent::cancel();
6f07a6a2 677 $DB->delete_records('gradingform_rubric_fillings', array('instanceid' => $this->get_id()));
36937f02
MG
678 }
679
680 /**
681 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
682 * the specified values)
683 *
684 * @param int $raterid value for raterid in the duplicate
685 * @param int $itemid value for itemid in the duplicate
686 * @return int id of the new instance
687 */
688 public function copy($raterid, $itemid) {
689 global $DB;
690 $instanceid = parent::copy($raterid, $itemid);
691 $currentgrade = $this->get_rubric_filling();
5060997b 692 foreach ($currentgrade['criteria'] as $criterionid => $record) {
6f07a6a2 693 $params = array('instanceid' => $instanceid, 'criterionid' => $criterionid,
5060997b 694 'levelid' => $record['levelid'], 'remark' => $record['remark'], 'remarkformat' => $record['remarkformat']);
36937f02
MG
695 $DB->insert_record('gradingform_rubric_fillings', $params);
696 }
36937f02
MG
697 return $instanceid;
698 }
699
700 /**
701 * Validates that rubric is fully completed and contains valid grade on each criterion
3c2b3cb3
MG
702 *
703 * @param array $elementvalue value of element as came in form submit
36937f02
MG
704 * @return boolean true if the form data is validated and contains no errors
705 */
706 public function validate_grading_element($elementvalue) {
36937f02 707 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
5060997b 708 if (!isset($elementvalue['criteria']) || !is_array($elementvalue['criteria']) || sizeof($elementvalue['criteria']) < sizeof($criteria)) {
36937f02
MG
709 return false;
710 }
711 foreach ($criteria as $id => $criterion) {
5060997b
MG
712 if (!isset($elementvalue['criteria'][$id]['levelid'])
713 || !array_key_exists($elementvalue['criteria'][$id]['levelid'], $criterion['levels'])) {
36937f02
MG
714 return false;
715 }
716 }
717 return true;
718 }
719
720 /**
721 * Retrieves from DB and returns the data how this rubric was filled
722 *
5060997b 723 * @param boolean $force whether to force DB query even if the data is cached
36937f02
MG
724 * @return array
725 */
5060997b 726 public function get_rubric_filling($force = false) {
36937f02 727 global $DB;
5060997b 728 if ($this->rubric === null || $force) {
6f07a6a2 729 $records = $DB->get_records('gradingform_rubric_fillings', array('instanceid' => $this->get_id()));
5060997b
MG
730 $this->rubric = array('criteria' => array());
731 foreach ($records as $record) {
732 $this->rubric['criteria'][$record->criterionid] = (array)$record;
36937f02 733 }
36937f02 734 }
5060997b 735 return $this->rubric;
36937f02
MG
736 }
737
738 /**
739 * Updates the instance with the data received from grading form. This function may be
740 * called via AJAX when grading is not yet completed, so it does not change the
741 * status of the instance.
fc05f222
MG
742 *
743 * @param array $data
36937f02
MG
744 */
745 public function update($data) {
746 global $DB;
747 $currentgrade = $this->get_rubric_filling();
fc05f222 748 parent::update($data);
5060997b
MG
749 foreach ($data['criteria'] as $criterionid => $record) {
750 if (!array_key_exists($criterionid, $currentgrade['criteria'])) {
6f07a6a2 751 $newrecord = array('instanceid' => $this->get_id(), 'criterionid' => $criterionid,
0136124e
MG
752 'levelid' => $record['levelid'], 'remarkformat' => FORMAT_MOODLE);
753 if (isset($record['remark'])) {
754 $newrecord['remark'] = $record['remark'];
755 }
5060997b
MG
756 $DB->insert_record('gradingform_rubric_fillings', $newrecord);
757 } else {
758 $newrecord = array('id' => $currentgrade['criteria'][$criterionid]['id']);
d22e9e32
MG
759 foreach (array('levelid', 'remark'/*, 'remarkformat' */) as $key) {
760 // TODO MDL-31235 format is not supported yet
0136124e 761 if (isset($record[$key]) && $currentgrade['criteria'][$criterionid][$key] != $record[$key]) {
5060997b
MG
762 $newrecord[$key] = $record[$key];
763 }
764 }
765 if (count($newrecord) > 1) {
766 $DB->update_record('gradingform_rubric_fillings', $newrecord);
767 }
36937f02
MG
768 }
769 }
5060997b
MG
770 foreach ($currentgrade['criteria'] as $criterionid => $record) {
771 if (!array_key_exists($criterionid, $data['criteria'])) {
772 $DB->delete_records('gradingform_rubric_fillings', array('id' => $record['id']));
36937f02
MG
773 }
774 }
5060997b 775 $this->get_rubric_filling(true);
36937f02
MG
776 }
777
778 /**
779 * Calculates the grade to be pushed to the gradebook
9e2eca0f
MG
780 *
781 * @return int the valid grade from $this->get_controller()->get_grade_range()
36937f02
MG
782 */
783 public function get_grade() {
784 global $DB, $USER;
785 $grade = $this->get_rubric_filling();
786
a19d1057 787 if (!($scores = $this->get_controller()->get_min_max_score()) || $scores['maxscore'] <= $scores['minscore']) {
9e2eca0f
MG
788 return -1;
789 }
790
791 $graderange = array_keys($this->get_controller()->get_grade_range());
792 if (empty($graderange)) {
36937f02
MG
793 return -1;
794 }
9e2eca0f
MG
795 sort($graderange);
796 $mingrade = $graderange[0];
797 $maxgrade = $graderange[sizeof($graderange) - 1];
36937f02
MG
798
799 $curscore = 0;
5060997b
MG
800 foreach ($grade['criteria'] as $id => $record) {
801 $curscore += $this->get_controller()->get_definition()->rubric_criteria[$id]['levels'][$record['levelid']]['score'];
36937f02 802 }
a19d1057 803 return round(($curscore-$scores['minscore'])/($scores['maxscore']-$scores['minscore'])*($maxgrade-$mingrade), 0) + $mingrade;
36937f02
MG
804 }
805
36937f02
MG
806 /**
807 * Returns html for form element of type 'grading'.
808 *
809 * @param moodle_page $page
d22e9e32 810 * @param MoodleQuickForm_grading $gradingformelement
36937f02
MG
811 * @return string
812 */
813 public function render_grading_element($page, $gradingformelement) {
814 global $USER;
815 if (!$gradingformelement->_flagFrozen) {
816 $module = array('name'=>'gradingform_rubric', 'fullpath'=>'/grade/grading/form/rubric/js/rubric.js');
817 $page->requires->js_init_call('M.gradingform_rubric.init', array(array('name' => $gradingformelement->getName())), true, $module);
818 $mode = gradingform_rubric_controller::DISPLAY_EVAL;
819 } else {
820 if ($gradingformelement->_persistantFreeze) {
821 $mode = gradingform_rubric_controller::DISPLAY_EVAL_FROZEN;
822 } else {
823 $mode = gradingform_rubric_controller::DISPLAY_REVIEW;
824 }
825 }
826 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
39c6f4b6 827 $options = $this->get_controller()->get_options();
36937f02 828 $value = $gradingformelement->getValue();
0136124e 829 $html = '';
36937f02
MG
830 if ($value === null) {
831 $value = $this->get_rubric_filling();
0136124e
MG
832 } else if (!$this->validate_grading_element($value)) {
833 $html .= html_writer::tag('div', get_string('rubricnotcompleted', 'gradingform_rubric'), array('class' => 'gradingform_rubric-error'));
834 }
835 $currentinstance = $this->get_current_instance();
836 if ($currentinstance && $currentinstance->get_status() == gradingform_instance::INSTANCE_STATUS_NEEDUPDATE) {
837 $html .= html_writer::tag('div', get_string('needregrademessage', 'gradingform_rubric'), array('class' => 'gradingform_rubric-regrade'));
36937f02 838 }
188e840b
MG
839 $haschanges = false;
840 if ($currentinstance) {
841 $curfilling = $currentinstance->get_rubric_filling();
842 foreach ($curfilling['criteria'] as $criterionid => $curvalues) {
843 $value['criteria'][$criterionid]['savedlevelid'] = $curvalues['levelid'];
844 $newremark = null;
845 $newlevelid = null;
846 if (isset($value['criteria'][$criterionid]['remark'])) $newremark = $value['criteria'][$criterionid]['remark'];
847 if (isset($value['criteria'][$criterionid]['levelid'])) $newlevelid = $value['criteria'][$criterionid]['levelid'];
848 if ($newlevelid != $curvalues['levelid'] || $newremark != $curvalues['remark']) {
849 $haschanges = true;
850 }
851 }
852 }
853 if ($this->get_data('isrestored') && $haschanges) {
854 $html .= html_writer::tag('div', get_string('restoredfromdraft', 'gradingform_rubric'), array('class' => 'gradingform_rubric-restored'));
855 }
577c8964
MG
856 if (!empty($options['showdescriptionteacher'])) {
857 $html .= html_writer::tag('div', $this->get_controller()->get_formatted_description(), array('class' => 'gradingform_rubric-description'));
858 }
0136124e
MG
859 $html .= $this->get_controller()->get_renderer($page)->display_rubric($criteria, $options, $mode, $gradingformelement->getName(), $value);
860 return $html;
36937f02 861 }
3599b113 862}