Replaced deprecated get_system_context() with the new context_system::instance()
[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 */
3599b113 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 71 if ($this->definition === false) {
7622ae95 72 // if definition does not exist yet, create a blank one
9e2eca0f 73 // (we need id to save files embedded in description)
3599b113 74 parent::update_definition(new stdClass(), $usermodified);
9e2eca0f
MG
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);
3599b113 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) {
2ae7faf1
MG
138 if (isset($level['score'])) {
139 $level['score'] = (float)$level['score'];
140 if ($level['score']<0) {
141 // TODO why we can't allow negative score for rubric?
142 $level['score'] = 0;
143 }
144 }
fe817d87
DM
145 if (preg_match('/^NEWID\d+$/', $levelid)) {
146 // insert level into DB
147 $data = array('criterionid' => $id, 'definitionformat' => FORMAT_MOODLE); // TODO format is not supported yet
148 foreach ($levelfields as $key) {
149 if (array_key_exists($key, $level)) {
150 $data[$key] = $level[$key];
c586d2bf
MG
151 }
152 }
fe817d87 153 $levelid = $DB->insert_record('gradingform_rubric_levels', $data);
c586d2bf
MG
154 $haschanges = true;
155 } else {
fe817d87 156 // update level in DB
c586d2bf 157 $data = array();
fe817d87
DM
158 foreach ($levelfields as $key) {
159 if (array_key_exists($key, $level) && $level[$key] != $currentcriteria[$id]['levels'][$levelid][$key]) {
160 $data[$key] = $level[$key];
c586d2bf
MG
161 }
162 }
163 if (!empty($data)) {
164 // update only if something is changed
fe817d87
DM
165 $data['id'] = $levelid;
166 $DB->update_record('gradingform_rubric_levels', $data);
c586d2bf 167 $haschanges = true;
c586d2bf
MG
168 }
169 }
170 }
c586d2bf 171 }
fe817d87
DM
172 // remove deleted criteria from DB
173 foreach (array_keys($currentcriteria) as $id) {
174 if (!array_key_exists($id, $newcriteria)) {
175 $DB->delete_records('gradingform_rubric_criteria', array('id' => $id));
176 $DB->delete_records('gradingform_rubric_levels', array('criterionid' => $id));
177 $haschanges = true;
178 }
c586d2bf 179 }
fe817d87 180 $this->load_definition();
c586d2bf
MG
181 }
182
183 /**
fe817d87 184 * Loads the rubric form definition if it exists
c586d2bf 185 *
fe817d87 186 * There is a new array called 'rubric_criteria' appended to the list of parent's definition properties.
c586d2bf 187 */
fe817d87 188 protected function load_definition() {
c586d2bf 189 global $DB;
fe817d87
DM
190 $sql = "SELECT gd.*,
191 rc.id AS rcid, rc.sortorder AS rcsortorder, rc.description AS rcdescription, rc.descriptionformat AS rcdescriptionformat,
192 rl.id AS rlid, rl.score AS rlscore, rl.definition AS rldefinition, rl.definitionformat AS rldefinitionformat
193 FROM {grading_definitions} gd
194 LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.formid = gd.id)
195 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)
196 WHERE gd.areaid = :areaid AND gd.method = :method
197 ORDER BY rc.sortorder,rl.score";
198 $params = array('areaid' => $this->areaid, 'method' => $this->get_method_name());
199
200 $rs = $DB->get_recordset_sql($sql, $params);
201 $this->definition = false;
202 foreach ($rs as $record) {
203 // pick the common definition data
5060997b 204 if ($this->definition === false) {
fe817d87
DM
205 $this->definition = new stdClass();
206 foreach (array('id', 'name', 'description', 'descriptionformat', 'status', 'copiedfromid',
3f3ee711 207 'timecreated', 'usercreated', 'timemodified', 'usermodified', 'timecopied', 'options') as $fieldname) {
fe817d87
DM
208 $this->definition->$fieldname = $record->$fieldname;
209 }
210 $this->definition->rubric_criteria = array();
211 }
212 // pick the criterion data
213 if (!empty($record->rcid) and empty($this->definition->rubric_criteria[$record->rcid])) {
214 foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
215 $this->definition->rubric_criteria[$record->rcid][$fieldname] = $record->{'rc'.$fieldname};
216 }
217 $this->definition->rubric_criteria[$record->rcid]['levels'] = array();
c586d2bf 218 }
fe817d87
DM
219 // pick the level data
220 if (!empty($record->rlid)) {
221 foreach (array('id', 'score', 'definition', 'definitionformat') as $fieldname) {
2ae7faf1
MG
222 $value = $record->{'rl'.$fieldname};
223 if ($fieldname == 'score') {
224 $value = (float)$value; // To prevent display like 1.00000
225 }
226 $this->definition->rubric_criteria[$record->rcid]['levels'][$record->rlid][$fieldname] = $value;
c586d2bf
MG
227 }
228 }
229 }
fe817d87 230 $rs->close();
39c6f4b6
MG
231 $options = $this->get_options();
232 if (!$options['sortlevelsasc']) {
233 foreach (array_keys($this->definition->rubric_criteria) as $rcid) {
234 $this->definition->rubric_criteria[$rcid]['levels'] = array_reverse($this->definition->rubric_criteria[$rcid]['levels'], true);
235 }
236 }
237 }
238
239 public static function get_default_options() {
240 $options = array(
241 'sortlevelsasc' => 1,
242 //'showdescriptionteacher' => 1,
243 //'showdescriptionstudent' => 1,
244 'showscoreteacher' => 1,
245 'showscorestudent' => 1,
246 'enableremarks' => 1,
247 'showremarksstudent' => 1
248 );
249 // TODO description options
250 return $options;
251 }
252
253 public function get_options() {
254 $options = self::get_default_options();
255 if (!empty($this->definition->options)) {
256 $thisoptions = json_decode($this->definition->options);
257 foreach ($thisoptions as $option => $value) {
258 $options[$option] = $value;
259 }
260 }
261 return $options;
c586d2bf
MG
262 }
263
264 /**
fe817d87 265 * Converts the current definition into an object suitable for the editor form's set_data()
c586d2bf 266 *
fe817d87 267 * @return stdClass
c586d2bf 268 */
fe817d87
DM
269 public function get_definition_for_editing() {
270
271 $definition = $this->get_definition();
c586d2bf 272 $properties = new stdClass();
fe817d87
DM
273 $properties->areaid = $this->areaid;
274 if ($definition) {
39c6f4b6 275 foreach (array('id', 'name', 'description', 'descriptionformat', 'status') as $key) {
fe817d87 276 $properties->$key = $definition->$key;
c586d2bf 277 }
c586d2bf 278 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
279 $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
280 'gradingform_rubric', 'definition_description', $definition->id);
281 }
39c6f4b6 282 $properties->rubric = array('criteria' => array(), 'options' => $this->get_options());
fe817d87 283 if (!empty($definition->rubric_criteria)) {
39c6f4b6 284 $properties->rubric['criteria'] = $definition->rubric_criteria;
c586d2bf 285 }
c586d2bf 286
c586d2bf
MG
287 return $properties;
288 }
289
fde33804
DM
290 /**
291 * Returns the form definition suitable for cloning into another area
292 *
293 * @see parent::get_definition_copy()
294 * @param gradingform_controller $target the controller of the new copy
295 * @return stdClass definition structure to pass to the target's {@link update_definition()}
296 */
297 public function get_definition_copy(gradingform_controller $target) {
298
299 $new = parent::get_definition_copy($target);
8722a322
MG
300 $old = $this->get_definition_for_editing();
301 $new->description_editor = $old->description_editor;
39c6f4b6 302 $new->rubric = array('criteria' => array(), 'options' => $old->rubric['options']);
fde33804
DM
303 $newcritid = 1;
304 $newlevid = 1;
39c6f4b6 305 foreach ($old->rubric['criteria'] as $oldcritid => $oldcrit) {
fde33804
DM
306 unset($oldcrit['id']);
307 if (isset($oldcrit['levels'])) {
308 foreach ($oldcrit['levels'] as $oldlevid => $oldlev) {
309 unset($oldlev['id']);
310 $oldcrit['levels']['NEWID'.$newlevid] = $oldlev;
311 unset($oldcrit['levels'][$oldlevid]);
312 $newlevid++;
313 }
314 } else {
315 $oldcrit['levels'] = array();
316 }
39c6f4b6 317 $new->rubric['criteria']['NEWID'.$newcritid] = $oldcrit;
fde33804
DM
318 $newcritid++;
319 }
320
321 return $new;
322 }
323
c586d2bf
MG
324 // TODO the following functions may be moved to parent:
325
fe817d87
DM
326 /**
327 * @return array options for the form description field
328 */
c586d2bf
MG
329 public static function description_form_field_options($context) {
330 global $CFG;
331 return array(
332 'maxfiles' => -1,
333 'maxbytes' => get_max_upload_file_size($CFG->maxbytes),
fe817d87 334 'context' => $context,
c586d2bf
MG
335 );
336 }
337
3599b113
MG
338 /**
339 * Formats the definition description for display on page
340 *
341 * @return string
342 */
c586d2bf 343 public function get_formatted_description() {
3599b113
MG
344 if (!isset($this->definition->description)) {
345 return '';
c586d2bf
MG
346 }
347 $context = $this->get_context();
348
349 $options = self::description_form_field_options($this->get_context());
fe817d87
DM
350 $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
351 'gradingform_rubric', 'definition_description', $this->definition->id, $options);
c586d2bf
MG
352
353 $formatoptions = array(
354 'noclean' => false,
355 'trusted' => false,
356 'filter' => true,
357 'context' => $context
358 );
359 return format_text($description, $this->definition->descriptionformat, $formatoptions);
360 }
361
6832a102
DM
362 /**
363 * Returns the rubric plugin renderer
364 *
365 * @param moodle_page $page the target page
366 * @return renderer_base
367 */
368 public function get_renderer(moodle_page $page) {
369 return $page->get_renderer('gradingform_'. $this->get_method_name());
370 }
371
372 /**
373 * Returns the HTML code displaying the preview of the grading form
374 *
375 * @param moodle_page $page the target page
376 * @return string
377 */
378 public function render_preview(moodle_page $page) {
379
20836db9
DM
380 if (!$this->is_form_defined()) {
381 throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
382 }
6832a102 383
6832a102 384 $output = $this->get_renderer($page);
36937f02 385 $criteria = $this->definition->rubric_criteria;
39c6f4b6
MG
386 $options = $this->get_options();
387 $rubric = $output->display_rubric($criteria, $options, self::DISPLAY_PREVIEW, 'rubric');
6832a102 388
20836db9 389 return $rubric;
6832a102 390 }
671ec8f5
DM
391
392 /**
393 * Deletes the rubric definition and all the associated information
394 */
395 protected function delete_plugin_definition() {
396 global $DB;
397
398 // get the list of instances
399 $instances = array_keys($DB->get_records('grading_instances', array('formid' => $this->definition->id), '', 'id'));
400 // delete all fillings
401 $DB->delete_records_list('gradingform_rubric_fillings', 'forminstanceid', $instances);
402 // delete instances
403 $DB->delete_records_list('grading_instances', 'id', $instances);
404 // get the list of criteria records
405 $criteria = array_keys($DB->get_records('gradingform_rubric_criteria', array('formid' => $this->definition->id), '', 'id'));
406 // delete levels
407 $DB->delete_records_list('gradingform_rubric_levels', 'criterionid', $criteria);
408 // delete critera
409 $DB->delete_records_list('gradingform_rubric_criteria', 'id', $criteria);
410 }
36937f02
MG
411
412 /**
413 * Returns html code to be included in student's feedback.
414 *
415 * @param moodle_page $page
416 * @param int $itemid
9e2eca0f 417 * @param array $grading_info result of function grade_get_grades
36937f02
MG
418 * @param string $defaultcontent default string to be returned if no active grading is found
419 * @return string
420 */
9e2eca0f 421 public function render_grade($page, $itemid, $grading_info, $defaultcontent) {
36937f02
MG
422 $instances = $this->get_current_instances($itemid);
423 return $this->get_renderer($page)->display_instances($this->get_current_instances($itemid), $defaultcontent);
424 }
20836db9
DM
425
426 //// full-text search support /////////////////////////////////////////////
427
428 /**
429 * Prepare the part of the search query to append to the FROM statement
430 *
431 * @param string $gdid the alias of grading_definitions.id column used by the caller
432 * @return string
433 */
434 public static function sql_search_from_tables($gdid) {
435 return " LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.formid = $gdid)
436 LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)";
437 }
438
439 /**
440 * Prepare the parts of the SQL WHERE statement to search for the given token
441 *
442 * The returned array cosists of the list of SQL comparions and the list of
443 * respective parameters for the comparisons. The returned chunks will be joined
444 * with other conditions using the OR operator.
445 *
446 * @param string $token token to search for
447 * @return array
448 */
449 public static function sql_search_where($token) {
450 global $DB;
451
452 $subsql = array();
453 $params = array();
454
455 // search in rubric criteria description
456 $subsql[] = $DB->sql_like('rc.description', '?', false, false);
457 $params[] = '%'.$DB->sql_like_escape($token).'%';
458
459 // search in rubric levels definition
460 $subsql[] = $DB->sql_like('rl.definition', '?', false, false);
461 $params[] = '%'.$DB->sql_like_escape($token).'%';
462
463 return array($subsql, $params);
464 }
9b8550f8 465}
36937f02
MG
466
467/**
468 * Class to manage one rubric grading instance. Stores information and performs actions like
469 * update, copy, validate, submit, etc.
470 *
471 * @copyright 2011 Marina Glancy
472 */
473class gradingform_rubric_instance extends gradingform_instance {
474
5060997b
MG
475 protected $rubric;
476
36937f02
MG
477 /**
478 * Deletes this (INCOMPLETE) instance from database.
479 */
480 public function cancel() {
481 global $DB;
482 parent::cancel();
483 $DB->delete_records('gradingform_rubric_fillings', array('forminstanceid' => $this->get_id()));
484 }
485
486 /**
487 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
488 * the specified values)
489 *
490 * @param int $raterid value for raterid in the duplicate
491 * @param int $itemid value for itemid in the duplicate
492 * @return int id of the new instance
493 */
494 public function copy($raterid, $itemid) {
495 global $DB;
496 $instanceid = parent::copy($raterid, $itemid);
497 $currentgrade = $this->get_rubric_filling();
5060997b
MG
498 foreach ($currentgrade['criteria'] as $criterionid => $record) {
499 $params = array('forminstanceid' => $instanceid, 'criterionid' => $criterionid,
500 'levelid' => $record['levelid'], 'remark' => $record['remark'], 'remarkformat' => $record['remarkformat']);
36937f02
MG
501 $DB->insert_record('gradingform_rubric_fillings', $params);
502 }
36937f02
MG
503 return $instanceid;
504 }
505
506 /**
507 * Validates that rubric is fully completed and contains valid grade on each criterion
508 * @return boolean true if the form data is validated and contains no errors
509 */
510 public function validate_grading_element($elementvalue) {
511 // TODO: if there is nothing selected in rubric, we don't enter this function at all :(
512 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
5060997b 513 if (!isset($elementvalue['criteria']) || !is_array($elementvalue['criteria']) || sizeof($elementvalue['criteria']) < sizeof($criteria)) {
36937f02
MG
514 return false;
515 }
516 foreach ($criteria as $id => $criterion) {
5060997b
MG
517 if (!isset($elementvalue['criteria'][$id]['levelid'])
518 || !array_key_exists($elementvalue['criteria'][$id]['levelid'], $criterion['levels'])) {
36937f02
MG
519 return false;
520 }
521 }
522 return true;
523 }
524
525 /**
526 * Retrieves from DB and returns the data how this rubric was filled
527 *
5060997b 528 * @param boolean $force whether to force DB query even if the data is cached
36937f02
MG
529 * @return array
530 */
5060997b 531 public function get_rubric_filling($force = false) {
36937f02 532 global $DB;
5060997b
MG
533 if ($this->rubric === null || $force) {
534 $records = $DB->get_records('gradingform_rubric_fillings', array('forminstanceid' => $this->get_id()));
535 $this->rubric = array('criteria' => array());
536 foreach ($records as $record) {
537 $this->rubric['criteria'][$record->criterionid] = (array)$record;
36937f02 538 }
36937f02 539 }
5060997b 540 return $this->rubric;
36937f02
MG
541 }
542
543 /**
544 * Updates the instance with the data received from grading form. This function may be
545 * called via AJAX when grading is not yet completed, so it does not change the
546 * status of the instance.
fc05f222
MG
547 *
548 * @param array $data
36937f02
MG
549 */
550 public function update($data) {
551 global $DB;
552 $currentgrade = $this->get_rubric_filling();
fc05f222 553 parent::update($data);
5060997b
MG
554 foreach ($data['criteria'] as $criterionid => $record) {
555 if (!array_key_exists($criterionid, $currentgrade['criteria'])) {
556 $newrecord = array('forminstanceid' => $this->get_id(), 'criterionid' => $criterionid,
557 'levelid' => $record['levelid'], 'remark' => $record['remark'], 'remarkformat' => FORMAT_MOODLE);
558 $DB->insert_record('gradingform_rubric_fillings', $newrecord);
559 } else {
560 $newrecord = array('id' => $currentgrade['criteria'][$criterionid]['id']);
561 foreach (array('levelid', 'remark'/*, 'remarkformat' TODO */) as $key) {
562 if ($currentgrade['criteria'][$criterionid][$key] != $record[$key]) {
563 $newrecord[$key] = $record[$key];
564 }
565 }
566 if (count($newrecord) > 1) {
567 $DB->update_record('gradingform_rubric_fillings', $newrecord);
568 }
36937f02
MG
569 }
570 }
5060997b
MG
571 foreach ($currentgrade['criteria'] as $criterionid => $record) {
572 if (!array_key_exists($criterionid, $data['criteria'])) {
573 $DB->delete_records('gradingform_rubric_fillings', array('id' => $record['id']));
36937f02
MG
574 }
575 }
5060997b 576 $this->get_rubric_filling(true);
36937f02
MG
577 }
578
579 /**
580 * Calculates the grade to be pushed to the gradebook
9e2eca0f
MG
581 *
582 * @return int the valid grade from $this->get_controller()->get_grade_range()
36937f02
MG
583 */
584 public function get_grade() {
585 global $DB, $USER;
586 $grade = $this->get_rubric_filling();
587
588 $minscore = 0;
589 $maxscore = 0;
590 foreach ($this->get_controller()->get_definition()->rubric_criteria as $id => $criterion) {
3599b113
MG
591 $scores = array();
592 foreach ($criterion['levels'] as $level) {
593 $scores[] = $level['score'];
594 }
595 sort($scores);
6184b843
MG
596 $minscore += $scores[0];
597 $maxscore += $scores[sizeof($scores)-1];
36937f02
MG
598 }
599
9e2eca0f
MG
600 if ($maxscore <= $minscore) {
601 return -1;
602 }
603
604 $graderange = array_keys($this->get_controller()->get_grade_range());
605 if (empty($graderange)) {
36937f02
MG
606 return -1;
607 }
9e2eca0f
MG
608 sort($graderange);
609 $mingrade = $graderange[0];
610 $maxgrade = $graderange[sizeof($graderange) - 1];
36937f02
MG
611
612 $curscore = 0;
5060997b
MG
613 foreach ($grade['criteria'] as $id => $record) {
614 $curscore += $this->get_controller()->get_definition()->rubric_criteria[$id]['levels'][$record['levelid']]['score'];
36937f02 615 }
9e2eca0f 616 return round(($curscore-$minscore)/($maxscore-$minscore)*($maxgrade-$mingrade), 0) + $mingrade; // TODO mapping
36937f02
MG
617 }
618
619 /**
620 * Returns the error message displayed in case of validation failed
621 *
622 * @return string
623 */
624 public function default_validation_error_message() {
625 return 'The rubric is incomplete'; //TODO string
626 }
627
628 /**
629 * Returns html for form element of type 'grading'.
630 *
631 * @param moodle_page $page
632 * @param MoodleQuickForm_grading $formelement
633 * @return string
634 */
635 public function render_grading_element($page, $gradingformelement) {
636 global $USER;
637 if (!$gradingformelement->_flagFrozen) {
638 $module = array('name'=>'gradingform_rubric', 'fullpath'=>'/grade/grading/form/rubric/js/rubric.js');
639 $page->requires->js_init_call('M.gradingform_rubric.init', array(array('name' => $gradingformelement->getName())), true, $module);
640 $mode = gradingform_rubric_controller::DISPLAY_EVAL;
641 } else {
642 if ($gradingformelement->_persistantFreeze) {
643 $mode = gradingform_rubric_controller::DISPLAY_EVAL_FROZEN;
644 } else {
645 $mode = gradingform_rubric_controller::DISPLAY_REVIEW;
646 }
647 }
648 $criteria = $this->get_controller()->get_definition()->rubric_criteria;
39c6f4b6 649 $options = $this->get_controller()->get_options();
36937f02
MG
650 $value = $gradingformelement->getValue();
651 if ($value === null) {
652 $value = $this->get_rubric_filling();
653 }
39c6f4b6 654 return $this->get_controller()->get_renderer($page)->display_rubric($criteria, $options, $mode, $gradingformelement->getName(), $value);
36937f02 655 }
3599b113
MG
656}
657
658
659/**
660 * Processes file requests for the gradingform_rubric
661 *
662 * Required to serve files for this plugin
663 * Called from pluginfile.php
664 *
665 * @global moodle_database $DB
666 * @param stdClass $course
667 * @param null $cm
668 * @param stdClass $context
669 * @param string $filearea
670 * @param array $args
671 * @param bool $forcedownload
672 * @return void|false
673 */
674function gradingform_rubric_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
675 global $CFG, $DB;
676 // First argument should ALWAYS be the itemid
677 $itemid = (int)array_shift($args);
678 // Construct a URL to the file and check it exists
679 $fs = get_file_storage();
680 $relativepath = implode('/', $args);
681 $fullpath = "/$context->id/gradingform_rubric/$filearea/$itemid/$relativepath";
682 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
683 // File doesnt exist anyway no point proceeding.
684 return false;
685 }
686 // Switch by the fileare and check the appropriate information
687 switch ($filearea) {
688 case 'definition_description' :
689 // Make sure the itemid points to a valid definition
690 if ($DB->record_exists('grading_definitions', array('id' => $itemid))) {
691 send_stored_file($file, 0, 0, $forcedownload);
692 }
693 break;
694 }
695 // Obviosly bogus comething or other in there
696 return false;
697}