-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.php
1687 lines (1430 loc) · 64.2 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
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/>.
/**
* Definition of the grade_forecast_report class is defined
*
* @package gradereport_forecast
* @copyright 2016 Louisiana State University, Chad Mazilly, Robert Russo, Dave Elliott
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/grade/report/lib.php');
require_once($CFG->libdir.'/tablelib.php');
// Values for showhiddenitems.
define("GRADE_REPORT_FORECAST_HIDE_HIDDEN", 0);
define("GRADE_REPORT_FORECAST_HIDE_UNTIL", 1);
define("GRADE_REPORT_FORECAST_SHOW_HIDDEN", 2);
/**
* Class providing an API for the user report building and displaying.
* @uses grade_report
* @package gradereport_forecast
*/
class grade_report_forecast extends grade_report {
/**
* The user.
* @var object $user
*/
public $user;
/**
* A flexitable to hold the data.
* @var object $table
*/
public $table;
/**
* An array of table headers
* @var array
*/
public $tableheaders = array();
/**
* An array of table columns
* @var array
*/
public $tablecolumns = array();
/**
* An array containing rows of data for the table.
* @var type
*/
public $tabledata = array();
/**
* The grade tree structure
* @var grade_tree
*/
public $gtree;
/**
* Flat structure similar to grade tree
*/
public $gseq;
/**
* Decimal points to use for values in the report, default 2
* @var int
*/
public $decimals = 2;
/**
* The number of decimal places to round range to, default 0
* @var int
*/
public $rangedecimals = 0;
/**
* Show letter grades in the report, default true
* @var bool
*/
public $showlettergrade = true;
/**
* Show grade percentages in the report, default true
* @var bool
*/
public $showgradepercentage = true;
public $maxdepth;
public $evenodd;
public $canviewhidden;
public $switch;
/**
* Show hidden items even when user does not have required cap
*/
public $showhiddenitems;
public $showtotalsifcontainhidden;
public $baseurl;
public $pbarurl;
public $courseid;
/*
* The course's grade letters array
*
* bounday => letter
*/
public $letters = [];
/*
* Formatted input grade data
*
* array: grades(array: grade_item_id => input value) | totalUngradedItemCount | inputGradeItemCount
*/
public $inputdata;
/*
* An array of grade_items and their "aggregate" array
*
* grade_item_id => grade | grademin | grademax | calculatedValue
*/
public $itemaggregates;
/*
* The master course category's details
*
* array: grade_category | element
*/
public $coursegradedata;
/*
* string: the missing (ungraded) grade item id
*/
public $ungradedgradeitemkey;
/*
* An array of DOM element ids, grouped by course letters "boundary", with corresponding grade output string
*
* string: must make element id => grade output
*/
public $mustmakearray;
/*
* Response array that will be converted to JSON
*
* array: showmustmake | mustmakearray | cats | course
*/
public $response;
/**
* The modinfo object to be used.
*
* @var course_modinfo
*/
protected $modinfo = null;
/**
* View as user.
*
* When this is set to true, the visibility checks, and capability checks will be
* applied to the user whose grades are being displayed. This is very useful when
* a mentor/parent is viewing the report of their mentee because they need to have
* access to the same information, but not more, not less.
*
* @var boolean
*/
protected $viewasuser = false;
/**
* An array that collects the aggregationhints for every
* grade_item. The hints contain grade, grademin, grademax
* status, weight and parent.
*
* @var array
*/
protected $aggregationhints = array();
/**
* Constructor. Sets local copies of user preferences and initialises grade_tree.
* @param int $courseid
* @param object $gpr grade plugin return tracking object
* @param string $context
* @param int $userid The id of the user
* @param bool $viewasuser Set this to true when the current user is a mentor/parent of the targetted user.
* @param array $inputdata
*/
public function __construct($courseid, $gpr, $context, $userid, $viewasuser = null, $inputdata = []) {
global $DB, $CFG;
parent::__construct($courseid, $gpr, $context);
$this->showhiddenitems = grade_get_setting($this->courseid,
'report_forecast_showhiddenitems',
$CFG->grade_report_forecast_showhiddenitems);
$this->showtotalsifcontainhidden = array($this->courseid => grade_get_setting(
$this->courseid,
'report_forecast_showtotalsifcontainhidden',
$CFG->grade_report_forecast_showtotalsifcontainhidden));
$this->showlettergrade = grade_get_setting(
$this->courseid,
'report_forecast_showlettergrade',
!empty($CFG->grade_report_forecast_showlettergrade));
$this->showgradepercentage = grade_get_setting(
$this->courseid,
'report_forecast_showgradepercentage',
!empty($CFG->grade_report_forecast_showgradepercentage));
$this->viewasuser = $viewasuser;
// The default grade decimals is 2.
$defaultdecimals = 2;
if (property_exists($CFG, 'grade_decimalpoints')) {
$defaultdecimals = $CFG->grade_decimalpoints;
}
$this->decimals = grade_get_setting($this->courseid, 'decimalpoints', $defaultdecimals);
// The default range decimals is 0.
$defaultrangedecimals = 0;
if (property_exists($CFG, 'grade_report_forecast_rangedecimals')) {
$defaultrangedecimals = $CFG->grade_report_forecast_rangedecimals;
}
$this->rangedecimals = grade_get_setting($this->courseid, 'report_forecast_rangedecimals', $defaultrangedecimals);
if (property_exists($CFG, 'grade_report_forecast_enabledforstudents')) {
$defaultenabledforstudents = $CFG->grade_report_forecast_enabledforstudents;
}
$this->enabledforstudents = grade_get_setting($this->courseid, 'report_forecast_rangedecimals', $defaultenabledforstudents);
// Hard set this to true as we need the gtree to be consistent.
$this->switch = true;
// Grab the grade_tree for this course.
$this->gtree = new grade_tree($this->courseid, false, $this->switch, null, !$CFG->enableoutcomes);
// Get the user (for full name).
$this->user = $DB->get_record('user', array('id' => $userid));
// What user are we viewing this as?
$coursecontext = context_course::instance($this->courseid);
if ($viewasuser) {
$this->modinfo = new course_modinfo($this->course, $this->user->id);
$this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext, $this->user->id);
} else {
$this->modinfo = $this->gtree->modinfo;
$this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext);
}
// Determine the number of rows and indentation.
$this->maxdepth = 1;
$this->inject_rowspans($this->gtree->top_element);
$this->maxdepth++; // Need to account for the lead column that spans all children.
for ($i = 1; $i <= $this->maxdepth; $i++) {
$this->evenodd[$i] = 0;
}
$this->tabledata = array();
// Base url for sorting by first/last name.
$this->baseurl = $CFG->wwwroot.'/grade/report?id='.$courseid.'&userid='.$userid;
$this->pbarurl = $this->baseurl;
$this->courseid = $courseid;
$this->letters = grade_get_letters($coursecontext);
$this->inputdata = $this->formatrawinputdata($inputdata);
$this->itemaggregates = [];
$this->coursegradedata = [];
$this->ungradedgradeitemkey = '';
$this->mustmakearray = [];
$this->response = $this->newresponse();
// No groups on this report - rank is from all course users.
$this->setup_table();
}
/**
* Returns a JSON array of this user's forecasted category and course grades for this course considering any input values
*
* @return JSON array
*/
public function getjsonresponse() {
$showmustmake = $this->shouldshowmustmake();
// Add grades to response.
$this->addgradestoresponse($showmustmake);
// Add "must make" data to response.
if ($this->response['showmustmake'] = $showmustmake) {
$this->response['ungradedgradeitemkey'] = $this->ungradedgradeitemkey;
$this->response['mustmakearray'] = $this->mustmakearray;
}
return $this->formattedjsonresponse();
}
/**
* Adds forecasted grade information to the response
*
* @param bool $shouldCalculateMustMake whether or not to calculate must make array
* @return void
*/
private function addgradestoresponse($shouldcalculatemustmake = false) {
// Include all transformed, aggregated sub-category grades.
$this->response['cats'] = $this->gettransformedcategorygrades();
// Include the transformed master course grade.
if (!empty($this->coursegradedata)) {
$this->response['course'] = $this->gettransformedcoursegrade();
}
if ($shouldcalculatemustmake) {
$this->calculatemustmake();
}
}
/**
* Returns a formatted JSON array of the report's current "response"
*
* @return JSON array
*/
private function formattedjsonresponse() {
return json_encode($this->response);
}
/**
* Returns a default "response" array
*
* @return array
*/
private function newresponse() {
return [
'cats' => [],
'course' => '',
'showmustmake' => false,
'mustmakearray' => [],
];
}
/**
* Returns an array of this course's "category" grade_items and their corresponding calculated aggregates
*
* By default, formats output as: grade_item_id => display_string
*
* If no transform, output as array: categoryItem|aggregate
*
* @param boolean $transform whether or not to transform the output
* @return array
*/
private function gettransformedcategorygrades($transform = true) {
// Get the inverted gtree "levels" array.
$levels = array_reverse($this->gtree->levels, true);
$categorygrades = [];
// Iterate through each of the course's reversed gtree "levels", aggregating "level"-level categories along the way.
// LevelIndex = gtree "level" number index (0 as course level).
// LevelItems = gtree "level" array.
foreach ($levels as $levelindex => $levelitems) {
// Iterate through the level items (which can be of type: item, categoryitem, category, courseitem).
foreach ($levelitems as $key => $levelitem) {
// Act only on "category" level items, which can include courses and any sub-categories.
if ($levelitem['type'] == 'category') {
// Pluck the gtree element.
$element = $this->getlevelitemelement($levelitem);
// Extract the grade_category from this element.
$category = $this->getelementobject($element);
// If this is a master level "course" category, cache its data for final aggregation.
if ($this->iscoursecategory($category)) {
$this->coursegradedata = [
'category' => $category,
'element' => $element,
];
continue;
}
// Fetch the grade_item representation of this grade_category.
// TODO: get grade_item from element children "categoryitem"?
// TODO: cache this result and check for in the following processes.
$categoryitem = $this->getgradeitemfromcategory($category);
// If this item has already been aggregated, move on.
if ($this->itemidalreadyaggregated($categoryitem->id)) {
// Add "or needs to be updated" here?
return;
}
// Get all grade_items (only) that will be considered in the category aggregation calculation.
$categorygradeitems = $this->getelementchildren($element, ['item', 'category'], true);
// Get all grade values belonging to the given grade items, removing ungraded/uninput items from calculation.
$categorygradevalues = $this->getcategorygradeitemvaluesarray($category, $categorygradeitems, true);
// Get the aggregate of this category using the given grade items and values.
$aggregate = $this->getcategorygradeaggregate($category, $categorygradeitems, $categorygradevalues, true);
// Add to output.
$categorygrades[] = ['categoryitem' => $categoryitem, 'aggregate' => $aggregate];
// Store this value for future aggregations.
$this->storeitemaggregate($categoryitem->id, $aggregate);
}
}
}
return ($transform) ? $this->transformcategorygradesforresponse($categorygrades) : $categorygrades;
}
/**
* Tranforms given category grade arrays to prep for response
*
* @param array $categoryGrades categoryItem|aggregate
* @return array category_grade_item_id => formatted total display
*/
private function transformcategorygradesforresponse($categorygrades) {
$output = [];
foreach ($categorygrades as $cg) {
$output[$cg['categoryitem']->id] = $this->formatitemaggregatedisplay($cg['categoryitem'], $cg['aggregate']);
}
return $output;
}
/**
* Returns the master course's transformed, aggregated total
*
* By default, formats as display string
*
* If no transform, output as array: courseItem|aggregate
*
* @param boolean $transform whether or not to transform the output
* @param boolean $transformOnly if transforming, show only this field
* @return array
*/
private function gettransformedcoursegrade($transform = true, $transformonly = '') {
$coursegrade = [];
// Get the course's grade item.
$courseitem = $this->getgradeitemfromcategory($this->coursegradedata['category'], 'course');
// Get all grade_items (only) that will be considered in the course aggregation calculation.
$coursegradeitems = $this->getelementchildren($this->coursegradedata['element'], ['item', 'category'], true);
// Get all grade values belonging to the given grade items, setting ungraded/uninput items to zero.
$coursegradevalues = $this->getcategorygradeitemvaluesarray($this->coursegradedata['category'], $coursegradeitems);
// Get the aggregate of this course using the given grade items and values.
$aggregate = $this->getcategorygradeaggregate(
$this->coursegradedata['category'], $coursegradeitems, $coursegradevalues, true);
// Add to output.
$coursegrade = ['courseitem' => $courseitem, 'aggregate' => $aggregate];
return ($transform) ? $this->formatitemaggregatedisplay(
$coursegrade['courseitem'], $coursegrade['aggregate'], $transformonly) : $coursegrade;
}
/**
* Populates the "must make" array by iterating through a course's "letter" boundaries and
* determining what missing grade is necessary to achieve each boundary
*
* @return void
*/
private function calculatemustmake() {
// Get the sole missing item.
$missingitem = grade_item::fetch(['id' => $this->ungradedgradeitemkey]);
if ($missingitem) {
// First, determine if the user will outright pass all boundaries with a zero.
$boundaries = array_reverse(array_keys($this->letters));
foreach ($boundaries as $boundary) {
// Find the passing grade value for this item and this boundary and add to results.
$mustmakearray[$this->getmustmakeletterid($boundary)] = $this->getpassinggradeitemvalue(
$boundary, $missingitem->grademin, $missingitem->grademax);
}
// Set must make array.
$this->mustmakearray = $mustmakearray;
}
}
/**
* Returns the minimum passing grade value necessary (within given bounds) to achieve to given minimum grade value threshold,
* or notification of an outright pass or fail (in the form of html symbols)
* @param int $minimumGradeValueBoundary minimum grade value for a letter
* @param int $minValue minimum grade value possible for this search attempt
* @param int $maxValue maximum grade value possible for this search attempt
* @return string
*/
private function getpassinggradeitemvalue($minimumgradevalueboundary, $minvalue, $maxvalue) {
// First, determine if the user will outright meet the minimum with the minimum value possible.
if ($this->calculatetotalwithungradedvalue($minvalue) >= $minimumgradevalueboundary) {
// Return pass symbol.
return $this->getsymbolcheckmark();
} else if ($this->calculatetotalwithungradedvalue($maxvalue) < $minimumgradevalueboundary) {
// Return fail symbol.
return $this->getsymbolxmark();
}
// If not, try a binary search attempt and return result.
$left = $minvalue;
$right = $maxvalue;
while ($left <= $right) {
$attempt = floor(($left + $right) / 2);
$calc = $this->calculatetotalwithungradedvalue($attempt);
if ($calc == $minimumgradevalueboundary) {
// Once we find a good result, decrement the attempt value until we hit the floor.
while ($this->calculatetotalwithungradedvalue($attempt - 1) >= $minimumgradevalueboundary) {
$attempt--;
}
return $attempt;
} else if ($calc > $minimumgradevalueboundary) {
$right = $attempt - 1;
} else if ($calc < $minimumgradevalueboundary) {
$left = $attempt + 1;
}
}
// Return fail notification.
return $this->getsymbolxmark();
}
/**
* Helper function for rendering a check mark
*
* @return string
*/
private function getsymbolcheckmark() {
return '✓';
}
/**
* Helper function for rendering an "X" mark
*
* @return string
*/
private function getsymbolxmark() {
return '✕';
}
/**
* Returns a calculated course whole number total given a value to add as it's missing item input
*
* @param int $gradeItemValue grade value for its course's missing item
* @return int calculated course total as whole number rounded down
*/
private function calculatetotalwithungradedvalue($gradeitemvalue) {
// Clear the calculated aggregate cache.
$this->itemaggregates = [];
// Add the grade value to the stored grade input index.
$this->inputdata['grades'][$this->ungradedgradeitemkey] = $gradeitemvalue;
// Recalculate all categories.
$this->gettransformedcategorygrades();
// Transform value into a whole number.
$calculatedtotal = $this->gettransformedcoursegrade(true, 'percentage-value');
return $calculatedtotal;
}
/**
* Returns a "must make" array with all boundary levels containing the same value
*
* @param string $value
* @return array
*/
private function createmustmakearray($value) {
$mustmakearray = [];
// Iterate through the boundaries, starting at the lowest.
foreach ($this->letters as $boundary => $letter) {
// Include the transformed master course grade.
if (!empty($this->coursegradedata)) {
$mustmakearray[$this->getmustmakeletterid($boundary)] = $value;
}
}
return $mustmakearray;
}
/**
* Returns the HTML for the "must make" modal component
*
* @return string
*/
public function getmustmakemodal() {
$mustmakemarkup = '
<div class="modal fade" tabindex="-1" role="dialog" id="mustMakeModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">' . get_string('must_make_modal_heading', 'gradereport_forecast') . '</h4>
</div>';
$mustmakemarkup .= $this->getmustmakemodaltable();
$mustmakemarkup .= '
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-lg btn-block" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>';
return $mustmakemarkup;
}
/**
* Returns an HTML table of letters and bounds to be embedded into the "must make" modal
*
* @return string
*/
private function getmustmakemodaltable() {
$modaltable = '
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>' . get_string('must_make_modal_letter_column_heading', 'gradereport_forecast') . '</th>
<th>' . get_string('must_make_modal_grade_column_heading', 'gradereport_forecast') . '</th>
<th></th>
</tr>
</thead>';
foreach ($this->letters as $boundary => $letter) {
$modaltable .= '
<tbody>
<tr>
<td width="10%"></td>
<td width="40%">' . $letter . '</td>
<td width="40%" id="' . $this->getmustmakeletterid($boundary) . '"></td>
<td width="10%"></td>
</tr>
</tbody>';
}
$modaltable .= '</table>';
return $modaltable;
}
/**
* Converts a letter "boundary" number to an id tag
*
* @param string $boundary
* @return string
*/
private function getmustmakeletterid($boundary) {
return $this->getmustmakeletteridprefix() . str_replace('.', '-', $boundary);
}
/**
* Checks whether "must make" modal should be displayed based off of grade input
*
* @return bool
*/
private function shouldshowmustmake() {
global $CFG;
if (!$CFG->grade_report_forecast_mustmakeenabled) {
return false;
}
if (!(array_key_exists('totalungradeditemcount', $this->inputdata)
and array_key_exists('inputgradeitemcount', $this->inputdata))) {
return false;
}
return (((int)$this->inputdata['totalungradeditemcount'] - (int)$this->inputdata['inputgradeitemcount']) == 1)
? true : false;
}
/**
* Helper function for retrieving a specific grade_tree "level" item
*
* @param array $levelItem a gtree "level" item
* @return array $element a gtree "element"
*/
private function getlevelitemelement($levelitem) {
$element = $this->gtree->locate_element($levelitem['eid']);
return $element;
}
/**
* Helper function for retrieving the "object" from a given element
*
* @param array $element a gtree "element"
* @return object (grade_category)
*/
private function getelementobject($element) {
if (!array_key_exists('object', $element)) {
return false;
}
return $element['object'];
}
/**
* Reports whether or not this grade category is the main course-level category
*
* @param grade_category $category
* @return boolean
*/
private function iscoursecategory($category) {
return (is_null($category->parent)) ? true : false;
}
/**
* Reports whether or not this grade item id already exists in the itemaggregates array
*
* @param int $itemId
* @return boolean
*/
private function itemidalreadyaggregated($itemid) {
return array_key_exists($itemid, $this->itemaggregates);
}
/**
* Helper function for retrieving the "object" from a given element
*
* @param array $element a gtree "element"
* @param array $types a list of types of element children to be included (item|courseitem|category|categoryitem)
* @param boolean $itemsOnly if true, will add only children "grade_item" object to results
* @return array child object id => object
*/
private function getelementchildren($element, $types = array(), $itemsonly = true) {
if (!array_key_exists('children', $element)) {
return false;
}
$elementchildren = $element['children'];
$results = [];
// Iterate through all children.
foreach ($elementchildren as $key => $child) {
// Add each wanted type to results array as: object id => object.
if (in_array($child['type'], $types)) {
$childobject = $child['object'];
if ($child['type'] == 'category' and $itemsonly) {
// Get this category's grade_item.
$gradeitem = $this->getgradeitemfromcategory($childobject);
$results[$gradeitem->id] = $gradeitem;
} else {
$results[$childobject->id] = $childobject;
}
}
}
return $results;
}
/**
* Returns a given grade_category's grade_item object of a specified type
*
* @param grade_category $gradeCategory
* @param string $itemType category|course
* @return grade_item
*/
private function getgradeitemfromcategory($gradecategory, $itemtype = 'category') {
$gradeitem = grade_item::fetch([
'itemtype' => $itemtype,
'iteminstance' => $gradecategory->id,
]);
if (!$gradeitem or ! property_exists($gradeitem, 'id')) {
return false;
}
return $gradeitem;
}
/**
* Returns an array of grade_item grade values by reconciling calculated category values, input data,
* and this user's actual grades, and then applying a given parent grade_category's rules.
*
* Sets ungraded/uninput item grades to zero (default), or optionally removes them from the given grade_items.
*
* @param grade_category $gradeCategory
* @param array $gradeItems
* @param bool $removeUngradedItems whether or not to remove an ungraded, grade item from grade_items
* @return array (as: grade_item id => grade value)
*/
private function getcategorygradeitemvaluesarray($gradecategory, &$gradeitems, $removeungradeditems = false) {
$values = [];
foreach ($gradeitems as $gradeitemid => $gradeitem) {
// If this is a category, try to get the value from the master array, otherwise, give it a zero and remove.
if ($gradeitem->itemtype == 'category') {
if ( ! array_key_exists($gradeitemid, $this->itemaggregates)) {
// Remove grade, or set to zero depending on selected option.
if ($removeungradeditems) {
// Remove the item from the item container.
unset($gradeitems[$gradeitemid]);
} else {
// Set this items grade to zero.
$values[$gradeitemid] = 0;
}
} else {
// Otherwise, include the grade in the grade value container.
$values[$gradeitemid] = $this->itemaggregates[$gradeitemid]['calculatedvalue'];
}
// Otherwise, this is an item, if a "forecasted" grade has been input for this item, include it in the container.
} else if (array_key_exists($gradeitemid, $this->inputdata['grades'])) {
$values[$gradeitemid] = $this->inputdata['grades'][$gradeitemid];
// Otherwise, try to get a real grade for this grade_item for this user.
} else {
$grade = $gradeitem->get_grade($this->user->id);
if ($grade->is_excluded()) {
// Remove the item from the item container.
unset($gradeitems[$gradeitemid]);
} else if (is_null($grade->finalgrade)) {
// Cache this missing (ungraded) grade item key.
$this->ungradedgradeitemkey = $gradeitemid;
// Remove grade, or set to zero depending on selected option.
if ($removeungradeditems) {
// Remove the item from the item container.
unset($gradeitems[$gradeitemid]);
} else {
// Set this items grade to zero.
$values[$gradeitemid] = 0;
}
} else {
// Otherwise, include the grade in the grade value container.
$values[$gradeitemid] = $grade->finalgrade;
}
}
}
// Apply any special category rules (drop lowest/highest) to the remaining list of values.
$gradecategory->apply_limit_rules($values, $gradeitems);
return $values;
}
/**
* Returns a calculated grade_category aggregate given grade_items and their corresponding values to consider
*
* @param grade_category $gradeCategory
* @param array $gradeItems grade_item_id => grade_item
* @param array $gradeItemValues grade_item_id => value
* @param bool $normalizeValues whether or not to "normalize" grade values before calculating
* @return decimal (from 0.0000 to 1.0000)
*/
private function getcategorygradeaggregate($gradecategory, $gradeitems, $gradeitemvalues, $normalizevalues = true) {
$gradeitemvalues = ($normalizevalues) ? $this->normalizegradevalues($gradeitems, $gradeitemvalues) : $gradeitemvalues;
$aggregate = $gradecategory->aggregate_values_and_adjust_bounds($gradeitemvalues, $gradeitems);
return (!is_null($aggregate)) ? $aggregate : false;
}
/**
* Returns an array of normalized grade values by referencing their corresponding grade_item max values
*
* @param array $gradeItems grade_item_id => grade_item
* @param array $gradeValues grade_item_id => value
* @return array
*/
private function normalizegradevalues($gradeitems, $gradevalues) {
$normalizedvalues = [];
foreach ($gradevalues as $id => $value) {
// If this grade item is using a scale.
if ($this->isscaleitem($gradeitems[$id])) {
if ($gradeitems[$id]->get_parent_category()->aggregation == GRADE_AGGREGATE_SUM) {
$normalizedvalues[$id] = $value / $gradeitems[$id]->grademax;
} else {
if ($value > 1) {
$normalizedvalues[$id] = $value / $gradeitems[$id]->grademax;
} else {
$normalizedvalues[$id] = 0;
}
}
} else {
// Normalize using the item's max & min.
$normalizedvalues[$id] = $value / ($gradeitems[$id]->grademax - $gradeitems[$id]->grademin);
}
}
return $normalizedvalues;
}
private function isscaleitem($gradeitem) {
return $gradeitem->gradetype == GRADE_TYPE_SCALE;
}
/**
* Stores an aggregate array for a given grade_item id
*
* @param int $itemId a grade_item id
* @param array $aggregate [grade|grademin|grademax]
* @return void
*/
private function storeitemaggregate($itemid, $aggregate) {
$this->itemaggregates[$itemid] = [
'grade' => $aggregate['grade'],
'grademin' => $aggregate['grademin'],
'grademax' => $aggregate['grademax'],
'calculatedvalue' => ($aggregate['grade'] * $aggregate['grademax'])
];
}
/**
* Returns a formatted display of a given grade item and aggregate
*
* @param grade_item $gradeItem
* @param array $aggregate [grade|grademin|grademax]
* @param string $transformOnly if set, return only this value
* @return string
*/
private function formatitemaggregatedisplay($gradeitem, $aggregate, $transformonly = '') {
$value = $aggregate['grade'];
if ($transformonly == 'percentage-value') {
return floor($value * 100);
}
// Get decimal display config.
$decimalplaces = $gradeitem->get_decimals();
// Calculate the total "points" for this category.
$points = $this->formatnumber($value * $gradeitem->grademax, $decimalplaces);
// Show total (points) by default.
$output = $points . ' pts';
// Optionally show percentage.
if ($this->showgradepercentage) {
$percentage = $this->formatpercentage($value * 100, $decimalplaces);
$output .= ' | ' . $percentage;
}
// Optionally show letter grade.
if ($this->showlettergrade) {
$letter = $this->formatletter($value);
$output .= ' | ' . $letter;
}
return $output;
}
/**
* Helper for rounding a number to the configured amount of decimal places
*
* @param mixed $value
* @return decimal
*/
private function formatnumber($value, $decimals) {
return number_format($value, $decimals);
}
/**
* Helper for displaying a letter grade given a specific value
*
* Note: This is from Moodle core (minus value bounds)
*
* @param mixed $value
* @return string