MDL-29794 Initial support for re-using a shared grading form
[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
39c6f4b6
MG
41 const DISPLAY_REVIEW = 6; // Teacher reviews filled rubric
42 const DISPLAY_VIEW = 7; // Dispaly filled rubric (i.e. students see their grades)
9b8550f8
DM
43
44 /**
45 * Extends the module settings navigation with the rubric grading settings
46 *
47 * This function is called when the context for the page is an activity module with the
48 * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
49 * and there is an area with the active grading method set to 'rubric'.
50 *
51 * @param settings_navigation $settingsnav {@link settings_navigation}
52 * @param navigation_node $node {@link navigation_node}
53 */
54 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
55 $node->add(get_string('definerubric', 'gradingform_rubric'),
6832a102 56 $this->get_editor_url(), settings_navigation::TYPE_CUSTOM,
9b8550f8
DM
57 null, null, new pix_icon('icon', '', 'gradingform_rubric'));
58 }
21d37aa6 59
c586d2bf 60 /**
fe817d87 61 * Saves the rubric definition into the database
c586d2bf 62 *
fe817d87 63 * @see parent::update_definition()
9e2eca0f 64 * @param stdClass $newdefinition rubric definition data as coming from gradingform_rubric_editrubric::get_data()
fe817d87 65 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
c586d2bf 66 */
fe817d87 67 public function update_definition(stdClass $newdefinition, $usermodified = null) {
c586d2bf 68 global $DB;
c586d2bf 69
fe817d87 70 // firstly update the common definition data in the {grading_definition} table
9e2eca0f
MG
71 if ($this->definition === false) {
72 // if definition does not exist yet, create a blank one with only required fields set
73 // (we need id to save files embedded in description)
74 parent::update_definition((object)array('descriptionformat' => FORMAT_MOODLE), $usermodified);
75 parent::load_definition();
76 }
39c6f4b6
MG
77 if (!isset($newdefinition->rubric['options'])) {
78 $newdefinition->rubric['options'] = self::get_default_options();
79 }
80 $newdefinition->options = json_encode($newdefinition->rubric['options']);
81 $editoroptions = self::description_form_field_options($this->get_context());
82 $newdefinition = file_postupdate_standard_editor($newdefinition, 'description', $editoroptions, $this->get_context(),
9e2eca0f 83 'gradingform_rubric', 'definition_description', $this->definition->id);
fe817d87 84 parent::update_definition($newdefinition, $usermodified);
9e2eca0f 85
fe817d87 86 // reload the definition from the database
9e2eca0f 87 $currentdefinition = $this->get_definition(true);
fe817d87 88
9e2eca0f 89 // update rubric data
fe817d87 90 $haschanges = false;
39c6f4b6 91 if (empty($newdefinition->rubric['criteria'])) {
fe817d87 92 $newcriteria = array();
c586d2bf 93 } else {
39c6f4b6 94 $newcriteria = $newdefinition->rubric['criteria']; // new ones to be saved
c586d2bf 95 }
fe817d87
DM
96 $currentcriteria = $currentdefinition->rubric_criteria;
97 $criteriafields = array('sortorder', 'description', 'descriptionformat');
98 $levelfields = array('score', 'definition', 'definitionformat');
99 foreach ($newcriteria as $id => $criterion) {
100 // get list of submitted levels
101 $levelsdata = array();
102 if (array_key_exists('levels', $criterion)) {
103 $levelsdata = $criterion['levels'];
104 }
105 if (preg_match('/^NEWID\d+$/', $id)) {
106 // insert criterion into DB
107 $data = array('formid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE); // TODO format is not supported yet
108 foreach ($criteriafields as $key) {
109 if (array_key_exists($key, $criterion)) {
110 $data[$key] = $criterion[$key];
111 }
112 }
113 $id = $DB->insert_record('gradingform_rubric_criteria', $data);
114 $haschanges = true;
115 } else {
116 // update criterion in DB
117 $data = array();
118 foreach ($criteriafields as $key) {
119 if (array_key_exists($key, $criterion) && $criterion[$key] != $currentcriteria[$id][$key]) {
120 $data[$key] = $criterion[$key];
121 }
122 }
123 if (!empty($data)) {
124 // update only if something is changed
125 $data['id'] = $id;
126 $DB->update_record('gradingform_rubric_criteria', $data);
127 $haschanges = true;
c586d2bf 128 }
fe817d87
DM
129 // remove deleted levels from DB
130 foreach (array_keys($currentcriteria[$id]['levels']) as $levelid) {
131 if (!array_key_exists($levelid, $levelsdata)) {
132 $DB->delete_records('gradingform_rubric_levels', array('id' => $levelid));
133 $haschanges = true;
134 }
135 }
136 }
137 foreach ($levelsdata as $levelid => $level) {
138 if (preg_match('/^NEWID\d+$/', $levelid)) {
139 // insert level into DB
140 $data = array('criterionid' => $id, 'definitionformat' => FORMAT_MOODLE); // TODO format is not supported yet
141 foreach ($levelfields as $key) {
142 if (array_key_exists($key, $level)) {
143 $data[$key] = $level[$key];
c586d2bf
MG
144 }
145 }
fe817d87 146 $levelid = $DB->insert_record('gradingform_rubric_levels', $data);
c586d2bf
MG
147 $haschanges = true;
148 } else {
fe817d87 149 // update level in DB
c586d2bf 150 $data = array();
fe817d87
DM
151 foreach ($levelfields as $key) {
152 if (array_key_exists($key, $level) && $level[$key] != $currentcriteria[$id]['levels'][$levelid][$key]) {
153 $data[$key] = $level[$key];
c586d2bf
MG
154 }
155 }
156 if (!empty($data)) {
157 // update only if something is changed
fe817d87
DM
158 $data['id'] = $levelid;
159 $DB->update_record('gradingform_rubric_levels', $data);
c586d2bf 160 $haschanges = true;
c586d2bf
MG
161 }
162 }
163 }
c586d2bf 164 }
fe817d87
DM
165 // remove deleted criteria from DB
166 foreach (array_keys($currentcriteria) as $id) {
167 if (!array_key_exists($id, $newcriteria)) {
168 $DB->delete_records('gradingform_rubric_criteria', array('id' => $id));
169 $DB->delete_records('gradingform_rubric_levels', array('criterionid' => $id));
170 $haschanges = true;
171 }
c586d2bf 172 }
fe817d87 173 $this->load_definition();
c586d2bf
MG
174 }
175
176 /**
fe817d87 177 * Loads the rubric form definition if it exists
c586d2bf 178 *
fe817d87 179 * There is a new array called 'rubric_criteria' appended to the list of parent's definition properties.
c586d2bf 180 */
fe817d87 181 protected function load_definition() {
c586d2bf 182 global $DB;
fe817d87
DM
183 $sql = "SELECT gd.*,
184 rc.id AS rcid, rc.sortorder AS rcsortorder, rc.description AS rcdescription, rc.descriptionformat AS rcdescriptionformat,
185 rl.id AS rlid, rl.score AS rlscore, rl.definition AS rldefinition, rl.definitionformat AS rldefinitionformat
186 FROM {grading_definitions} gd
187 LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.formid = gd.id)
188 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)
189 WHERE gd.areaid = :areaid AND gd.method = :method
190 ORDER BY rc.sortorder,rl.score";
191 $params = array('areaid' => $this->areaid, 'method' => $this->get_method_name());
192
193 $rs = $DB->get_recordset_sql($sql, $params);
194 $this->definition = false;
195 foreach ($rs as $record) {
196 // pick the common definition data
5060997b 197 if ($this->definition === false) {
fe817d87
DM
198 $this->definition = new stdClass();
199 foreach (array('id', 'name', 'description', 'descriptionformat', 'status', 'copiedfromid',
200 'timecreated', 'usercreated', 'timemodified', 'usermodified', 'options') as $fieldname) {
201 $this->definition->$fieldname = $record->$fieldname;
202 }
203 $this->definition->rubric_criteria = array();
204 }
205 // pick the criterion data
206 if (!empty($record->rcid) and empty($this->definition->rubric_criteria[$record->rcid])) {
207 foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
208 $this->definition->rubric_criteria[$record->rcid][$fieldname] = $record->{'rc'.$fieldname};
209 }
210 $this->definition->rubric_criteria[$record->rcid]['levels'] = array();
c586d2bf 211 }
fe817d87
DM
212 // pick the level data
213 if (!empty($record->rlid)) {
214 foreach (array('id', 'score', 'definition', 'definitionformat') as $fieldname) {
215 $this->definition->rubric_criteria[$record->rcid]['levels'][$record->rlid][$fieldname] = $record->{'rl'.$fieldname};
c586d2bf
MG
216 }
217 }
218 }
fe817d87 219 $rs->close();
39c6f4b6
MG
220 $options = $this->get_options();
221 if (!$options['sortlevelsasc']) {
222 foreach (array_keys($this->definition->rubric_criteria) as $rcid) {
223 $this->definition->rubric_criteria[$rcid]['levels'] = array_reverse($this->definition->rubric_criteria[$rcid]['levels'], true);
224 }
225 }
226 }
227
228 public static function get_default_options() {
229 $options = array(
230 'sortlevelsasc' => 1,
231 //'showdescriptionteacher' => 1,
232 //'showdescriptionstudent' => 1,
233 'showscoreteacher' => 1,
234 'showscorestudent' => 1,
235 'enableremarks' => 1,
236 'showremarksstudent' => 1
237 );
238 // TODO description options
239 return $options;
240 }
241
242 public function get_options() {
243 $options = self::get_default_options();
244 if (!empty($this->definition->options)) {
245 $thisoptions = json_decode($this->definition->options);
246 foreach ($thisoptions as $option => $value) {
247 $options[$option] = $value;
248 }
249 }
250 return $options;
c586d2bf
MG
251 }
252
253 /**
fe817d87 254 * Converts the current definition into an object suitable for the editor form's set_data()
c586d2bf 255 *
fe817d87 256 * @return stdClass
c586d2bf 257 */
fe817d87
DM
258 public function get_definition_for_editing() {
259
260 $definition = $this->get_definition();
c586d2bf 261 $properties = new stdClass();
fe817d87
DM
262 $properties->areaid = $this->areaid;
263 if ($definition) {
39c6f4b6 264 foreach (array('id', 'name', 'description', 'descriptionformat', 'status') as $key) {
fe817d87 265 $properties->$key = $definition->$key;
c586d2bf 266 }
c586d2bf 267 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
268 $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
269 'gradingform_rubric', 'definition_description', $definition->id);
270 }
39c6f4b6 271 $properties->rubric = array('criteria' => array(), 'options' => $this->get_options());
fe817d87 272 if (!empty($definition->rubric_criteria)) {
39c6f4b6 273 $properties->rubric['criteria'] = $definition->rubric_criteria;
c586d2bf 274 }
c586d2bf 275
c586d2bf
MG
276 return $properties;
277 }
278
fde33804
DM
279 /**
280 * Returns the form definition suitable for cloning into another area
281 *
282 * @see parent::get_definition_copy()
283 * @param gradingform_controller $target the controller of the new copy
284 * @return stdClass definition structure to pass to the target's {@link update_definition()}
285 */
286 public function get_definition_copy(gradingform_controller $target) {
287
288 $new = parent::get_definition_copy($target);
8722a322
MG
289 $old = $this->get_definition_for_editing();
290 $new->description_editor = $old->description_editor;
39c6f4b6 291 $new->rubric = array('criteria' => array(), 'options' => $old->rubric['options']);
fde33804
DM
292 $newcritid = 1;
293 $newlevid = 1;
39c6f4b6 294 foreach ($old->rubric['criteria'] as $oldcritid => $oldcrit) {
fde33804
DM
295 unset($oldcrit['id']);
296 if (isset($oldcrit['levels'])) {
297 foreach ($oldcrit['levels'] as $oldlevid => $oldlev) {
298 unset($oldlev['id']);
299 $oldcrit['levels']['NEWID'.$newlevid] = $oldlev;
300 unset($oldcrit['levels'][$oldlevid]);
301 $newlevid++;
302 }
303 } else {
304 $oldcrit['levels'] = array();
305 }
39c6f4b6 306 $new->rubric['criteria']['NEWID'.$newcritid] = $oldcrit;
fde33804
DM
307 $newcritid++;
308 }
309
310 return $new;
311 }
312
c586d2bf
MG
313 // TODO the following functions may be moved to parent:
314
fe817d87
DM
315 /**
316 * @return array options for the form description field
317 */
c586d2bf
MG
318 public static function description_form_field_options($context) {
319 global $CFG;
320 return array(
321 'maxfiles' => -1,
322 'maxbytes' => get_max_upload_file_size($CFG->maxbytes),
fe817d87 323 'context' => $context,
c586d2bf
MG
324 );
325 }
326
327 public function get_formatted_description() {
5060997b 328 if ($this->definition === false) {
c586d2bf
MG
329 return null;
330 }
331 $context = $this->get_context();
332
333 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
334 $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
335 'gradingform_rubric', 'definition_description', $this->definition->id, $options);
c586d2bf
MG
336
337 $formatoptions = array(
338 'noclean' => false,
339 'trusted' => false,
340 'filter' => true,
341 'context' => $context
342 );
343 return format_text($description, $this->definition->descriptionformat, $formatoptions);
344 }
345
18e6298c
MG
346 public function is_form_available($foruserid = null) {
347 return true;
348 // TODO this is temporary for testing!
349 }
6798c63e 350
6832a102
DM
351 /**
352 * Returns the rubric plugin renderer
353 *
354 * @param moodle_page $page the target page
355 * @return renderer_base
356 */
357 public function get_renderer(moodle_page $page) {
358 return $page->get_renderer('gradingform_'. $this->get_method_name());
359 }
360
361 /**
362 * Returns the HTML code displaying the preview of the grading form
363 *
364 * @param moodle_page $page the target page
365 * @return string
366 */
367 public function render_preview(moodle_page $page) {
368
20836db9
DM
369 if (!$this->is_form_defined()) {
370 throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
371 }
6832a102 372
6832a102 373 $output = $this->get_renderer($page);
36937f02 374 $criteria = $this->definition->rubric_criteria;
39c6f4b6
MG
375 $options = $this->get_options();
376 $rubric = $output->display_rubric($criteria, $options, self::DISPLAY_PREVIEW, 'rubric');
6832a102 377
20836db9 378 return $rubric;
6832a102 379 }
671ec8f5
DM
380
381 /**
382 * Deletes the rubric definition and all the associated information
383 */
384 protected function delete_plugin_definition() {
385 global $DB;
386
387 // get the list of instances
388 $instances = array_keys($DB->get_records('grading_instances', array('formid' => $this->definition->id), '', 'id'));
389 // delete all fillings
390 $DB->delete_records_list('gradingform_rubric_fillings', 'forminstanceid', $instances);
391 // delete instances
392 $DB->delete_records_list('grading_instances', 'id', $instances);
393 // get the list of criteria records
394 $criteria = array_keys($DB->get_records('gradingform_rubric_criteria', array('formid' => $this->definition->id), '', 'id'));
395 // delete levels
396 $DB->delete_records_list('gradingform_rubric_levels', 'criterionid', $criteria);
397 // delete critera
398 $DB->delete_records_list('gradingform_rubric_criteria', 'id', $criteria);
399 }
36937f02
MG
400
401 /**
402 * Returns html code to be included in student's feedback.
403 *
404 * @param moodle_page $page
405 * @param int $itemid
9e2eca0f 406 * @param array $grading_info result of function grade_get_grades
36937f02
MG
407 * @param string $defaultcontent default string to be returned if no active grading is found
408 * @return string
409 */
9e2eca0f 410 public function render_grade($page, $itemid, $grading_info, $defaultcontent) {
36937f02
MG
411 $instances = $this->get_current_instances($itemid);
412 return $this->get_renderer($page)->display_instances($this->get_current_instances($itemid), $defaultcontent);
413 }
20836db9
DM
414
415 //// full-text search support /////////////////////////////////////////////
416
417 /**
418 * Prepare the part of the search query to append to the FROM statement
419 *
420 * @param string $gdid the alias of grading_definitions.id column used by the caller
421 * @return string
422 */
423 public static function sql_search_from_tables($gdid) {
424 return " LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.formid = $gdid)
425 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)";
426 }
427
428 /**
429 * Prepare the parts of the SQL WHERE statement to search for the given token
430 *
431 * The returned array cosists of the list of SQL comparions and the list of
432 * respective parameters for the comparisons. The returned chunks will be joined
433 * with other conditions using the OR operator.
434 *
435 * @param string $token token to search for
436 * @return array
437 */
438 public static function sql_search_where($token) {
439 global $DB;
440
441 $subsql = array();
442 $params = array();
443
444 // search in rubric criteria description
445 $subsql[] = $DB->sql_like('rc.description', '?', false, false);
446 $params[] = '%'.$DB->sql_like_escape($token).'%';
447
448 // search in rubric levels definition
449 $subsql[] = $DB->sql_like('rl.definition', '?', false, false);
450 $params[] = '%'.$DB->sql_like_escape($token).'%';
451
452 return array($subsql, $params);
453 }
9b8550f8 454}
36937f02
MG
455
456/**
457 * Class to manage one rubric grading instance. Stores information and performs actions like
458 * update, copy, validate, submit, etc.
459 *
460 * @copyright 2011 Marina Glancy
461 */
462class gradingform_rubric_instance extends gradingform_instance {
463
5060997b
MG
464 protected $rubric;
465
36937f02
MG
466 /**
467 * Deletes this (INCOMPLETE) instance from database.
468 */
469 public function cancel() {
470 global $DB;
471 parent::cancel();
472 $DB->delete_records('gradingform_rubric_fillings', array('forminstanceid' => $this->get_id()));
473 }
474
475 /**
476 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
477 * the specified values)
478 *
479 * @param int $raterid value for raterid in the duplicate
480 * @param int $itemid value for itemid in the duplicate
481 * @return int id of the new instance
482 */
483 public function copy($raterid, $itemid) {
484 global $DB;
485 $instanceid = parent::copy($raterid, $itemid);
486 $currentgrade = $this->get_rubric_filling();
5060997b
MG
487 foreach ($currentgrade['criteria'] as $criterionid => $record) {
488 $params = array('forminstanceid' => $instanceid, 'criterionid' => $criterionid,
489 'levelid' => $record['levelid'], 'remark' => $record['remark'], 'remarkformat' => $record['remarkformat']);
36937f02
MG
490 $DB->insert_record('gradingform_rubric_fillings', $params);
491 }
36937f02
MG
492 return $instanceid;
493 }
494
495 /**
496 * Validates that rubric is fully completed and contains valid grade on each criterion
497 * @return boolean true if the form data is validated and contains no errors
498 */
499 public function validate_grading_element($elementvalue) {
500 // TODO: if there is nothing selected in rubric, we don't enter this function at all :(
501 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
5060997b 502 if (!isset($elementvalue['criteria']) || !is_array($elementvalue['criteria']) || sizeof($elementvalue['criteria']) < sizeof($criteria)) {
36937f02
MG
503 return false;
504 }
505 foreach ($criteria as $id => $criterion) {
5060997b
MG
506 if (!isset($elementvalue['criteria'][$id]['levelid'])
507 || !array_key_exists($elementvalue['criteria'][$id]['levelid'], $criterion['levels'])) {
36937f02
MG
508 return false;
509 }
510 }
511 return true;
512 }
513
514 /**
515 * Retrieves from DB and returns the data how this rubric was filled
516 *
5060997b 517 * @param boolean $force whether to force DB query even if the data is cached
36937f02
MG
518 * @return array
519 */
5060997b 520 public function get_rubric_filling($force = false) {
36937f02 521 global $DB;
5060997b
MG
522 if ($this->rubric === null || $force) {
523 $records = $DB->get_records('gradingform_rubric_fillings', array('forminstanceid' => $this->get_id()));
524 $this->rubric = array('criteria' => array());
525 foreach ($records as $record) {
526 $this->rubric['criteria'][$record->criterionid] = (array)$record;
36937f02 527 }
36937f02 528 }
5060997b 529 return $this->rubric;
36937f02
MG
530 }
531
532 /**
533 * Updates the instance with the data received from grading form. This function may be
534 * called via AJAX when grading is not yet completed, so it does not change the
535 * status of the instance.
fc05f222
MG
536 *
537 * @param array $data
36937f02
MG
538 */
539 public function update($data) {
540 global $DB;
541 $currentgrade = $this->get_rubric_filling();
fc05f222 542 parent::update($data);
5060997b
MG
543 foreach ($data['criteria'] as $criterionid => $record) {
544 if (!array_key_exists($criterionid, $currentgrade['criteria'])) {
545 $newrecord = array('forminstanceid' => $this->get_id(), 'criterionid' => $criterionid,
546 'levelid' => $record['levelid'], 'remark' => $record['remark'], 'remarkformat' => FORMAT_MOODLE);
547 $DB->insert_record('gradingform_rubric_fillings', $newrecord);
548 } else {
549 $newrecord = array('id' => $currentgrade['criteria'][$criterionid]['id']);
550 foreach (array('levelid', 'remark'/*, 'remarkformat' TODO */) as $key) {
551 if ($currentgrade['criteria'][$criterionid][$key] != $record[$key]) {
552 $newrecord[$key] = $record[$key];
553 }
554 }
555 if (count($newrecord) > 1) {
556 $DB->update_record('gradingform_rubric_fillings', $newrecord);
557 }
36937f02
MG
558 }
559 }
5060997b
MG
560 foreach ($currentgrade['criteria'] as $criterionid => $record) {
561 if (!array_key_exists($criterionid, $data['criteria'])) {
562 $DB->delete_records('gradingform_rubric_fillings', array('id' => $record['id']));
36937f02
MG
563 }
564 }
5060997b 565 $this->get_rubric_filling(true);
36937f02
MG
566 }
567
568 /**
569 * Calculates the grade to be pushed to the gradebook
9e2eca0f
MG
570 *
571 * @return int the valid grade from $this->get_controller()->get_grade_range()
36937f02
MG
572 */
573 public function get_grade() {
574 global $DB, $USER;
575 $grade = $this->get_rubric_filling();
576
577 $minscore = 0;
578 $maxscore = 0;
579 foreach ($this->get_controller()->get_definition()->rubric_criteria as $id => $criterion) {
580 $keys = array_keys($criterion['levels']);
9e2eca0f 581 sort($keys);
36937f02
MG
582 $minscore += $criterion['levels'][$keys[0]]['score'];
583 $maxscore += $criterion['levels'][$keys[sizeof($keys)-1]]['score'];
584 }
585
9e2eca0f
MG
586 if ($maxscore <= $minscore) {
587 return -1;
588 }
589
590 $graderange = array_keys($this->get_controller()->get_grade_range());
591 if (empty($graderange)) {
36937f02
MG
592 return -1;
593 }
9e2eca0f
MG
594 sort($graderange);
595 $mingrade = $graderange[0];
596 $maxgrade = $graderange[sizeof($graderange) - 1];
36937f02
MG
597
598 $curscore = 0;
5060997b
MG
599 foreach ($grade['criteria'] as $id => $record) {
600 $curscore += $this->get_controller()->get_definition()->rubric_criteria[$id]['levels'][$record['levelid']]['score'];
36937f02 601 }
9e2eca0f 602 return round(($curscore-$minscore)/($maxscore-$minscore)*($maxgrade-$mingrade), 0) + $mingrade; // TODO mapping
36937f02
MG
603 }
604
605 /**
606 * Returns the error message displayed in case of validation failed
607 *
608 * @return string
609 */
610 public function default_validation_error_message() {
611 return 'The rubric is incomplete'; //TODO string
612 }
613
614 /**
615 * Returns html for form element of type 'grading'.
616 *
617 * @param moodle_page $page
618 * @param MoodleQuickForm_grading $formelement
619 * @return string
620 */
621 public function render_grading_element($page, $gradingformelement) {
622 global $USER;
623 if (!$gradingformelement->_flagFrozen) {
624 $module = array('name'=>'gradingform_rubric', 'fullpath'=>'/grade/grading/form/rubric/js/rubric.js');
625 $page->requires->js_init_call('M.gradingform_rubric.init', array(array('name' => $gradingformelement->getName())), true, $module);
626 $mode = gradingform_rubric_controller::DISPLAY_EVAL;
627 } else {
628 if ($gradingformelement->_persistantFreeze) {
629 $mode = gradingform_rubric_controller::DISPLAY_EVAL_FROZEN;
630 } else {
631 $mode = gradingform_rubric_controller::DISPLAY_REVIEW;
632 }
633 }
634 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
39c6f4b6 635 $options = $this->get_controller()->get_options();
36937f02
MG
636 $value = $gradingformelement->getValue();
637 if ($value === null) {
638 $value = $this->get_rubric_filling();
639 }
39c6f4b6 640 return $this->get_controller()->get_renderer($page)->display_rubric($criteria, $options, $mode, $gradingformelement->getName(), $value);
36937f02
MG
641 }
642}