feb37ce68689a14ecda0c7475a0c702e0f48ed31
[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         // Get the user (for full name).
240         $this->user = $DB->get_record('user', array('id' => $userid));
242         // What user are we viewing this as?
243         $coursecontext = context_course::instance($this->courseid);
244         if ($viewasuser) {
245             $this->modinfo = new course_modinfo($this->course, $this->user->id);
246             $this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext, $this->user->id);
247         } else {
248             $this->modinfo = $this->gtree->modinfo;
249             $this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext);
250         }
252         // Determine the number of rows and indentation.
253         $this->maxdepth = 1;
254         $this->inject_rowspans($this->gtree->top_element);
255         $this->maxdepth++; // Need to account for the lead column that spans all children.
256         for ($i = 1; $i <= $this->maxdepth; $i++) {
257             $this->evenodd[$i] = 0;
258         }
260         $this->tabledata = array();
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             // If category is hidden then do not include it in the rowspan.
291             if ($child['type'] == 'category' && $child['object']->is_hidden() && !$this->canviewhidden
292                     && ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN
293                     || ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$child['object']->is_hiddenuntil()))) {
294                 // Just calculate the rowspans for children of this category, don't add them to the count.
295                 $this->inject_rowspans($element['children'][$key]);
296             } else {
297                 $count += $this->inject_rowspans($element['children'][$key]);
298             }
299         }
301         $element['rowspan'] = $count;
302         return $count;
303     }
306     /**
307      * Prepares the headers and attributes of the flexitable.
308      */
309     public function setup_table() {
310         /*
311          * Table has 1-8 columns
312          *| All columns except for itemname/description are optional
313          */
315         // setting up table headers
317         $this->tablecolumns = array('itemname');
318         $this->tableheaders = array($this->get_lang_string('gradeitem', 'grades'));
320         if ($this->showweight) {
321             $this->tablecolumns[] = 'weight';
322             $this->tableheaders[] = $this->get_lang_string('weightuc', 'grades');
323         }
325         if ($this->showgrade) {
326             $this->tablecolumns[] = 'grade';
327             $this->tableheaders[] = $this->get_lang_string('grade', 'grades');
328         }
330         if ($this->showrange) {
331             $this->tablecolumns[] = 'range';
332             $this->tableheaders[] = $this->get_lang_string('range', 'grades');
333         }
335         if ($this->showpercentage) {
336             $this->tablecolumns[] = 'percentage';
337             $this->tableheaders[] = $this->get_lang_string('percentage', 'grades');
338         }
340         if ($this->showlettergrade) {
341             $this->tablecolumns[] = 'lettergrade';
342             $this->tableheaders[] = $this->get_lang_string('lettergrade', 'grades');
343         }
345         if ($this->showrank) {
346             $this->tablecolumns[] = 'rank';
347             $this->tableheaders[] = $this->get_lang_string('rank', 'grades');
348         }
350         if ($this->showaverage) {
351             $this->tablecolumns[] = 'average';
352             $this->tableheaders[] = $this->get_lang_string('average', 'grades');
353         }
355         if ($this->showfeedback) {
356             $this->tablecolumns[] = 'feedback';
357             $this->tableheaders[] = $this->get_lang_string('feedback', 'grades');
358         }
360         if ($this->showcontributiontocoursetotal) {
361             $this->tablecolumns[] = 'contributiontocoursetotal';
362             $this->tableheaders[] = $this->get_lang_string('contributiontocoursetotal', 'grades');
363         }
364     }
366     function fill_table() {
367         //print "<pre>";
368         //print_r($this->gtree->top_element);
369         $this->fill_table_recursive($this->gtree->top_element);
370         //print_r($this->tabledata);
371         //print "</pre>";
372         return true;
373     }
375     /**
376      * Fill the table with data.
377      *
378      * @param $element - An array containing the table data for the current row.
379      */
380     private function fill_table_recursive(&$element) {
381         global $DB, $CFG;
383         $type = $element['type'];
384         $depth = $element['depth'];
385         $grade_object = $element['object'];
386         $eid = $grade_object->id;
387         $element['userid'] = $this->user->id;
388         $fullname = $this->gtree->get_element_header($element, true, true, true, true);
389         $data = array();
390         $hidden = '';
391         $excluded = '';
392         $itemlevel = ($type == 'categoryitem' || $type == 'category' || $type == 'courseitem') ? $depth : ($depth + 1);
393         $class = 'level' . $itemlevel . ' level' . ($itemlevel % 2 ? 'odd' : 'even');
394         $classfeedback = '';
396         // If this is a hidden grade category, hide it completely from the user
397         if ($type == 'category' && $grade_object->is_hidden() && !$this->canviewhidden && (
398                 $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
399                 ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_object->is_hiddenuntil()))) {
400             return false;
401         }
403         if ($type == 'category') {
404             $this->evenodd[$depth] = (($this->evenodd[$depth] + 1) % 2);
405         }
406         $alter = ($this->evenodd[$depth] == 0) ? 'even' : 'odd';
408         /// Process those items that have scores associated
409         if ($type == 'item' or $type == 'categoryitem' or $type == 'courseitem') {
410             $header_row = "row_{$eid}_{$this->user->id}";
411             $header_cat = "cat_{$grade_object->categoryid}_{$this->user->id}";
413             if (! $grade_grade = grade_grade::fetch(array('itemid'=>$grade_object->id,'userid'=>$this->user->id))) {
414                 $grade_grade = new grade_grade();
415                 $grade_grade->userid = $this->user->id;
416                 $grade_grade->itemid = $grade_object->id;
417             }
419             $grade_grade->load_grade_item();
421             /// Hidden Items
422             if ($grade_grade->grade_item->is_hidden()) {
423                 $hidden = ' dimmed_text';
424             }
426             $hide = false;
427             // If this is a hidden grade item, hide it completely from the user.
428             if ($grade_grade->is_hidden() && !$this->canviewhidden && (
429                     $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
430                     ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_grade->is_hiddenuntil()))) {
431                 $hide = true;
432             } else if (!empty($grade_object->itemmodule) && !empty($grade_object->iteminstance)) {
433                 // The grade object can be marked visible but still be hidden if
434                 // the student cannot see the activity due to conditional access
435                 // and it's set to be hidden entirely.
436                 $instances = $this->modinfo->get_instances_of($grade_object->itemmodule);
437                 if (!empty($instances[$grade_object->iteminstance])) {
438                     $cm = $instances[$grade_object->iteminstance];
439                     if (!$cm->uservisible) {
440                         // If there is 'availableinfo' text then it is only greyed
441                         // out and not entirely hidden.
442                         if (!$cm->availableinfo) {
443                             $hide = true;
444                         }
445                     }
446                 }
447             }
449             if (!$hide) {
450                 /// Excluded Item
451                 /**
452                 if ($grade_grade->is_excluded()) {
453                     $fullname .= ' ['.get_string('excluded', 'grades').']';
454                     $excluded = ' excluded';
455                 }
456                 **/
458                 /// Other class information
459                 $class .= $hidden . $excluded;
460                 if ($this->switch) { // alter style based on whether aggregation is first or last
461                    $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggt b2b" : " item b1b";
462                 } else {
463                    $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggb" : " item b1b";
464                 }
465                 if ($type == 'categoryitem' or $type == 'courseitem') {
466                     $header_cat = "cat_{$grade_object->iteminstance}_{$this->user->id}";
467                 }
469                 /// Name
470                 $data['itemname']['content'] = $fullname;
471                 $data['itemname']['class'] = $class;
472                 $data['itemname']['colspan'] = ($this->maxdepth - $depth);
473                 $data['itemname']['celltype'] = 'th';
474                 $data['itemname']['id'] = $header_row;
476                 /// Actual Grade
477                 $gradeval = $grade_grade->finalgrade;
478                 $hint = $grade_grade->get_aggregation_hint();
479                 if (!$this->canviewhidden) {
480                     /// Virtual Grade (may be calculated excluding hidden items etc).
481                     $adjustedgrade = $this->blank_hidden_total_and_adjust_bounds($this->courseid,
482                                                                                  $grade_grade->grade_item,
483                                                                                  $gradeval);
485                     $gradeval = $adjustedgrade['grade'];
487                     // We temporarily adjust the view of this grade item - because the min and
488                     // max are affected by the hidden values in the aggregation.
489                     $grade_grade->grade_item->grademax = $adjustedgrade['grademax'];
490                     $grade_grade->grade_item->grademin = $adjustedgrade['grademin'];
491                     $hint['status'] = $adjustedgrade['aggregationstatus'];
492                     $hint['weight'] = $adjustedgrade['aggregationweight'];
493                 } else {
494                     // The max and min for an aggregation may be different to the grade_item.
495                     if (!is_null($gradeval)) {
496                         $grade_grade->grade_item->grademax = $grade_grade->rawgrademax;
497                         $grade_grade->grade_item->grademin = $grade_grade->rawgrademin;
498                     }
499                 }
501                 if ($this->showfeedback) {
502                     // Copy $class before appending itemcenter as feedback should not be centered
503                     $classfeedback = $class;
504                 }
505                 $class .= " itemcenter ";
506                 if ($this->showweight) {
507                     $data['weight']['class'] = $class;
508                     $data['weight']['content'] = '-';
509                     $data['weight']['headers'] = "$header_cat $header_row weight";
510                     // has a weight assigned, might be extra credit
512                     // This obliterates the weight because it provides a more informative description.
513                     if (is_numeric($hint['weight'])) {
514                         $data['weight']['content'] = format_float($hint['weight'] * 100.0, 2) . ' %';
515                     }
516                     if ($hint['status'] != 'used' && $hint['status'] != 'unknown') {
517                         $data['weight']['content'] .= '<br>' . get_string('aggregationhint' . $hint['status'], 'grades');
518                     }
519                 }
521                 if ($this->showgrade) {
522                     if ($grade_grade->grade_item->needsupdate) {
523                         $data['grade']['class'] = $class.' gradingerror';
524                         $data['grade']['content'] = get_string('error');
525                     } else if (!empty($CFG->grade_hiddenasdate) and $grade_grade->get_datesubmitted() and !$this->canviewhidden and $grade_grade->is_hidden()
526                            and !$grade_grade->grade_item->is_category_item() and !$grade_grade->grade_item->is_course_item()) {
527                         // 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
528                         $class .= ' datesubmitted';
529                         $data['grade']['class'] = $class;
530                         $data['grade']['content'] = get_string('submittedon', 'grades', userdate($grade_grade->get_datesubmitted(), get_string('strftimedatetimeshort')));
532                     } else if ($grade_grade->is_hidden()) {
533                         $data['grade']['class'] = $class.' dimmed_text';
534                         $data['grade']['content'] = '-';
535                         if ($this->canviewhidden) {
536                             $data['grade']['content'] = grade_format_gradevalue($gradeval,
537                                                                                 $grade_grade->grade_item,
538                                                                                 true);
539                         }
540                     } else {
541                         $data['grade']['class'] = $class;
542                         $data['grade']['content'] = grade_format_gradevalue($gradeval,
543                                                                             $grade_grade->grade_item,
544                                                                             true);
545                     }
546                     $data['grade']['headers'] = "$header_cat $header_row grade";
547                 }
549                 // Range
550                 if ($this->showrange) {
551                     $data['range']['class'] = $class;
552                     $data['range']['content'] = $grade_grade->grade_item->get_formatted_range(GRADE_DISPLAY_TYPE_REAL, $this->rangedecimals);
553                     $data['range']['headers'] = "$header_cat $header_row range";
554                 }
556                 // Percentage
557                 if ($this->showpercentage) {
558                     if ($grade_grade->grade_item->needsupdate) {
559                         $data['percentage']['class'] = $class.' gradingerror';
560                         $data['percentage']['content'] = get_string('error');
561                     } else if ($grade_grade->is_hidden()) {
562                         $data['percentage']['class'] = $class.' dimmed_text';
563                         $data['percentage']['content'] = '-';
564                         if ($this->canviewhidden) {
565                             $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
566                         }
567                     } else {
568                         $data['percentage']['class'] = $class;
569                         $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
570                     }
571                     $data['percentage']['headers'] = "$header_cat $header_row percentage";
572                 }
574                 // Lettergrade
575                 if ($this->showlettergrade) {
576                     if ($grade_grade->grade_item->needsupdate) {
577                         $data['lettergrade']['class'] = $class.' gradingerror';
578                         $data['lettergrade']['content'] = get_string('error');
579                     } else if ($grade_grade->is_hidden()) {
580                         $data['lettergrade']['class'] = $class.' dimmed_text';
581                         if (!$this->canviewhidden) {
582                             $data['lettergrade']['content'] = '-';
583                         } else {
584                             $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
585                         }
586                     } else {
587                         $data['lettergrade']['class'] = $class;
588                         $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
589                     }
590                     $data['lettergrade']['headers'] = "$header_cat $header_row lettergrade";
591                 }
593                 // Rank
594                 if ($this->showrank) {
595                     if ($grade_grade->grade_item->needsupdate) {
596                         $data['rank']['class'] = $class.' gradingerror';
597                         $data['rank']['content'] = get_string('error');
598                         } elseif ($grade_grade->is_hidden()) {
599                             $data['rank']['class'] = $class.' dimmed_text';
600                             $data['rank']['content'] = '-';
601                     } else if (is_null($gradeval)) {
602                         // no grade, no rank
603                         $data['rank']['class'] = $class;
604                         $data['rank']['content'] = '-';
606                     } else {
607                         /// find the number of users with a higher grade
608                         $sql = "SELECT COUNT(DISTINCT(userid))
609                                   FROM {grade_grades}
610                                  WHERE finalgrade > ?
611                                        AND itemid = ?
612                                        AND hidden = 0";
613                         $rank = $DB->count_records_sql($sql, array($grade_grade->finalgrade, $grade_grade->grade_item->id)) + 1;
615                         $data['rank']['class'] = $class;
616                         $data['rank']['content'] = "$rank/".$this->get_numusers(false); // total course users
617                     }
618                     $data['rank']['headers'] = "$header_cat $header_row rank";
619                 }
621                 // Average
622                 if ($this->showaverage) {
623                     $data['average']['class'] = $class;
624                     if (!empty($this->gtree->items[$eid]->avg)) {
625                         $data['average']['content'] = $this->gtree->items[$eid]->avg;
626                     } else {
627                         $data['average']['content'] = '-';
628                     }
629                     $data['average']['headers'] = "$header_cat $header_row average";
630                 }
632                 // Feedback
633                 if ($this->showfeedback) {
634                     if ($grade_grade->overridden > 0 AND ($type == 'categoryitem' OR $type == 'courseitem')) {
635                     $data['feedback']['class'] = $classfeedback.' feedbacktext';
636                         $data['feedback']['content'] = get_string('overridden', 'grades').': ' . format_text($grade_grade->feedback, $grade_grade->feedbackformat);
637                     } else if (empty($grade_grade->feedback) or (!$this->canviewhidden and $grade_grade->is_hidden())) {
638                         $data['feedback']['class'] = $classfeedback.' feedbacktext';
639                         $data['feedback']['content'] = '&nbsp;';
640                     } else {
641                         $data['feedback']['class'] = $classfeedback.' feedbacktext';
642                         $data['feedback']['content'] = format_text($grade_grade->feedback, $grade_grade->feedbackformat);
643                     }
644                     $data['feedback']['headers'] = "$header_cat $header_row feedback";
645                 }
646                 // Contribution to the course total column.
647                 if ($this->showcontributiontocoursetotal) {
648                     $data['contributiontocoursetotal']['class'] = $class;
649                     $data['contributiontocoursetotal']['content'] = '-';
650                     $data['contributiontocoursetotal']['headers'] = "$header_cat $header_row contributiontocoursetotal";
652                     $hint['grademax'] = $grade_grade->grade_item->grademax;
653                     $hint['grademin'] = $grade_grade->grade_item->grademin;
654                     $hint['grade'] = $gradeval;
655                     $parent = $grade_object->load_parent_category();
656                     if ($grade_object->is_category_item()) {
657                         $parent = $parent->load_parent_category();
658                     }
659                     $hint['parent'] = $parent->load_grade_item()->id;
660                     $this->aggregationhints[$grade_grade->itemid] = $hint;
661                 }
662             }
663         }
665         /// Category
666         if ($type == 'category') {
667             $data['leader']['class'] = $class.' '.$alter."d$depth b1t b2b b1l";
668             $data['leader']['rowspan'] = $element['rowspan'];
670             if ($this->switch) { // alter style based on whether aggregation is first or last
671                $data['itemname']['class'] = $class.' '.$alter."d$depth b1b b1t";
672             } else {
673                $data['itemname']['class'] = $class.' '.$alter."d$depth b2t";
674             }
675             $data['itemname']['colspan'] = ($this->maxdepth - $depth + count($this->tablecolumns) - 1);
676             $data['itemname']['content'] = $fullname;
677             $data['itemname']['celltype'] = 'th';
678             $data['itemname']['id'] = "cat_{$grade_object->id}_{$this->user->id}";
679         }
681         /// Add this row to the overall system
682         foreach ($data as $key => $celldata) {
683             $data[$key]['class'] .= ' column-' . $key;
684         }
685         $this->tabledata[] = $data;
687         /// Recursively iterate through all child elements
688         if (isset($element['children'])) {
689             foreach ($element['children'] as $key=>$child) {
690                 $this->fill_table_recursive($element['children'][$key]);
691             }
692         }
694         // Check we are showing this column, and we are looking at the root of the table.
695         // This should be the very last thing this fill_table_recursive function does.
696         if ($this->showcontributiontocoursetotal && ($type == 'category' && $depth == 1)) {
697             // We should have collected all the hints by now - walk the tree again and build the contributions column.
699             $this->fill_contributions_column($element);
700         }
701     }
703     /**
704      * This function is called after the table has been built and the aggregationhints
705      * have been collected. We need this info to walk up the list of parents of each
706      * grade_item.
707      *
708      * @param $element - An array containing the table data for the current row.
709      */
710     public function fill_contributions_column($element) {
712         // Recursively iterate through all child elements.
713         if (isset($element['children'])) {
714             foreach ($element['children'] as $key=>$child) {
715                 $this->fill_contributions_column($element['children'][$key]);
716             }
717         } else if ($element['type'] == 'item') {
718             // This is a grade item (We don't do this for categories or we would double count).
719             $grade_object = $element['object'];
720             $itemid = $grade_object->id;
722             // Ignore anything with no hint - e.g. a hidden row.
723             if (isset($this->aggregationhints[$itemid])) {
725                 // Normalise the gradeval.
726                 $gradecat = $grade_object->load_parent_category();
727                 if ($gradecat->aggregation == GRADE_AGGREGATE_SUM) {
728                     // Natural aggregation/Sum of grades does not consider the mingrade, cannot traditionnally normalise it.
729                     $graderange = $this->aggregationhints[$itemid]['grademax'];
730                     $gradeval = $this->aggregationhints[$itemid]['grade'] / $graderange;
731                 } else {
732                     $gradeval = grade_grade::standardise_score($this->aggregationhints[$itemid]['grade'],
733                         $this->aggregationhints[$itemid]['grademin'], $this->aggregationhints[$itemid]['grademax'], 0, 1);
734                 }
736                 // Multiply the normalised value by the weight
737                 // of all the categories higher in the tree.
738                 do {
739                     if (!is_null($this->aggregationhints[$itemid]['weight'])) {
740                         $gradeval *= $this->aggregationhints[$itemid]['weight'];
741                     }
743                     // The second part of this if is to prevent infinite loops
744                     // in case of crazy data.
745                     if (isset($this->aggregationhints[$itemid]['parent']) &&
746                             $this->aggregationhints[$itemid]['parent'] != $itemid) {
747                         $parent = $this->aggregationhints[$itemid]['parent'];
748                         $itemid = $parent;
749                     } else {
750                         // We are at the top of the tree.
751                         $parent = false;
752                     }
753                 } while ($parent);
755                 // Convert to percent.
756                 $gradeval *= 100;
758                 // Now we need to loop through the "built" table data and update the
759                 // contributions column for the current row.
760                 $header_row = "row_{$grade_object->id}_{$this->user->id}";
761                 foreach ($this->tabledata as $key => $row) {
762                     if (isset($row['itemname']) && ($row['itemname']['id'] == $header_row)) {
763                         // Found it - update the column.
764                         $decimals = $grade_object->get_decimals();
765                         $this->tabledata[$key]['contributiontocoursetotal']['content'] = format_float($gradeval, $decimals, true) . ' %';
766                         break;
767                     }
768                 }
769             }
770         }
771     }
773     /**
774      * Prints or returns the HTML from the flexitable.
775      * @param bool $return Whether or not to return the data instead of printing it directly.
776      * @return string
777      */
778     public function print_table($return=false) {
779          $maxspan = $this->maxdepth;
781         /// Build table structure
782         $html = "
783             <table cellspacing='0'
784                    cellpadding='0'
785                    summary='" . s($this->get_lang_string('tablesummary', 'gradereport_user')) . "'
786                    class='boxaligncenter generaltable user-grade'>
787             <thead>
788                 <tr>
789                     <th id='".$this->tablecolumns[0]."' class=\"header column-{$this->tablecolumns[0]}\" colspan='$maxspan'>".$this->tableheaders[0]."</th>\n";
791         for ($i = 1; $i < count($this->tableheaders); $i++) {
792             $html .= "<th id='".$this->tablecolumns[$i]."' class=\"header column-{$this->tablecolumns[$i]}\">".$this->tableheaders[$i]."</th>\n";
793         }
795         $html .= "
796                 </tr>
797             </thead>
798             <tbody>\n";
800         /// Print out the table data
801         for ($i = 0; $i < count($this->tabledata); $i++) {
802             $html .= "<tr>\n";
803             if (isset($this->tabledata[$i]['leader'])) {
804                 $rowspan = $this->tabledata[$i]['leader']['rowspan'];
805                 $class = $this->tabledata[$i]['leader']['class'];
806                 $html .= "<td class='$class' rowspan='$rowspan'></td>\n";
807             }
808             for ($j = 0; $j < count($this->tablecolumns); $j++) {
809                 $name = $this->tablecolumns[$j];
810                 $class = (isset($this->tabledata[$i][$name]['class'])) ? $this->tabledata[$i][$name]['class'] : '';
811                 $colspan = (isset($this->tabledata[$i][$name]['colspan'])) ? "colspan='".$this->tabledata[$i][$name]['colspan']."'" : '';
812                 $content = (isset($this->tabledata[$i][$name]['content'])) ? $this->tabledata[$i][$name]['content'] : null;
813                 $celltype = (isset($this->tabledata[$i][$name]['celltype'])) ? $this->tabledata[$i][$name]['celltype'] : 'td';
814                 $id = (isset($this->tabledata[$i][$name]['id'])) ? "id='{$this->tabledata[$i][$name]['id']}'" : '';
815                 $headers = (isset($this->tabledata[$i][$name]['headers'])) ? "headers='{$this->tabledata[$i][$name]['headers']}'" : '';
816                 if (isset($content)) {
817                     $html .= "<$celltype $id $headers class='$class' $colspan>$content</$celltype>\n";
818                 }
819             }
820             $html .= "</tr>\n";
821         }
823         $html .= "</tbody></table>";
825         if ($return) {
826             return $html;
827         } else {
828             echo $html;
829         }
830     }
832     /**
833      * Processes the data sent by the form (grades and feedbacks).
834      * @var array $data
835      * @return bool Success or Failure (array of errors).
836      */
837     function process_data($data) {
838     }
839     function process_action($target, $action) {
840     }
842     /**
843      * Builds the grade item averages.
844      */
845     function calculate_averages() {
846         global $USER, $DB;
848         if ($this->showaverage) {
849             // This settings are actually grader report settings (not user report)
850             // however we're using them as having two separate but identical settings the
851             // user would have to keep in sync would be annoying.
852             $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
853             $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
854             $meanselection         = $this->get_pref('meanselection');
855             $shownumberofgrades    = $this->get_pref('shownumberofgrades');
857             $avghtml = '';
858             $groupsql = $this->groupsql;
859             $groupwheresql = $this->groupwheresql;
860             $totalcount = $this->get_numusers(false);
862             // We want to query both the current context and parent contexts.
863             list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
865             // Limit to users with a gradeable role ie students.
866             list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
868             // Limit to users with an active enrolment.
869             list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
871             $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams, $relatedctxparams);
872             $params['courseid'] = $this->courseid;
874             // find sums of all grade items in course
875             $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
876                       FROM {grade_items} gi
877                       JOIN {grade_grades} gg ON gg.itemid = gi.id
878                       JOIN {user} u ON u.id = gg.userid
879                       JOIN ($enrolledsql) je ON je.id = gg.userid
880                       JOIN (
881                                    SELECT DISTINCT ra.userid
882                                      FROM {role_assignments} ra
883                                     WHERE ra.roleid $gradebookrolessql
884                                       AND ra.contextid $relatedctxsql
885                            ) rainner ON rainner.userid = u.id
886                       $groupsql
887                      WHERE gi.courseid = :courseid
888                        AND u.deleted = 0
889                        AND gg.finalgrade IS NOT NULL
890                        AND gg.hidden = 0
891                        $groupwheresql
892                   GROUP BY gg.itemid";
894             $sum_array = array();
895             $sums = $DB->get_recordset_sql($sql, $params);
896             foreach ($sums as $itemid => $csum) {
897                 $sum_array[$itemid] = $csum->sum;
898             }
899             $sums->close();
901             $columncount=0;
903             // Empty grades must be evaluated as grademin, NOT always 0
904             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
905             // No join condition when joining grade_items and user to get a grade item row for every user
906             // Then left join with grade_grades and look for rows with null final grade (which includes grade items with no grade_grade)
907             $sql = "SELECT gi.id, COUNT(u.id) AS count
908                       FROM {grade_items} gi
909                       JOIN {user} u ON u.deleted = 0
910                       JOIN ($enrolledsql) je ON je.id = u.id
911                       JOIN (
912                                SELECT DISTINCT ra.userid
913                                  FROM {role_assignments} ra
914                                 WHERE ra.roleid $gradebookrolessql
915                                   AND ra.contextid $relatedctxsql
916                            ) rainner ON rainner.userid = u.id
917                       LEFT JOIN {grade_grades} gg
918                              ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL AND gg.hidden = 0)
919                       $groupsql
920                      WHERE gi.courseid = :courseid
921                            AND gg.finalgrade IS NULL
922                            $groupwheresql
923                   GROUP BY gi.id";
925             $ungraded_counts = $DB->get_records_sql($sql, $params);
927             foreach ($this->gtree->items as $itemid=>$unused) {
928                 if (!empty($this->gtree->items[$itemid]->avg)) {
929                     continue;
930                 }
931                 $item = $this->gtree->items[$itemid];
933                 if ($item->needsupdate) {
934                     $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
935                     continue;
936                 }
938                 if (empty($sum_array[$item->id])) {
939                     $sum_array[$item->id] = 0;
940                 }
942                 if (empty($ungraded_counts[$itemid])) {
943                     $ungraded_count = 0;
944                 } else {
945                     $ungraded_count = $ungraded_counts[$itemid]->count;
946                 }
948                 //do they want the averages to include all grade items
949                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
950                     $mean_count = $totalcount - $ungraded_count;
951                 } else { // Bump up the sum by the number of ungraded items * grademin
952                     $sum_array[$item->id] += ($ungraded_count * $item->grademin);
953                     $mean_count = $totalcount;
954                 }
956                 // Determine which display type to use for this average
957                 if (!empty($USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
958                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
960                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
961                     $displaytype = $item->get_displaytype();
963                 } else {
964                     $displaytype = $averagesdisplaytype;
965                 }
967                 // Override grade_item setting if a display preference (not inherit) was set for the averages
968                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
969                     $decimalpoints = $item->get_decimals();
970                 } else {
971                     $decimalpoints = $averagesdecimalpoints;
972                 }
974                 if (empty($sum_array[$item->id]) || $mean_count == 0) {
975                     $this->gtree->items[$itemid]->avg = '-';
976                 } else {
977                     $sum = $sum_array[$item->id];
978                     $avgradeval = $sum/$mean_count;
979                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
981                     $numberofgrades = '';
982                     if ($shownumberofgrades) {
983                         $numberofgrades = " ($mean_count)";
984                     }
986                     $this->gtree->items[$itemid]->avg = $gradehtml.$numberofgrades;
987                 }
988             }
989         }
990     }
993 function grade_report_user_settings_definition(&$mform) {
994     global $CFG;
996     $options = array(-1 => get_string('default', 'grades'),
997                       0 => get_string('hide'),
998                       1 => get_string('show'));
1000     if (empty($CFG->grade_report_user_showrank)) {
1001         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1002     } else {
1003         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1004     }
1006     $mform->addElement('select', 'report_user_showrank', get_string('showrank', 'grades'), $options);
1007     $mform->addHelpButton('report_user_showrank', 'showrank', 'grades');
1009     if (empty($CFG->grade_report_user_showpercentage)) {
1010         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1011     } else {
1012         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1013     }
1015     $mform->addElement('select', 'report_user_showpercentage', get_string('showpercentage', 'grades'), $options);
1016     $mform->addHelpButton('report_user_showpercentage', 'showpercentage', 'grades');
1018     if (empty($CFG->grade_report_user_showgrade)) {
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_showgrade', get_string('showgrade', 'grades'), $options);
1026     if (empty($CFG->grade_report_user_showfeedback)) {
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_showfeedback', get_string('showfeedback', 'grades'), $options);
1034     if (empty($CFG->grade_report_user_showweight)) {
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_showweight', get_string('showweight', 'grades'), $options);
1042     if (empty($CFG->grade_report_user_showaverage)) {
1043         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1044     } else {
1045         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1046     }
1048     $mform->addElement('select', 'report_user_showaverage', get_string('showaverage', 'grades'), $options);
1049     $mform->addHelpButton('report_user_showaverage', 'showaverage', 'grades');
1051     if (empty($CFG->grade_report_user_showlettergrade)) {
1052         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1053     } else {
1054         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1055     }
1057     $mform->addElement('select', 'report_user_showlettergrade', get_string('showlettergrade', 'grades'), $options);
1058     if (empty($CFG->grade_report_user_showcontributiontocoursetotal)) {
1059         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1060     } else {
1061         $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showcontributiontocoursetotal]);
1062     }
1064     $mform->addElement('select', 'report_user_showcontributiontocoursetotal', get_string('showcontributiontocoursetotal', 'grades'), $options);
1065     $mform->addHelpButton('report_user_showcontributiontocoursetotal', 'showcontributiontocoursetotal', 'grades');
1067     if (empty($CFG->grade_report_user_showrange)) {
1068         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1069     } else {
1070         $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1071     }
1073     $mform->addElement('select', 'report_user_showrange', get_string('showrange', 'grades'), $options);
1075     $options = array(0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5);
1076     if (! empty($CFG->grade_report_user_rangedecimals)) {
1077         $options[-1] = $options[$CFG->grade_report_user_rangedecimals];
1078     }
1079     $mform->addElement('select', 'report_user_rangedecimals', get_string('rangedecimals', 'grades'), $options);
1081     $options = array(-1 => get_string('default', 'grades'),
1082                       0 => get_string('shownohidden', 'grades'),
1083                       1 => get_string('showhiddenuntilonly', 'grades'),
1084                       2 => get_string('showallhidden', 'grades'));
1086     if (empty($CFG->grade_report_user_showhiddenitems)) {
1087         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1088     } else {
1089         $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showhiddenitems]);
1090     }
1092     $mform->addElement('select', 'report_user_showhiddenitems', get_string('showhiddenitems', 'grades'), $options);
1093     $mform->addHelpButton('report_user_showhiddenitems', 'showhiddenitems', 'grades');
1095     //showtotalsifcontainhidden
1096     $options = array(-1 => get_string('default', 'grades'),
1097                       GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN => get_string('hide'),
1098                       GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowexhiddenitems', 'grades'),
1099                       GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowinchiddenitems', 'grades') );
1101     if (empty($CFG->grade_report_user_showtotalsifcontainhidden)) {
1102         $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1103     } else {
1104         $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showtotalsifcontainhidden]);
1105     }
1107     $mform->addElement('select', 'report_user_showtotalsifcontainhidden', get_string('hidetotalifhiddenitems', 'grades'), $options);
1108     $mform->addHelpButton('report_user_showtotalsifcontainhidden', 'hidetotalifhiddenitems', 'grades');
1112 /**
1113  * Profile report callback.
1114  *
1115  * @param object $course The course.
1116  * @param object $user The user.
1117  * @param boolean $viewasuser True when we are viewing this as the targetted user sees it.
1118  */
1119 function grade_report_user_profilereport($course, $user, $viewasuser = false) {
1120     global $OUTPUT;
1121     if (!empty($course->showgrades)) {
1123         $context = context_course::instance($course->id);
1125         //first make sure we have proper final grades - this must be done before constructing of the grade tree
1126         grade_regrade_final_grades($course->id);
1128         /// return tracking object
1129         $gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'user', 'courseid'=>$course->id, 'userid'=>$user->id));
1130         // Create a report instance
1131         $report = new grade_report_user($course->id, $gpr, $context, $user->id, $viewasuser);
1133         // print the page
1134         echo '<div class="grade-report-user">'; // css fix to share styles with real report page
1135         echo $OUTPUT->heading(get_string('pluginname', 'gradereport_user'). ' - '.fullname($report->user));
1137         if ($report->fill_table()) {
1138             echo $report->print_table(true);
1139         }
1140         echo '</div>';
1141     }