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