MDL-31890 version bump
[moodle.git] / grade / grading / form / 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/**
21d37aa6
DM
18 * Common classes used by gradingform plugintypes are defined here
19 *
d22e9e32 20 * @package core_grading
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
27/**
d22e9e32
MG
28 * Class represents a grading form definition used in a particular area
29 *
30 * General data about definition is stored in the standard DB table
31 * grading_definitions. A separate entry is created for each grading area
32 * (i.e. for each module). Plugins may define and use additional tables
33 * to store additional data about definitions.
34 *
35 * Advanced grading plugins must declare a class gradingform_xxxx_controller
36 * extending this class and put it in lib.php in the plugin folder.
37 *
38 * See {@link gradingform_rubric_controller} as an example
39 *
40 * Except for overwriting abstract functions, plugin developers may want
41 * to overwrite functions responsible for loading and saving of the
42 * definition to include additional data stored.
43 *
5dc1ca87 44 * @package core_grading
d22e9e32
MG
45 * @copyright 2011 David Mudrak <david@moodle.com>
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 * @category grading
9b8550f8 48 */
3e43eff5 49abstract class gradingform_controller {
9b8550f8 50
7622ae95
DM
51 /** undefined definition status */
52 const DEFINITION_STATUS_NULL = 0;
53 /** the form is currently being edited and is not ready for usage yet */
54 const DEFINITION_STATUS_DRAFT = 10;
d22e9e32 55 /** the form was marked as ready for actual usage */
7622ae95 56 const DEFINITION_STATUS_READY = 20;
21d37aa6 57
9b8550f8
DM
58 /** @var stdClass the context */
59 protected $context;
60
61 /** @var string the frankenstyle name of the component */
62 protected $component;
63
64 /** @var string the name of the gradable area */
65 protected $area;
66
67 /** @var int the id of the gradable area record */
68 protected $areaid;
69
fe817d87 70 /** @var stdClass|false the definition structure */
5060997b 71 protected $definition = false;
3e43eff5 72
9e2eca0f
MG
73 /** @var array graderange array of valid grades for this area. Use set_grade_range and get_grade_range to access this */
74 private $graderange = null;
75
170f6e60
MG
76 /** @var bool if decimal values are allowed as grades. */
77 private $allowgradedecimals = false;
78
0136124e
MG
79 /** @var boolean|null cached result of function has_active_instances() */
80 protected $hasactiveinstances = null;
81
9b8550f8
DM
82 /**
83 * Do not instantinate this directly, use {@link grading_manager::get_controller()}
84 *
fe817d87
DM
85 * @param stdClass $context the context of the form
86 * @param string $component the frankenstyle name of the component
87 * @param string $area the name of the gradable area
88 * @param int $areaid the id of the gradable area record
9b8550f8
DM
89 */
90 public function __construct(stdClass $context, $component, $area, $areaid) {
3e43eff5
DM
91 global $DB;
92
93 $this->context = $context;
56da374e 94 list($type, $name) = core_component::normalize_component($component);
fe817d87 95 $this->component = $type.'_'.$name;
3e43eff5
DM
96 $this->area = $area;
97 $this->areaid = $areaid;
98
99 $this->load_definition();
100 }
101
fe817d87 102 /**
d22e9e32
MG
103 * Returns controller context
104 *
fe817d87
DM
105 * @return stdClass controller context
106 */
107 public function get_context() {
108 return $this->context;
109 }
110
111 /**
d22e9e32
MG
112 * Returns gradable component name
113 *
fe817d87
DM
114 * @return string gradable component name
115 */
116 public function get_component() {
117 return $this->component;
118 }
119
120 /**
d22e9e32
MG
121 * Returns gradable area name
122 *
fe817d87
DM
123 * @return string gradable area name
124 */
125 public function get_area() {
126 return $this->area;
127 }
128
129 /**
d22e9e32
MG
130 * Returns gradable area id
131 *
fe817d87
DM
132 * @return int gradable area id
133 */
134 public function get_areaid() {
135 return $this->areaid;
136 }
137
6832a102
DM
138 /**
139 * Is the form definition record available?
140 *
141 * Note that this actually checks whether the process of defining the form ever started
142 * and not whether the form definition should be considered as final.
143 *
144 * @return boolean
145 */
146 public function is_form_defined() {
5060997b 147 return ($this->definition !== false);
6832a102
DM
148 }
149
3e43eff5 150 /**
7622ae95 151 * Is the grading form defined and ready for usage?
3e43eff5
DM
152 *
153 * @return boolean
154 */
7622ae95 155 public function is_form_available() {
3599b113 156 return ($this->is_form_defined() && $this->definition->status == self::DEFINITION_STATUS_READY);
3e43eff5
DM
157 }
158
967d346f
DM
159 /**
160 * Is the grading form saved as a shared public template?
161 *
162 * @return boolean
163 */
164 public function is_shared_template() {
165 return ($this->get_context()->id == context_system::instance()->id
166 and $this->get_component() == 'core_grading');
167 }
168
169 /**
170 * Is the grading form owned by the given user?
171 *
172 * The form owner is the user who created this instance of the form.
173 *
174 * @param int $userid the user id to check, defaults to the current user
175 * @return boolean|null null if the form not defined yet, boolean otherwise
176 */
177 public function is_own_form($userid = null) {
178 global $USER;
179
180 if (!$this->is_form_defined()) {
181 return null;
182 }
183 if (is_null($userid)) {
184 $userid = $USER->id;
185 }
186 return ($this->definition->usercreated == $userid);
187 }
188
2ae7faf1
MG
189 /**
190 * Returns a message why this form is unavailable. Maybe overriden by plugins to give more details.
191 * @see is_form_available()
192 *
193 * @return string
194 */
195 public function form_unavailable_notification() {
196 if ($this->is_form_available()) {
197 return null;
198 }
0e2a1d75 199 return get_string('gradingformunavailable', 'grading');
2ae7faf1
MG
200 }
201
6832a102
DM
202 /**
203 * Returns URL of a page where the grading form can be defined and edited.
204 *
205 * @param moodle_url $returnurl optional URL of a page where the user should be sent once they are finished with editing
206 * @return moodle_url
207 */
208 public function get_editor_url(moodle_url $returnurl = null) {
209
210 $params = array('areaid' => $this->areaid);
211
212 if (!is_null($returnurl)) {
213 $params['returnurl'] = $returnurl->out(false);
214 }
215
216 return new moodle_url('/grade/grading/form/'.$this->get_method_name().'/edit.php', $params);
217 }
218
9b8550f8
DM
219 /**
220 * Extends the module settings navigation
221 *
222 * This function is called when the context for the page is an activity module with the
223 * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
224 * and there is an area with the active grading method set to the given plugin.
225 *
226 * @param settings_navigation $settingsnav {@link settings_navigation}
227 * @param navigation_node $node {@link navigation_node}
228 */
229 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
230 // do not extend by default
231 }
3e43eff5 232
577c8964
MG
233 /**
234 * Extends the module navigation
235 *
236 * This function is called when the context for the page is an activity module with the
237 * FEATURE_ADVANCED_GRADING and there is an area with the active grading method set to the given plugin.
238 *
239 * @param global_navigation $navigation {@link global_navigation}
240 * @param navigation_node $node {@link navigation_node}
241 */
242 public function extend_navigation(global_navigation $navigation, navigation_node $node=null) {
243 // do not extend by default
244 }
245
3e43eff5 246 /**
fe817d87 247 * Returns the grading form definition structure
3e43eff5 248 *
9e2eca0f 249 * @param boolean $force whether to force loading from DB even if it was already loaded
fe817d87 250 * @return stdClass|false definition data or false if the form is not defined yet
3e43eff5 251 */
9e2eca0f 252 public function get_definition($force = false) {
5060997b 253 if ($this->definition === false || $force) {
fe817d87
DM
254 $this->load_definition();
255 }
256 return $this->definition;
3e43eff5
DM
257 }
258
fde33804
DM
259 /**
260 * Returns the form definition suitable for cloning into another area
261 *
262 * @param gradingform_controller $target the controller of the new copy
263 * @return stdClass definition structure to pass to the target's {@link update_definition()}
264 */
265 public function get_definition_copy(gradingform_controller $target) {
266
267 if (get_class($this) != get_class($target)) {
268 throw new coding_exception('The source and copy controller mismatch');
269 }
270
271 if ($target->is_form_defined()) {
272 throw new coding_exception('The target controller already contains a form definition');
273 }
274
275 $old = $this->get_definition();
276 // keep our id
277 $new = new stdClass();
278 $new->copiedfromid = $old->id;
279 $new->name = $old->name;
280 // once we support files embedded into the description, we will want to
281 // relink them into the new file area here (that is why we accept $target)
282 $new->description = $old->description;
283 $new->descriptionformat = $old->descriptionformat;
284 $new->options = $old->options;
3599b113 285 $new->status = $old->status;
fde33804
DM
286
287 return $new;
288 }
289
3e43eff5 290 /**
fe817d87 291 * Saves the defintion data into the database
21d37aa6 292 *
fe817d87
DM
293 * The implementation in this base class stores the common data into the record
294 * into the {grading_definition} table. The plugins are likely to extend this
295 * and save their data into own tables, too.
21d37aa6 296 *
fe817d87
DM
297 * @param stdClass $definition data containing values for the {grading_definition} table
298 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
21d37aa6 299 */
3599b113 300 public function update_definition(stdClass $definition, $usermodified = null) {
21d37aa6
DM
301 global $DB, $USER;
302
303 if (is_null($usermodified)) {
304 $usermodified = $USER->id;
305 }
306
fe817d87
DM
307 if (!empty($this->definition->id)) {
308 // prepare a record to be updated
309 $record = new stdClass();
310 // populate it with scalar values from the passed definition structure
311 foreach ($definition as $prop => $val) {
312 if (is_array($val) or is_object($val)) {
313 // probably plugin's data
314 continue;
315 }
316 $record->{$prop} = $val;
317 }
318 // make sure we do not override some crucial values by accident
319 if (!empty($record->id) and $record->id != $this->definition->id) {
320 throw new coding_exception('Attempting to update other definition record.');
321 }
322 $record->id = $this->definition->id;
323 unset($record->areaid);
324 unset($record->method);
325 unset($record->timecreated);
326 // set the modification flags
327 $record->timemodified = time();
328 $record->usermodified = $usermodified;
21d37aa6 329
fe817d87 330 $DB->update_record('grading_definitions', $record);
21d37aa6
DM
331
332 } else if ($this->definition === false) {
fe817d87
DM
333 // prepare a record to be inserted
334 $record = new stdClass();
335 // populate it with scalar values from the passed definition structure
336 foreach ($definition as $prop => $val) {
337 if (is_array($val) or is_object($val)) {
338 // probably plugin's data
339 continue;
340 }
341 $record->{$prop} = $val;
342 }
343 // make sure we do not override some crucial values by accident
344 if (!empty($record->id)) {
345 throw new coding_exception('Attempting to create a new record while there is already one existing.');
346 }
347 unset($record->id);
348 $record->areaid = $this->areaid;
349 $record->method = $this->get_method_name();
350 $record->timecreated = time();
351 $record->usercreated = $usermodified;
ac16cedf
DM
352 $record->timemodified = $record->timecreated;
353 $record->usermodified = $record->usercreated;
3599b113 354 if (empty($record->status)) {
7622ae95
DM
355 $record->status = self::DEFINITION_STATUS_DRAFT;
356 }
3599b113
MG
357 if (empty($record->descriptionformat)) {
358 $record->descriptionformat = FORMAT_MOODLE; // field can not be empty
359 }
21d37aa6 360
ac16cedf 361 $DB->insert_record('grading_definitions', $record);
21d37aa6
DM
362
363 } else {
fe817d87 364 throw new coding_exception('Unknown status of the cached definition record.');
21d37aa6
DM
365 }
366 }
367
3599b113
MG
368 /**
369 * Formats the definition description for display on page
370 *
371 * @return string
372 */
373 public function get_formatted_description() {
374 if (!isset($this->definition->description)) {
375 return '';
376 }
377 return format_text($this->definition->description, $this->definition->descriptionformat);
378 }
379
21d37aa6 380 /**
0136124e
MG
381 * Returns the current instance (either with status ACTIVE or NEEDUPDATE) for this definition for the
382 * specified $raterid and $itemid (if multiple raters are allowed, or only for $itemid otherwise).
21d37aa6 383 *
21d37aa6
DM
384 * @param int $raterid
385 * @param int $itemid
36937f02
MG
386 * @param boolean $idonly
387 * @return mixed if $idonly=true returns id of the found instance, otherwise returns the instance object
21d37aa6 388 */
36937f02 389 public function get_current_instance($raterid, $itemid, $idonly = false) {
21d37aa6 390 global $DB;
0136124e 391 $params = array(
71ab436a 392 'definitionid' => $this->definition->id,
36937f02 393 'itemid' => $itemid,
0136124e
MG
394 'status1' => gradingform_instance::INSTANCE_STATUS_ACTIVE,
395 'status2' => gradingform_instance::INSTANCE_STATUS_NEEDUPDATE);
71ab436a 396 $select = 'definitionid=:definitionid and itemid=:itemid and (status=:status1 or status=:status2)';
5dc1ca87
MG
397 if (false) {
398 // TODO MDL-31237 should be: if ($manager->allow_multiple_raters())
0136124e
MG
399 $select .= ' and raterid=:raterid';
400 $params['raterid'] = $raterid;
21d37aa6 401 }
36937f02 402 if ($idonly) {
0136124e 403 if ($current = $DB->get_record_select('grading_instances', $select, $params, 'id', IGNORE_MISSING)) {
36937f02
MG
404 return $current->id;
405 }
21d37aa6 406 } else {
0136124e 407 if ($current = $DB->get_record_select('grading_instances', $select, $params, '*', IGNORE_MISSING)) {
36937f02
MG
408 return $this->get_instance($current);
409 }
21d37aa6 410 }
36937f02 411 return null;
21d37aa6
DM
412 }
413
18e6298c 414 /**
0136124e
MG
415 * Returns list of ACTIVE instances for the specified $itemid
416 * (intentionally does not return instances with status NEEDUPDATE)
36937f02
MG
417 *
418 * @param int $itemid
419 * @return array of gradingform_instance objects
18e6298c 420 */
0136124e 421 public function get_active_instances($itemid) {
36937f02 422 global $DB;
71ab436a 423 $conditions = array('definitionid' => $this->definition->id,
36937f02
MG
424 'itemid' => $itemid,
425 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
426 $records = $DB->get_recordset('grading_instances', $conditions);
427 $rv = array();
428 foreach ($records as $record) {
429 $rv[] = $this->get_instance($record);
430 }
431 return $rv;
432 }
6798c63e 433
9028d9b5
PC
434 /**
435 * Returns an array of all active instances for this definition.
436 * (intentionally does not return instances with status NEEDUPDATE)
437 *
98c2189d 438 * @param int since only return instances with timemodified >= since
9028d9b5
PC
439 * @return array of gradingform_instance objects
440 */
441 public function get_all_active_instances($since = 0) {
442 global $DB;
443 $conditions = array ($this->definition->id,
444 gradingform_instance::INSTANCE_STATUS_ACTIVE,
445 $since);
446 $where = "definitionid = ? AND status = ? AND timemodified >= ?";
447 $records = $DB->get_records_select('grading_instances', $where, $conditions);
448 $rv = array();
449 foreach ($records as $record) {
450 $rv[] = $this->get_instance($record);
451 }
452 return $rv;
453 }
454
0136124e
MG
455 /**
456 * Returns true if there are already people who has been graded on this definition.
457 * In this case plugins may restrict changes of the grading definition
458 *
459 * @return boolean
460 */
461 public function has_active_instances() {
462 global $DB;
2d41a911
MG
463 if (empty($this->definition->id)) {
464 return false;
465 }
0136124e 466 if ($this->hasactiveinstances === null) {
71ab436a 467 $conditions = array('definitionid' => $this->definition->id,
0136124e
MG
468 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
469 $this->hasactiveinstances = $DB->record_exists('grading_instances', $conditions);
470 }
471 return $this->hasactiveinstances;
472 }
473
6798c63e 474 /**
36937f02 475 * Returns the object of type gradingform_XXX_instance (where XXX is the plugin method name)
6798c63e 476 *
36937f02
MG
477 * @param mixed $instance id or row from grading_isntances table
478 * @return gradingform_instance
6798c63e 479 */
36937f02
MG
480 protected function get_instance($instance) {
481 global $DB;
482 if (is_scalar($instance)) {
483 // instance id is passed as parameter
484 $instance = $DB->get_record('grading_instances', array('id' => $instance), '*', MUST_EXIST);
485 }
486 if ($instance) {
487 $class = 'gradingform_'. $this->get_method_name(). '_instance';
488 return new $class($this, $instance);
489 }
490 return null;
6798c63e
MG
491 }
492
493 /**
36937f02
MG
494 * This function is invoked when user (teacher) starts grading.
495 * It creates and returns copy of the current ACTIVE instance if it exists. If this is the
496 * first grading attempt, a new instance is created.
497 * The status of the returned instance is INCOMPLETE
6798c63e 498 *
36937f02
MG
499 * @param int $raterid
500 * @param int $itemid
501 * @return gradingform_instance
6798c63e 502 */
fc05f222 503 public function create_instance($raterid, $itemid = null) {
6f19a2a9 504
36937f02 505 // first find if there is already an active instance for this itemid
fc05f222 506 if ($itemid && $current = $this->get_current_instance($raterid, $itemid)) {
36937f02
MG
507 return $this->get_instance($current->copy($raterid, $itemid));
508 } else {
509 $class = 'gradingform_'. $this->get_method_name(). '_instance';
510 return $this->get_instance($class::create_new($this->definition->id, $raterid, $itemid));
511 }
6798c63e 512 }
18e6298c 513
13926e73
MG
514 /**
515 * If instanceid is specified and grading instance exists and it is created by this rater for
516 * this item, this instance is returned.
517 * Otherwise new instance is created for the specified rater and itemid
518 *
519 * @param int $instanceid
520 * @param int $raterid
521 * @param int $itemid
522 * @return gradingform_instance
523 */
524 public function get_or_create_instance($instanceid, $raterid, $itemid) {
525 global $DB;
526 if ($instanceid &&
527 $instance = $DB->get_record('grading_instances', array('id' => $instanceid, 'raterid' => $raterid, 'itemid' => $itemid), '*', IGNORE_MISSING)) {
528 return $this->get_instance($instance);
529 }
530 return $this->create_instance($raterid, $itemid);
531 }
532
ab156741 533 /**
6832a102 534 * Returns the HTML code displaying the preview of the grading form
ab156741 535 *
20836db9 536 * Plugins are forced to override this. Ideally they should delegate
6832a102
DM
537 * the task to their own renderer.
538 *
539 * @param moodle_page $page the target page
540 * @return string
ab156741 541 */
20836db9 542 abstract public function render_preview(moodle_page $page);
ab156741 543
671ec8f5
DM
544 /**
545 * Deletes the form definition and all the associated data
546 *
547 * @see delete_plugin_definition()
548 * @return void
549 */
550 public function delete_definition() {
551 global $DB;
552
553 if (!$this->is_form_defined()) {
554 // nothing to do
555 return;
556 }
fe817d87 557
671ec8f5
DM
558 // firstly, let the plugin delete everything from their own tables
559 $this->delete_plugin_definition();
560 // then, delete all instances left
71ab436a 561 $DB->delete_records('grading_instances', array('definitionid' => $this->definition->id));
671ec8f5
DM
562 // finally, delete the main definition record
563 $DB->delete_records('grading_definitions', array('id' => $this->definition->id));
564
565 $this->definition = false;
566 }
567
20836db9
DM
568 /**
569 * Prepare the part of the search query to append to the FROM statement
570 *
571 * @param string $gdid the alias of grading_definitions.id column used by the caller
572 * @return string
573 */
574 public static function sql_search_from_tables($gdid) {
575 return '';
576 }
577
578 /**
579 * Prepare the parts of the SQL WHERE statement to search for the given token
580 *
581 * The returned array cosists of the list of SQL comparions and the list of
582 * respective parameters for the comparisons. The returned chunks will be joined
583 * with other conditions using the OR operator.
584 *
585 * @param string $token token to search for
586 * @return array
587 */
588 public static function sql_search_where($token) {
20836db9
DM
589
590 $subsql = array();
591 $params = array();
592
593 return array($subsql, $params);
594 }
595
d22e9e32 596 // //////////////////////////////////////////////////////////////////////////
fe817d87 597
21d37aa6
DM
598 /**
599 * Loads the form definition if it exists
3e43eff5 600 *
21d37aa6 601 * The default implementation just tries to load the record from the {grading_definitions}
3e43eff5
DM
602 * table. The plugins are likely to override this with a more complex query that loads
603 * all required data at once.
604 */
605 protected function load_definition() {
606 global $DB;
3e43eff5
DM
607 $this->definition = $DB->get_record('grading_definitions', array(
608 'areaid' => $this->areaid,
609 'method' => $this->get_method_name()), '*', IGNORE_MISSING);
610 }
21d37aa6 611
671ec8f5
DM
612 /**
613 * Deletes all plugin data associated with the given form definiton
614 *
615 * @see delete_definition()
616 */
617 abstract protected function delete_plugin_definition();
618
21d37aa6 619 /**
d22e9e32
MG
620 * Returns the name of the grading method plugin, eg 'rubric'
621 *
fe817d87
DM
622 * @return string the name of the grading method plugin, eg 'rubric'
623 * @see PARAM_PLUGIN
21d37aa6 624 */
fe817d87
DM
625 protected function get_method_name() {
626 if (preg_match('/^gradingform_([a-z][a-z0-9_]*[a-z0-9])_controller$/', get_class($this), $matches)) {
627 return $matches[1];
628 } else {
629 throw new coding_exception('Invalid class name');
630 }
21d37aa6 631 }
36937f02
MG
632
633 /**
634 * Returns html code to be included in student's feedback.
635 *
636 * @param moodle_page $page
637 * @param int $itemid
3c2b3cb3 638 * @param array $gradinginfo result of function grade_get_grades if plugin want to use some of their info
9e2eca0f 639 * @param string $defaultcontent default string to be returned if no active grading is found or for some reason can not be shown to a user
0136124e 640 * @param boolean $cangrade whether current user has capability to grade in this context
36937f02
MG
641 * @return string
642 */
3c2b3cb3 643 public function render_grade($page, $itemid, $gradinginfo, $defaultcontent, $cangrade) {
36937f02
MG
644 return $defaultcontent;
645 }
9e2eca0f
MG
646
647 /**
648 * Sets the range of grades used in this area. This is usually either range like 0-100
170f6e60
MG
649 * or the scale where keys start from 1.
650 *
651 * Typically modules will call it:
652 * $controller->set_grade_range(make_grades_menu($gradingtype), $gradingtype > 0);
653 * Negative $gradingtype means that scale is used and the grade must be rounded
654 * to the nearest int. Positive $gradingtype means that range 0..$gradingtype
655 * is used for the grades and in this case grade does not have to be rounded.
656 *
657 * Sometimes modules always expect grade to be rounded (like mod_assignment does).
3c2b3cb3 658 *
170f6e60
MG
659 * @param array $graderange array where first _key_ is the minimum grade and the
660 * last key is the maximum grade.
661 * @param bool $allowgradedecimals if decimal values are allowed as grades.
9e2eca0f 662 */
170f6e60 663 public final function set_grade_range(array $graderange, $allowgradedecimals = false) {
9e2eca0f 664 $this->graderange = $graderange;
170f6e60 665 $this->allowgradedecimals = $allowgradedecimals;
9e2eca0f
MG
666 }
667
668 /**
669 * Returns the range of grades used in this area
3c2b3cb3 670 *
9e2eca0f
MG
671 * @return array
672 */
673 public final function get_grade_range() {
674 if (empty($this->graderange)) {
675 return array();
676 }
677 return $this->graderange;
678 }
3f0ea6d8 679
170f6e60
MG
680 /**
681 * Returns if decimal values are allowed as grades
682 *
683 * @return bool
684 */
685 public final function get_allow_grade_decimals() {
686 return $this->allowgradedecimals;
687 }
688
3f0ea6d8
PC
689 /**
690 * Overridden by sub classes that wish to make definition details available to web services.
691 * When not overridden, only definition data common to all grading methods is made available.
692 * When overriding, the return value should be an array containing one or more key/value pairs.
693 * These key/value pairs should match the definition returned by the get_definition() function.
694 * For examples, look at:
695 * $gradingform_rubric_controller->get_external_definition_details()
696 * $gradingform_guide_controller->get_external_definition_details()
697 * @return array An array of one or more key/value pairs containing the external_multiple_structure/s
698 * corresponding to the definition returned by $controller->get_definition()
699 * @since Moodle 2.5
700 */
701 public static function get_external_definition_details() {
702 return null;
703 }
9028d9b5
PC
704
705 /**
706 * Overridden by sub classes that wish to make instance filling details available to web services.
707 * When not overridden, only instance filling data common to all grading methods is made available.
708 * When overriding, the return value should be an array containing one or more key/value pairs.
709 * These key/value pairs should match the filling data returned by the get_<method>_filling() function
710 * in the gradingform_instance subclass.
711 * For examples, look at:
712 * $gradingform_rubric_controller->get_external_instance_filling_details()
713 * $gradingform_guide_controller->get_external_instance_filling_details()
714 *
715 * @return array An array of one or more key/value pairs containing the external_multiple_structure/s
716 * corresponding to the definition returned by $gradingform_<method>_instance->get_<method>_filling()
717 * @since Moodle 2.6
718 */
719 public static function get_external_instance_filling_details() {
720 return null;
721 }
21d37aa6 722}
36937f02
MG
723
724/**
d22e9e32
MG
725 * Class to manage one gradingform instance.
726 *
727 * Gradingform instance is created for each evaluation of a student, using advanced grading.
728 * It is stored as an entry in the DB table gradingform_instance.
729 *
730 * One instance (usually the latest) has the status INSTANCE_STATUS_ACTIVE. Sometimes it may
731 * happen that a teacher wants to change the definition when some students have already been
732 * graded. In this case their instances change status to INSTANCE_STATUS_NEEDUPDATE.
733 *
734 * To support future use of AJAX for background saving of incomplete evaluations the
735 * status INSTANCE_STATUS_INCOMPLETE is introduced. If 'Cancel' is pressed this entry
736 * is deleted.
737 * When grade is updated the previous active instance receives status INSTANCE_STATUS_ACTIVE.
738 *
739 * Advanced grading plugins must declare a class gradingform_xxxx_instance
740 * extending this class and put it in lib.php in the plugin folder.
741 *
742 * The reference to an instance of this class is passed to an advanced grading form element
743 * included in the grading form, so this class must implement functions for rendering
744 * and validation of this form element. See {@link MoodleQuickForm_grading}
36937f02 745 *
5dc1ca87 746 * @package core_grading
36937f02 747 * @copyright 2011 Marina Glancy
d22e9e32
MG
748 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
749 * @category grading
36937f02
MG
750 */
751abstract class gradingform_instance {
d22e9e32 752 /** Valid istance status */
36937f02 753 const INSTANCE_STATUS_ACTIVE = 1;
d22e9e32 754 /** The grade needs to be updated by grader (usually because of changes is grading method) */
0136124e 755 const INSTANCE_STATUS_NEEDUPDATE = 2;
d22e9e32 756 /** The grader started grading but did clicked neither submit nor cancel */
36937f02 757 const INSTANCE_STATUS_INCOMPLETE = 0;
d22e9e32 758 /** Grader re-graded the student and this is the status for previous grade stored as history */
36937f02
MG
759 const INSTANCE_STATUS_ARCHIVE = 3;
760
761 /** @var stdClass record from table grading_instances */
762 protected $data;
763 /** @var gradingform_controller link to the corresponding controller */
764 protected $controller;
765
766 /**
767 * Creates an instance
768 *
769 * @param gradingform_controller $controller
770 * @param stdClass $data
771 */
772 public function __construct($controller, $data) {
773 $this->data = (object)$data;
774 $this->controller = $controller;
775 }
776
777 /**
778 * Creates a new empty instance in DB and mark its status as INCOMPLETE
779 *
71ab436a 780 * @param int $definitionid
36937f02
MG
781 * @param int $raterid
782 * @param int $itemid
783 * @return int id of the created instance
784 */
71ab436a 785 public static function create_new($definitionid, $raterid, $itemid) {
36937f02
MG
786 global $DB;
787 $instance = new stdClass();
71ab436a 788 $instance->definitionid = $definitionid;
36937f02
MG
789 $instance->raterid = $raterid;
790 $instance->itemid = $itemid;
791 $instance->status = self::INSTANCE_STATUS_INCOMPLETE;
792 $instance->timemodified = time();
793 $instance->feedbackformat = FORMAT_MOODLE;
794 $instanceid = $DB->insert_record('grading_instances', $instance);
795 return $instanceid;
796 }
797
798 /**
799 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
800 * the specified values)
801 * Plugins may want to override this function to copy data from additional tables as well
802 *
803 * @param int $raterid value for raterid in the duplicate
804 * @param int $itemid value for itemid in the duplicate
805 * @return int id of the new instance
806 */
807 public function copy($raterid, $itemid) {
808 global $DB;
809 $data = (array)$this->data; // Cast to array to make a copy
810 unset($data['id']);
811 $data['raterid'] = $raterid;
812 $data['itemid'] = $itemid;
813 $data['timemodified'] = time();
814 $data['status'] = self::INSTANCE_STATUS_INCOMPLETE;
815 $instanceid = $DB->insert_record('grading_instances', $data);
816 return $instanceid;
817 }
818
0136124e
MG
819 /**
820 * Returns the current (active or needupdate) instance for the same raterid and itemid as this
821 * instance. This function is useful to find the status of the currently modified instance
822 *
823 * @return gradingform_instance
824 */
825 public function get_current_instance() {
826 if ($this->get_status() == self::INSTANCE_STATUS_ACTIVE || $this->get_status() == self::INSTANCE_STATUS_NEEDUPDATE) {
827 return $this;
828 }
829 return $this->get_controller()->get_current_instance($this->data->raterid, $this->data->itemid);
830 }
831
36937f02
MG
832 /**
833 * Returns the controller
834 *
835 * @return gradingform_controller
836 */
837 public function get_controller() {
838 return $this->controller;
839 }
840
188e840b
MG
841 /**
842 * Returns the specified element from object $this->data
843 *
844 * @param string $key
845 * @return mixed
846 */
847 public function get_data($key) {
848 if (isset($this->data->$key)) {
849 return $this->data->$key;
850 }
851 return null;
852 }
853
36937f02
MG
854 /**
855 * Returns instance id
856 *
857 * @return int
858 */
859 public function get_id() {
188e840b 860 return $this->get_data('id');
36937f02
MG
861 }
862
0136124e
MG
863 /**
864 * Returns instance status
865 *
866 * @return int
867 */
868 public function get_status() {
188e840b 869 return $this->get_data('status');
0136124e
MG
870 }
871
36937f02
MG
872 /**
873 * Marks the instance as ACTIVE and current active instance (if exists) as ARCHIVE
874 */
875 protected function make_active() {
876 global $DB;
877 if ($this->data->status == self::INSTANCE_STATUS_ACTIVE) {
878 // already active
879 return;
880 }
fc05f222
MG
881 if (empty($this->data->itemid)) {
882 throw new coding_exception('You cannot mark active the grading instance without itemid');
883 }
36937f02 884 $currentid = $this->get_controller()->get_current_instance($this->data->raterid, $this->data->itemid, true);
0136124e
MG
885 if ($currentid && $currentid != $this->get_id()) {
886 $DB->update_record('grading_instances', array('id' => $currentid, 'status' => self::INSTANCE_STATUS_ARCHIVE));
36937f02 887 }
0136124e 888 $DB->update_record('grading_instances', array('id' => $this->get_id(), 'status' => self::INSTANCE_STATUS_ACTIVE));
36937f02
MG
889 $this->data->status = self::INSTANCE_STATUS_ACTIVE;
890 }
891
892 /**
893 * Deletes this (INCOMPLETE) instance from database. This function is invoked on cancelling the
894 * grading form and/or during cron cleanup.
895 * Plugins using additional tables must override this method to remove additional data.
896 * Note that if the teacher just closes the window or presses 'Back' button of the browser,
897 * this function is not invoked.
898 */
899 public function cancel() {
900 global $DB;
d22e9e32 901 // TODO MDL-31239 throw exception if status is not INSTANCE_STATUS_INCOMPLETE
36937f02
MG
902 $DB->delete_records('grading_instances', array('id' => $this->get_id()));
903 }
904
905 /**
906 * Updates the instance with the data received from grading form. This function may be
907 * called via AJAX when grading is not yet completed, so it does not change the
908 * status of the instance.
fc05f222
MG
909 *
910 * @param array $elementvalue
36937f02
MG
911 */
912 public function update($elementvalue) {
fc05f222
MG
913 global $DB;
914 $newdata = new stdClass();
915 $newdata->id = $this->get_id();
916 $newdata->timemodified = time();
917 if (isset($elementvalue['itemid']) && $elementvalue['itemid'] != $this->data->itemid) {
918 $newdata->itemid = $elementvalue['itemid'];
919 }
d22e9e32 920 // TODO MDL-31087 also update: rawgrade, feedback, feedbackformat
fc05f222
MG
921 $DB->update_record('grading_instances', $newdata);
922 foreach ($newdata as $key => $value) {
923 $this->data->$key = $value;
924 }
36937f02
MG
925 }
926
927 /**
928 * Calculates the grade to be pushed to the gradebook
9e2eca0f 929 *
170f6e60
MG
930 * Returned grade must be in range $this->get_controller()->get_grade_range()
931 * Plugins must returned grade converted to int unless
932 * $this->get_controller()->get_allow_grade_decimals() is true.
933 *
934 * @return float|int
36937f02
MG
935 */
936 abstract public function get_grade();
937
938 /**
939 * Called when teacher submits the grading form:
fc05f222
MG
940 * updates the instance in DB, marks it as ACTIVE and returns the grade to be pushed to the gradebook.
941 * $itemid must be specified here (it was not required when the instance was
942 * created, because it might not existed in draft)
943 *
944 * @param array $elementvalue
945 * @param int $itemid
36937f02
MG
946 * @return int the grade on 0-100 scale
947 */
fc05f222
MG
948 public function submit_and_get_grade($elementvalue, $itemid) {
949 $elementvalue['itemid'] = $itemid;
36937f02
MG
950 $this->update($elementvalue);
951 $this->make_active();
952 return $this->get_grade();
953 }
954
955
956 /**
957 * Returns html for form element of type 'grading'. If there is a form input element
958 * it must have the name $gradingformelement->getName().
959 * If there are more than one input elements they MUST be elements of array with
960 * name $gradingformelement->getName().
961 * Example: {NAME}[myelement1], {NAME}[myelement2][sub1], {NAME}[myelement2][sub2], etc.
9e2eca0f 962 * ( {NAME} is a shortcut for $gradingformelement->getName() )
36937f02
MG
963 * After submitting the form the value of $_POST[{NAME}] is passed to the functions
964 * validate_grading_element() and submit_and_get_grade()
965 *
966 * Plugins may use $gradingformelement->getValue() to get the value passed on previous
9e2eca0f 967 * form submit
36937f02
MG
968 *
969 * When forming html it is a plugin's responsibility to analyze flags
970 * $gradingformelement->_flagFrozen and $gradingformelement->_persistantFreeze:
971 *
972 * (_flagFrozen == false) => form element is editable
973 *
974 * (_flagFrozen == false && _persistantFreeze == true) => form element is not editable
975 * but all values are passed as hidden elements
976 *
977 * (_flagFrozen == false && _persistantFreeze == false) => form element is not editable
978 * and no values are passed as hidden elements
979 *
980 * Plugins are welcome to use AJAX in the form element. But it is strongly recommended
981 * that the grading only becomes active when teacher presses 'Submit' button (the
982 * method submit_and_get_grade() is invoked)
983 *
984 * Also client-side JS validation may be implemented here
985 *
986 * @see MoodleQuickForm_grading in lib/form/grading.php
987 *
988 * @param moodle_page $page
989 * @param MoodleQuickForm_grading $gradingformelement
990 * @return string
991 */
992 abstract function render_grading_element($page, $gradingformelement);
993
994 /**
995 * Server-side validation of the data received from grading form.
996 *
997 * @param mixed $elementvalue is the scalar or array received in $_POST
998 * @return boolean true if the form data is validated and contains no errors
999 */
1000 public function validate_grading_element($elementvalue) {
1001 return true;
1002 }
1003
1004 /**
1005 * Returns the error message displayed if validation failed.
1006 * If plugin wants to display custom message, the empty string should be returned here
1007 * and the custom message should be output in render_grading_element()
1008 *
d22e9e32
MG
1009 * Please note that in assignments grading in 2.2 the grading form is not validated
1010 * properly and this message is not being displayed.
1011 *
36937f02
MG
1012 * @see validate_grading_element()
1013 * @return string
1014 */
1015 public function default_validation_error_message() {
1016 return '';
1017 }
98c2189d 1018}