forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gradelib.php
1447 lines (1229 loc) · 52.4 KB
/
gradelib.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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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/>.
/**
* Library of functions for gradebook - both public and internal
*
* @package core_grades
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** Include essential files */
require_once($CFG->libdir . '/grade/constants.php');
require_once($CFG->libdir . '/grade/grade_category.php');
require_once($CFG->libdir . '/grade/grade_item.php');
require_once($CFG->libdir . '/grade/grade_grade.php');
require_once($CFG->libdir . '/grade/grade_scale.php');
require_once($CFG->libdir . '/grade/grade_outcome.php');
/////////////////////////////////////////////////////////////////////
///// Start of public API for communication with modules/blocks /////
/////////////////////////////////////////////////////////////////////
/**
* Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
* rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded'.
* Missing property or key means does not change the existing value.
*
* Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
* 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
*
* Manual, course or category items can not be updated by this function.
*
* @category grade
* @param string $source Source of the grade such as 'mod/assignment'
* @param int $courseid ID of course
* @param string $itemtype Type of grade item. For example, mod or block
* @param string $itemmodule More specific then $itemtype. For example, assignment or forum. May be NULL for some item types
* @param int $iteminstance Instance ID of graded item
* @param int $itemnumber Most probably 0. Modules can use other numbers when having more than one grade for each user
* @param mixed $grades Grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
* @param mixed $itemdetails Object or array describing the grading item, NULL if no change
* @return int Returns GRADE_UPDATE_OK, GRADE_UPDATE_FAILED, GRADE_UPDATE_MULTIPLE or GRADE_UPDATE_ITEM_LOCKED
*/
function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
global $USER, $CFG, $DB;
// only following grade_item properties can be changed in this function
$allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
// list of 10,5 numeric fields
$floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
// grade item identification
$params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
if (is_null($courseid) or is_null($itemtype)) {
debugging('Missing courseid or itemtype');
return GRADE_UPDATE_FAILED;
}
if (!$grade_items = grade_item::fetch_all($params)) {
// create a new one
$grade_item = false;
} else if (count($grade_items) == 1){
$grade_item = reset($grade_items);
unset($grade_items); //release memory
} else {
debugging('Found more than one grade item');
return GRADE_UPDATE_MULTIPLE;
}
if (!empty($itemdetails['deleted'])) {
if ($grade_item) {
if ($grade_item->delete($source)) {
return GRADE_UPDATE_OK;
} else {
return GRADE_UPDATE_FAILED;
}
}
return GRADE_UPDATE_OK;
}
/// Create or update the grade_item if needed
if (!$grade_item) {
if ($itemdetails) {
$itemdetails = (array)$itemdetails;
// grademin and grademax ignored when scale specified
if (array_key_exists('scaleid', $itemdetails)) {
if ($itemdetails['scaleid']) {
unset($itemdetails['grademin']);
unset($itemdetails['grademax']);
}
}
foreach ($itemdetails as $k=>$v) {
if (!in_array($k, $allowed)) {
// ignore it
continue;
}
if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
// no grade item needed!
return GRADE_UPDATE_OK;
}
$params[$k] = $v;
}
}
$grade_item = new grade_item($params);
$grade_item->insert();
} else {
if ($grade_item->is_locked()) {
// no notice() here, test returned value instead!
return GRADE_UPDATE_ITEM_LOCKED;
}
if ($itemdetails) {
$itemdetails = (array)$itemdetails;
$update = false;
foreach ($itemdetails as $k=>$v) {
if (!in_array($k, $allowed)) {
// ignore it
continue;
}
if (in_array($k, $floats)) {
if (grade_floats_different($grade_item->{$k}, $v)) {
$grade_item->{$k} = $v;
$update = true;
}
} else {
if ($grade_item->{$k} != $v) {
$grade_item->{$k} = $v;
$update = true;
}
}
}
if ($update) {
$grade_item->update();
}
}
}
/// reset grades if requested
if (!empty($itemdetails['reset'])) {
$grade_item->delete_all_grades('reset');
return GRADE_UPDATE_OK;
}
/// Some extra checks
// do we use grading?
if ($grade_item->gradetype == GRADE_TYPE_NONE) {
return GRADE_UPDATE_OK;
}
// no grade submitted
if (empty($grades)) {
return GRADE_UPDATE_OK;
}
/// Finally start processing of grades
if (is_object($grades)) {
$grades = array($grades->userid=>$grades);
} else {
if (array_key_exists('userid', $grades)) {
$grades = array($grades['userid']=>$grades);
}
}
/// normalize and verify grade array
foreach($grades as $k=>$g) {
if (!is_array($g)) {
$g = (array)$g;
$grades[$k] = $g;
}
if (empty($g['userid']) or $k != $g['userid']) {
debugging('Incorrect grade array index, must be user id! Grade ignored.');
unset($grades[$k]);
}
}
if (empty($grades)) {
return GRADE_UPDATE_FAILED;
}
$count = count($grades);
if ($count > 0 and $count < 200) {
list($uids, $params) = $DB->get_in_or_equal(array_keys($grades), SQL_PARAMS_NAMED, $start='uid');
$params['gid'] = $grade_item->id;
$sql = "SELECT * FROM {grade_grades} WHERE itemid = :gid AND userid $uids";
} else {
$sql = "SELECT * FROM {grade_grades} WHERE itemid = :gid";
$params = array('gid'=>$grade_item->id);
}
$rs = $DB->get_recordset_sql($sql, $params);
$failed = false;
while (count($grades) > 0) {
$grade_grade = null;
$grade = null;
foreach ($rs as $gd) {
$userid = $gd->userid;
if (!isset($grades[$userid])) {
// this grade not requested, continue
continue;
}
// existing grade requested
$grade = $grades[$userid];
$grade_grade = new grade_grade($gd, false);
unset($grades[$userid]);
break;
}
if (is_null($grade_grade)) {
if (count($grades) == 0) {
// no more grades to process
break;
}
$grade = reset($grades);
$userid = $grade['userid'];
$grade_grade = new grade_grade(array('itemid'=>$grade_item->id, 'userid'=>$userid), false);
$grade_grade->load_optional_fields(); // add feedback and info too
unset($grades[$userid]);
}
$rawgrade = false;
$feedback = false;
$feedbackformat = FORMAT_MOODLE;
$usermodified = $USER->id;
$datesubmitted = null;
$dategraded = null;
if (array_key_exists('rawgrade', $grade)) {
$rawgrade = $grade['rawgrade'];
}
if (array_key_exists('feedback', $grade)) {
$feedback = $grade['feedback'];
}
if (array_key_exists('feedbackformat', $grade)) {
$feedbackformat = $grade['feedbackformat'];
}
if (array_key_exists('usermodified', $grade)) {
$usermodified = $grade['usermodified'];
}
if (array_key_exists('datesubmitted', $grade)) {
$datesubmitted = $grade['datesubmitted'];
}
if (array_key_exists('dategraded', $grade)) {
$dategraded = $grade['dategraded'];
}
// update or insert the grade
if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified, $dategraded, $datesubmitted, $grade_grade)) {
$failed = true;
}
}
if ($rs) {
$rs->close();
}
if (!$failed) {
return GRADE_UPDATE_OK;
} else {
return GRADE_UPDATE_FAILED;
}
}
/**
* Updates a user's outcomes. Manual outcomes can not be updated.
*
* @category grade
* @param string $source Source of the grade such as 'mod/assignment'
* @param int $courseid ID of course
* @param string $itemtype Type of grade item. For example, 'mod' or 'block'
* @param string $itemmodule More specific then $itemtype. For example, 'forum' or 'quiz'. May be NULL for some item types
* @param int $iteminstance Instance ID of graded item. For example the forum ID.
* @param int $userid ID of the graded user
* @param array $data Array consisting of grade item itemnumber ({@link grade_update()}) => outcomegrade
* @return bool returns true if grade items were found and updated successfully
*/
function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
$result = true;
foreach ($items as $item) {
if (!array_key_exists($item->itemnumber, $data)) {
continue;
}
$grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
$result = ($item->update_final_grade($userid, $grade, $source) && $result);
}
return $result;
}
return false; //grade items not found
}
/**
* Returns grading information for given activity, optionally with user grades
* Manual, course or category items can not be queried.
*
* @category grade
* @param int $courseid ID of course
* @param string $itemtype Type of grade item. For example, 'mod' or 'block'
* @param string $itemmodule More specific then $itemtype. For example, 'forum' or 'quiz'. May be NULL for some item types
* @param int $iteminstance ID of the item module
* @param mixed $userid_or_ids Either a single user ID, an array of user IDs or null. If user ID or IDs are not supplied returns information about grade_item
* @return array Array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
*/
function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=null) {
global $CFG;
$return = new stdClass();
$return->items = array();
$return->outcomes = array();
$course_item = grade_item::fetch_course_item($courseid);
$needsupdate = array();
if ($course_item->needsupdate) {
$result = grade_regrade_final_grades($courseid);
if ($result !== true) {
$needsupdate = array_keys($result);
}
}
if ($grade_items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
foreach ($grade_items as $grade_item) {
$decimalpoints = null;
if (empty($grade_item->outcomeid)) {
// prepare information about grade item
$item = new stdClass();
$item->itemnumber = $grade_item->itemnumber;
$item->scaleid = $grade_item->scaleid;
$item->name = $grade_item->get_name();
$item->grademin = $grade_item->grademin;
$item->grademax = $grade_item->grademax;
$item->gradepass = $grade_item->gradepass;
$item->locked = $grade_item->is_locked();
$item->hidden = $grade_item->is_hidden();
$item->grades = array();
switch ($grade_item->gradetype) {
case GRADE_TYPE_NONE:
continue;
case GRADE_TYPE_VALUE:
$item->scaleid = 0;
break;
case GRADE_TYPE_TEXT:
$item->scaleid = 0;
$item->grademin = 0;
$item->grademax = 0;
$item->gradepass = 0;
break;
}
if (empty($userid_or_ids)) {
$userids = array();
} else if (is_array($userid_or_ids)) {
$userids = $userid_or_ids;
} else {
$userids = array($userid_or_ids);
}
if ($userids) {
$grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
foreach ($userids as $userid) {
$grade_grades[$userid]->grade_item =& $grade_item;
$grade = new stdClass();
$grade->grade = $grade_grades[$userid]->finalgrade;
$grade->locked = $grade_grades[$userid]->is_locked();
$grade->hidden = $grade_grades[$userid]->is_hidden();
$grade->overridden = $grade_grades[$userid]->overridden;
$grade->feedback = $grade_grades[$userid]->feedback;
$grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
$grade->usermodified = $grade_grades[$userid]->usermodified;
$grade->datesubmitted = $grade_grades[$userid]->get_datesubmitted();
$grade->dategraded = $grade_grades[$userid]->get_dategraded();
// create text representation of grade
if ($grade_item->gradetype == GRADE_TYPE_TEXT or $grade_item->gradetype == GRADE_TYPE_NONE) {
$grade->grade = null;
$grade->str_grade = '-';
$grade->str_long_grade = $grade->str_grade;
} else if (in_array($grade_item->id, $needsupdate)) {
$grade->grade = false;
$grade->str_grade = get_string('error');
$grade->str_long_grade = $grade->str_grade;
} else if (is_null($grade->grade)) {
$grade->str_grade = '-';
$grade->str_long_grade = $grade->str_grade;
} else {
$grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item);
if ($grade_item->gradetype == GRADE_TYPE_SCALE or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL) {
$grade->str_long_grade = $grade->str_grade;
} else {
$a = new stdClass();
$a->grade = $grade->str_grade;
$a->max = grade_format_gradevalue($grade_item->grademax, $grade_item);
$grade->str_long_grade = get_string('gradelong', 'grades', $a);
}
}
// create html representation of feedback
if (is_null($grade->feedback)) {
$grade->str_feedback = '';
} else {
$grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
}
$item->grades[$userid] = $grade;
}
}
$return->items[$grade_item->itemnumber] = $item;
} else {
if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
debugging('Incorect outcomeid found');
continue;
}
// outcome info
$outcome = new stdClass();
$outcome->itemnumber = $grade_item->itemnumber;
$outcome->scaleid = $grade_outcome->scaleid;
$outcome->name = $grade_outcome->get_name();
$outcome->locked = $grade_item->is_locked();
$outcome->hidden = $grade_item->is_hidden();
if (empty($userid_or_ids)) {
$userids = array();
} else if (is_array($userid_or_ids)) {
$userids = $userid_or_ids;
} else {
$userids = array($userid_or_ids);
}
if ($userids) {
$grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
foreach ($userids as $userid) {
$grade_grades[$userid]->grade_item =& $grade_item;
$grade = new stdClass();
$grade->grade = $grade_grades[$userid]->finalgrade;
$grade->locked = $grade_grades[$userid]->is_locked();
$grade->hidden = $grade_grades[$userid]->is_hidden();
$grade->feedback = $grade_grades[$userid]->feedback;
$grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
$grade->usermodified = $grade_grades[$userid]->usermodified;
// create text representation of grade
if (in_array($grade_item->id, $needsupdate)) {
$grade->grade = false;
$grade->str_grade = get_string('error');
} else if (is_null($grade->grade)) {
$grade->grade = 0;
$grade->str_grade = get_string('nooutcome', 'grades');
} else {
$grade->grade = (int)$grade->grade;
$scale = $grade_item->load_scale();
$grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
}
// create html representation of feedback
if (is_null($grade->feedback)) {
$grade->str_feedback = '';
} else {
$grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
}
$outcome->grades[$userid] = $grade;
}
}
if (isset($return->outcomes[$grade_item->itemnumber])) {
// itemnumber duplicates - lets fix them!
$newnumber = $grade_item->itemnumber + 1;
while(grade_item::fetch(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid, 'itemnumber'=>$newnumber))) {
$newnumber++;
}
$outcome->itemnumber = $newnumber;
$grade_item->itemnumber = $newnumber;
$grade_item->update('system');
}
$return->outcomes[$grade_item->itemnumber] = $outcome;
}
}
}
// sort results using itemnumbers
ksort($return->items, SORT_NUMERIC);
ksort($return->outcomes, SORT_NUMERIC);
return $return;
}
///////////////////////////////////////////////////////////////////
///// End of public API for communication with modules/blocks /////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///// Internal API: used by gradebook plugins and Moodle core /////
///////////////////////////////////////////////////////////////////
/**
* Returns a course gradebook setting
*
* @param int $courseid
* @param string $name of setting, maybe null if reset only
* @param string $default value to return if setting is not found
* @param bool $resetcache force reset of internal static cache
* @return string value of the setting, $default if setting not found, NULL if supplied $name is null
*/
function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
global $DB;
static $cache = array();
if ($resetcache or !array_key_exists($courseid, $cache)) {
$cache[$courseid] = array();
} else if (is_null($name)) {
return null;
} else if (array_key_exists($name, $cache[$courseid])) {
return $cache[$courseid][$name];
}
if (!$data = $DB->get_record('grade_settings', array('courseid'=>$courseid, 'name'=>$name))) {
$result = null;
} else {
$result = $data->value;
}
if (is_null($result)) {
$result = $default;
}
$cache[$courseid][$name] = $result;
return $result;
}
/**
* Returns all course gradebook settings as object properties
*
* @param int $courseid
* @return object
*/
function grade_get_settings($courseid) {
global $DB;
$settings = new stdClass();
$settings->id = $courseid;
if ($records = $DB->get_records('grade_settings', array('courseid'=>$courseid))) {
foreach ($records as $record) {
$settings->{$record->name} = $record->value;
}
}
return $settings;
}
/**
* Add, update or delete a course gradebook setting
*
* @param int $courseid The course ID
* @param string $name Name of the setting
* @param string $value Value of the setting. NULL means delete the setting.
*/
function grade_set_setting($courseid, $name, $value) {
global $DB;
if (is_null($value)) {
$DB->delete_records('grade_settings', array('courseid'=>$courseid, 'name'=>$name));
} else if (!$existing = $DB->get_record('grade_settings', array('courseid'=>$courseid, 'name'=>$name))) {
$data = new stdClass();
$data->courseid = $courseid;
$data->name = $name;
$data->value = $value;
$DB->insert_record('grade_settings', $data);
} else {
$data = new stdClass();
$data->id = $existing->id;
$data->value = $value;
$DB->update_record('grade_settings', $data);
}
grade_get_setting($courseid, null, null, true); // reset the cache
}
/**
* Returns string representation of grade value
*
* @param float $value The grade value
* @param object $grade_item Grade item object passed by reference to prevent scale reloading
* @param bool $localized use localised decimal separator
* @param int $displaytype type of display. For example GRADE_DISPLAY_TYPE_REAL, GRADE_DISPLAY_TYPE_PERCENTAGE, GRADE_DISPLAY_TYPE_LETTER
* @param int $decimals The number of decimal places when displaying float values
* @return string
*/
function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
return '';
}
// no grade yet?
if (is_null($value)) {
return '-';
}
if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
//unknown type??
return '';
}
if (is_null($displaytype)) {
$displaytype = $grade_item->get_displaytype();
}
if (is_null($decimals)) {
$decimals = $grade_item->get_decimals();
}
switch ($displaytype) {
case GRADE_DISPLAY_TYPE_REAL:
return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized);
case GRADE_DISPLAY_TYPE_PERCENTAGE:
return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized);
case GRADE_DISPLAY_TYPE_LETTER:
return grade_format_gradevalue_letter($value, $grade_item);
case GRADE_DISPLAY_TYPE_REAL_PERCENTAGE:
return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
case GRADE_DISPLAY_TYPE_REAL_LETTER:
return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
grade_format_gradevalue_letter($value, $grade_item) . ')';
case GRADE_DISPLAY_TYPE_PERCENTAGE_REAL:
return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
case GRADE_DISPLAY_TYPE_LETTER_REAL:
return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
case GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE:
return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
case GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER:
return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
grade_format_gradevalue_letter($value, $grade_item) . ')';
default:
return '';
}
}
/**
* Returns a float representation of a grade value
*
* @param float $value The grade value
* @param object $grade_item Grade item object
* @param int $decimals The number of decimal places
* @param bool $localized use localised decimal separator
* @return string
*/
function grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) {
if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
if (!$scale = $grade_item->load_scale()) {
return get_string('error');
}
$value = $grade_item->bounded_grade($value);
return format_string($scale->scale_items[$value-1]);
} else {
return format_float($value, $decimals, $localized);
}
}
/**
* Returns a percentage representation of a grade value
*
* @param float $value The grade value
* @param object $grade_item Grade item object
* @param int $decimals The number of decimal places
* @param bool $localized use localised decimal separator
* @return string
*/
function grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) {
$min = $grade_item->grademin;
$max = $grade_item->grademax;
if ($min == $max) {
return '';
}
$value = $grade_item->bounded_grade($value);
$percentage = (($value-$min)*100)/($max-$min);
return format_float($percentage, $decimals, $localized).' %';
}
/**
* Returns a letter grade representation of a grade value
* The array of grade letters used is produced by {@link grade_get_letters()} using the course context
*
* @param float $value The grade value
* @param object $grade_item Grade item object
* @return string
*/
function grade_format_gradevalue_letter($value, $grade_item) {
$context = context_course::instance($grade_item->courseid, IGNORE_MISSING);
if (!$letters = grade_get_letters($context)) {
return ''; // no letters??
}
if (is_null($value)) {
return '-';
}
$value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
$value = bounded_number(0, $value, 100); // just in case
foreach ($letters as $boundary => $letter) {
if ($value >= $boundary) {
return format_string($letter);
}
}
return '-'; // no match? maybe '' would be more correct
}
/**
* Returns grade options for gradebook grade category menu
*
* @param int $courseid The course ID
* @param bool $includenew Include option for new category at array index -1
* @return array of grade categories in course
*/
function grade_get_categories_menu($courseid, $includenew=false) {
$result = array();
if (!$categories = grade_category::fetch_all(array('courseid'=>$courseid))) {
//make sure course category exists
if (!grade_category::fetch_course_category($courseid)) {
debugging('Can not create course grade category!');
return $result;
}
$categories = grade_category::fetch_all(array('courseid'=>$courseid));
}
foreach ($categories as $key=>$category) {
if ($category->is_course_category()) {
$result[$category->id] = get_string('uncategorised', 'grades');
unset($categories[$key]);
}
}
if ($includenew) {
$result[-1] = get_string('newcategory', 'grades');
}
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->get_name();
}
core_collator::asort($cats);
return ($result+$cats);
}
/**
* Returns the array of grade letters to be used in the supplied context
*
* @param object $context Context object or null for defaults
* @return array of grade_boundary (minimum) => letter_string
*/
function grade_get_letters($context=null) {
global $DB;
if (empty($context)) {
//default grading letters
return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
}
static $cache = array();
if (array_key_exists($context->id, $cache)) {
return $cache[$context->id];
}
if (count($cache) > 100) {
$cache = array(); // cache size limit
}
$letters = array();
$contexts = $context->get_parent_context_ids();
array_unshift($contexts, $context->id);
foreach ($contexts as $ctxid) {
if ($records = $DB->get_records('grade_letters', array('contextid'=>$ctxid), 'lowerboundary DESC')) {
foreach ($records as $record) {
$letters[$record->lowerboundary] = $record->letter;
}
}
if (!empty($letters)) {
$cache[$context->id] = $letters;
return $letters;
}
}
$letters = grade_get_letters(null);
$cache[$context->id] = $letters;
return $letters;
}
/**
* Verify new value of grade item idnumber. Checks for uniqueness of new ID numbers. Old ID numbers are kept intact.
*
* @param string $idnumber string (with magic quotes)
* @param int $courseid ID numbers are course unique only
* @param grade_item $grade_item The grade item this idnumber is associated with
* @param stdClass $cm used for course module idnumbers and items attached to modules
* @return bool true means idnumber ok
*/
function grade_verify_idnumber($idnumber, $courseid, $grade_item=null, $cm=null) {
global $DB;
if ($idnumber == '') {
//we allow empty idnumbers
return true;
}
// keep existing even when not unique
if ($cm and $cm->idnumber == $idnumber) {
if ($grade_item and $grade_item->itemnumber != 0) {
// grade item with itemnumber > 0 can't have the same idnumber as the main
// itemnumber 0 which is synced with course_modules
return false;
}
return true;
} else if ($grade_item and $grade_item->idnumber == $idnumber) {
return true;
}
if ($DB->record_exists('course_modules', array('course'=>$courseid, 'idnumber'=>$idnumber))) {
return false;
}
if ($DB->record_exists('grade_items', array('courseid'=>$courseid, 'idnumber'=>$idnumber))) {
return false;
}
return true;
}
/**
* Force final grade recalculation in all course items
*
* @param int $courseid The course ID to recalculate
*/
function grade_force_full_regrading($courseid) {
global $DB;
$DB->set_field('grade_items', 'needsupdate', 1, array('courseid'=>$courseid));
}
/**
* Forces regrading of all site grades. Used when changing site setings
*/
function grade_force_site_regrading() {
global $CFG, $DB;
$DB->set_field('grade_items', 'needsupdate', 1);
}
/**
* Recover a user's grades from grade_grades_history
* @param int $userid the user ID whose grades we want to recover
* @param int $courseid the relevant course
* @return bool true if successful or false if there was an error or no grades could be recovered
*/
function grade_recover_history_grades($userid, $courseid) {
global $CFG, $DB;
if ($CFG->disablegradehistory) {
debugging('Attempting to recover grades when grade history is disabled.');
return false;
}
//Were grades recovered? Flag to return.
$recoveredgrades = false;
//Check the user is enrolled in this course
//Dont bother checking if they have a gradeable role. They may get one later so recover
//whatever grades they have now just in case.
$course_context = context_course::instance($courseid);
if (!is_enrolled($course_context, $userid)) {
debugging('Attempting to recover the grades of a user who is deleted or not enrolled. Skipping recover.');
return false;
}
//Check for existing grades for this user in this course
//Recovering grades when the user already has grades can lead to duplicate indexes and bad data
//In the future we could move the existing grades to the history table then recover the grades from before then
$sql = "SELECT gg.id
FROM {grade_grades} gg
JOIN {grade_items} gi ON gi.id = gg.itemid
WHERE gi.courseid = :courseid AND gg.userid = :userid";
$params = array('userid' => $userid, 'courseid' => $courseid);
if ($DB->record_exists_sql($sql, $params)) {
debugging('Attempting to recover the grades of a user who already has grades. Skipping recover.');
return false;
} else {
//Retrieve the user's old grades
//have history ID as first column to guarantee we a unique first column
$sql = "SELECT h.id, gi.itemtype, gi.itemmodule, gi.iteminstance as iteminstance, gi.itemnumber, h.source, h.itemid, h.userid, h.rawgrade, h.rawgrademax,
h.rawgrademin, h.rawscaleid, h.usermodified, h.finalgrade, h.hidden, h.locked, h.locktime, h.exported, h.overridden, h.excluded, h.feedback,
h.feedbackformat, h.information, h.informationformat, h.timemodified, itemcreated.tm AS timecreated
FROM {grade_grades_history} h
JOIN (SELECT itemid, MAX(id) AS id
FROM {grade_grades_history}
WHERE userid = :userid1
GROUP BY itemid) maxquery ON h.id = maxquery.id AND h.itemid = maxquery.itemid
JOIN {grade_items} gi ON gi.id = h.itemid
JOIN (SELECT itemid, MAX(timemodified) AS tm
FROM {grade_grades_history}
WHERE userid = :userid2 AND action = :insertaction
GROUP BY itemid) itemcreated ON itemcreated.itemid = h.itemid
WHERE gi.courseid = :courseid";
$params = array('userid1' => $userid, 'userid2' => $userid , 'insertaction' => GRADE_HISTORY_INSERT, 'courseid' => $courseid);
$oldgrades = $DB->get_records_sql($sql, $params);
//now move the old grades to the grade_grades table
foreach ($oldgrades as $oldgrade) {
unset($oldgrade->id);
$grade = new grade_grade($oldgrade, false);//2nd arg false as dont want to try and retrieve a record from the DB
$grade->insert($oldgrade->source);
//dont include default empty grades created when activities are created
if (!is_null($oldgrade->finalgrade) || !is_null($oldgrade->feedback)) {
$recoveredgrades = true;
}
}
}
//Some activities require manual grade synching (moving grades from the activity into the gradebook)
//If the student was deleted when synching was done they may have grades in the activity that haven't been moved across
grade_grab_course_grades($courseid, null, $userid);
return $recoveredgrades;
}
/**