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