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