MDL-70034 gradingform_guide: use new API to retrieve grade item name
[moodle.git] / grade / grading / form / guide / lib.php
blob371a5ff2d22c971e4be291c5306d8cbede87c1ac
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.
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/>.
17 /**
18 * Grading method controller for the guide plugin
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
25 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->dirroot.'/grade/grading/form/lib.php');
29 /** guide: Used to compare our gradeitem_type against. */
30 const MARKING_GUIDE = 'guide';
32 /**
33 * This controller encapsulates the guide grading logic
35 * @package gradingform_guide
36 * @copyright 2012 Dan Marsden <dan@danmarsden.com>
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class gradingform_guide_controller extends gradingform_controller {
40 // Modes of displaying the guide (used in gradingform_guide_renderer).
41 /** guide display mode: For editing (moderator or teacher creates a guide) */
42 const DISPLAY_EDIT_FULL = 1;
43 /** guide display mode: Preview the guide design with hidden fields */
44 const DISPLAY_EDIT_FROZEN = 2;
45 /** guide display mode: Preview the guide design (for person with manage permission) */
46 const DISPLAY_PREVIEW = 3;
47 /** guide display mode: Preview the guide (for people being graded) */
48 const DISPLAY_PREVIEW_GRADED= 8;
49 /** guide display mode: For evaluation, enabled (teacher grades a student) */
50 const DISPLAY_EVAL = 4;
51 /** guide display mode: For evaluation, with hidden fields */
52 const DISPLAY_EVAL_FROZEN = 5;
53 /** guide display mode: Teacher reviews filled guide */
54 const DISPLAY_REVIEW = 6;
55 /** guide display mode: Dispaly filled guide (i.e. students see their grades) */
56 const DISPLAY_VIEW = 7;
58 /** @var stdClass|false the definition structure */
59 protected $moduleinstance = false;
61 /**
62 * Extends the module settings navigation with the guide grading settings
64 * This function is called when the context for the page is an activity module with the
65 * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
66 * and there is an area with the active grading method set to 'guide'.
68 * @param settings_navigation $settingsnav {@link settings_navigation}
69 * @param navigation_node $node {@link navigation_node}
71 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
72 $node->add(get_string('definemarkingguide', 'gradingform_guide'),
73 $this->get_editor_url(), settings_navigation::TYPE_CUSTOM,
74 null, null, new pix_icon('icon', '', 'gradingform_guide'));
77 /**
78 * Extends the module navigation
80 * This function is called when the context for the page is an activity module with the
81 * FEATURE_ADVANCED_GRADING and there is an area with the active grading method set to the given plugin.
83 * @param global_navigation $navigation {@link global_navigation}
84 * @param navigation_node $node {@link navigation_node}
85 * @return void
87 public function extend_navigation(global_navigation $navigation, navigation_node $node=null) {
88 if (has_capability('moodle/grade:managegradingforms', $this->get_context())) {
89 // No need for preview if user can manage forms, he will have link to manage.php in settings instead.
90 return;
92 if ($this->is_form_defined() && ($options = $this->get_options()) && !empty($options['alwaysshowdefinition'])) {
93 $node->add(get_string('gradingof', 'gradingform_guide', get_grading_manager($this->get_areaid())->get_area_title()),
94 new moodle_url('/grade/grading/form/'.$this->get_method_name().'/preview.php',
95 array('areaid' => $this->get_areaid())), settings_navigation::TYPE_CUSTOM);
99 /**
100 * Saves the guide definition into the database
102 * @see parent::update_definition()
103 * @param stdClass $newdefinition guide definition data as coming from gradingform_guide_editguide::get_data()
104 * @param int $usermodified optional userid of the author of the definition, defaults to the current user
106 public function update_definition(stdClass $newdefinition, $usermodified = null) {
107 $this->update_or_check_guide($newdefinition, $usermodified, true);
108 if (isset($newdefinition->guide['regrade']) && $newdefinition->guide['regrade']) {
109 $this->mark_for_regrade();
114 * Either saves the guide definition into the database or check if it has been changed.
116 * Returns the level of changes:
117 * 0 - no changes
118 * 1 - only texts or criteria sortorders are changed, students probably do not require re-grading
119 * 2 - added levels but maximum score on guide is the same, students still may not require re-grading
120 * 3 - removed criteria or changed number of points, students require re-grading but may be re-graded automatically
121 * 4 - removed levels - students require re-grading and not all students may be re-graded automatically
122 * 5 - added criteria - all students require manual re-grading
124 * @param stdClass $newdefinition guide definition data as coming from gradingform_guide_editguide::get_data()
125 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
126 * @param bool $doupdate if true actually updates DB, otherwise performs a check
127 * @return int
129 public function update_or_check_guide(stdClass $newdefinition, $usermodified = null, $doupdate = false) {
130 global $DB;
132 // Firstly update the common definition data in the {grading_definition} table.
133 if ($this->definition === false) {
134 if (!$doupdate) {
135 // If we create the new definition there is no such thing as re-grading anyway.
136 return 5;
138 // If definition does not exist yet, create a blank one
139 // (we need id to save files embedded in description).
140 parent::update_definition(new stdClass(), $usermodified);
141 parent::load_definition();
143 if (!isset($newdefinition->guide['options'])) {
144 $newdefinition->guide['options'] = self::get_default_options();
146 $newdefinition->options = json_encode($newdefinition->guide['options']);
147 $editoroptions = self::description_form_field_options($this->get_context());
148 $newdefinition = file_postupdate_standard_editor($newdefinition, 'description', $editoroptions, $this->get_context(),
149 'grading', 'description', $this->definition->id);
151 // Reload the definition from the database.
152 $currentdefinition = $this->get_definition(true);
154 // Update guide data.
155 $haschanges = array();
156 if (empty($newdefinition->guide['criteria'])) {
157 $newcriteria = array();
158 } else {
159 $newcriteria = $newdefinition->guide['criteria']; // New ones to be saved.
161 $currentcriteria = $currentdefinition->guide_criteria;
162 $criteriafields = array('sortorder', 'description', 'descriptionformat', 'descriptionmarkers',
163 'descriptionmarkersformat', 'shortname', 'maxscore');
164 foreach ($newcriteria as $id => $criterion) {
165 if (preg_match('/^NEWID\d+$/', $id)) {
166 // Insert criterion into DB.
167 $data = array('definitionid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE,
168 'descriptionmarkersformat' => FORMAT_MOODLE); // TODO format is not supported yet.
169 foreach ($criteriafields as $key) {
170 if (array_key_exists($key, $criterion)) {
171 $data[$key] = $criterion[$key];
174 if ($doupdate) {
175 $id = $DB->insert_record('gradingform_guide_criteria', $data);
177 $haschanges[5] = true;
178 } else {
179 // Update criterion in DB.
180 $data = array();
181 foreach ($criteriafields as $key) {
182 if (array_key_exists($key, $criterion) && $criterion[$key] != $currentcriteria[$id][$key]) {
183 $data[$key] = $criterion[$key];
186 if (!empty($data)) {
187 // Update only if something is changed.
188 $data['id'] = $id;
189 if ($doupdate) {
190 $DB->update_record('gradingform_guide_criteria', $data);
192 $haschanges[1] = true;
196 // Remove deleted criteria from DB.
197 foreach (array_keys($currentcriteria) as $id) {
198 if (!array_key_exists($id, $newcriteria)) {
199 if ($doupdate) {
200 $DB->delete_records('gradingform_guide_criteria', array('id' => $id));
202 $haschanges[3] = true;
205 // Now handle comments.
206 if (empty($newdefinition->guide['comments'])) {
207 $newcomment = array();
208 } else {
209 $newcomment = $newdefinition->guide['comments']; // New ones to be saved.
211 $currentcomments = $currentdefinition->guide_comments;
212 $commentfields = array('sortorder', 'description');
213 foreach ($newcomment as $id => $comment) {
214 if (preg_match('/^NEWID\d+$/', $id)) {
215 // Insert criterion into DB.
216 $data = array('definitionid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE);
217 foreach ($commentfields as $key) {
218 if (array_key_exists($key, $comment)) {
219 // Check if key is the comment's description.
220 if ($key === 'description') {
221 // Get a trimmed value for the comment description.
222 $description = trim($comment[$key]);
223 // Check if the comment description is empty.
224 if (empty($description)) {
225 // Continue to the next comment object if the description is empty.
226 continue 2;
229 $data[$key] = $comment[$key];
232 if ($doupdate) {
233 $id = $DB->insert_record('gradingform_guide_comments', $data);
235 } else {
236 // Update criterion in DB.
237 $data = array();
238 foreach ($commentfields as $key) {
239 if (array_key_exists($key, $comment) && $comment[$key] != $currentcomments[$id][$key]) {
240 $data[$key] = $comment[$key];
243 if (!empty($data)) {
244 // Update only if something is changed.
245 $data['id'] = $id;
246 if ($doupdate) {
247 $DB->update_record('gradingform_guide_comments', $data);
252 // Remove deleted criteria from DB.
253 foreach (array_keys($currentcomments) as $id) {
254 if (!array_key_exists($id, $newcomment)) {
255 if ($doupdate) {
256 $DB->delete_records('gradingform_guide_comments', array('id' => $id));
260 // End comments handle.
261 foreach (array('status', 'description', 'descriptionformat', 'name', 'options') as $key) {
262 if (isset($newdefinition->$key) && $newdefinition->$key != $this->definition->$key) {
263 $haschanges[1] = true;
266 if ($usermodified && $usermodified != $this->definition->usermodified) {
267 $haschanges[1] = true;
269 if (!count($haschanges)) {
270 return 0;
272 if ($doupdate) {
273 parent::update_definition($newdefinition, $usermodified);
274 $this->load_definition();
276 // Return the maximum level of changes.
277 $changelevels = array_keys($haschanges);
278 sort($changelevels);
279 return array_pop($changelevels);
283 * Marks all instances filled with this guide with the status INSTANCE_STATUS_NEEDUPDATE
285 public function mark_for_regrade() {
286 global $DB;
287 if ($this->has_active_instances()) {
288 $conditions = array('definitionid' => $this->definition->id,
289 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
290 $DB->set_field('grading_instances', 'status', gradingform_instance::INSTANCE_STATUS_NEEDUPDATE, $conditions);
295 * Loads the guide form definition if it exists
297 * There is a new array called 'guide_criteria' appended to the list of parent's definition properties.
299 protected function load_definition() {
300 global $DB;
302 // Check to see if the user prefs have changed - putting here as this function is called on post even when
303 // validation on the page fails. - hard to find a better place to locate this as it is specific to the guide.
304 $showdesc = optional_param('showmarkerdesc', null, PARAM_BOOL); // Check if we need to change pref.
305 $showdescstudent = optional_param('showstudentdesc', null, PARAM_BOOL); // Check if we need to change pref.
306 if ($showdesc !== null) {
307 set_user_preference('gradingform_guide-showmarkerdesc', $showdesc);
309 if ($showdescstudent !== null) {
310 set_user_preference('gradingform_guide-showstudentdesc', $showdescstudent);
313 // Get definition.
314 $definition = $DB->get_record('grading_definitions', array('areaid' => $this->areaid,
315 'method' => $this->get_method_name()), '*');
316 if (!$definition) {
317 // The definition doesn't have to exist. It may be that we are only now creating it.
318 $this->definition = false;
319 return false;
322 $this->definition = $definition;
323 // Now get criteria.
324 $this->definition->guide_criteria = array();
325 $this->definition->guide_comments = array();
326 $criteria = $DB->get_recordset('gradingform_guide_criteria', array('definitionid' => $this->definition->id), 'sortorder');
327 foreach ($criteria as $criterion) {
328 foreach (array('id', 'sortorder', 'description', 'descriptionformat',
329 'maxscore', 'descriptionmarkers', 'descriptionmarkersformat', 'shortname') as $fieldname) {
330 if ($fieldname == 'maxscore') { // Strip any trailing 0.
331 $this->definition->guide_criteria[$criterion->id][$fieldname] = (float)$criterion->{$fieldname};
332 } else {
333 $this->definition->guide_criteria[$criterion->id][$fieldname] = $criterion->{$fieldname};
337 $criteria->close();
339 // Now get comments.
340 $comments = $DB->get_recordset('gradingform_guide_comments', array('definitionid' => $this->definition->id), 'sortorder');
341 foreach ($comments as $comment) {
342 foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
343 $this->definition->guide_comments[$comment->id][$fieldname] = $comment->{$fieldname};
346 $comments->close();
347 if (empty($this->moduleinstance)) { // Only set if empty.
348 $modulename = $this->get_component();
349 $context = $this->get_context();
350 if (strpos($modulename, 'mod_') === 0) {
351 $dbman = $DB->get_manager();
352 $modulename = substr($modulename, 4);
353 if ($dbman->table_exists($modulename)) {
354 $cm = get_coursemodule_from_id($modulename, $context->instanceid);
355 if (!empty($cm)) { // This should only occur when the course is being deleted.
356 $this->moduleinstance = $DB->get_record($modulename, array("id"=>$cm->instance));
364 * Returns the default options for the guide display
366 * @return array
368 public static function get_default_options() {
369 $options = array(
370 'alwaysshowdefinition' => 1,
371 'showmarkspercriterionstudents' => 1,
373 return $options;
377 * Gets the options of this guide definition, fills the missing options with default values
379 * @return array
381 public function get_options() {
382 $options = self::get_default_options();
383 if (!empty($this->definition->options)) {
384 $thisoptions = json_decode($this->definition->options);
385 foreach ($thisoptions as $option => $value) {
386 $options[$option] = $value;
389 return $options;
393 * Converts the current definition into an object suitable for the editor form's set_data()
395 * @param bool $addemptycriterion whether to add an empty criterion if the guide is completely empty (just being created)
396 * @return stdClass
398 public function get_definition_for_editing($addemptycriterion = false) {
400 $definition = $this->get_definition();
401 $properties = new stdClass();
402 $properties->areaid = $this->areaid;
403 if (isset($this->moduleinstance->grade)) {
404 $properties->modulegrade = $this->moduleinstance->grade;
406 if ($definition) {
407 foreach (array('id', 'name', 'description', 'descriptionformat', 'status') as $key) {
408 $properties->$key = $definition->$key;
410 $options = self::description_form_field_options($this->get_context());
411 $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
412 'grading', 'description', $definition->id);
414 $properties->guide = array('criteria' => array(), 'options' => $this->get_options(), 'comments' => array());
415 if (!empty($definition->guide_criteria)) {
416 $properties->guide['criteria'] = $definition->guide_criteria;
417 } else if (!$definition && $addemptycriterion) {
418 $properties->guide['criteria'] = array('addcriterion' => 1);
420 if (!empty($definition->guide_comments)) {
421 $properties->guide['comments'] = $definition->guide_comments;
422 } else if (!$definition && $addemptycriterion) {
423 $properties->guide['comments'] = array('addcomment' => 1);
425 return $properties;
429 * Returns the form definition suitable for cloning into another area
431 * @see parent::get_definition_copy()
432 * @param gradingform_controller $target the controller of the new copy
433 * @return stdClass definition structure to pass to the target's {@link update_definition()}
435 public function get_definition_copy(gradingform_controller $target) {
437 $new = parent::get_definition_copy($target);
438 $old = $this->get_definition_for_editing();
439 $new->description_editor = $old->description_editor;
440 $new->guide = array('criteria' => array(), 'options' => $old->guide['options'], 'comments' => array());
441 $newcritid = 1;
442 foreach ($old->guide['criteria'] as $oldcritid => $oldcrit) {
443 unset($oldcrit['id']);
444 $new->guide['criteria']['NEWID'.$newcritid] = $oldcrit;
445 $newcritid++;
447 $newcomid = 1;
448 foreach ($old->guide['comments'] as $oldcritid => $oldcom) {
449 unset($oldcom['id']);
450 $new->guide['comments']['NEWID'.$newcomid] = $oldcom;
451 $newcomid++;
453 return $new;
457 * Options for displaying the guide description field in the form
459 * @param context $context
460 * @return array options for the form description field
462 public static function description_form_field_options($context) {
463 global $CFG;
464 return array(
465 'maxfiles' => -1,
466 'maxbytes' => get_max_upload_file_size($CFG->maxbytes),
467 'context' => $context,
472 * Formats the definition description for display on page
474 * @return string
476 public function get_formatted_description() {
477 if (!isset($this->definition->description)) {
478 return '';
480 $context = $this->get_context();
482 $options = self::description_form_field_options($this->get_context());
483 $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
484 'grading', 'description', $this->definition->id, $options);
486 $formatoptions = array(
487 'noclean' => false,
488 'trusted' => false,
489 'filter' => true,
490 'context' => $context
492 return format_text($description, $this->definition->descriptionformat, $formatoptions);
496 * Returns the guide plugin renderer
498 * @param moodle_page $page the target page
499 * @return gradingform_guide_renderer
501 public function get_renderer(moodle_page $page) {
502 return $page->get_renderer('gradingform_'. $this->get_method_name());
506 * Returns the HTML code displaying the preview of the grading form
508 * @param moodle_page $page the target page
509 * @return string
511 public function render_preview(moodle_page $page) {
513 if (!$this->is_form_defined()) {
514 throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
517 // Check if current user is able to see preview
518 $options = $this->get_options();
519 if (empty($options['alwaysshowdefinition']) && !has_capability('moodle/grade:managegradingforms', $page->context)) {
520 return '';
523 $criteria = $this->definition->guide_criteria;
524 $comments = $this->definition->guide_comments;
525 $output = $this->get_renderer($page);
527 $guide = '';
528 $guide .= $output->box($this->get_formatted_description(), 'gradingform_guide-description');
529 if (has_capability('moodle/grade:managegradingforms', $page->context)) {
530 $guide .= $output->display_guide_mapping_explained($this->get_min_max_score());
531 $guide .= $output->display_guide($criteria, $comments, $options, self::DISPLAY_PREVIEW, 'guide');
532 } else {
533 $guide .= $output->display_guide($criteria, $comments, $options, self::DISPLAY_PREVIEW_GRADED, 'guide');
536 return $guide;
540 * Deletes the guide definition and all the associated information
542 protected function delete_plugin_definition() {
543 global $DB;
545 // Get the list of instances.
546 $instances = array_keys($DB->get_records('grading_instances', array('definitionid' => $this->definition->id), '', 'id'));
547 // Delete all fillings.
548 $DB->delete_records_list('gradingform_guide_fillings', 'instanceid', $instances);
549 // Delete instances.
550 $DB->delete_records_list('grading_instances', 'id', $instances);
551 // Get the list of criteria records.
552 $criteria = array_keys($DB->get_records('gradingform_guide_criteria',
553 array('definitionid' => $this->definition->id), '', 'id'));
554 // Delete critera.
555 $DB->delete_records_list('gradingform_guide_criteria', 'id', $criteria);
556 // Delete comments.
557 $DB->delete_records('gradingform_guide_comments', array('definitionid' => $this->definition->id));
561 * If instanceid is specified and grading instance exists and it is created by this rater for
562 * this item, this instance is returned.
563 * If there exists a draft for this raterid+itemid, take this draft (this is the change from parent)
564 * Otherwise new instance is created for the specified rater and itemid
566 * @param int $instanceid
567 * @param int $raterid
568 * @param int $itemid
569 * @return gradingform_instance
571 public function get_or_create_instance($instanceid, $raterid, $itemid) {
572 global $DB;
573 if ($instanceid &&
574 $instance = $DB->get_record('grading_instances',
575 array('id' => $instanceid, 'raterid' => $raterid, 'itemid' => $itemid), '*', IGNORE_MISSING)) {
576 return $this->get_instance($instance);
578 if ($itemid && $raterid) {
579 $params = array('definitionid' => $this->definition->id, 'raterid' => $raterid, 'itemid' => $itemid);
580 if ($rs = $DB->get_records('grading_instances', $params, 'timemodified DESC', '*', 0, 1)) {
581 $record = reset($rs);
582 $currentinstance = $this->get_current_instance($raterid, $itemid);
583 if ($record->status == gradingform_guide_instance::INSTANCE_STATUS_INCOMPLETE &&
584 (!$currentinstance || $record->timemodified > $currentinstance->get_data('timemodified'))) {
585 $record->isrestored = true;
586 return $this->get_instance($record);
590 return $this->create_instance($raterid, $itemid);
594 * Returns html code to be included in student's feedback.
596 * @param moodle_page $page
597 * @param int $itemid
598 * @param array $gradinginfo result of function grade_get_grades
599 * @param string $defaultcontent default string to be returned if no active grading is found
600 * @param bool $cangrade whether current user has capability to grade in this context
601 * @return string
603 public function render_grade($page, $itemid, $gradinginfo, $defaultcontent, $cangrade) {
604 return $this->get_renderer($page)->display_instances($this->get_active_instances($itemid), $defaultcontent, $cangrade);
607 // Full-text search support.
610 * Prepare the part of the search query to append to the FROM statement
612 * @param string $gdid the alias of grading_definitions.id column used by the caller
613 * @return string
615 public static function sql_search_from_tables($gdid) {
616 return " LEFT JOIN {gradingform_guide_criteria} gc ON (gc.definitionid = $gdid)";
620 * Prepare the parts of the SQL WHERE statement to search for the given token
622 * The returned array cosists of the list of SQL comparions and the list of
623 * respective parameters for the comparisons. The returned chunks will be joined
624 * with other conditions using the OR operator.
626 * @param string $token token to search for
627 * @return array An array containing two more arrays
628 * Array of search SQL fragments
629 * Array of params for the search fragments
631 public static function sql_search_where($token) {
632 global $DB;
634 $subsql = array();
635 $params = array();
637 // Search in guide criteria description.
638 $subsql[] = $DB->sql_like('gc.description', '?', false, false);
639 $params[] = '%'.$DB->sql_like_escape($token).'%';
641 return array($subsql, $params);
645 * Calculates and returns the possible minimum and maximum score (in points) for this guide
647 * @return array
649 public function get_min_max_score() {
650 if (!$this->is_form_available()) {
651 return null;
653 $returnvalue = array('minscore' => 0, 'maxscore' => 0);
654 $maxscore = 0;
655 foreach ($this->get_definition()->guide_criteria as $id => $criterion) {
656 $maxscore += $criterion['maxscore'];
658 $returnvalue['maxscore'] = $maxscore;
659 $returnvalue['minscore'] = 0;
660 $fieldname = \core_grades\component_gradeitems::get_field_name_for_itemname($this->component, $this->area, 'grade');
661 if (!empty($this->moduleinstance->{$fieldname})) {
662 $graderange = make_grades_menu($this->moduleinstance->{$fieldname});
663 $returnvalue['modulegrade'] = count($graderange) - 1;
665 return $returnvalue;
669 * @return array An array containing 2 key/value pairs which hold the external_multiple_structure
670 * for the 'guide_criteria' and the 'guide_comments'.
671 * @see gradingform_controller::get_external_definition_details()
672 * @since Moodle 2.5
674 public static function get_external_definition_details() {
675 $guide_criteria = new external_multiple_structure(
676 new external_single_structure(
677 array(
678 'id' => new external_value(PARAM_INT, 'criterion id', VALUE_OPTIONAL),
679 'sortorder' => new external_value(PARAM_INT, 'sortorder', VALUE_OPTIONAL),
680 'description' => new external_value(PARAM_RAW, 'description', VALUE_OPTIONAL),
681 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
682 'shortname' => new external_value(PARAM_TEXT, 'description'),
683 'descriptionmarkers' => new external_value(PARAM_RAW, 'markers description', VALUE_OPTIONAL),
684 'descriptionmarkersformat' => new external_format_value('descriptionmarkers', VALUE_OPTIONAL),
685 'maxscore' => new external_value(PARAM_FLOAT, 'maximum score')
689 $guide_comments = new external_multiple_structure(
690 new external_single_structure(
691 array(
692 'id' => new external_value(PARAM_INT, 'criterion id', VALUE_OPTIONAL),
693 'sortorder' => new external_value(PARAM_INT, 'sortorder', VALUE_OPTIONAL),
694 'description' => new external_value(PARAM_RAW, 'description', VALUE_OPTIONAL),
695 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL)
697 ), 'comments', VALUE_OPTIONAL
699 return array('guide_criteria' => $guide_criteria, 'guide_comments' => $guide_comments);
703 * Returns an array that defines the structure of the guide's filling. This function is used by
704 * the web service function core_grading_external::get_gradingform_instances().
706 * @return An array containing a single key/value pair with the 'criteria' external_multiple_structure
707 * @see gradingform_controller::get_external_instance_filling_details()
708 * @since Moodle 2.6
710 public static function get_external_instance_filling_details() {
711 $criteria = new external_multiple_structure(
712 new external_single_structure(
713 array(
714 'id' => new external_value(PARAM_INT, 'filling id'),
715 'criterionid' => new external_value(PARAM_INT, 'criterion id'),
716 'levelid' => new external_value(PARAM_INT, 'level id', VALUE_OPTIONAL),
717 'remark' => new external_value(PARAM_RAW, 'remark', VALUE_OPTIONAL),
718 'remarkformat' => new external_format_value('remark', VALUE_OPTIONAL),
719 'score' => new external_value(PARAM_FLOAT, 'maximum score')
721 ), 'filling', VALUE_OPTIONAL
723 return array ('criteria' => $criteria);
729 * Class to manage one guide grading instance. Stores information and performs actions like
730 * update, copy, validate, submit, etc.
732 * @package gradingform_guide
733 * @copyright 2012 Dan Marsden <dan@danmarsden.com>
734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
736 class gradingform_guide_instance extends gradingform_instance {
738 /** @var array */
739 protected $guide;
741 /** @var array An array of validation errors */
742 protected $validationerrors = array();
745 * Deletes this (INCOMPLETE) instance from database.
747 public function cancel() {
748 global $DB;
749 parent::cancel();
750 $DB->delete_records('gradingform_guide_fillings', array('instanceid' => $this->get_id()));
754 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
755 * the specified values)
757 * @param int $raterid value for raterid in the duplicate
758 * @param int $itemid value for itemid in the duplicate
759 * @return int id of the new instance
761 public function copy($raterid, $itemid) {
762 global $DB;
763 $instanceid = parent::copy($raterid, $itemid);
764 $currentgrade = $this->get_guide_filling();
765 foreach ($currentgrade['criteria'] as $criterionid => $record) {
766 $params = array('instanceid' => $instanceid, 'criterionid' => $criterionid,
767 'score' => $record['score'], 'remark' => $record['remark'], 'remarkformat' => $record['remarkformat']);
768 $DB->insert_record('gradingform_guide_fillings', $params);
770 return $instanceid;
774 * Determines whether the submitted form was empty.
776 * @param array $elementvalue value of element submitted from the form
777 * @return boolean true if the form is empty
779 public function is_empty_form($elementvalue) {
780 $criteria = $this->get_controller()->get_definition()->guide_criteria;
781 foreach ($criteria as $id => $criterion) {
782 $score = $elementvalue['criteria'][$id]['score'];
783 $remark = $elementvalue['criteria'][$id]['remark'];
785 if ((isset($score) && $score !== '')
786 || ((isset($remark) && $remark !== ''))) {
787 return false;
790 return true;
794 * Validates that guide is fully completed and contains valid grade on each criterion
796 * @param array $elementvalue value of element as came in form submit
797 * @return boolean true if the form data is validated and contains no errors
799 public function validate_grading_element($elementvalue) {
800 $criteria = $this->get_controller()->get_definition()->guide_criteria;
801 if (!isset($elementvalue['criteria']) || !is_array($elementvalue['criteria']) ||
802 count($elementvalue['criteria']) < count($criteria)) {
803 return false;
805 // Reset validation errors.
806 $this->validationerrors = null;
807 foreach ($criteria as $id => $criterion) {
808 if (!isset($elementvalue['criteria'][$id]['score'])
809 || $criterion['maxscore'] < $elementvalue['criteria'][$id]['score']
810 || !is_numeric($elementvalue['criteria'][$id]['score'])
811 || $elementvalue['criteria'][$id]['score'] < 0) {
812 $this->validationerrors[$id]['score'] = $elementvalue['criteria'][$id]['score'];
815 if (!empty($this->validationerrors)) {
816 return false;
818 return true;
822 * Retrieves from DB and returns the data how this guide was filled
824 * @param bool $force whether to force DB query even if the data is cached
825 * @return array
827 public function get_guide_filling($force = false) {
828 global $DB;
829 if ($this->guide === null || $force) {
830 $records = $DB->get_records('gradingform_guide_fillings', array('instanceid' => $this->get_id()));
831 $this->guide = array('criteria' => array());
832 foreach ($records as $record) {
833 $record->score = (float)$record->score; // Strip trailing 0.
834 $this->guide['criteria'][$record->criterionid] = (array)$record;
837 return $this->guide;
841 * Updates the instance with the data received from grading form. This function may be
842 * called via AJAX when grading is not yet completed, so it does not change the
843 * status of the instance.
845 * @param array $data
847 public function update($data) {
848 global $DB;
849 $currentgrade = $this->get_guide_filling();
850 parent::update($data);
852 foreach ($data['criteria'] as $criterionid => $record) {
853 if (!array_key_exists($criterionid, $currentgrade['criteria'])) {
854 $newrecord = array('instanceid' => $this->get_id(), 'criterionid' => $criterionid,
855 'score' => $record['score'], 'remarkformat' => FORMAT_MOODLE);
856 if (isset($record['remark'])) {
857 $newrecord['remark'] = $record['remark'];
859 $DB->insert_record('gradingform_guide_fillings', $newrecord);
860 } else {
861 $newrecord = array('id' => $currentgrade['criteria'][$criterionid]['id']);
862 foreach (array('score', 'remark'/*, 'remarkformat' TODO */) as $key) {
863 if (isset($record[$key]) && $currentgrade['criteria'][$criterionid][$key] != $record[$key]) {
864 $newrecord[$key] = $record[$key];
867 if (count($newrecord) > 1) {
868 $DB->update_record('gradingform_guide_fillings', $newrecord);
872 foreach ($currentgrade['criteria'] as $criterionid => $record) {
873 if (!array_key_exists($criterionid, $data['criteria'])) {
874 $DB->delete_records('gradingform_guide_fillings', array('id' => $record['id']));
877 $this->get_guide_filling(true);
881 * Removes the attempt from the gradingform_guide_fillings table
882 * @param array $data the attempt data
884 public function clear_attempt($data) {
885 global $DB;
887 foreach ($data['criteria'] as $criterionid => $record) {
888 $DB->delete_records('gradingform_guide_fillings',
889 array('criterionid' => $criterionid, 'instanceid' => $this->get_id()));
894 * Calculates the grade to be pushed to the gradebook
896 * @return float|int the valid grade from $this->get_controller()->get_grade_range()
898 public function get_grade() {
899 $grade = $this->get_guide_filling();
901 if (!($scores = $this->get_controller()->get_min_max_score()) || $scores['maxscore'] <= $scores['minscore']) {
902 return -1;
905 $graderange = array_keys($this->get_controller()->get_grade_range());
906 if (empty($graderange)) {
907 return -1;
909 sort($graderange);
910 $mingrade = $graderange[0];
911 $maxgrade = $graderange[count($graderange) - 1];
913 $curscore = 0;
914 foreach ($grade['criteria'] as $record) {
915 $curscore += $record['score'];
917 $gradeoffset = ($curscore-$scores['minscore'])/($scores['maxscore']-$scores['minscore'])*
918 ($maxgrade-$mingrade);
919 if ($this->get_controller()->get_allow_grade_decimals()) {
920 return $gradeoffset + $mingrade;
922 return round($gradeoffset, 0) + $mingrade;
926 * Returns html for form element of type 'grading'.
928 * @param moodle_page $page
929 * @param MoodleQuickForm_grading $gradingformelement
930 * @return string
932 public function render_grading_element($page, $gradingformelement) {
933 if (!$gradingformelement->_flagFrozen) {
934 $module = array('name'=>'gradingform_guide', 'fullpath'=>'/grade/grading/form/guide/js/guide.js');
935 $page->requires->js_init_call('M.gradingform_guide.init', array(
936 array('name' => $gradingformelement->getName())), true, $module);
937 $mode = gradingform_guide_controller::DISPLAY_EVAL;
938 } else {
939 if ($gradingformelement->_persistantFreeze) {
940 $mode = gradingform_guide_controller::DISPLAY_EVAL_FROZEN;
941 } else {
942 $mode = gradingform_guide_controller::DISPLAY_REVIEW;
945 $criteria = $this->get_controller()->get_definition()->guide_criteria;
946 $comments = $this->get_controller()->get_definition()->guide_comments;
947 $options = $this->get_controller()->get_options();
948 $value = $gradingformelement->getValue();
949 $html = '';
950 if ($value === null) {
951 $value = $this->get_guide_filling();
952 } else if (!$this->validate_grading_element($value)) {
953 $html .= html_writer::tag('div', get_string('guidenotcompleted', 'gradingform_guide'),
954 array('class' => 'gradingform_guide-error'));
955 if (!empty($this->validationerrors)) {
956 foreach ($this->validationerrors as $id => $err) {
957 $a = new stdClass();
958 $a->criterianame = s($criteria[$id]['shortname']);
959 $a->maxscore = $criteria[$id]['maxscore'];
960 if ($this->validationerrors[$id]['score'] < 0) {
961 $html .= html_writer::tag('div', get_string('err_scoreisnegative', 'gradingform_guide', $a),
962 array('class' => 'gradingform_guide-error'));
963 } else {
964 $html .= html_writer::tag('div', get_string('err_scoreinvalid', 'gradingform_guide', $a),
965 array('class' => 'gradingform_guide-error'));
970 $currentinstance = $this->get_current_instance();
971 if ($currentinstance && $currentinstance->get_status() == gradingform_instance::INSTANCE_STATUS_NEEDUPDATE) {
972 $html .= html_writer::tag('div', get_string('needregrademessage', 'gradingform_guide'),
973 array('class' => 'gradingform_guide-regrade', 'role' => 'alert'));
975 $haschanges = false;
976 if ($currentinstance) {
977 $curfilling = $currentinstance->get_guide_filling();
978 foreach ($curfilling['criteria'] as $criterionid => $curvalues) {
979 $value['criteria'][$criterionid]['score'] = $curvalues['score'];
980 $newremark = null;
981 $newscore = null;
982 if (isset($value['criteria'][$criterionid]['remark'])) {
983 $newremark = $value['criteria'][$criterionid]['remark'];
985 if (isset($value['criteria'][$criterionid]['score'])) {
986 $newscore = $value['criteria'][$criterionid]['score'];
988 if ($newscore != $curvalues['score'] || $newremark != $curvalues['remark']) {
989 $haschanges = true;
993 if ($this->get_data('isrestored') && $haschanges) {
994 $html .= html_writer::tag('div', get_string('restoredfromdraft', 'gradingform_guide'),
995 array('class' => 'gradingform_guide-restored'));
997 $html .= html_writer::tag('div', $this->get_controller()->get_formatted_description(),
998 array('class' => 'gradingform_guide-description'));
999 $html .= $this->get_controller()->get_renderer($page)->display_guide($criteria, $comments, $options, $mode,
1000 $gradingformelement->getName(), $value, $this->validationerrors);
1001 return $html;
1006 * Get the icon mapping for font-awesome.
1008 * @return array
1010 function gradingform_guide_get_fontawesome_icon_map(): array {
1011 return [
1012 'gradingform_guide:info' => 'fa-info-circle',
1013 'gradingform_guide:plus' => 'fa-plus',