057351054b98cbe6bfc6e883c8ecf48e0233abc9
[moodle.git] / grade / report / user / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Definition of the grade_user_report class is defined
19  *
20  * @package gradereport_user
21  * @copyright 2007 Nicolas Connault
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 require_once($CFG->dirroot . '/grade/report/lib.php');
26 require_once($CFG->libdir.'/tablelib.php');
28 //showhiddenitems values
29 define("GRADE_REPORT_USER_HIDE_HIDDEN", 0);
30 define("GRADE_REPORT_USER_HIDE_UNTIL", 1);
31 define("GRADE_REPORT_USER_SHOW_HIDDEN", 2);
33 /**
34  * Class providing an API for the user report building and displaying.
35  * @uses grade_report
36  * @package gradereport_user
37  */
38 class grade_report_user extends grade_report {
40     /**
41      * The user.
42      * @var object $user
43      */
44     public $user;
46     /**
47      * A flexitable to hold the data.
48      * @var object $table
49      */
50     public $table;
52     /**
53      * An array of table headers
54      * @var array
55      */
56     public $tableheaders = array();
58     /**
59      * An array of table columns
60      * @var array
61      */
62     public $tablecolumns = array();
64     /**
65      * An array containing rows of data for the table.
66      * @var type
67      */
68     public $tabledata = array();
70     /**
71      * The grade tree structure
72      * @var grade_tree
73      */
74     public $gtree;
76     /**
77      * Flat structure similar to grade tree
78      */
79     public $gseq;
81     /**
82      * show student ranks
83      */
84     public $showrank;
86     /**
87      * show grade percentages
88      */
89     public $showpercentage;
91     /**
92      * Show range
93      */
94     public $showrange = true;
96     /**
97      * Show grades in the report, default true
98      * @var bool
99      */
100     public $showgrade = true;
102     /**
103      * Decimal points to use for values in the report, default 2
104      * @var int
105      */
106     public $decimals = 2;
108     /**
109      * The number of decimal places to round range to, default 0
110      * @var int
111      */
112     public $rangedecimals = 0;
114     /**
115      * Show grade feedback in the report, default true
116      * @var bool
117      */
118     public $showfeedback = true;
120     /**
121      * Show grade weighting in the report, default true.
122      * @var bool
123      */
124     public $showweight = true;
126     /**
127      * Show letter grades in the report, default false
128      * @var bool
129      */
130     public $showlettergrade = false;
132     /**
133      * Show the calculated contribution to the course total column.
134      * @var bool
135      */
136     public $showcontributiontocoursetotal = true;
138     /**
139      * Show average grades in the report, default false.
140      * @var false
141      */
142     public $showaverage = false;
144     public $maxdepth;
145     public $evenodd;
147     public $canviewhidden;
149     public $switch;
151     /**
152      * Show hidden items even when user does not have required cap
153      */
154     public $showhiddenitems;
155     public $showtotalsifcontainhidden;
157     public $baseurl;
158     public $pbarurl;
160     /**
161      * The modinfo object to be used.
162      *
163      * @var course_modinfo
164      */
165     protected $modinfo = null;
167     /**
168      * View as user.
169      *
170      * When this is set to true, the visibility checks, and capability checks will be
171      * applied to the user whose grades are being displayed. This is very useful when
172      * a mentor/parent is viewing the report of their mentee because they need to have
173      * access to the same information, but not more, not less.
174      *
175      * @var boolean
176      */
177     protected $viewasuser = false;
179     /**
180      * An array that collects the aggregationhints for every
181      * grade_item. The hints contain grade, grademin, grademax
182      * status, weight and parent.
183      *
184      * @var array
185      */
186     protected $aggregationhints = array();
188     /**
189      * Constructor. Sets local copies of user preferences and initialises grade_tree.
190      * @param int $courseid
191      * @param object $gpr grade plugin return tracking object
192      * @param string $context
193      * @param int $userid The id of the user
194      * @param bool $viewasuser Set this to true when the current user is a mentor/parent of the targetted user.
195      */
196     public function __construct($courseid, $gpr, $context, $userid, $viewasuser = null) {
197         global $DB, $CFG;
198         parent::__construct($courseid, $gpr, $context);
200         $this->showrank        = grade_get_setting($this->courseid, 'report_user_showrank', $CFG->grade_report_user_showrank);
201         $this->showpercentage  = grade_get_setting($this->courseid, 'report_user_showpercentage', $CFG->grade_report_user_showpercentage);
202         $this->showhiddenitems = grade_get_setting($this->courseid, 'report_user_showhiddenitems', $CFG->grade_report_user_showhiddenitems);
203         $this->showtotalsifcontainhidden = array($this->courseid => grade_get_setting($this->courseid, 'report_user_showtotalsifcontainhidden', $CFG->grade_report_user_showtotalsifcontainhidden));
205         $this->showgrade       = grade_get_setting($this->courseid, 'report_user_showgrade',       !empty($CFG->grade_report_user_showgrade));
206         $this->showrange       = grade_get_setting($this->courseid, 'report_user_showrange',       !empty($CFG->grade_report_user_showrange));
207         $this->showfeedback    = grade_get_setting($this->courseid, 'report_user_showfeedback',    !empty($CFG->grade_report_user_showfeedback));
209         $this->showweight = grade_get_setting($this->courseid, 'report_user_showweight',
210             !empty($CFG->grade_report_user_showweight));
212         $this->showcontributiontocoursetotal = grade_get_setting($this->courseid, 'report_user_showcontributiontocoursetotal',
213             !empty($CFG->grade_report_user_showcontributiontocoursetotal));
215         $this->showlettergrade = grade_get_setting($this->courseid, 'report_user_showlettergrade', !empty($CFG->grade_report_user_showlettergrade));
216         $this->showaverage     = grade_get_setting($this->courseid, 'report_user_showaverage',     !empty($CFG->grade_report_user_showaverage));
218         $this->viewasuser = $viewasuser;
220         // The default grade decimals is 2
221         $defaultdecimals = 2;
222         if (property_exists($CFG, 'grade_decimalpoints')) {
223             $defaultdecimals = $CFG->grade_decimalpoints;
224         }
225         $this->decimals = grade_get_setting($this->courseid, 'decimalpoints', $defaultdecimals);
227         // The default range decimals is 0
228         $defaultrangedecimals = 0;
229         if (property_exists($CFG, 'grade_report_user_rangedecimals')) {
230             $defaultrangedecimals = $CFG->grade_report_user_rangedecimals;
231         }
232         $this->rangedecimals = grade_get_setting($this->courseid, 'report_user_rangedecimals', $defaultrangedecimals);
234         $this->switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
236         // Grab the grade_tree for this course
237         $this->gtree = new grade_tree($this->courseid, false, $this->switch, null, !$CFG->enableoutcomes);
239         // Determine the number of rows and indentation
240         $this->maxdepth = 1;
241         $this->inject_rowspans($this->gtree->top_element);
242         $this->maxdepth++; // Need to account for the lead column that spans all children
243         for ($i = 1; $i <= $this->maxdepth; $i++) {
244             $this->evenodd[$i] = 0;
245         }
247         $this->tabledata = array();
249         // Get the user (for full name).
250         $this->user = $DB->get_record('user', array('id' => $userid));
252         // What user are we viewing this as?
253         $coursecontext = context_course::instance($this->courseid);
254         if ($viewasuser) {
255             $this->modinfo = new course_modinfo($this->course, $this->user->id);
256             $this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext, $this->user->id);
257         } else {
258             $this->modinfo = $this->gtree->modinfo;
259             $this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext);
260         }
262         // base url for sorting by first/last name
263         $this->baseurl = $CFG->wwwroot.'/grade/report?id='.$courseid.'&amp;userid='.$userid;
264         $this->pbarurl = $this->baseurl;
266         // no groups on this report - rank is from all course users
267         $this->setup_table();
269         //optionally calculate grade item averages
270         $this->calculate_averages();
271     }
273     /**
274      * Recurses through a tree of elements setting the rowspan property on each element
275      *
276      * @param array $element Either the top element or, during recursion, the current element
277      * @return int The number of elements processed
278      */
279     function inject_rowspans(&$element) {
281         if ($element['depth'] > $this->maxdepth) {
282             $this->maxdepth = $element['depth'];
283         }
284         if (empty($element['children'])) {
285             return 1;
286         }
287         $count = 1;
289         foreach ($element['children'] as $key=>$child) {
290             $count += $this->inject_rowspans($element['children'][$key]);
291         }
293         $element['rowspan'] = $count;
294         return $count;
295     }
298     /**
299      * Prepares the headers and attributes of the flexitable.
300      */
301     public function setup_table() {
302         /*
303          * Table has 1-8 columns
304          *| All columns except for itemname/description are optional
305          */
307         // setting up table headers
309         $this->tablecolumns = array('itemname');
310         $this->tableheaders = array($this->get_lang_string('gradeitem', 'grades'));
312         if ($this->showweight) {
313             $this->tablecolumns[] = 'weight';
314             $this->tableheaders[] = $this->get_lang_string('weightuc', 'grades');
315         }
317         if ($this->showgrade) {
318             $this->tablecolumns[] = 'grade';
319             $this->tableheaders[] = $this->get_lang_string('grade', 'grades');
320         }
322         if ($this->showrange) {
323             $this->tablecolumns[] = 'range';
324             $this->tableheaders[] = $this->get_lang_string('range', 'grades');
325         }
327         if ($this->showpercentage) {
328             $this->tablecolumns[] = 'percentage';
329             $this->tableheaders[] = $this->get_lang_string('percentage', 'grades');
330         }
332         if ($this->showlettergrade) {
333             $this->tablecolumns[] = 'lettergrade';
334             $this->tableheaders[] = $this->get_lang_string('lettergrade', 'grades');
335         }
337         if ($this->showrank) {
338             $this->tablecolumns[] = 'rank';
339             $this->tableheaders[] = $this->get_lang_string('rank', 'grades');
340         }
342         if ($this->showaverage) {
343             $this->tablecolumns[] = 'average';
344             $this->tableheaders[] = $this->get_lang_string('average', 'grades');
345         }
347         if ($this->showfeedback) {
348             $this->tablecolumns[] = 'feedback';
349             $this->tableheaders[] = $this->get_lang_string('feedback', 'grades');
350         }
352         if ($this->showcontributiontocoursetotal) {
353             $this->tablecolumns[] = 'contributiontocoursetotal';
354             $this->tableheaders[] = $this->get_lang_string('contributiontocoursetotal', 'grades');
355         }
356     }
358     function fill_table() {
359         //print "<pre>";
360         //print_r($this->gtree->top_element);
361         $this->fill_table_recursive($this->gtree->top_element);
362         //print_r($this->tabledata);
363         //print "</pre>";
364         return true;
365     }
367     /**
368      * Fill the table with data.
369      *
370      * @param $element - An array containing the table data for the current row.
371      */
372     private function fill_table_recursive(&$element) {
373         global $DB, $CFG;
375         $type = $element['type'];
376         $depth = $element['depth'];
377         $grade_object = $element['object'];
378         $eid = $grade_object->id;
379         $element['userid'] = $this->user->id;
380         $fullname = $this->gtree->get_element_header($element, true, true, true, true);
381         $data = array();
382         $hidden = '';
383         $excluded = '';
384         $itemlevel = ($type == 'categoryitem' || $type == 'category' || $type == 'courseitem') ? $depth : ($depth + 1);
385         $class = 'level' . $itemlevel . ' level' . ($itemlevel % 2 ? 'odd' : 'even');
386         $classfeedback = '';
388         // If this is a hidden grade category, hide it completely from the user
389         if ($type == 'category' && $grade_object->is_hidden() && !$this->canviewhidden && (
390                 $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
391                 ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_object->is_hiddenuntil()))) {
392             return false;
393         }
395         if ($type == 'category') {
396             $this->evenodd[$depth] = (($this->evenodd[$depth] + 1) % 2);
397         }
398         $alter = ($this->evenodd[$depth] == 0) ? 'even' : 'odd';
400         /// Process those items that have scores associated
401         if ($type == 'item' or $type == 'categoryitem' or $type == 'courseitem') {
402             $header_row = "row_{$eid}_{$this->user->id}";
403             $header_cat = "cat_{$grade_object->categoryid}_{$this->user->id}";
405             if (! $grade_grade = grade_grade::fetch(array('itemid'=>$grade_object->id,'userid'=>$this->user->id))) {
406                 $grade_grade = new grade_grade();
407                 $grade_grade->userid = $this->user->id;
408                 $grade_grade->itemid = $grade_object->id;
409             }
411             $grade_grade->load_grade_item();
413             /// Hidden Items
414             if ($grade_grade->grade_item->is_hidden()) {
415                 $hidden = ' dimmed_text';
416             }
418             $hide = false;
419             // If this is a hidden grade item, hide it completely from the user.
420             if ($grade_grade->is_hidden() && !$this->canviewhidden && (
421                     $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
422                     ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_grade->is_hiddenuntil()))) {
423                 $hide = true;
424             } else if (!empty($grade_object->itemmodule) && !empty($grade_object->iteminstance)) {
425                 // The grade object can be marked visible but still be hidden if
426                 // the student cannot see the activity due to conditional access
427                 // and it's set to be hidden entirely.
428                 $instances = $this->modinfo->get_instances_of($grade_object->itemmodule);
429                 if (!empty($instances[$grade_object->iteminstance])) {
430                     $cm = $instances[$grade_object->iteminstance];
431                     if (!$cm->uservisible) {
432                         // If there is 'availableinfo' text then it is only greyed
433                         // out and not entirely hidden.
434                         if (!$cm->availableinfo) {
435                             $hide = true;
436                         }
437                     }
438                 }
439             }
441             if (!$hide) {
442                 /// Excluded Item
443                 /**
444                 if ($grade_grade->is_excluded()) {
445                     $fullname .= ' ['.get_string('excluded', 'grades').']';
446                     $excluded = ' excluded';
447                 }
448                 **/
450                 /// Other class information
451                 $class .= $hidden . $excluded;
452                 if ($this->switch) { // alter style based on whether aggregation is first or last
453                    $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggt b2b" : " item b1b";
454                 } else {
455                    $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggb" : " item b1b";
456                 }
457                 if ($type == 'categoryitem' or $type == 'courseitem') {
458                     $header_cat = "cat_{$grade_object->iteminstance}_{$this->user->id}";
459                 }
461                 /// Name
462                 $data['itemname']['content'] = $fullname;
463                 $data['itemname']['class'] = $class;
464                 $data['itemname']['colspan'] = ($this->maxdepth - $depth);
465                 $data['itemname']['celltype'] = 'th';
466                 $data['itemname']['id'] = $header_row;
468                 /// Actual Grade
469                 $gradeval = $grade_grade->finalgrade;
470                 $hint = $grade_grade->get_aggregation_hint();
471                 if (!$this->canviewhidden) {
472                     /// Virtual Grade (may be calculated excluding hidden items etc).
473                     $adjustedgrade = $this->blank_hidden_total_and_adjust_bounds($this->courseid,
474                                                                                  $grade_grade->grade_item,
475                                                                                  $gradeval);
477                     $gradeval = $adjustedgrade['grade'];
479                     // We temporarily adjust the view of this grade item - because the min and
480                     // max are affected by the hidden values in the aggregation.
481                     $grade_grade->grade_item->grademax = $adjustedgrade['grademax'];
482                     $grade_grade->grade_item->grademin = $adjustedgrade['grademin'];
483                     $hint['status'] = $adjustedgrade['aggregationstatus'];
484                     $hint['weight'] = $adjustedgrade['aggregationweight'];
485                 } else {
486                     // The max and min for an aggregation may be different to the grade_item.
487                     if (!is_null($gradeval)) {
488                         $grade_grade->grade_item->grademax = $grade_grade->rawgrademax;
489                         $grade_grade->grade_item->grademin = $grade_grade->rawgrademin;
490                     }
491                 }
493                 if ($this->showfeedback) {
494                     // Copy $class before appending itemcenter as feedback should not be centered
495                     $classfeedback = $class;
496                 }
497                 $class .= " itemcenter ";
498                 if ($this->showweight) {
499                     $data['weight']['class'] = $class;
500                     $data['weight']['content'] = '-';
501                     $data['weight']['headers'] = "$header_cat $header_row weight";
502                     // has a weight assigned, might be extra credit
504                     // This obliterates the weight because it provides a more informative description.
505                     if (is_numeric($hint['weight'])) {
506                         $data['weight']['content'] = format_float($hint['weight'] * 100.0, 2) . ' %';
507                     }
508                     if ($hint['status'] != 'used' && $hint['status'] != 'unknown') {
509                         $data['weight']['content'] .= '<br>' . get_string('aggregationhint' . $hint['status'], 'grades');
510                     }
511                 }
513                 if ($this->showgrade) {
514                     if ($grade_grade->grade_item->needsupdate) {
515                         $data['grade']['class'] = $class.' gradingerror';
516                         $data['grade']['content'] = get_string('error');
517                     } else if (!empty($CFG->grade_hiddenasdate) and $grade_grade->get_datesubmitted() and !$this->canviewhidden and $grade_grade->is_hidden()
518                            and !$grade_grade->grade_item->is_category_item() and !$grade_grade->grade_item->is_course_item()) {
519                         // the problem here is that we do not have the time when grade value was modified, 'timemodified' is general modification date for grade_grades records
520                         $class .= ' datesubmitted';
521                         $data['grade']['class'] = $class;
522                         $data['grade']['content'] = get_string('submittedon', 'grades', userdate($grade_grade->get_datesubmitted(), get_string('strftimedatetimeshort')));
524                     } else if ($grade_grade->is_hidden()) {
525                         $data['grade']['class'] = $class.' dimmed_text';
526                         $data['grade']['content'] = '-';
527                         if ($this->canviewhidden) {
528                             $data['grade']['content'] = grade_format_gradevalue($gradeval,
529                                                                                 $grade_grade->grade_item,
530                                                                                 true);
531                         }
532                     } else {
533                         $data['grade']['class'] = $class;
534                         $data['grade']['content'] = grade_format_gradevalue($gradeval,
535                                                                             $grade_grade->grade_item,
536                                                                             true);
537                     }
538                     $data['grade']['headers'] = "$header_cat $header_row grade";
539                 }
541                 // Range
542                 if ($this->showrange) {
543                     $data['range']['class'] = $class;
544                     $data['range']['content'] = $grade_grade->grade_item->get_formatted_range(GRADE_DISPLAY_TYPE_REAL, $this->rangedecimals);
545                     $data['range']['headers'] = "$header_cat $header_row range";
546                 }
548                 // Percentage
549                 if ($this->showpercentage) {
550                     if ($grade_grade->grade_item->needsupdate) {
551                         $data['percentage']['class'] = $class.' gradingerror';
552                         $data['percentage']['content'] = get_string('error');
553                     } else if ($grade_grade->is_hidden()) {
554                         $data['percentage']['class'] = $class.' dimmed_text';
555                         $data['percentage']['content'] = '-';
556                         if ($this->canviewhidden) {
557                             $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
558                         }
559                     } else {
560                         $data['percentage']['class'] = $class;
561                         $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
562                     }
563                     $data['percentage']['headers'] = "$header_cat $header_row percentage";
564                 }
566                 // Lettergrade
567                 if ($this->showlettergrade) {
568                     if ($grade_grade->grade_item->needsupdate) {
569                         $data['lettergrade']['class'] = $class.' gradingerror';
570                         $data['lettergrade']['content'] = get_string('error');
571                     } else if ($grade_grade->is_hidden()) {
572                         $data['lettergrade']['class'] = $class.' dimmed_text';
573                         if (!$this->canviewhidden) {
574                             $data['lettergrade']['content'] = '-';
575                         } else {
576                             $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
577                         }
578                     } else {
579                         $data['lettergrade']['class'] = $class;
580                         $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
581                     }
582                     $data['lettergrade']['headers'] = "$header_cat $header_row lettergrade";
583                 }
585                 // Rank
586                 if ($this->showrank) {
587                     if ($grade_grade->grade_item->needsupdate) {
588                         $data['rank']['class'] = $class.' gradingerror';
589                         $data['rank']['content'] = get_string('error');
590                         } elseif ($grade_grade->is_hidden()) {
591                             $data['rank']['class'] = $class.' dimmed_text';
592                             $data['rank']['content'] = '-';
593                     } else if (is_null($gradeval)) {
594                         // no grade, no rank
595                         $data['rank']['class'] = $class;
596                         $data['rank']['content'] = '-';
598                     } else {
599                         /// find the number of users with a higher grade
600                         $sql = "SELECT COUNT(DISTINCT(userid))
601                                   FROM {grade_grades}
602                                  WHERE finalgrade > ?
603                                        AND itemid = ?
604                                        AND hidden = 0";
605                         $rank = $DB->count_records_sql($sql, array($grade_grade->finalgrade, $grade_grade->grade_item->id)) + 1;
607                         $data['rank']['class'] = $class;
608                         $data['rank']['content'] = "$rank/".$this->get_numusers(false); // total course users
609                     }
610                     $data['rank']['headers'] = "$header_cat $header_row rank";
611                 }
613                 // Average
614                 if ($this->showaverage) {
615                     $data['average']['class'] = $class;
616                     if (!empty($this->gtree->items[$eid]->avg)) {
617                         $data['average']['content'] = $this->gtree->items[$eid]->avg;
618                     } else {
619                         $data['average']['content'] = '-';
620                     }
621                     $data['average']['headers'] = "$header_cat $header_row average";
622                 }
624                 // Feedback
625                 if ($this->showfeedback) {
626                     if ($grade_grade->overridden > 0 AND ($type == 'categoryitem' OR $type == 'courseitem')) {
627                     $data['feedback']['class'] = $classfeedback.' feedbacktext';
628                         $data['feedback']['content'] = get_string('overridden', 'grades').': ' . format_text($grade_grade->feedback, $grade_grade->feedbackformat);
629                     } else if (empty($grade_grade->feedback) or (!$this->canviewhidden and $grade_grade->is_hidden())) {
630                         $data['feedback']['class'] = $classfeedback.' feedbacktext';
631                         $data['feedback']['content'] = '&nbsp;';
632                     } else {
633                         $data['feedback']['class'] = $classfeedback.' feedbacktext';
634                         $data['feedback']['content'] = format_text($grade_grade->feedback, $grade_grade->feedbackformat);
635                     }
636                     $data['feedback']['headers'] = "$header_cat $header_row feedback";
637                 }
638                 // Contribution to the course total column.
639                 if ($this->showcontributiontocoursetotal) {
640                     $data['contributiontocoursetotal']['class'] = $class;
641                     $data['contributiontocoursetotal']['content'] = '-';
642                     $data['contributiontocoursetotal']['headers'] = "$header_cat $header_row contributiontocoursetotal";
644                     $hint['grademax'] = $grade_grade->grade_item->grademax;
645                     $hint['grademin'] = $grade_grade->grade_item->grademin;
646                     $hint['grade'] = $gradeval;
647                     $parent = $grade_object->load_parent_category();
648                     if ($grade_object->is_category_item()) {
649                         $parent = $parent->load_parent_category();
650                     }
651                     $hint['parent'] = $parent->load_grade_item()->id;
652                     $this->aggregationhints[$grade_grade->itemid] = $hint;
653                 }
654             }
655         }
657         /// Category
658         if ($type == 'category') {
659             $data['leader']['class'] = $class.' '.$alter."d$depth b1t b2b b1l";
660             $data['leader']['rowspan'] = $element['rowspan'];
662             if ($this->switch) { // alter style based on whether aggregation is first or last
663                $data['itemname']['class'] = $class.' '.$alter."d$depth b1b b1t";
664             } else {
665                $data['itemname']['class'] = $class.' '.$alter."d$depth b2t";
666             }
667             $data['itemname']['colspan'] = ($this->maxdepth - $depth + count($this->tablecolumns) - 1);
668             $data['itemname']['content'] = $fullname;
669             $data['itemname']['celltype'] = 'th';
670             $data['itemname']['id'] = "cat_{$grade_object->id}_{$this->user->id}";
671         }
673         /// Add this row to the overall system
674         foreach ($data as $key => $celldata) {
675             $data[$key]['class'] .= ' column-' . $key;
676         }
677         $this->tabledata[] = $data;
679         /// Recursively iterate through all child elements
680         if (isset($element['children'])) {
681             foreach ($element['children'] as $key=>$child) {
682                 $this->fill_table_recursive($element['children'][$key]);
683             }
684         }
686         // Check we are showing this column, and we are looking at the root of the table.
687         // This should be the very last thing this fill_table_recursive function does.
688         if ($this->showcontributiontocoursetotal && ($type == 'category' && $depth == 1)) {
689             // We should have collected all the hints by now - walk the tree again and build the contributions column.
691             $this->fill_contributions_column($element);
692         }
693     }
695     /**
696      * This function is called after the table has been built and the aggregationhints
697      * have been collected. We need this info to walk up the list of parents of each
698      * grade_item.
699      *
700      * @param $element - An array containing the table data for the current row.
701      */
702     public function fill_contributions_column($element) {
704         // Recursively iterate through all child elements.
705         if (isset($element['children'])) {
706             foreach ($element['children'] as $key=>$child) {
707                 $this->fill_contributions_column($element['children'][$key]);
708             }
709         } else if ($element['type'] == 'item') {
710             // This is a grade item (We don't do this for categories or we would double count).
711             $grade_object = $element['object'];
712             $itemid = $grade_object->id;
714             // Ignore anything with no hint - e.g. a hidden row.
715             if (isset($this->aggregationhints[$itemid])) {
717                 // Normalise the gradeval.
718                 $gradecat = $grade_object->load_parent_category();
719                 if ($gradecat->aggregation == GRADE_AGGREGATE_SUM) {
720                     // Natural aggregation/Sum of grades does not consider the mingrade, cannot traditionnally normalise it.
721                     $graderange = $this->aggregationhints[$itemid]['grademax'];
722                     $gradeval = $this->aggregationhints[$itemid]['grade'] / $graderange;
723                 } else {
724                     $gradeval = grade_grade::standardise_score($this->aggregationhints[$itemid]['grade'],
725                         $this->aggregationhints[$itemid]['grademin'], $this->aggregationhints[$itemid]['grademax'], 0, 1);
726                 }
728                 // Multiply the normalised value by the weight
729                 // of all the categories higher in the tree.
730                 do {
731                     if (!is_null($this->aggregationhints[$itemid]['weight'])) {
732                         $gradeval *= $this->aggregationhints[$itemid]['weight'];
733                     }
735                     // The second part of this if is to prevent infinite loops
736                     // in case of crazy data.
737                     if (isset($this->aggregationhints[$itemid]['parent']) &&
738                             $this->aggregationhints[$itemid]['parent'] != $itemid) {
739                         $parent = $this->aggregationhints[$itemid]['parent'];
740                         $itemid = $parent;
741                     } else {
742                         // We are at the top of the tree.
743                         $parent = false;
744                     }
745                 } while ($parent);
747                 // Convert to percent.
748                 $gradeval *= 100;
750                 // Now we need to loop through the "built" table data and update the
751                 // contributions column for the current row.
752                 $header_row = "row_{$grade_object->id}_{$this->user->id}";
753                 foreach ($this->tabledata as $key => $row) {
754                     if (isset($row['itemname']) && ($row['itemname']['id'] == $header_row)) {
755                         // Found it - update the column.
756                         $decimals = $grade_object->get_decimals();
757                         $this->tabledata[$key]['contributiontocoursetotal']['content'] = format_float($gradeval, $decimals, true) . ' %';
758                         break;
759                     }
760                 }
761             }
762         }
763     }
765     /**
766      * Prints or returns the HTML from the flexitable.
767      * @param bool $return Whether or not to return the data instead of printing it directly.
768      * @return string
769      */
770     public function print_table($return=false) {
771          $maxspan = $this->maxdepth;
773         /// Build table structure
774         $html = "
775             <table cellspacing='0'
776                    cellpadding='0'
777                    summary='" . s($this->get_lang_string('tablesummary', 'gradereport_user')) . "'
778                    class='boxaligncenter generaltable user-grade'>
779             <thead>
780                 <tr>
781                     <th id='".$this->tablecolumns[0]."' class=\"header column-{$this->tablecolumns[0]}\" colspan='$maxspan'>".$this->tableheaders[0]."</th>\n";
783         for ($i = 1; $i < count($this->tableheaders); $i++) {
784             $html .= "<th id='".$this->tablecolumns[$i]."' class=\"header column-{$this->tablecolumns[$i]}\">".$this->tableheaders[$i]."</th>\n";
785         }
787         $html .= "
788                 </tr>
789             </thead>
790             <tbody>\n";
792         /// Print out the table data
793         for ($i = 0; $i < count($this->tabledata); $i++) {
794             $html .= "<tr>\n";
795             if (isset($this->tabledata[$i]['leader'])) {
796                 $rowspan = $this->tabledata[$i]['leader']['rowspan'];
797                 $class = $this->tabledata[$i]['leader']['class'];
798                 $html .= "<td class='$class' rowspan='$rowspan'></td>\n";
799             }
800             for ($j = 0; $j < count($this->tablecolumns); $j++) {
801                 $name = $this->tablecolumns[$j];
802                 $class = (isset($this->tabledata[$i][$name]['class'])) ? $this->tabledata[$i][$name]['class'] : '';
803                 $colspan = (isset($this->tabledata[$i][$name]['colspan'])) ? "colspan='".$this->tabledata[$i][$name]['colspan']."'" : '';
804                 $content = (isset($this->tabledata[$i][$name]['content'])) ? $this->tabledata[$i][$name]['content'] : null;
805                 $celltype = (isset($this->tabledata[$i][$name]['celltype'])) ? $this->tabledata[$i][$name]['celltype'] : 'td';
806                 $id = (isset($this->tabledata[$i][$name]['id'])) ? "id='{$this->tabledata[$i][$name]['id']}'" : '';
807                 $headers = (isset($this->tabledata[$i][$name]['headers'])) ? "headers='{$this->tabledata[$i][$name]['headers']}'" : '';
808                 if (isset($content)) {
809                     $html .= "<$celltype $id $headers class='$class' $colspan>$content</$celltype>\n";
810                 }
811             }
812             $html .= "</tr>\n";
813         }
815         $html .= "</tbody></table>";
817         if ($return) {
818             return $html;
819         } else {
820             echo $html;
821         }
822     }
824     /**
825      * Processes the data sent by the form (grades and feedbacks).
826      * @var array $data
827      * @return bool Success or Failure (array of errors).
828      */
829     function process_data($data) {
830     }
831     function process_action($target, $action) {
832     }
834     /**
835      * Builds the grade item averages.
836      */
837     function calculate_averages() {
838         global $USER, $DB;
840         if ($this->showaverage) {
841             // This settings are actually grader report settings (not user report)
842             // however we're using them as having two separate but identical settings the
843             // user would have to keep in sync would be annoying.
844             $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
845             $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
846             $meanselection         = $this->get_pref('meanselection');
847             $shownumberofgrades    = $this->get_pref('shownumberofgrades');
849             $avghtml = '';
850             $groupsql = $this->groupsql;
851             $groupwheresql = $this->groupwheresql;
852             $totalcount = $this->get_numusers(false);
854             // We want to query both the current context and parent contexts.
855             list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
857             // Limit to users with a gradeable role ie students.
858             list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
860             // Limit to users with an active enrolment.
861             list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
863             $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams, $relatedctxparams);
864             $params['courseid'] = $this->courseid;
866             // find sums of all grade items in course
867             $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
868                       FROM {grade_items} gi
869                       JOIN {grade_grades} gg ON gg.itemid = gi.id
870                       JOIN {user} u ON u.id = gg.userid
871                       JOIN ($enrolledsql) je ON je.id = gg.userid
872                       JOIN (
873                                    SELECT DISTINCT ra.userid
874                                      FROM {role_assignments} ra
875                                     WHERE ra.roleid $gradebookrolessql
876                                       AND ra.contextid $relatedctxsql
877                            ) rainner ON rainner.userid = u.id
878                       $groupsql
879                      WHERE gi.courseid = :courseid
880                        AND u.deleted = 0
881                        AND gg.finalgrade IS NOT NULL
882                        AND gg.hidden = 0
883                        $groupwheresql
884                   GROUP BY gg.itemid";
886             $sum_array = array();
887             $sums = $DB->get_recordset_sql($sql, $params);
888             foreach ($sums as $itemid => $csum) {
889                 $sum_array[$itemid] = $csum->sum;
890             }
891             $sums->close();
893             $columncount=0;
895             // Empty grades must be evaluated as grademin, NOT always 0
896             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
897             // No join condition when joining grade_items and user to get a grade item row for every user
898             // Then left join with grade_grades and look for rows with null final grade (which includes grade items with no grade_grade)
899             $sql = "SELECT gi.id, COUNT(u.id) AS count
900                       FROM {grade_items} gi
901                       JOIN {user} u ON u.deleted = 0
902                       JOIN ($enrolledsql) je ON je.id = u.id
903                       JOIN (
904                                SELECT DISTINCT ra.userid
905                                  FROM {role_assignments} ra
906                                 WHERE ra.roleid $gradebookrolessql
907                                   AND ra.contextid $relatedctxsql
908                            ) rainner ON rainner.userid = u.id
909                       LEFT JOIN {grade_grades} gg
910                              ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL AND gg.hidden = 0)
911                       $groupsql
912                      WHERE gi.courseid = :courseid
913                            AND gg.finalgrade IS NULL
914                            $groupwheresql
915                   GROUP BY gi.id";
917             $ungraded_counts = $DB->get_records_sql($sql, $params);
919             foreach ($this->gtree->items as $itemid=>$unused) {
920                 if (!empty($this->gtree->items[$itemid]->avg)) {
921                     continue;
922                 }
923                 $item = $this->gtree->items[$itemid];
925                 if ($item->needsupdate) {
926                     $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
927                     continue;
928                 }
930                 if (empty($sum_array[$item->id])) {
931                     $sum_array[$item->id] = 0;
932                 }
934                 if (empty($ungraded_counts[$itemid])) {
935                     $ungraded_count = 0;
936                 } else {
937                     $ungraded_count = $ungraded_counts[$itemid]->count;
938                 }
940                 //do they want the averages to include all grade items
941                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
942                     $mean_count = $totalcount - $ungraded_count;
943                 } else { // Bump up the sum by the number of ungraded items * grademin
944                     $sum_array[$item->id] += ($ungraded_count * $item->grademin);
945                     $mean_count = $totalcount;
946                 }
948                 // Determine which display type to use for this average
949                 if (!empty($USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
950                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
952                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
953                     $displaytype = $item->get_displaytype();
955                 } else {
956                     $displaytype = $averagesdisplaytype;
957                 }
959                 // Override grade_item setting if a display preference (not inherit) was set for the averages
960                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
961                     $decimalpoints = $item->get_decimals();
962                 } else {
963                     $decimalpoints = $averagesdecimalpoints;
964                 }
966                 if (empty($sum_array[$item->id]) || $mean_count == 0) {
967                     $this->gtree->items[$itemid]->avg = '-';
968                 } else {
969                     $sum = $sum_array[$item->id];
970                     $avgradeval = $sum/$mean_count;
971                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
973                     $numberofgrades = '';
974                     if ($shownumberofgrades) {
975                         $numberofgrades = " ($mean_count)";
976                     }
978                     $this->gtree->items[$itemid]->avg = $gradehtml.$numberofgrades;
979                 }
980             }
981         }
982     }
985 function grade_report_user_settings_definition(&$mform) {
986     global $CFG;
988     $options = array(-1 => get_string('default', 'grades'),
989                       0 => get_string('hide'),
990                       1 => get_string('show'));
992     if (empty($CFG->grade_report_user_showrank)) {
993         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
994     } else {
995         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
996     }
998     $mform->addElement('select', 'report_user_showrank', get_string('showrank', 'grades'), $options);
999     $mform->addHelpButton('report_user_showrank', 'showrank', 'grades');
1001     if (empty($CFG->grade_report_user_showpercentage)) {
1002         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1003     } else {
1004         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1005     }
1007     $mform->addElement('select', 'report_user_showpercentage', get_string('showpercentage', 'grades'), $options);
1008     $mform->addHelpButton('report_user_showpercentage', 'showpercentage', 'grades');
1010     if (empty($CFG->grade_report_user_showgrade)) {
1011         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1012     } else {
1013         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1014     }
1016     $mform->addElement('select', 'report_user_showgrade', get_string('showgrade', 'grades'), $options);
1018     if (empty($CFG->grade_report_user_showfeedback)) {
1019         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1020     } else {
1021         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1022     }
1024     $mform->addElement('select', 'report_user_showfeedback', get_string('showfeedback', 'grades'), $options);
1026     if (empty($CFG->grade_report_user_showweight)) {
1027         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1028     } else {
1029         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1030     }
1032     $mform->addElement('select', 'report_user_showweight', get_string('showweight', 'grades'), $options);
1034     if (empty($CFG->grade_report_user_showaverage)) {
1035         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1036     } else {
1037         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1038     }
1040     $mform->addElement('select', 'report_user_showaverage', get_string('showaverage', 'grades'), $options);
1041     $mform->addHelpButton('report_user_showaverage', 'showaverage', 'grades');
1043     if (empty($CFG->grade_report_user_showlettergrade)) {
1044         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1045     } else {
1046         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1047     }
1049     $mform->addElement('select', 'report_user_showlettergrade', get_string('showlettergrade', 'grades'), $options);
1050     if (empty($CFG->grade_report_user_showcontributiontocoursetotal)) {
1051         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1052     } else {
1053         $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showcontributiontocoursetotal]);
1054     }
1056     $mform->addElement('select', 'report_user_showcontributiontocoursetotal', get_string('showcontributiontocoursetotal', 'grades'), $options);
1057     $mform->addHelpButton('report_user_showcontributiontocoursetotal', 'showcontributiontocoursetotal', 'grades');
1059     if (empty($CFG->grade_report_user_showrange)) {
1060         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1061     } else {
1062         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1063     }
1065     $mform->addElement('select', 'report_user_showrange', get_string('showrange', 'grades'), $options);
1067     $options = array(0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5);
1068     if (! empty($CFG->grade_report_user_rangedecimals)) {
1069         $options[-1] = $options[$CFG->grade_report_user_rangedecimals];
1070     }
1071     $mform->addElement('select', 'report_user_rangedecimals', get_string('rangedecimals', 'grades'), $options);
1073     $options = array(-1 => get_string('default', 'grades'),
1074                       0 => get_string('shownohidden', 'grades'),
1075                       1 => get_string('showhiddenuntilonly', 'grades'),
1076                       2 => get_string('showallhidden', 'grades'));
1078     if (empty($CFG->grade_report_user_showhiddenitems)) {
1079         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1080     } else {
1081         $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showhiddenitems]);
1082     }
1084     $mform->addElement('select', 'report_user_showhiddenitems', get_string('showhiddenitems', 'grades'), $options);
1085     $mform->addHelpButton('report_user_showhiddenitems', 'showhiddenitems', 'grades');
1087     //showtotalsifcontainhidden
1088     $options = array(-1 => get_string('default', 'grades'),
1089                       GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN => get_string('hide'),
1090                       GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowexhiddenitems', 'grades'),
1091                       GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowinchiddenitems', 'grades') );
1093     if (empty($CFG->grade_report_user_showtotalsifcontainhidden)) {
1094         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1095     } else {
1096         $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showtotalsifcontainhidden]);
1097     }
1099     $mform->addElement('select', 'report_user_showtotalsifcontainhidden', get_string('hidetotalifhiddenitems', 'grades'), $options);
1100     $mform->addHelpButton('report_user_showtotalsifcontainhidden', 'hidetotalifhiddenitems', 'grades');
1104 /**
1105  * Profile report callback.
1106  *
1107  * @param object $course The course.
1108  * @param object $user The user.
1109  * @param boolean $viewasuser True when we are viewing this as the targetted user sees it.
1110  */
1111 function grade_report_user_profilereport($course, $user, $viewasuser = false) {
1112     global $OUTPUT;
1113     if (!empty($course->showgrades)) {
1115         $context = context_course::instance($course->id);
1117         //first make sure we have proper final grades - this must be done before constructing of the grade tree
1118         grade_regrade_final_grades($course->id);
1120         /// return tracking object
1121         $gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'user', 'courseid'=>$course->id, 'userid'=>$user->id));
1122         // Create a report instance
1123         $report = new grade_report_user($course->id, $gpr, $context, $user->id, $viewasuser);
1125         // print the page
1126         echo '<div class="grade-report-user">'; // css fix to share styles with real report page
1127         echo $OUTPUT->heading(get_string('pluginname', 'gradereport_user'). ' - '.fullname($report->user));
1129         if ($report->fill_table()) {
1130             echo $report->print_table(true);
1131         }
1132         echo '</div>';
1133     }