MDL-30085 core_grades functions moved to correct location
[moodle.git] / grade / report / user / lib.php
CommitLineData
e060e33d 1<?php
e060e33d 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/>.
8ad36f4c 16
f7998fbc 17/**
a153c9f2
AD
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
f7998fbc 23 */
24
25require_once($CFG->dirroot . '/grade/report/lib.php');
26require_once($CFG->libdir.'/tablelib.php');
27
a83507f2
AD
28//showhiddenitems values
29define("GRADE_REPORT_USER_HIDE_HIDDEN", 0);
30define("GRADE_REPORT_USER_HIDE_UNTIL", 1);
31define("GRADE_REPORT_USER_SHOW_HIDDEN", 2);
32
f7998fbc 33/**
34 * Class providing an API for the user report building and displaying.
35 * @uses grade_report
a153c9f2 36 * @package gradereport_user
f7998fbc 37 */
38class grade_report_user extends grade_report {
39
40 /**
41 * The user.
42 * @var object $user
43 */
5c75a0a3 44 public $user;
f7998fbc 45
46 /**
47 * A flexitable to hold the data.
48 * @var object $table
49 */
5c75a0a3 50 public $table;
f7998fbc 51
a071dbb6 52 /**
53 * An array of table headers
54 * @var array
55 */
56 public $tableheaders = array();
57
58 /**
59 * An array of table columns
60 * @var array
61 */
62 public $tablecolumns = array();
63
64 /**
65 * An array containing rows of data for the table.
66 * @var type
67 */
68 public $tabledata = array();
69
70 /**
71 * The grade tree structure
72 * @var grade_tree
73 */
74 public $gtree;
653a8648 75
e0724506 76 /**
77 * Flat structure similar to grade tree
78 */
5c75a0a3 79 public $gseq;
e0724506 80
26ed0305 81 /**
82 * show student ranks
83 */
5c75a0a3 84 public $showrank;
26ed0305 85
699da6b5 86 /**
87 * show grade percentages
88 */
89 public $showpercentage;
90
5528217e 91 /**
92 * Show range
93 */
a071dbb6 94 public $showrange = true;
5528217e 95
a071dbb6 96 /**
97 * Show grades in the report, default true
98 * @var bool
99 */
100 public $showgrade = true;
5528217e 101
a071dbb6 102 /**
103 * Decimal points to use for values in the report, default 2
104 * @var int
105 */
106 public $decimals = 2;
5528217e 107
a071dbb6 108 /**
109 * The number of decimal places to round range to, default 0
110 * @var int
111 */
112 public $rangedecimals = 0;
5528217e 113
a071dbb6 114 /**
115 * Show grade feedback in the report, default true
116 * @var bool
117 */
118 public $showfeedback = true;
119
120 /**
121 * Show grade weighting in the report, default false
122 * @var bool
123 */
124 public $showweight = false;
125
126 /**
127 * Show letter grades in the report, default false
128 * @var bool
129 */
130 public $showlettergrade = false;
131
132 /**
133 * Show average grades in the report, default false.
134 * @var false
135 */
136 public $showaverage = false;
137
138 public $maxdepth;
139 public $evenodd;
140
141 public $canviewhidden;
142
143 public $switch;
5528217e 144
26ed0305 145 /**
146 * Show hidden items even when user does not have required cap
147 */
5c75a0a3 148 public $showhiddenitems;
a071dbb6 149 public $showtotalsifcontainhidden;
150
151 public $baseurl;
152 public $pbarurl;
26ed0305 153
f7998fbc 154 /**
155 * Constructor. Sets local copies of user preferences and initialises grade_tree.
156 * @param int $courseid
d30c4481 157 * @param object $gpr grade plugin return tracking object
f7998fbc 158 * @param string $context
159 * @param int $userid The id of the user
160 */
5c75a0a3 161 public function __construct($courseid, $gpr, $context, $userid) {
a071dbb6 162 global $DB, $CFG;
5c75a0a3 163 parent::__construct($courseid, $gpr, $context);
f7998fbc 164
597f50e6 165 $this->showrank = grade_get_setting($this->courseid, 'report_user_showrank', $CFG->grade_report_user_showrank);
699da6b5 166 $this->showpercentage = grade_get_setting($this->courseid, 'report_user_showpercentage', $CFG->grade_report_user_showpercentage);
597f50e6 167 $this->showhiddenitems = grade_get_setting($this->courseid, 'report_user_showhiddenitems', $CFG->grade_report_user_showhiddenitems);
5df9bc39 168 $this->showtotalsifcontainhidden = array($this->courseid => grade_get_setting($this->courseid, 'report_user_showtotalsifcontainhidden', $CFG->grade_report_user_showtotalsifcontainhidden));
653a8648 169
a071dbb6 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));
176
177 // The default grade decimals is 2
178 $defaultdecimals = 2;
179 if (property_exists($CFG, 'grade_decimalpoints')) {
180 $defaultdecimals = $CFG->grade_decimalpoints;
181 }
182 $this->decimals = grade_get_setting($this->courseid, 'decimalpoints', $defaultdecimals);
183
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;
188 }
189 $this->rangedecimals = grade_get_setting($this->courseid, 'report_user_rangedecimals', $defaultrangedecimals);
190
5528217e 191 $this->switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
192
193 // Grab the grade_tree for this course
4d27bc79 194 $this->gtree = new grade_tree($this->courseid, false, $this->switch, null, !$CFG->enableoutcomes);
26ed0305 195
5528217e 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;
202 }
203
204 $this->tabledata = array();
e0724506 205
d4060472 206 $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->courseid));
4faf5f99 207
f7998fbc 208 // get the user (for full name)
5c75a0a3 209 $this->user = $DB->get_record('user', array('id' => $userid));
f7998fbc 210
211 // base url for sorting by first/last name
212 $this->baseurl = $CFG->wwwroot.'/grade/report?id='.$courseid.'&amp;userid='.$userid;
90d3960c 213 $this->pbarurl = $this->baseurl;
f7998fbc 214
d1214909 215 // no groups on this report - rank is from all course users
90d3960c 216 $this->setup_table();
a071dbb6 217
218 //optionally calculate grade item averages
219 $this->calculate_averages();
f7998fbc 220 }
221
10d8f085
AD
222 /**
223 * Recurses through a tree of elements setting the rowspan property on each element
224 *
225 * @param array $element Either the top element or, during recursion, the current element
226 * @return int The number of elements processed
227 */
5528217e 228 function inject_rowspans(&$element) {
10d8f085 229
5528217e 230 if ($element['depth'] > $this->maxdepth) {
231 $this->maxdepth = $element['depth'];
232 }
233 if (empty($element['children'])) {
234 return 1;
235 }
236 $count = 1;
10d8f085 237
5528217e 238 foreach ($element['children'] as $key=>$child) {
239 $count += $this->inject_rowspans($element['children'][$key]);
240 }
10d8f085 241
5528217e 242 $element['rowspan'] = $count;
243 return $count;
244 }
245
246
f7998fbc 247 /**
248 * Prepares the headers and attributes of the flexitable.
249 */
5c75a0a3 250 public function setup_table() {
f7998fbc 251 /*
a071dbb6 252 * Table has 1-8 columns
253 *| All columns except for itemname/description are optional
d1214909 254 */
f7998fbc 255
256 // setting up table headers
a071dbb6 257
258 $this->tablecolumns = array('itemname');
259 $this->tableheaders = array($this->get_lang_string('gradeitem', 'grades'));
260
261 if ($this->showweight) {
262 $this->tablecolumns[] = 'weight';
263 $this->tableheaders[] = $this->get_lang_string('weightuc', 'grades');
264 }
265
266 if ($this->showgrade) {
267 $this->tablecolumns[] = 'grade';
268 $this->tableheaders[] = $this->get_lang_string('grade', 'grades');
269 }
699da6b5 270
5528217e 271 if ($this->showrange) {
272 $this->tablecolumns[] = 'range';
273 $this->tableheaders[] = $this->get_lang_string('range', 'grades');
274 }
275
699da6b5 276 if ($this->showpercentage) {
5528217e 277 $this->tablecolumns[] = 'percentage';
278 $this->tableheaders[] = $this->get_lang_string('percentage', 'grades');
699da6b5 279 }
280
a071dbb6 281 if ($this->showlettergrade) {
282 $this->tablecolumns[] = 'lettergrade';
283 $this->tableheaders[] = $this->get_lang_string('lettergrade', 'grades');
284 }
285
26ed0305 286 if ($this->showrank) {
5528217e 287 $this->tablecolumns[] = 'rank';
288 $this->tableheaders[] = $this->get_lang_string('rank', 'grades');
02973505 289 }
f7998fbc 290
a071dbb6 291 if ($this->showaverage) {
292 $this->tablecolumns[] = 'average';
293 $this->tableheaders[] = $this->get_lang_string('average', 'grades');
294 }
f7998fbc 295
a071dbb6 296 if ($this->showfeedback) {
297 $this->tablecolumns[] = 'feedback';
298 $this->tableheaders[] = $this->get_lang_string('feedback', 'grades');
299 }
5528217e 300 }
f7998fbc 301
5528217e 302 function fill_table() {
303 //print "<pre>";
304 //print_r($this->gtree->top_element);
305 $this->fill_table_recursive($this->gtree->top_element);
306 //print_r($this->tabledata);
307 //print "</pre>";
308 return true;
f7998fbc 309 }
310
5528217e 311 private function fill_table_recursive(&$element) {
a071dbb6 312 global $DB, $CFG;
f7998fbc 313
5528217e 314 $type = $element['type'];
315 $depth = $element['depth'];
316 $grade_object = $element['object'];
317 $eid = $grade_object->id;
c97933ff 318 $element['userid'] = $this->user->id;
5528217e 319 $fullname = $this->gtree->get_element_header($element, true, true, true);
320 $data = array();
321 $hidden = '';
322 $excluded = '';
323 $class = '';
62a966ad 324 $classfeedback = '';
f7998fbc 325
a83507f2 326 // If this is a hidden grade category, hide it completely from the user
9e322c8c 327 if ($type == 'category' && $grade_object->is_hidden() && !$this->canviewhidden && (
a83507f2
AD
328 $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
329 ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_object->is_hiddenuntil()))) {
653a8648 330 return false;
331 }
6391ebe7 332
5528217e 333 if ($type == 'category') {
334 $this->evenodd[$depth] = (($this->evenodd[$depth] + 1) % 2);
b89a70ce 335 }
5528217e 336 $alter = ($this->evenodd[$depth] == 0) ? 'even' : 'odd';
6391ebe7 337
5528217e 338 /// Process those items that have scores associated
339 if ($type == 'item' or $type == 'categoryitem' or $type == 'courseitem') {
f19dd840
SB
340 $header_row = "row_{$eid}_{$this->user->id}";
341 $header_cat = "cat_{$grade_object->categoryid}_{$this->user->id}";
342
5528217e 343 if (! $grade_grade = grade_grade::fetch(array('itemid'=>$grade_object->id,'userid'=>$this->user->id))) {
344 $grade_grade = new grade_grade();
345 $grade_grade->userid = $this->user->id;
346 $grade_grade->itemid = $grade_object->id;
d297269d 347 }
6391ebe7 348
5528217e 349 $grade_grade->load_grade_item();
f7998fbc 350
5528217e 351 /// Hidden Items
352 if ($grade_grade->grade_item->is_hidden()) {
353 $hidden = ' hidden';
ced5ee59 354 }
355
5fee56d5 356 $hide = false;
a83507f2 357 // If this is a hidden grade item, hide it completely from the user.
653a8648 358 if ($grade_grade->is_hidden() && !$this->canviewhidden && (
a83507f2
AD
359 $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
360 ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_grade->is_hiddenuntil()))) {
5fee56d5
FM
361 $hide = true;
362 } else if (!empty($grade_object->itemmodule) && !empty($grade_object->iteminstance)) {
5e762271
AD
363 // The grade object can be marked visible but still be hidden if...
364 // 1) "enablegroupmembersonly" is on and the activity is assigned to a grouping the user is not in.
365 // 2) the student cannot see the activity due to conditional access and its set to be hidden entirely.
5fee56d5
FM
366 $instances = $this->gtree->modinfo->get_instances_of($grade_object->itemmodule);
367 if (!empty($instances[$grade_object->iteminstance])) {
368 $cm = $instances[$grade_object->iteminstance];
5e762271
AD
369 if (!$cm->uservisible) {
370 // Further checks are required to determine whether the activity is entirely hidden or just greyed out.
9e1fe421
TH
371 if ($cm->is_user_access_restricted_by_group() || $cm->is_user_access_restricted_by_conditional_access() ||
372 $cm->is_user_access_restricted_by_capability()) {
5e762271
AD
373 $hide = true;
374 }
aee748d3
AD
375 }
376 }
5fee56d5
FM
377 }
378
379 if (!$hide) {
1762a264
AD
380 /// Excluded Item
381 if ($grade_grade->is_excluded()) {
382 $fullname .= ' ['.get_string('excluded', 'grades').']';
383 $excluded = ' excluded';
384 }
653a8648 385
1762a264
AD
386 /// Other class information
387 $class = "$hidden $excluded";
388 if ($this->switch) { // alter style based on whether aggregation is first or last
389 $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggt b2b" : " item b1b";
390 } else {
391 $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggb" : " item b1b";
392 }
1196cc4d
DW
393 if ($type == 'categoryitem' or $type == 'courseitem') {
394 $header_cat = "cat_{$grade_object->iteminstance}_{$this->user->id}";
395 }
f7998fbc 396
1762a264
AD
397 /// Name
398 $data['itemname']['content'] = $fullname;
399 $data['itemname']['class'] = $class;
400 $data['itemname']['colspan'] = ($this->maxdepth - $depth);
f19dd840
SB
401 $data['itemname']['celltype'] = 'th';
402 $data['itemname']['id'] = $header_row;
e0724506 403
1762a264
AD
404 /// Actual Grade
405 $gradeval = $grade_grade->finalgrade;
a071dbb6 406
62a966ad
AD
407 if ($this->showfeedback) {
408 // Copy $class before appending itemcenter as feedback should not be centered
409 $classfeedback = $class;
410 }
a071dbb6 411 $class .= " itemcenter ";
412 if ($this->showweight) {
413 $data['weight']['class'] = $class;
414 $data['weight']['content'] = '-';
f19dd840 415 $data['weight']['headers'] = "$header_cat $header_row weight";
a071dbb6 416 // has a weight assigned, might be extra credit
417 if ($grade_object->aggregationcoef > 0 && $type <> 'courseitem') {
1301a07a 418 $data['weight']['content'] = number_format($grade_object->aggregationcoef,2);
a071dbb6 419 }
699da6b5 420 }
6391ebe7 421
a071dbb6 422 if ($this->showgrade) {
423 if ($grade_grade->grade_item->needsupdate) {
424 $data['grade']['class'] = $class.' gradingerror';
425 $data['grade']['content'] = get_string('error');
426 } else if (!empty($CFG->grade_hiddenasdate) and $grade_grade->get_datesubmitted() and !$this->canviewhidden and $grade_grade->is_hidden()
427 and !$grade_grade->grade_item->is_category_item() and !$grade_grade->grade_item->is_course_item()) {
428 // 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
429 $class .= ' datesubmitted';
430 $data['grade']['class'] = $class;
431 $data['grade']['content'] = get_string('submittedon', 'grades', userdate($grade_grade->get_datesubmitted(), get_string('strftimedatetimeshort')));
432
433 } elseif ($grade_grade->is_hidden()) {
434 $data['grade']['class'] = $class.' hidden';
435 $data['grade']['content'] = '-';
436 } else {
437 $data['grade']['class'] = $class;
438 $gradeval = $this->blank_hidden_total($this->courseid, $grade_grade->grade_item, $gradeval);
439 $data['grade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true);
440 }
f19dd840 441 $data['grade']['headers'] = "$header_cat $header_row grade";
a071dbb6 442 }
443
444 // Range
445 if ($this->showrange) {
446 $data['range']['class'] = $class;
447 $data['range']['content'] = $grade_grade->grade_item->get_formatted_range(GRADE_DISPLAY_TYPE_REAL, $this->rangedecimals);
f19dd840 448 $data['range']['headers'] = "$header_cat $header_row range";
a071dbb6 449 }
450
451 // Percentage
1762a264
AD
452 if ($this->showpercentage) {
453 if ($grade_grade->grade_item->needsupdate) {
454 $data['percentage']['class'] = $class.' gradingerror';
455 $data['percentage']['content'] = get_string('error');
a071dbb6 456 } else if ($grade_grade->is_hidden()) {
457 $data['percentage']['class'] = $class.' hidden';
458 $data['percentage']['content'] = '-';
1762a264
AD
459 } else {
460 $data['percentage']['class'] = $class;
461 $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
462 }
f19dd840 463 $data['percentage']['headers'] = "$header_cat $header_row percentage";
1762a264
AD
464 }
465
a071dbb6 466 // Lettergrade
467 if ($this->showlettergrade) {
468 if ($grade_grade->grade_item->needsupdate) {
469 $data['lettergrade']['class'] = $class.' gradingerror';
470 $data['lettergrade']['content'] = get_string('error');
471 } else if ($grade_grade->is_hidden()) {
472 $data['lettergrade']['class'] = $class.' hidden';
473 if (!$this->canviewhidden) {
474 $data['lettergrade']['content'] = '-';
475 } else {
476 $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
477 }
478 } else {
479 $data['lettergrade']['class'] = $class;
480 $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
481 }
f19dd840 482 $data['lettergrade']['headers'] = "$header_cat $header_row lettergrade";
a071dbb6 483 }
484
485 // Rank
1762a264 486 if ($this->showrank) {
1762a264
AD
487 if ($grade_grade->grade_item->needsupdate) {
488 $data['rank']['class'] = $class.' gradingerror';
489 $data['rank']['content'] = get_string('error');
490 } elseif ($grade_grade->is_hidden()) {
491 $data['rank']['class'] = $class.' hidden';
492 $data['rank']['content'] = '-';
493 } else if (is_null($gradeval)) {
494 // no grade, no rank
495 $data['rank']['class'] = $class;
653a8648 496 $data['rank']['content'] = '-';
26ed0305 497
1762a264
AD
498 } else {
499 /// find the number of users with a higher grade
500 $sql = "SELECT COUNT(DISTINCT(userid))
501 FROM {grade_grades}
502 WHERE finalgrade > ?
a071dbb6 503 AND itemid = ?
504 AND hidden = 0";
1762a264
AD
505 $rank = $DB->count_records_sql($sql, array($grade_grade->finalgrade, $grade_grade->grade_item->id)) + 1;
506
507 $data['rank']['class'] = $class;
508 $data['rank']['content'] = "$rank/".$this->get_numusers(false); // total course users
509 }
f19dd840 510 $data['rank']['headers'] = "$header_cat $header_row rank";
02973505 511 }
f7998fbc 512
a071dbb6 513 // Average
514 if ($this->showaverage) {
515 $data['average']['class'] = $class;
516 if (!empty($this->gtree->items[$eid]->avg)) {
517 $data['average']['content'] = $this->gtree->items[$eid]->avg;
518 } else {
519 $data['average']['content'] = '-';
520 }
f19dd840 521 $data['average']['headers'] = "$header_cat $header_row average";
1762a264 522 }
6391ebe7 523
a071dbb6 524 // Feedback
525 if ($this->showfeedback) {
526 if ($grade_grade->overridden > 0 AND ($type == 'categoryitem' OR $type == 'courseitem')) {
62a966ad 527 $data['feedback']['class'] = $classfeedback.' feedbacktext';
a071dbb6 528 $data['feedback']['content'] = get_string('overridden', 'grades').': ' . format_text($grade_grade->feedback, $grade_grade->feedbackformat);
529 } else if (empty($grade_grade->feedback) or (!$this->canviewhidden and $grade_grade->is_hidden())) {
62a966ad 530 $data['feedback']['class'] = $classfeedback.' feedbacktext';
a071dbb6 531 $data['feedback']['content'] = '&nbsp;';
532 } else {
62a966ad 533 $data['feedback']['class'] = $classfeedback.' feedbacktext';
a071dbb6 534 $data['feedback']['content'] = format_text($grade_grade->feedback, $grade_grade->feedbackformat);
535 }
f19dd840 536 $data['feedback']['headers'] = "$header_cat $header_row feedback";
1762a264 537 }
5528217e 538 }
f7998fbc 539 }
e0724506 540
5528217e 541 /// Category
542 if ($type == 'category') {
543 $data['leader']['class'] = $class.' '.$alter."d$depth b1t b2b b1l";
544 $data['leader']['rowspan'] = $element['rowspan'];
545
546 if ($this->switch) { // alter style based on whether aggregation is first or last
547 $data['itemname']['class'] = $class.' '.$alter."d$depth b1b b1t";
548 } else {
549 $data['itemname']['class'] = $class.' '.$alter."d$depth b2t";
550 }
551 $data['itemname']['colspan'] = ($this->maxdepth - $depth + count($this->tablecolumns) - 1);
552 $data['itemname']['content'] = $fullname;
f19dd840
SB
553 $data['itemname']['celltype'] = 'th';
554 $data['itemname']['id'] = "cat_{$grade_object->id}_{$this->user->id}";
5528217e 555 }
556
557 /// Add this row to the overall system
558 $this->tabledata[] = $data;
559
560 /// Recursively iterate through all child elements
561 if (isset($element['children'])) {
562 foreach ($element['children'] as $key=>$child) {
563 $this->fill_table_recursive($element['children'][$key]);
564 }
565 }
f7998fbc 566 }
567
568 /**
569 * Prints or returns the HTML from the flexitable.
570 * @param bool $return Whether or not to return the data instead of printing it directly.
571 * @return string
572 */
5c75a0a3 573 public function print_table($return=false) {
5528217e 574 $maxspan = $this->maxdepth;
575
576 /// Build table structure
577 $html = "
e1e9ade5
DW
578 <table cellspacing='0'
579 cellpadding='0'
1196cc4d 580 summary='" . s($this->get_lang_string('tablesummary', 'gradereport_user')) . "'
e1e9ade5 581 class='boxaligncenter generaltable user-grade'>
5528217e 582 <thead>
583 <tr>
f19dd840 584 <th id='".$this->tablecolumns[0]."' class=\"header\" colspan='$maxspan'>".$this->tableheaders[0]."</th>\n";
5528217e 585
586 for ($i = 1; $i < count($this->tableheaders); $i++) {
f19dd840 587 $html .= "<th id='".$this->tablecolumns[$i]."' class=\"header\">".$this->tableheaders[$i]."</th>\n";
5528217e 588 }
589
590 $html .= "
591 </tr>
592 </thead>
593 <tbody>\n";
594
595 /// Print out the table data
596 for ($i = 0; $i < count($this->tabledata); $i++) {
597 $html .= "<tr>\n";
598 if (isset($this->tabledata[$i]['leader'])) {
599 $rowspan = $this->tabledata[$i]['leader']['rowspan'];
600 $class = $this->tabledata[$i]['leader']['class'];
601 $html .= "<td class='$class' rowspan='$rowspan'></td>\n";
602 }
603 for ($j = 0; $j < count($this->tablecolumns); $j++) {
604 $name = $this->tablecolumns[$j];
605 $class = (isset($this->tabledata[$i][$name]['class'])) ? $this->tabledata[$i][$name]['class'] : '';
606 $colspan = (isset($this->tabledata[$i][$name]['colspan'])) ? "colspan='".$this->tabledata[$i][$name]['colspan']."'" : '';
607 $content = (isset($this->tabledata[$i][$name]['content'])) ? $this->tabledata[$i][$name]['content'] : null;
f19dd840
SB
608 $celltype = (isset($this->tabledata[$i][$name]['celltype'])) ? $this->tabledata[$i][$name]['celltype'] : 'td';
609 $id = (isset($this->tabledata[$i][$name]['id'])) ? "id='{$this->tabledata[$i][$name]['id']}'" : '';
610 $headers = (isset($this->tabledata[$i][$name]['headers'])) ? "headers='{$this->tabledata[$i][$name]['headers']}'" : '';
5528217e 611 if (isset($content)) {
f19dd840 612 $html .= "<$celltype $id $headers class='$class' $colspan>$content</$celltype>\n";
5528217e 613 }
614 }
615 $html .= "</tr>\n";
616 }
617
618 $html .= "</tbody></table>";
619
f7998fbc 620 if ($return) {
621 return $html;
622 } else {
623 echo $html;
624 }
625 }
626
627 /**
628 * Processes the data sent by the form (grades and feedbacks).
629 * @var array $data
630 * @return bool Success or Failure (array of errors).
631 */
653a8648 632 function process_data($data) {
5c75a0a3 633 }
653a8648 634 function process_action($target, $action) {
f7998fbc 635 }
a071dbb6 636
637 /**
638 * Builds the grade item averages.
a071dbb6 639 */
640 function calculate_averages() {
641 global $USER, $DB;
642
643 if ($this->showaverage) {
4e829d48 644 // This settings are actually grader report settings (not user report)
a071dbb6 645 // however we're using them as having two separate but identical settings the
4e829d48 646 // user would have to keep in sync would be annoying.
a071dbb6 647 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
648 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
649 $meanselection = $this->get_pref('meanselection');
650 $shownumberofgrades = $this->get_pref('shownumberofgrades');
651
652 $avghtml = '';
a071dbb6 653 $groupsql = $this->groupsql;
654 $groupwheresql = $this->groupwheresql;
a071dbb6 655 $totalcount = $this->get_numusers(false);
656
4e829d48
MN
657 // We want to query both the current context and parent contexts.
658 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
659
660 // Limit to users with a gradeable role ie students.
a071dbb6 661 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
662
4e829d48 663 // Limit to users with an active enrolment.
a071dbb6 664 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
665
4e829d48 666 $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams, $relatedctxparams);
a071dbb6 667 $params['courseid'] = $this->courseid;
668
669 // find sums of all grade items in course
670 $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
671 FROM {grade_items} gi
656d17c2
AD
672 JOIN {grade_grades} gg ON gg.itemid = gi.id
673 JOIN {user} u ON u.id = gg.userid
674 JOIN ($enrolledsql) je ON je.id = gg.userid
675 JOIN (
676 SELECT DISTINCT ra.userid
677 FROM {role_assignments} ra
678 WHERE ra.roleid $gradebookrolessql
4e829d48 679 AND ra.contextid $relatedctxsql
656d17c2 680 ) rainner ON rainner.userid = u.id
a071dbb6 681 $groupsql
682 WHERE gi.courseid = :courseid
656d17c2
AD
683 AND u.deleted = 0
684 AND gg.finalgrade IS NOT NULL
685 AND gg.hidden = 0
686 $groupwheresql
a071dbb6 687 GROUP BY gg.itemid";
688
689 $sum_array = array();
cc65dc36
EL
690 $sums = $DB->get_recordset_sql($sql, $params);
691 foreach ($sums as $itemid => $csum) {
692 $sum_array[$itemid] = $csum->sum;
a071dbb6 693 }
cc65dc36 694 $sums->close();
a071dbb6 695
696 $columncount=0;
697
698 // Empty grades must be evaluated as grademin, NOT always 0
699 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
700 // No join condition when joining grade_items and user to get a grade item row for every user
701 // Then left join with grade_grades and look for rows with null final grade (which includes grade items with no grade_grade)
702 $sql = "SELECT gi.id, COUNT(u.id) AS count
703 FROM {grade_items} gi
d3e30347 704 JOIN {user} u ON u.deleted = 0
656d17c2
AD
705 JOIN ($enrolledsql) je ON je.id = u.id
706 JOIN (
707 SELECT DISTINCT ra.userid
708 FROM {role_assignments} ra
709 WHERE ra.roleid $gradebookrolessql
4e829d48 710 AND ra.contextid $relatedctxsql
656d17c2 711 ) rainner ON rainner.userid = u.id
a1e26b5e 712 LEFT JOIN {grade_grades} gg
d3e30347 713 ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL AND gg.hidden = 0)
a071dbb6 714 $groupsql
656d17c2 715 WHERE gi.courseid = :courseid
656d17c2
AD
716 AND gg.finalgrade IS NULL
717 $groupwheresql
718 GROUP BY gi.id";
a071dbb6 719
720 $ungraded_counts = $DB->get_records_sql($sql, $params);
721
722 foreach ($this->gtree->items as $itemid=>$unused) {
723 if (!empty($this->gtree->items[$itemid]->avg)) {
724 continue;
725 }
726 $item = $this->gtree->items[$itemid];
727
728 if ($item->needsupdate) {
729 $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
730 continue;
731 }
732
733 if (empty($sum_array[$item->id])) {
734 $sum_array[$item->id] = 0;
735 }
736
737 if (empty($ungraded_counts[$itemid])) {
738 $ungraded_count = 0;
739 } else {
740 $ungraded_count = $ungraded_counts[$itemid]->count;
741 }
742
743 //do they want the averages to include all grade items
744 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
745 $mean_count = $totalcount - $ungraded_count;
746 } else { // Bump up the sum by the number of ungraded items * grademin
747 $sum_array[$item->id] += ($ungraded_count * $item->grademin);
748 $mean_count = $totalcount;
749 }
750
a071dbb6 751 // Determine which display type to use for this average
752 if (!empty($USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
753 $displaytype = GRADE_DISPLAY_TYPE_REAL;
754
755 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
756 $displaytype = $item->get_displaytype();
757
758 } else {
759 $displaytype = $averagesdisplaytype;
760 }
761
762 // Override grade_item setting if a display preference (not inherit) was set for the averages
763 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
764 $decimalpoints = $item->get_decimals();
a071dbb6 765 } else {
766 $decimalpoints = $averagesdecimalpoints;
767 }
768
769 if (empty($sum_array[$item->id]) || $mean_count == 0) {
770 $this->gtree->items[$itemid]->avg = '-';
771 } else {
772 $sum = $sum_array[$item->id];
773 $avgradeval = $sum/$mean_count;
774 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
775
776 $numberofgrades = '';
777 if ($shownumberofgrades) {
778 $numberofgrades = " ($mean_count)";
779 }
780
781 $this->gtree->items[$itemid]->avg = $gradehtml.$numberofgrades;
782 }
783 }
784 }
785 }
26ed0305 786}
787
788function grade_report_user_settings_definition(&$mform) {
789 global $CFG;
790
791 $options = array(-1 => get_string('default', 'grades'),
792 0 => get_string('hide'),
793 1 => get_string('show'));
794
cd52d909 795 if (empty($CFG->grade_report_user_showrank)) {
26ed0305 796 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
797 } else {
798 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
799 }
800
801 $mform->addElement('select', 'report_user_showrank', get_string('showrank', 'grades'), $options);
1cc3165e 802 $mform->addHelpButton('report_user_showrank', 'showrank', 'grades');
26ed0305 803
699da6b5 804 if (empty($CFG->grade_report_user_showpercentage)) {
aea45e7e 805 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
5528217e 806 } else {
807 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
699da6b5 808 }
809
810 $mform->addElement('select', 'report_user_showpercentage', get_string('showpercentage', 'grades'), $options);
ff268dcb 811 $mform->addHelpButton('report_user_showpercentage', 'showpercentage', 'grades');
699da6b5 812
a071dbb6 813 if (empty($CFG->grade_report_user_showgrade)) {
814 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
815 } else {
816 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
817 }
818
819 $mform->addElement('select', 'report_user_showgrade', get_string('showgrade', 'grades'), $options);
820
821 if (empty($CFG->grade_report_user_showfeedback)) {
822 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
823 } else {
824 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
825 }
826
827 $mform->addElement('select', 'report_user_showfeedback', get_string('showfeedback', 'grades'), $options);
828
829 if (empty($CFG->grade_report_user_showweight)) {
830 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
831 } else {
832 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
833 }
834
835 $mform->addElement('select', 'report_user_showweight', get_string('showweight', 'grades'), $options);
836
837 if (empty($CFG->grade_report_user_showaverage)) {
838 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
839 } else {
840 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
841 }
842
843 $mform->addElement('select', 'report_user_showaverage', get_string('showaverage', 'grades'), $options);
844 $mform->addHelpButton('report_user_showaverage', 'showaverage', 'grades');
845
846 if (empty($CFG->grade_report_user_showlettergrade)) {
847 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
848 } else {
849 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
850 }
851
852 $mform->addElement('select', 'report_user_showlettergrade', get_string('showlettergrade', 'grades'), $options);
853
854 if (empty($CFG->grade_report_user_showrange)) {
855 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
856 } else {
857 $options[-1] = get_string('defaultprev', 'grades', $options[1]);
858 }
859
860 $mform->addElement('select', 'report_user_showrange', get_string('showrange', 'grades'), $options);
861
862 $options = array(0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5);
863 if (! empty($CFG->grade_report_user_rangedecimals)) {
864 $options[-1] = $options[$CFG->grade_report_user_rangedecimals];
865 }
866 $mform->addElement('select', 'report_user_rangedecimals', get_string('rangedecimals', 'grades'), $options);
867
26ed0305 868 $options = array(-1 => get_string('default', 'grades'),
d69ef28b 869 0 => get_string('shownohidden', 'grades'),
597f50e6 870 1 => get_string('showhiddenuntilonly', 'grades'),
d69ef28b 871 2 => get_string('showallhidden', 'grades'));
26ed0305 872
cd52d909 873 if (empty($CFG->grade_report_user_showhiddenitems)) {
26ed0305 874 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
875 } else {
d69ef28b 876 $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showhiddenitems]);
26ed0305 877 }
878
879 $mform->addElement('select', 'report_user_showhiddenitems', get_string('showhiddenitems', 'grades'), $options);
69e3e962 880 $mform->addHelpButton('report_user_showhiddenitems', 'showhiddenitems', 'grades');
61541a5a
AD
881
882 //showtotalsifcontainhidden
883 $options = array(-1 => get_string('default', 'grades'),
884 GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN => get_string('hide'),
885 GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowexhiddenitems', 'grades'),
886 GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowinchiddenitems', 'grades') );
887
888 if (empty($CFG->grade_report_user_showtotalsifcontainhidden)) {
889 $options[-1] = get_string('defaultprev', 'grades', $options[0]);
890 } else {
891 $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showtotalsifcontainhidden]);
892 }
893
894 $mform->addElement('select', 'report_user_showtotalsifcontainhidden', get_string('hidetotalifhiddenitems', 'grades'), $options);
0459cc4d 895 $mform->addHelpButton('report_user_showtotalsifcontainhidden', 'hidetotalifhiddenitems', 'grades');
0a784551 896}
897
898function grade_report_user_profilereport($course, $user) {
91152a35 899 global $OUTPUT;
0a784551 900 if (!empty($course->showgrades)) {
901
d4060472 902 $context = context_course::instance($course->id);
0a784551 903
904 //first make sure we have proper final grades - this must be done before constructing of the grade tree
905 grade_regrade_final_grades($course->id);
906
907 /// return tracking object
908 $gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'user', 'courseid'=>$course->id, 'userid'=>$user->id));
909 // Create a report instance
910 $report = new grade_report_user($course->id, $gpr, $context, $user->id);
f7998fbc 911
0a784551 912 // print the page
913 echo '<div class="grade-report-user">'; // css fix to share styles with real report page
b5e7b2bf 914 echo $OUTPUT->heading(get_string('pluginname', 'gradereport_user'). ' - '.fullname($report->user));
0a784551 915
916 if ($report->fill_table()) {
917 echo $report->print_table(true);
918 }
919 echo '</div>';
920 }
f7998fbc 921}
0a784551 922
6c3ef410 923