MDL-29483: advanced grading methods support on assignment module, grading form elemen...
[moodle.git] / grade / grading / form / lib.php
CommitLineData
9b8550f8
DM
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
21d37aa6
DM
19 * Common classes used by gradingform plugintypes are defined here
20 *
9b8550f8
DM
21 * @package core
22 * @subpackage grading
23 * @copyright 2011 David Mudrak <david@moodle.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
21d37aa6 30 * Grading method controller represents a plugin used in a particular area
9b8550f8 31 */
3e43eff5 32abstract class gradingform_controller {
9b8550f8 33
21d37aa6
DM
34 const DEFINITION_STATUS_WORKINPROGRESS = 0;
35 const DEFINITION_STATUS_PRIVATE = 1;
36 const DEFINITION_STATUS_PUBLIC = 2;
37
9b8550f8
DM
38 /** @var stdClass the context */
39 protected $context;
40
41 /** @var string the frankenstyle name of the component */
42 protected $component;
43
44 /** @var string the name of the gradable area */
45 protected $area;
46
47 /** @var int the id of the gradable area record */
48 protected $areaid;
49
fe817d87 50 /** @var stdClass|false the definition structure */
3e43eff5
DM
51 protected $definition;
52
9b8550f8
DM
53 /**
54 * Do not instantinate this directly, use {@link grading_manager::get_controller()}
55 *
fe817d87
DM
56 * @param stdClass $context the context of the form
57 * @param string $component the frankenstyle name of the component
58 * @param string $area the name of the gradable area
59 * @param int $areaid the id of the gradable area record
9b8550f8
DM
60 */
61 public function __construct(stdClass $context, $component, $area, $areaid) {
3e43eff5
DM
62 global $DB;
63
64 $this->context = $context;
fe817d87
DM
65 list($type, $name) = normalize_component($component);
66 $this->component = $type.'_'.$name;
3e43eff5
DM
67 $this->area = $area;
68 $this->areaid = $areaid;
69
70 $this->load_definition();
71 }
72
fe817d87
DM
73 /**
74 * @return stdClass controller context
75 */
76 public function get_context() {
77 return $this->context;
78 }
79
80 /**
81 * @return string gradable component name
82 */
83 public function get_component() {
84 return $this->component;
85 }
86
87 /**
88 * @return string gradable area name
89 */
90 public function get_area() {
91 return $this->area;
92 }
93
94 /**
95 * @return int gradable area id
96 */
97 public function get_areaid() {
98 return $this->areaid;
99 }
100
6832a102
DM
101 /**
102 * Is the form definition record available?
103 *
104 * Note that this actually checks whether the process of defining the form ever started
105 * and not whether the form definition should be considered as final.
106 *
107 * @return boolean
108 */
109 public function is_form_defined() {
110 return !empty($this->definition);
111 }
112
3e43eff5 113 /**
21d37aa6 114 * Is the grading form defined and released for usage by the given user?
3e43eff5 115 *
21d37aa6 116 * @param int $foruserid the id of the user who attempts to work with the form
3e43eff5
DM
117 * @return boolean
118 */
21d37aa6
DM
119 public function is_form_available($foruserid = null) {
120 global $USER;
121
122 if (is_null($foruserid)) {
123 $foruserid = $USER->id;
124 }
125
6832a102 126 if (!$this->is_form_defined()) {
21d37aa6
DM
127 return false;
128 }
129
130 if ($this->definition->status == self::DEFINITION_STATUS_PUBLIC) {
131 return true;
132 }
133
134 if ($this->definition->status == self::DEFINITION_STATUS_PRIVATE) {
135 if ($this->definition->usercreated == $foruserid) {
136 return true;
137 }
138 }
139
140 return false;
3e43eff5
DM
141 }
142
6832a102
DM
143 /**
144 * Returns URL of a page where the grading form can be defined and edited.
145 *
146 * @param moodle_url $returnurl optional URL of a page where the user should be sent once they are finished with editing
147 * @return moodle_url
148 */
149 public function get_editor_url(moodle_url $returnurl = null) {
150
151 $params = array('areaid' => $this->areaid);
152
153 if (!is_null($returnurl)) {
154 $params['returnurl'] = $returnurl->out(false);
155 }
156
157 return new moodle_url('/grade/grading/form/'.$this->get_method_name().'/edit.php', $params);
158 }
159
9b8550f8
DM
160 /**
161 * Extends the module settings navigation
162 *
163 * This function is called when the context for the page is an activity module with the
164 * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
165 * and there is an area with the active grading method set to the given plugin.
166 *
167 * @param settings_navigation $settingsnav {@link settings_navigation}
168 * @param navigation_node $node {@link navigation_node}
169 */
170 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
171 // do not extend by default
172 }
3e43eff5
DM
173
174 /**
fe817d87 175 * Returns the grading form definition structure
3e43eff5 176 *
fe817d87 177 * @return stdClass|false definition data or false if the form is not defined yet
3e43eff5 178 */
fe817d87
DM
179 public function get_definition() {
180 if (is_null($this->definition)) {
181 $this->load_definition();
182 }
183 return $this->definition;
3e43eff5
DM
184 }
185
fde33804
DM
186 /**
187 * Returns the form definition suitable for cloning into another area
188 *
189 * @param gradingform_controller $target the controller of the new copy
190 * @return stdClass definition structure to pass to the target's {@link update_definition()}
191 */
192 public function get_definition_copy(gradingform_controller $target) {
193
194 if (get_class($this) != get_class($target)) {
195 throw new coding_exception('The source and copy controller mismatch');
196 }
197
198 if ($target->is_form_defined()) {
199 throw new coding_exception('The target controller already contains a form definition');
200 }
201
202 $old = $this->get_definition();
203 // keep our id
204 $new = new stdClass();
205 $new->copiedfromid = $old->id;
206 $new->name = $old->name;
207 // once we support files embedded into the description, we will want to
208 // relink them into the new file area here (that is why we accept $target)
209 $new->description = $old->description;
210 $new->descriptionformat = $old->descriptionformat;
211 $new->options = $old->options;
212
213 return $new;
214 }
215
3e43eff5 216 /**
fe817d87 217 * Saves the defintion data into the database
21d37aa6 218 *
fe817d87
DM
219 * The implementation in this base class stores the common data into the record
220 * into the {grading_definition} table. The plugins are likely to extend this
221 * and save their data into own tables, too.
21d37aa6 222 *
fe817d87
DM
223 * @param stdClass $definition data containing values for the {grading_definition} table
224 * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
21d37aa6
DM
225 */
226 public function update_definition(stdClass $definition, $usermodified = null) {
227 global $DB, $USER;
228
229 if (is_null($usermodified)) {
230 $usermodified = $USER->id;
231 }
232
fe817d87
DM
233 if (!empty($this->definition->id)) {
234 // prepare a record to be updated
235 $record = new stdClass();
236 // populate it with scalar values from the passed definition structure
237 foreach ($definition as $prop => $val) {
238 if (is_array($val) or is_object($val)) {
239 // probably plugin's data
240 continue;
241 }
242 $record->{$prop} = $val;
243 }
244 // make sure we do not override some crucial values by accident
245 if (!empty($record->id) and $record->id != $this->definition->id) {
246 throw new coding_exception('Attempting to update other definition record.');
247 }
248 $record->id = $this->definition->id;
249 unset($record->areaid);
250 unset($record->method);
251 unset($record->timecreated);
252 // set the modification flags
253 $record->timemodified = time();
254 $record->usermodified = $usermodified;
21d37aa6 255
fe817d87 256 $DB->update_record('grading_definitions', $record);
21d37aa6
DM
257
258 } else if ($this->definition === false) {
fe817d87
DM
259 // prepare a record to be inserted
260 $record = new stdClass();
261 // populate it with scalar values from the passed definition structure
262 foreach ($definition as $prop => $val) {
263 if (is_array($val) or is_object($val)) {
264 // probably plugin's data
265 continue;
266 }
267 $record->{$prop} = $val;
268 }
269 // make sure we do not override some crucial values by accident
270 if (!empty($record->id)) {
271 throw new coding_exception('Attempting to create a new record while there is already one existing.');
272 }
273 unset($record->id);
274 $record->areaid = $this->areaid;
275 $record->method = $this->get_method_name();
276 $record->timecreated = time();
277 $record->usercreated = $usermodified;
ac16cedf
DM
278 $record->timemodified = $record->timecreated;
279 $record->usermodified = $record->usercreated;
fe817d87 280 $record->status = self::DEFINITION_STATUS_WORKINPROGRESS;
21d37aa6 281
ac16cedf 282 $DB->insert_record('grading_definitions', $record);
21d37aa6
DM
283
284 } else {
fe817d87 285 throw new coding_exception('Unknown status of the cached definition record.');
21d37aa6
DM
286 }
287 }
288
289 /**
36937f02
MG
290 * Returns the ACTIVE instance for this definition for the specified $raterid and $itemid
291 * (if multiple raters are allowed, or only for $itemid otherwise).
21d37aa6 292 *
21d37aa6
DM
293 * @param int $raterid
294 * @param int $itemid
36937f02
MG
295 * @param boolean $idonly
296 * @return mixed if $idonly=true returns id of the found instance, otherwise returns the instance object
21d37aa6 297 */
36937f02 298 public function get_current_instance($raterid, $itemid, $idonly = false) {
21d37aa6 299 global $DB;
36937f02
MG
300 $select = array(
301 'formid' => $this->definition->id,
302 'itemid' => $itemid,
303 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
304 if (false /* TODO $manager->allow_multiple_raters() */) {
305 $select['raterid'] = $raterid;
21d37aa6 306 }
36937f02
MG
307 if ($idonly) {
308 if ($current = $DB->get_record('grading_instances', $select, 'id', IGNORE_MISSING)) {
309 return $current->id;
310 }
21d37aa6 311 } else {
36937f02
MG
312 if ($current = $DB->get_record('grading_instances', $select, '*', IGNORE_MISSING)) {
313 return $this->get_instance($current);
314 }
21d37aa6 315 }
36937f02 316 return null;
21d37aa6
DM
317 }
318
18e6298c 319 /**
36937f02
MG
320 * Returns list of active instances for the specified $itemid
321 *
322 * @param int $itemid
323 * @return array of gradingform_instance objects
18e6298c 324 */
36937f02
MG
325 public function get_current_instances($itemid) {
326 global $DB;
327 $conditions = array('formid' => $this->definition->id,
328 'itemid' => $itemid,
329 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
330 $records = $DB->get_recordset('grading_instances', $conditions);
331 $rv = array();
332 foreach ($records as $record) {
333 $rv[] = $this->get_instance($record);
334 }
335 return $rv;
336 }
6798c63e
MG
337
338 /**
36937f02 339 * Returns the object of type gradingform_XXX_instance (where XXX is the plugin method name)
6798c63e 340 *
36937f02
MG
341 * @param mixed $instance id or row from grading_isntances table
342 * @return gradingform_instance
6798c63e 343 */
36937f02
MG
344 protected function get_instance($instance) {
345 global $DB;
346 if (is_scalar($instance)) {
347 // instance id is passed as parameter
348 $instance = $DB->get_record('grading_instances', array('id' => $instance), '*', MUST_EXIST);
349 }
350 if ($instance) {
351 $class = 'gradingform_'. $this->get_method_name(). '_instance';
352 return new $class($this, $instance);
353 }
354 return null;
6798c63e
MG
355 }
356
357 /**
36937f02
MG
358 * This function is invoked when user (teacher) starts grading.
359 * It creates and returns copy of the current ACTIVE instance if it exists. If this is the
360 * first grading attempt, a new instance is created.
361 * The status of the returned instance is INCOMPLETE
6798c63e 362 *
36937f02
MG
363 * @param int $raterid
364 * @param int $itemid
365 * @return gradingform_instance
6798c63e 366 */
36937f02
MG
367 public function create_instance($raterid, $itemid) {
368 global $DB;
369 // first find if there is already an active instance for this itemid
370 if ($current = $this->get_current_instance($raterid, $itemid)) {
371 return $this->get_instance($current->copy($raterid, $itemid));
372 } else {
373 $class = 'gradingform_'. $this->get_method_name(). '_instance';
374 return $this->get_instance($class::create_new($this->definition->id, $raterid, $itemid));
375 }
6798c63e 376 }
18e6298c 377
ab156741 378 /**
6832a102 379 * Returns the HTML code displaying the preview of the grading form
ab156741 380 *
6832a102
DM
381 * Plugins are supposed to override/extend this. Ideally they should delegate
382 * the task to their own renderer.
383 *
384 * @param moodle_page $page the target page
385 * @return string
ab156741 386 */
6832a102
DM
387 public function render_preview(moodle_page $page) {
388
389 if (!$this->is_form_defined()) {
390 throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
391 }
392
393 $output = $page->get_renderer('core_grading');
394
395 return $output->preview_definition_header($this);
ab156741
MG
396 }
397
671ec8f5
DM
398 /**
399 * Deletes the form definition and all the associated data
400 *
401 * @see delete_plugin_definition()
402 * @return void
403 */
404 public function delete_definition() {
405 global $DB;
406
407 if (!$this->is_form_defined()) {
408 // nothing to do
409 return;
410 }
fe817d87 411
671ec8f5
DM
412 // firstly, let the plugin delete everything from their own tables
413 $this->delete_plugin_definition();
414 // then, delete all instances left
415 $DB->delete_records('grading_instances', array('formid' => $this->definition->id));
416 // finally, delete the main definition record
417 $DB->delete_records('grading_definitions', array('id' => $this->definition->id));
418
419 $this->definition = false;
420 }
421
422 ////////////////////////////////////////////////////////////////////////////
fe817d87 423
21d37aa6
DM
424 /**
425 * Loads the form definition if it exists
3e43eff5 426 *
21d37aa6 427 * The default implementation just tries to load the record from the {grading_definitions}
3e43eff5
DM
428 * table. The plugins are likely to override this with a more complex query that loads
429 * all required data at once.
430 */
431 protected function load_definition() {
432 global $DB;
3e43eff5
DM
433 $this->definition = $DB->get_record('grading_definitions', array(
434 'areaid' => $this->areaid,
435 'method' => $this->get_method_name()), '*', IGNORE_MISSING);
436 }
21d37aa6 437
671ec8f5
DM
438 /**
439 * Deletes all plugin data associated with the given form definiton
440 *
441 * @see delete_definition()
442 */
443 abstract protected function delete_plugin_definition();
444
21d37aa6 445 /**
fe817d87
DM
446 * @return string the name of the grading method plugin, eg 'rubric'
447 * @see PARAM_PLUGIN
21d37aa6 448 */
fe817d87
DM
449 protected function get_method_name() {
450 if (preg_match('/^gradingform_([a-z][a-z0-9_]*[a-z0-9])_controller$/', get_class($this), $matches)) {
451 return $matches[1];
452 } else {
453 throw new coding_exception('Invalid class name');
454 }
21d37aa6 455 }
36937f02
MG
456
457 /**
458 * Returns html code to be included in student's feedback.
459 *
460 * @param moodle_page $page
461 * @param int $itemid
462 * @param string $defaultcontent default string to be returned if no active grading is found
463 * @return string
464 */
465 public function render_grade($page, $itemid, $defaultcontent) {
466 return $defaultcontent;
467 }
21d37aa6 468}
36937f02
MG
469
470/**
471 * Class to manage one grading instance. Stores information and performs actions like
472 * update, copy, validate, submit, etc.
473 *
474 * @copyright 2011 Marina Glancy
475 */
476abstract class gradingform_instance {
477 const INSTANCE_STATUS_ACTIVE = 1;
478 const INSTANCE_STATUS_INCOMPLETE = 0;
479 const INSTANCE_STATUS_ARCHIVE = 3;
480
481 /** @var stdClass record from table grading_instances */
482 protected $data;
483 /** @var gradingform_controller link to the corresponding controller */
484 protected $controller;
485
486 /**
487 * Creates an instance
488 *
489 * @param gradingform_controller $controller
490 * @param stdClass $data
491 */
492 public function __construct($controller, $data) {
493 $this->data = (object)$data;
494 $this->controller = $controller;
495 }
496
497 /**
498 * Creates a new empty instance in DB and mark its status as INCOMPLETE
499 *
500 * @param int $formid
501 * @param int $raterid
502 * @param int $itemid
503 * @return int id of the created instance
504 */
505 public static function create_new($formid, $raterid, $itemid) {
506 global $DB;
507 $instance = new stdClass();
508 $instance->formid = $formid;
509 $instance->raterid = $raterid;
510 $instance->itemid = $itemid;
511 $instance->status = self::INSTANCE_STATUS_INCOMPLETE;
512 $instance->timemodified = time();
513 $instance->feedbackformat = FORMAT_MOODLE;
514 $instanceid = $DB->insert_record('grading_instances', $instance);
515 return $instanceid;
516 }
517
518 /**
519 * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
520 * the specified values)
521 * Plugins may want to override this function to copy data from additional tables as well
522 *
523 * @param int $raterid value for raterid in the duplicate
524 * @param int $itemid value for itemid in the duplicate
525 * @return int id of the new instance
526 */
527 public function copy($raterid, $itemid) {
528 global $DB;
529 $data = (array)$this->data; // Cast to array to make a copy
530 unset($data['id']);
531 $data['raterid'] = $raterid;
532 $data['itemid'] = $itemid;
533 $data['timemodified'] = time();
534 $data['status'] = self::INSTANCE_STATUS_INCOMPLETE;
535 $instanceid = $DB->insert_record('grading_instances', $data);
536 return $instanceid;
537 }
538
539 /**
540 * Returns the controller
541 *
542 * @return gradingform_controller
543 */
544 public function get_controller() {
545 return $this->controller;
546 }
547
548 /**
549 * Returns instance id
550 *
551 * @return int
552 */
553 public function get_id() {
554 return $this->data->id;
555 }
556
557 /**
558 * Marks the instance as ACTIVE and current active instance (if exists) as ARCHIVE
559 */
560 protected function make_active() {
561 global $DB;
562 if ($this->data->status == self::INSTANCE_STATUS_ACTIVE) {
563 // already active
564 return;
565 }
566 $currentid = $this->get_controller()->get_current_instance($this->data->raterid, $this->data->itemid, true);
567 if ($currentid) {
568 if ($currentid != $this->get_id()) {
569 $DB->update_record('grading_instances', array('id' => $currentid, 'status' => self::INSTANCE_STATUS_ARCHIVE));
570 $DB->update_record('grading_instances', array('id' => $this->get_id(), 'status' => self::INSTANCE_STATUS_ACTIVE));
571 }
572 } else {
573 $DB->update_record('grading_instances', array('id' => $this->get_id(), 'status' => self::INSTANCE_STATUS_ACTIVE));
574 }
575 $this->data->status = self::INSTANCE_STATUS_ACTIVE;
576 }
577
578 /**
579 * Deletes this (INCOMPLETE) instance from database. This function is invoked on cancelling the
580 * grading form and/or during cron cleanup.
581 * Plugins using additional tables must override this method to remove additional data.
582 * Note that if the teacher just closes the window or presses 'Back' button of the browser,
583 * this function is not invoked.
584 */
585 public function cancel() {
586 global $DB;
587 // TODO what if we happen delete the ACTIVE instance, shall we rollback to the last ARCHIVE? or throw an exception?
588 // TODO create cleanup cron
589 $DB->delete_records('grading_instances', array('id' => $this->get_id()));
590 }
591
592 /**
593 * Updates the instance with the data received from grading form. This function may be
594 * called via AJAX when grading is not yet completed, so it does not change the
595 * status of the instance.
596 */
597 public function update($elementvalue) {
598 // TODO update timemodified at least
599 }
600
601 /**
602 * Calculates the grade to be pushed to the gradebook
603 * @return int the grade on 0-100 scale
604 */
605 abstract public function get_grade();
606
607 /**
608 * Called when teacher submits the grading form:
609 * updates the instance in DB, marks it as ACTIVE and returns the grade to be pushed to the gradebook
610 * @return int the grade on 0-100 scale
611 */
612 public function submit_and_get_grade($elementvalue) {
613 $this->update($elementvalue);
614 $this->make_active();
615 return $this->get_grade();
616 }
617
618
619 /**
620 * Returns html for form element of type 'grading'. If there is a form input element
621 * it must have the name $gradingformelement->getName().
622 * If there are more than one input elements they MUST be elements of array with
623 * name $gradingformelement->getName().
624 * Example: {NAME}[myelement1], {NAME}[myelement2][sub1], {NAME}[myelement2][sub2], etc.
625 * After submitting the form the value of $_POST[{NAME}] is passed to the functions
626 * validate_grading_element() and submit_and_get_grade()
627 *
628 * Plugins may use $gradingformelement->getValue() to get the value passed on previous
629 * from submit
630 *
631 * When forming html it is a plugin's responsibility to analyze flags
632 * $gradingformelement->_flagFrozen and $gradingformelement->_persistantFreeze:
633 *
634 * (_flagFrozen == false) => form element is editable
635 *
636 * (_flagFrozen == false && _persistantFreeze == true) => form element is not editable
637 * but all values are passed as hidden elements
638 *
639 * (_flagFrozen == false && _persistantFreeze == false) => form element is not editable
640 * and no values are passed as hidden elements
641 *
642 * Plugins are welcome to use AJAX in the form element. But it is strongly recommended
643 * that the grading only becomes active when teacher presses 'Submit' button (the
644 * method submit_and_get_grade() is invoked)
645 *
646 * Also client-side JS validation may be implemented here
647 *
648 * @see MoodleQuickForm_grading in lib/form/grading.php
649 *
650 * @param moodle_page $page
651 * @param MoodleQuickForm_grading $gradingformelement
652 * @return string
653 */
654 abstract function render_grading_element($page, $gradingformelement);
655
656 /**
657 * Server-side validation of the data received from grading form.
658 *
659 * @param mixed $elementvalue is the scalar or array received in $_POST
660 * @return boolean true if the form data is validated and contains no errors
661 */
662 public function validate_grading_element($elementvalue) {
663 return true;
664 }
665
666 /**
667 * Returns the error message displayed if validation failed.
668 * If plugin wants to display custom message, the empty string should be returned here
669 * and the custom message should be output in render_grading_element()
670 *
671 * @see validate_grading_element()
672 * @return string
673 */
674 public function default_validation_error_message() {
675 return '';
676 }
677}