Revert "MDL-33117 grade: adding unit tests for the user report function inject_rowspa...
[moodle.git] / grade / report / user / lib.php
blob1058c07f70559b034b5e6f41445bc5d49c682df5
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.
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
20 * @package gradereport_user
21 * @copyright 2007 Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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
38 class grade_report_user extends grade_report {
40 /**
41 * The user.
42 * @var object $user
44 public $user;
46 /**
47 * A flexitable to hold the data.
48 * @var object $table
50 public $table;
52 /**
53 * An array of table headers
54 * @var array
56 public $tableheaders = array();
58 /**
59 * An array of table columns
60 * @var array
62 public $tablecolumns = array();
64 /**
65 * An array containing rows of data for the table.
66 * @var type
68 public $tabledata = array();
70 /**
71 * The grade tree structure
72 * @var grade_tree
74 public $gtree;
76 /**
77 * Flat structure similar to grade tree
79 public $gseq;
81 /**
82 * show student ranks
84 public $showrank;
86 /**
87 * show grade percentages
89 public $showpercentage;
91 /**
92 * Show range
94 public $showrange = true;
96 /**
97 * Show grades in the report, default true
98 * @var bool
100 public $showgrade = true;
103 * Decimal points to use for values in the report, default 2
104 * @var int
106 public $decimals = 2;
109 * The number of decimal places to round range to, default 0
110 * @var int
112 public $rangedecimals = 0;
115 * Show grade feedback in the report, default true
116 * @var bool
118 public $showfeedback = true;
121 * Show grade weighting in the report, default false
122 * @var bool
124 public $showweight = false;
127 * Show letter grades in the report, default false
128 * @var bool
130 public $showlettergrade = false;
133 * Show average grades in the report, default false.
134 * @var false
136 public $showaverage = false;
138 public $maxdepth;
139 public $evenodd;
141 public $canviewhidden;
143 public $switch;
146 * Show hidden items even when user does not have required cap
148 public $showhiddenitems;
149 public $showtotalsifcontainhidden;
151 public $baseurl;
152 public $pbarurl;
155 * Constructor. Sets local copies of user preferences and initialises grade_tree.
156 * @param int $courseid
157 * @param object $gpr grade plugin return tracking object
158 * @param string $context
159 * @param int $userid The id of the user
161 public function __construct($courseid, $gpr, $context, $userid) {
162 global $DB, $CFG;
163 parent::__construct($courseid, $gpr, $context);
165 $this->showrank = grade_get_setting($this->courseid, 'report_user_showrank', $CFG->grade_report_user_showrank);
166 $this->showpercentage = grade_get_setting($this->courseid, 'report_user_showpercentage', $CFG->grade_report_user_showpercentage);
167 $this->showhiddenitems = grade_get_setting($this->courseid, 'report_user_showhiddenitems', $CFG->grade_report_user_showhiddenitems);
168 $this->showtotalsifcontainhidden = grade_get_setting($this->courseid, 'report_user_showtotalsifcontainhidden', $CFG->grade_report_user_showtotalsifcontainhidden);
170 $this->showgrade = grade_get_setting($this->courseid, 'report_user_showgrade', !empty($CFG->grade_report_user_showgrade));
171 $this->showrange = grade_get_setting($this->courseid, 'report_user_showrange', !empty($CFG->grade_report_user_showrange));
172 $this->showfeedback = grade_get_setting($this->courseid, 'report_user_showfeedback', !empty($CFG->grade_report_user_showfeedback));
173 $this->showweight = grade_get_setting($this->courseid, 'report_user_showweight', !empty($CFG->grade_report_user_showweight));
174 $this->showlettergrade = grade_get_setting($this->courseid, 'report_user_showlettergrade', !empty($CFG->grade_report_user_showlettergrade));
175 $this->showaverage = grade_get_setting($this->courseid, 'report_user_showaverage', !empty($CFG->grade_report_user_showaverage));
177 // The default grade decimals is 2
178 $defaultdecimals = 2;
179 if (property_exists($CFG, 'grade_decimalpoints')) {
180 $defaultdecimals = $CFG->grade_decimalpoints;
182 $this->decimals = grade_get_setting($this->courseid, 'decimalpoints', $defaultdecimals);
184 // The default range decimals is 0
185 $defaultrangedecimals = 0;
186 if (property_exists($CFG, 'grade_report_user_rangedecimals')) {
187 $defaultrangedecimals = $CFG->grade_report_user_rangedecimals;
189 $this->rangedecimals = grade_get_setting($this->courseid, 'report_user_rangedecimals', $defaultrangedecimals);
191 $this->switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
193 // Grab the grade_tree for this course
194 $this->gtree = new grade_tree($this->courseid, false, $this->switch, null, !$CFG->enableoutcomes);
196 // Determine the number of rows and indentation
197 $this->maxdepth = 1;
198 $this->inject_rowspans($this->gtree->top_element);
199 $this->maxdepth++; // Need to account for the lead column that spans all children
200 for ($i = 1; $i <= $this->maxdepth; $i++) {
201 $this->evenodd[$i] = 0;
204 $this->tabledata = array();
206 $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->courseid));
208 // get the user (for full name)
209 $this->user = $DB->get_record('user', array('id' => $userid));
211 // base url for sorting by first/last name
212 $this->baseurl = $CFG->wwwroot.'/grade/report?id='.$courseid.'&amp;userid='.$userid;
213 $this->pbarurl = $this->baseurl;
215 // no groups on this report - rank is from all course users
216 $this->setup_table();
218 //optionally calculate grade item averages
219 $this->calculate_averages();
222 function inject_rowspans(&$element) {
223 if ($element['depth'] > $this->maxdepth) {
224 $this->maxdepth = $element['depth'];
226 if (empty($element['children'])) {
227 return 1;
229 $count = 1;
230 foreach ($element['children'] as $key=>$child) {
231 $count += $this->inject_rowspans($element['children'][$key]);
233 $element['rowspan'] = $count;
234 return $count;
239 * Prepares the headers and attributes of the flexitable.
241 public function setup_table() {
243 * Table has 1-8 columns
244 *| All columns except for itemname/description are optional
247 // setting up table headers
249 $this->tablecolumns = array('itemname');
250 $this->tableheaders = array($this->get_lang_string('gradeitem', 'grades'));
252 if ($this->showweight) {
253 $this->tablecolumns[] = 'weight';
254 $this->tableheaders[] = $this->get_lang_string('weightuc', 'grades');
257 if ($this->showgrade) {
258 $this->tablecolumns[] = 'grade';
259 $this->tableheaders[] = $this->get_lang_string('grade', 'grades');
262 if ($this->showrange) {
263 $this->tablecolumns[] = 'range';
264 $this->tableheaders[] = $this->get_lang_string('range', 'grades');
267 if ($this->showpercentage) {
268 $this->tablecolumns[] = 'percentage';
269 $this->tableheaders[] = $this->get_lang_string('percentage', 'grades');
272 if ($this->showlettergrade) {
273 $this->tablecolumns[] = 'lettergrade';
274 $this->tableheaders[] = $this->get_lang_string('lettergrade', 'grades');
277 if ($this->showrank) {
278 $this->tablecolumns[] = 'rank';
279 $this->tableheaders[] = $this->get_lang_string('rank', 'grades');
282 if ($this->showaverage) {
283 $this->tablecolumns[] = 'average';
284 $this->tableheaders[] = $this->get_lang_string('average', 'grades');
287 if ($this->showfeedback) {
288 $this->tablecolumns[] = 'feedback';
289 $this->tableheaders[] = $this->get_lang_string('feedback', 'grades');
293 function fill_table() {
294 //print "<pre>";
295 //print_r($this->gtree->top_element);
296 $this->fill_table_recursive($this->gtree->top_element);
297 //print_r($this->tabledata);
298 //print "</pre>";
299 return true;
302 private function fill_table_recursive(&$element) {
303 global $DB, $CFG;
305 $type = $element['type'];
306 $depth = $element['depth'];
307 $grade_object = $element['object'];
308 $eid = $grade_object->id;
309 $element['userid'] = $this->user->id;
310 $fullname = $this->gtree->get_element_header($element, true, true, true);
311 $data = array();
312 $hidden = '';
313 $excluded = '';
314 $class = '';
315 $classfeedback = '';
317 // If this is a hidden grade category, hide it completely from the user
318 if ($type == 'category' && $grade_object->is_hidden() && !$this->canviewhidden && (
319 $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
320 ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_object->is_hiddenuntil()))) {
321 return false;
324 if ($type == 'category') {
325 $this->evenodd[$depth] = (($this->evenodd[$depth] + 1) % 2);
327 $alter = ($this->evenodd[$depth] == 0) ? 'even' : 'odd';
329 /// Process those items that have scores associated
330 if ($type == 'item' or $type == 'categoryitem' or $type == 'courseitem') {
331 if (! $grade_grade = grade_grade::fetch(array('itemid'=>$grade_object->id,'userid'=>$this->user->id))) {
332 $grade_grade = new grade_grade();
333 $grade_grade->userid = $this->user->id;
334 $grade_grade->itemid = $grade_object->id;
337 $grade_grade->load_grade_item();
339 /// Hidden Items
340 if ($grade_grade->grade_item->is_hidden()) {
341 $hidden = ' hidden';
344 $hide = false;
345 // If this is a hidden grade item, hide it completely from the user.
346 if ($grade_grade->is_hidden() && !$this->canviewhidden && (
347 $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
348 ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_grade->is_hiddenuntil()))) {
349 $hide = true;
350 } else if (!empty($grade_object->itemmodule) && !empty($grade_object->iteminstance)) {
351 // The grade object can be marked visible but still be hidden if...
352 // 1) "enablegroupmembersonly" is on and the activity is assigned to a grouping the user is not in.
353 // 2) the student cannot see the activity due to conditional access and its set to be hidden entirely.
354 $instances = $this->gtree->modinfo->get_instances_of($grade_object->itemmodule);
355 if (!empty($instances[$grade_object->iteminstance])) {
356 $cm = $instances[$grade_object->iteminstance];
357 if (!$cm->uservisible) {
358 // Further checks are required to determine whether the activity is entirely hidden or just greyed out.
359 if ($cm->is_user_access_restricted_by_group() || $cm->is_user_access_restricted_by_conditional_access()) {
360 $hide = true;
366 if (!$hide) {
367 /// Excluded Item
368 if ($grade_grade->is_excluded()) {
369 $fullname .= ' ['.get_string('excluded', 'grades').']';
370 $excluded = ' excluded';
373 /// Other class information
374 $class = "$hidden $excluded";
375 if ($this->switch) { // alter style based on whether aggregation is first or last
376 $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggt b2b" : " item b1b";
377 } else {
378 $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggb" : " item b1b";
381 /// Name
382 $data['itemname']['content'] = $fullname;
383 $data['itemname']['class'] = $class;
384 $data['itemname']['colspan'] = ($this->maxdepth - $depth);
386 /// Actual Grade
387 $gradeval = $grade_grade->finalgrade;
389 if ($this->showfeedback) {
390 // Copy $class before appending itemcenter as feedback should not be centered
391 $classfeedback = $class;
393 $class .= " itemcenter ";
394 if ($this->showweight) {
395 $data['weight']['class'] = $class;
396 $data['weight']['content'] = '-';
397 // has a weight assigned, might be extra credit
398 if ($grade_object->aggregationcoef > 0 && $type <> 'courseitem') {
399 $data['weight']['content'] = number_format($grade_object->aggregationcoef,2).'%';
403 if ($this->showgrade) {
404 if ($grade_grade->grade_item->needsupdate) {
405 $data['grade']['class'] = $class.' gradingerror';
406 $data['grade']['content'] = get_string('error');
407 } else if (!empty($CFG->grade_hiddenasdate) and $grade_grade->get_datesubmitted() and !$this->canviewhidden and $grade_grade->is_hidden()
408 and !$grade_grade->grade_item->is_category_item() and !$grade_grade->grade_item->is_course_item()) {
409 // 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
410 $class .= ' datesubmitted';
411 $data['grade']['class'] = $class;
412 $data['grade']['content'] = get_string('submittedon', 'grades', userdate($grade_grade->get_datesubmitted(), get_string('strftimedatetimeshort')));
414 } elseif ($grade_grade->is_hidden()) {
415 $data['grade']['class'] = $class.' hidden';
416 $data['grade']['content'] = '-';
417 } else {
418 $data['grade']['class'] = $class;
419 $gradeval = $this->blank_hidden_total($this->courseid, $grade_grade->grade_item, $gradeval);
420 $data['grade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true);
424 // Range
425 if ($this->showrange) {
426 $data['range']['class'] = $class;
427 $data['range']['content'] = $grade_grade->grade_item->get_formatted_range(GRADE_DISPLAY_TYPE_REAL, $this->rangedecimals);
430 // Percentage
431 if ($this->showpercentage) {
432 if ($grade_grade->grade_item->needsupdate) {
433 $data['percentage']['class'] = $class.' gradingerror';
434 $data['percentage']['content'] = get_string('error');
435 } else if ($grade_grade->is_hidden()) {
436 $data['percentage']['class'] = $class.' hidden';
437 $data['percentage']['content'] = '-';
438 } else {
439 $data['percentage']['class'] = $class;
440 $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
444 // Lettergrade
445 if ($this->showlettergrade) {
446 if ($grade_grade->grade_item->needsupdate) {
447 $data['lettergrade']['class'] = $class.' gradingerror';
448 $data['lettergrade']['content'] = get_string('error');
449 } else if ($grade_grade->is_hidden()) {
450 $data['lettergrade']['class'] = $class.' hidden';
451 if (!$this->canviewhidden) {
452 $data['lettergrade']['content'] = '-';
453 } else {
454 $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
456 } else {
457 $data['lettergrade']['class'] = $class;
458 $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
462 // Rank
463 if ($this->showrank) {
464 if ($grade_grade->grade_item->needsupdate) {
465 $data['rank']['class'] = $class.' gradingerror';
466 $data['rank']['content'] = get_string('error');
467 } elseif ($grade_grade->is_hidden()) {
468 $data['rank']['class'] = $class.' hidden';
469 $data['rank']['content'] = '-';
470 } else if (is_null($gradeval)) {
471 // no grade, no rank
472 $data['rank']['class'] = $class;
473 $data['rank']['content'] = '-';
475 } else {
476 /// find the number of users with a higher grade
477 $sql = "SELECT COUNT(DISTINCT(userid))
478 FROM {grade_grades}
479 WHERE finalgrade > ?
480 AND itemid = ?
481 AND hidden = 0";
482 $rank = $DB->count_records_sql($sql, array($grade_grade->finalgrade, $grade_grade->grade_item->id)) + 1;
484 $data['rank']['class'] = $class;
485 $data['rank']['content'] = "$rank/".$this->get_numusers(false); // total course users
489 // Average
490 if ($this->showaverage) {
491 $data['average']['class'] = $class;
492 if (!empty($this->gtree->items[$eid]->avg)) {
493 $data['average']['content'] = $this->gtree->items[$eid]->avg;
494 } else {
495 $data['average']['content'] = '-';
499 // Feedback
500 if ($this->showfeedback) {
501 if ($grade_grade->overridden > 0 AND ($type == 'categoryitem' OR $type == 'courseitem')) {
502 $data['feedback']['class'] = $classfeedback.' feedbacktext';
503 $data['feedback']['content'] = get_string('overridden', 'grades').': ' . format_text($grade_grade->feedback, $grade_grade->feedbackformat);
504 } else if (empty($grade_grade->feedback) or (!$this->canviewhidden and $grade_grade->is_hidden())) {
505 $data['feedback']['class'] = $classfeedback.' feedbacktext';
506 $data['feedback']['content'] = '&nbsp;';
507 } else {
508 $data['feedback']['class'] = $classfeedback.' feedbacktext';
509 $data['feedback']['content'] = format_text($grade_grade->feedback, $grade_grade->feedbackformat);
515 /// Category
516 if ($type == 'category') {
517 $data['leader']['class'] = $class.' '.$alter."d$depth b1t b2b b1l";
518 $data['leader']['rowspan'] = $element['rowspan'];
520 if ($this->switch) { // alter style based on whether aggregation is first or last
521 $data['itemname']['class'] = $class.' '.$alter."d$depth b1b b1t";
522 } else {
523 $data['itemname']['class'] = $class.' '.$alter."d$depth b2t";
525 $data['itemname']['colspan'] = ($this->maxdepth - $depth + count($this->tablecolumns) - 1);
526 $data['itemname']['content'] = $fullname;
529 /// Add this row to the overall system
530 $this->tabledata[] = $data;
532 /// Recursively iterate through all child elements
533 if (isset($element['children'])) {
534 foreach ($element['children'] as $key=>$child) {
535 $this->fill_table_recursive($element['children'][$key]);
541 * Prints or returns the HTML from the flexitable.
542 * @param bool $return Whether or not to return the data instead of printing it directly.
543 * @return string
545 public function print_table($return=false) {
546 $maxspan = $this->maxdepth;
548 /// Build table structure
549 $html = "
550 <table cellspacing='0' cellpadding='0' class='boxaligncenter generaltable user-grade'>
551 <thead>
552 <tr>
553 <th class=\"header\" colspan='$maxspan'>".$this->tableheaders[0]."</th>\n";
555 for ($i = 1; $i < count($this->tableheaders); $i++) {
556 $html .= "<th class=\"header\">".$this->tableheaders[$i]."</th>\n";
559 $html .= "
560 </tr>
561 </thead>
562 <tbody>\n";
564 /// Print out the table data
565 for ($i = 0; $i < count($this->tabledata); $i++) {
566 $html .= "<tr>\n";
567 if (isset($this->tabledata[$i]['leader'])) {
568 $rowspan = $this->tabledata[$i]['leader']['rowspan'];
569 $class = $this->tabledata[$i]['leader']['class'];
570 $html .= "<td class='$class' rowspan='$rowspan'></td>\n";
572 for ($j = 0; $j < count($this->tablecolumns); $j++) {
573 $name = $this->tablecolumns[$j];
574 $class = (isset($this->tabledata[$i][$name]['class'])) ? $this->tabledata[$i][$name]['class'] : '';
575 $colspan = (isset($this->tabledata[$i][$name]['colspan'])) ? "colspan='".$this->tabledata[$i][$name]['colspan']."'" : '';
576 $content = (isset($this->tabledata[$i][$name]['content'])) ? $this->tabledata[$i][$name]['content'] : null;
577 if (isset($content)) {
578 $html .= "<td class='$class' $colspan>$content</td>\n";
581 $html .= "</tr>\n";
584 $html .= "</tbody></table>";
586 if ($return) {
587 return $html;
588 } else {
589 echo $html;
594 * Processes the data sent by the form (grades and feedbacks).
595 * @var array $data
596 * @return bool Success or Failure (array of errors).
598 function process_data($data) {
600 function process_action($target, $action) {
604 * Builds the grade item averages.
607 function calculate_averages() {
608 global $USER, $DB;
610 if ($this->showaverage) {
611 // this settings are actually grader report settings (not user report)
612 // however we're using them as having two separate but identical settings the
613 // user would have to keep in sync would be annoying
614 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
615 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
616 $meanselection = $this->get_pref('meanselection');
617 $shownumberofgrades = $this->get_pref('shownumberofgrades');
619 $avghtml = '';
620 $avgcssclass = 'avg';
622 $straverage = get_string('overallaverage', 'grades');
624 $groupsql = $this->groupsql;
625 $groupwheresql = $this->groupwheresql;
626 //$groupwheresqlparams = ;
628 if ($shownumberofgrades) {
629 $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
632 $totalcount = $this->get_numusers(false);
634 //limit to users with a gradeable role ie students
635 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
637 //limit to users with an active enrolment
638 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
640 $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams);
641 $params['courseid'] = $this->courseid;
643 // find sums of all grade items in course
644 $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
645 FROM {grade_items} gi
646 JOIN {grade_grades} gg ON gg.itemid = gi.id
647 JOIN {user} u ON u.id = gg.userid
648 JOIN ($enrolledsql) je ON je.id = gg.userid
649 JOIN (
650 SELECT DISTINCT ra.userid
651 FROM {role_assignments} ra
652 WHERE ra.roleid $gradebookrolessql
653 AND ra.contextid " . get_related_contexts_string($this->context) . "
654 ) rainner ON rainner.userid = u.id
655 $groupsql
656 WHERE gi.courseid = :courseid
657 AND u.deleted = 0
658 AND gg.finalgrade IS NOT NULL
659 AND gg.hidden = 0
660 $groupwheresql
661 GROUP BY gg.itemid";
663 $sum_array = array();
664 $sums = $DB->get_recordset_sql($sql, $params);
665 foreach ($sums as $itemid => $csum) {
666 $sum_array[$itemid] = $csum->sum;
668 $sums->close();
670 $columncount=0;
672 // Empty grades must be evaluated as grademin, NOT always 0
673 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
674 // No join condition when joining grade_items and user to get a grade item row for every user
675 // Then left join with grade_grades and look for rows with null final grade (which includes grade items with no grade_grade)
676 $sql = "SELECT gi.id, COUNT(u.id) AS count
677 FROM {grade_items} gi
678 JOIN {user} u ON u.deleted = 0
679 JOIN ($enrolledsql) je ON je.id = u.id
680 JOIN (
681 SELECT DISTINCT ra.userid
682 FROM {role_assignments} ra
683 WHERE ra.roleid $gradebookrolessql
684 AND ra.contextid " . get_related_contexts_string($this->context) . "
685 ) rainner ON rainner.userid = u.id
686 LEFT JOIN {grade_grades} gg
687 ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL AND gg.hidden = 0)
688 $groupsql
689 WHERE gi.courseid = :courseid
690 AND gg.finalgrade IS NULL
691 $groupwheresql
692 GROUP BY gi.id";
694 $ungraded_counts = $DB->get_records_sql($sql, $params);
696 foreach ($this->gtree->items as $itemid=>$unused) {
697 if (!empty($this->gtree->items[$itemid]->avg)) {
698 continue;
700 $item = $this->gtree->items[$itemid];
702 if ($item->needsupdate) {
703 $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
704 continue;
707 if (empty($sum_array[$item->id])) {
708 $sum_array[$item->id] = 0;
711 if (empty($ungraded_counts[$itemid])) {
712 $ungraded_count = 0;
713 } else {
714 $ungraded_count = $ungraded_counts[$itemid]->count;
717 //do they want the averages to include all grade items
718 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
719 $mean_count = $totalcount - $ungraded_count;
720 } else { // Bump up the sum by the number of ungraded items * grademin
721 $sum_array[$item->id] += ($ungraded_count * $item->grademin);
722 $mean_count = $totalcount;
725 $decimalpoints = $item->get_decimals();
727 // Determine which display type to use for this average
728 if (!empty($USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
729 $displaytype = GRADE_DISPLAY_TYPE_REAL;
731 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
732 $displaytype = $item->get_displaytype();
734 } else {
735 $displaytype = $averagesdisplaytype;
738 // Override grade_item setting if a display preference (not inherit) was set for the averages
739 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
740 $decimalpoints = $item->get_decimals();
742 } else {
743 $decimalpoints = $averagesdecimalpoints;
746 if (empty($sum_array[$item->id]) || $mean_count == 0) {
747 $this->gtree->items[$itemid]->avg = '-';
748 } else {
749 $sum = $sum_array[$item->id];
750 $avgradeval = $sum/$mean_count;
751 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
753 $numberofgrades = '';
754 if ($shownumberofgrades) {
755 $numberofgrades = " ($mean_count)";
758 $this->gtree->items[$itemid]->avg = $gradehtml.$numberofgrades;
765 function grade_report_user_settings_definition(&$mform) {
766 global $CFG;
768 $options = array(-1 => get_string('default', 'grades'),
769 0 => get_string('hide'),
770 1 => get_string('show'));
772 if (empty($CFG->grade_report_user_showrank)) {
773 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
774 } else {
775 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
778 $mform->addElement('select', 'report_user_showrank', get_string('showrank', 'grades'), $options);
779 $mform->addHelpButton('report_user_showrank', 'showrank', 'grades');
781 if (empty($CFG->grade_report_user_showpercentage)) {
782 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
783 } else {
784 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
787 $mform->addElement('select', 'report_user_showpercentage', get_string('showpercentage', 'grades'), $options);
788 $mform->addHelpButton('report_user_showpercentage', 'showpercentage', 'grades');
790 if (empty($CFG->grade_report_user_showgrade)) {
791 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
792 } else {
793 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
796 $mform->addElement('select', 'report_user_showgrade', get_string('showgrade', 'grades'), $options);
798 if (empty($CFG->grade_report_user_showfeedback)) {
799 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
800 } else {
801 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
804 $mform->addElement('select', 'report_user_showfeedback', get_string('showfeedback', 'grades'), $options);
806 if (empty($CFG->grade_report_user_showweight)) {
807 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
808 } else {
809 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
812 $mform->addElement('select', 'report_user_showweight', get_string('showweight', 'grades'), $options);
814 if (empty($CFG->grade_report_user_showaverage)) {
815 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
816 } else {
817 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
820 $mform->addElement('select', 'report_user_showaverage', get_string('showaverage', 'grades'), $options);
821 $mform->addHelpButton('report_user_showaverage', 'showaverage', 'grades');
823 if (empty($CFG->grade_report_user_showlettergrade)) {
824 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
825 } else {
826 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
829 $mform->addElement('select', 'report_user_showlettergrade', get_string('showlettergrade', 'grades'), $options);
831 if (empty($CFG->grade_report_user_showrange)) {
832 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
833 } else {
834 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
837 $mform->addElement('select', 'report_user_showrange', get_string('showrange', 'grades'), $options);
839 $options = array(0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5);
840 if (! empty($CFG->grade_report_user_rangedecimals)) {
841 $options[-1] = $options[$CFG->grade_report_user_rangedecimals];
843 $mform->addElement('select', 'report_user_rangedecimals', get_string('rangedecimals', 'grades'), $options);
845 $options = array(-1 => get_string('default', 'grades'),
846 0 => get_string('shownohidden', 'grades'),
847 1 => get_string('showhiddenuntilonly', 'grades'),
848 2 => get_string('showallhidden', 'grades'));
850 if (empty($CFG->grade_report_user_showhiddenitems)) {
851 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
852 } else {
853 $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showhiddenitems]);
856 $mform->addElement('select', 'report_user_showhiddenitems', get_string('showhiddenitems', 'grades'), $options);
857 $mform->addHelpButton('report_user_showhiddenitems', 'showhiddenitems', 'grades');
859 //showtotalsifcontainhidden
860 $options = array(-1 => get_string('default', 'grades'),
861 GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN => get_string('hide'),
862 GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowexhiddenitems', 'grades'),
863 GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowinchiddenitems', 'grades') );
865 if (empty($CFG->grade_report_user_showtotalsifcontainhidden)) {
866 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
867 } else {
868 $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showtotalsifcontainhidden]);
871 $mform->addElement('select', 'report_user_showtotalsifcontainhidden', get_string('hidetotalifhiddenitems', 'grades'), $options);
872 $mform->addHelpButton('report_user_showtotalsifcontainhidden', 'hidetotalifhiddenitems', 'grades');
875 function grade_report_user_profilereport($course, $user) {
876 global $OUTPUT;
877 if (!empty($course->showgrades)) {
879 $context = get_context_instance(CONTEXT_COURSE, $course->id);
881 //first make sure we have proper final grades - this must be done before constructing of the grade tree
882 grade_regrade_final_grades($course->id);
884 /// return tracking object
885 $gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'user', 'courseid'=>$course->id, 'userid'=>$user->id));
886 // Create a report instance
887 $report = new grade_report_user($course->id, $gpr, $context, $user->id);
889 // print the page
890 echo '<div class="grade-report-user">'; // css fix to share styles with real report page
891 echo $OUTPUT->heading(get_string('pluginname', 'gradereport_user'). ' - '.fullname($report->user));
893 if ($report->fill_table()) {
894 echo $report->print_table(true);
896 echo '</div>';