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