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