MDL-63571 grade_report_grader: Use correct context for capability check
[moodle.git] / grade / report / grader / 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
4ba9941c 17/**
a153c9f2
AD
18 * Definition of the grader report class
19 *
20 * @package gradereport_grader
21 * @copyright 2007 Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4ba9941c 23 */
24
eea6690a 25require_once($CFG->dirroot . '/grade/report/lib.php');
4ba9941c 26require_once($CFG->libdir.'/tablelib.php');
4ba9941c 27
28/**
29 * Class providing an API for the grader report building and displaying.
eea6690a 30 * @uses grade_report
02d1a0a5
MA
31 * @copyright 2007 Nicolas Connault
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4ba9941c 33 */
eea6690a 34class grade_report_grader extends grade_report {
4ba9941c 35 /**
36 * The final grades.
b89a70ce 37 * @var array $grades
4ba9941c 38 */
d24832f9 39 public $grades;
4ba9941c 40
20180b31
MN
41 /**
42 * Contains all the grades for the course - even the ones not displayed in the grade tree.
43 *
44 * @var array $allgrades
45 */
46 private $allgrades;
47
bba75cb1
AA
48 /**
49 * Contains all grade items expect GRADE_TYPE_NONE.
50 *
51 * @var array $allgradeitems
52 */
53 private $allgradeitems;
54
4ba9941c 55 /**
56 * Array of errors for bulk grades updating.
57 * @var array $gradeserror
58 */
d24832f9 59 public $gradeserror = array();
4ba9941c 60
02d1a0a5 61 // SQL-RELATED
4ba9941c 62
4ba9941c 63 /**
64 * The id of the grade_item by which this report will be sorted.
65 * @var int $sortitemid
66 */
d24832f9 67 public $sortitemid;
4ba9941c 68
69 /**
70 * Sortorder used in the SQL selections.
71 * @var int $sortorder
72 */
d24832f9 73 public $sortorder;
4ba9941c 74
75 /**
76 * An SQL fragment affecting the search for users.
77 * @var string $userselect
78 */
d24832f9 79 public $userselect;
80
81 /**
82 * The bound params for $userselect
319770d7 83 * @var array $userselectparams
d24832f9 84 */
319770d7 85 public $userselectparams = array();
4ba9941c 86
4faf5f99 87 /**
384960dd 88 * List of collapsed categories from user preference
4faf5f99 89 * @var array $collapsed
90 */
d24832f9 91 public $collapsed;
4faf5f99 92
66ef0471 93 /**
94 * A count of the rows, used for css classes.
95 * @var int $rowcount
96 */
d24832f9 97 public $rowcount = 0;
66ef0471 98
6cc3e350 99 /**
57068674 100 * Capability check caching
02d1a0a5
MA
101 * @var boolean $canviewhidden
102 */
d24832f9 103 public $canviewhidden;
57068674 104
92ff6236
AD
105 /**
106 * Length at which feedback will be truncated (to the nearest word) and an ellipsis be added.
107 * TODO replace this by a report preference
108 * @var int $feedback_trunc_length
109 */
110 protected $feedback_trunc_length = 50;
111
0e999796
AD
112 /**
113 * Allow category grade overriding
114 * @var bool $overridecat
115 */
116 protected $overridecat;
117
4ba9941c 118 /**
119 * Constructor. Sets local copies of user preferences and initialises grade_tree.
120 * @param int $courseid
d30c4481 121 * @param object $gpr grade plugin return tracking object
eea6690a 122 * @param string $context
123 * @param int $page The current page being viewed (when report is paged)
124 * @param int $sortitemid The id of the grade_item by which to sort the table
4ba9941c 125 */
d24832f9 126 public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null) {
4ba9941c 127 global $CFG;
d24832f9 128 parent::__construct($courseid, $gpr, $context, $page);
4ba9941c 129
d4060472 130 $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->course->id));
57068674 131
4faf5f99 132 // load collapsed settings for this report
9fe5a1b8 133 $this->collapsed = static::get_collapsed_preferences($this->course->id);
384960dd 134
aea4df41 135 if (empty($CFG->enableoutcomes)) {
136 $nooutcomes = false;
137 } else {
138 $nooutcomes = get_user_preferences('grade_report_shownooutcomes');
139 }
140
e0724506 141 // if user report preference set or site report setting set use it, otherwise use course or site setting
142 $switch = $this->get_pref('aggregationposition');
05766b50 143 if ($switch == '') {
e0724506 144 $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
145 }
146
4faf5f99 147 // Grab the grade_tree for this course
e0724506 148 $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes);
4faf5f99 149
4ba9941c 150 $this->sortitemid = $sortitemid;
151
4ba9941c 152 // base url for sorting by first/last name
09cef06a 153
319770d7 154 $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
155
d3b698a4
AD
156 $studentsperpage = $this->get_students_per_page();
157 if (!empty($this->page) && !empty($studentsperpage)) {
158 $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
09cef06a 159 }
09cef06a 160
4a29d291 161 $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid));
4ba9941c 162
35079f53 163 $this->setup_groups();
8e4bf6cc 164 $this->setup_users();
4ba9941c 165 $this->setup_sortitemid();
0e999796
AD
166
167 $this->overridecat = (bool)get_config('moodle', 'grade_overridecat');
4ba9941c 168 }
169
4ba9941c 170 /**
171 * Processes the data sent by the form (grades and feedbacks).
6ef4878b 172 * Caller is responsible for all access control checks
75674470 173 * @param array $data form submission (with magic quotes)
174 * @return array empty array if success, array of warnings if something fails.
4ba9941c 175 */
d24832f9 176 public function process_data($data) {
5c75a0a3 177 global $DB;
75674470 178 $warnings = array();
d1a4346f 179
30ebb74f 180 $separategroups = false;
181 $mygroups = array();
182 if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
183 $separategroups = true;
184 $mygroups = groups_get_user_groups($this->course->id);
185 $mygroups = $mygroups[0]; // ignore groupings
ce8df92d 186 // reorder the groups fro better perf below
30ebb74f 187 $current = array_search($this->currentgroup, $mygroups);
188 if ($current !== false) {
189 unset($mygroups[$current]);
190 array_unshift($mygroups, $this->currentgroup);
191 }
192 }
20b2bbb9 193 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
30ebb74f 194
4ba9941c 195 // always initialize all arrays
196 $queue = array();
8e4bf6cc 197
8233747e
AD
198 $this->load_users();
199 $this->load_final_grades();
a740a0ad
AD
200
201 // Were any changes made?
202 $changedgrades = false;
09171b95 203 $timepageload = clean_param($data->timepageload, PARAM_INT);
a740a0ad 204
30793ea3 205 foreach ($data as $varname => $students) {
4ba9941c 206
207 $needsupdate = false;
4ba9941c 208
209 // skip, not a grade nor feedback
79eabc2a 210 if (strpos($varname, 'grade') === 0) {
319770d7 211 $datatype = 'grade';
79eabc2a 212 } else if (strpos($varname, 'feedback') === 0) {
319770d7 213 $datatype = 'feedback';
4ba9941c 214 } else {
215 continue;
216 }
217
30793ea3
PN
218 foreach ($students as $userid => $items) {
219 $userid = clean_param($userid, PARAM_INT);
220 foreach ($items as $itemid => $postedvalue) {
221 $itemid = clean_param($itemid, PARAM_INT);
222
223 // Was change requested?
224 $oldvalue = $this->grades[$userid][$itemid];
225 if ($datatype === 'grade') {
226 // If there was no grade and there still isn't
227 if (is_null($oldvalue->finalgrade) && $postedvalue == -1) {
228 // -1 means no grade
229 continue;
230 }
4ba9941c 231
30793ea3
PN
232 // If the grade item uses a custom scale
233 if (!empty($oldvalue->grade_item->scaleid)) {
1e2698f6 234
30793ea3
PN
235 if ((int)$oldvalue->finalgrade === (int)$postedvalue) {
236 continue;
237 }
238 } else {
239 // The grade item uses a numeric scale
1e2698f6 240
30793ea3
PN
241 // Format the finalgrade from the DB so that it matches the grade from the client
242 if ($postedvalue === format_float($oldvalue->finalgrade, $oldvalue->grade_item->get_decimals())) {
243 continue;
244 }
245 }
1e2698f6 246
30793ea3
PN
247 $changedgrades = true;
248
249 } else if ($datatype === 'feedback') {
986c8337
TL
250 // If quick grading is on, feedback needs to be compared without line breaks.
251 if ($this->get_pref('quickgrading')) {
252 $oldvalue->feedback = preg_replace("/\r\n|\r|\n/", "", $oldvalue->feedback);
253 }
02d1a0a5 254 if (($oldvalue->feedback === $postedvalue) or ($oldvalue->feedback === null and empty($postedvalue))) {
30793ea3
PN
255 continue;
256 }
1e2698f6 257 }
1e2698f6 258
30793ea3
PN
259 if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) {
260 print_error('invalidgradeitemid');
261 }
1e2698f6 262
30793ea3
PN
263 // Pre-process grade
264 if ($datatype == 'grade') {
265 $feedback = false;
266 $feedbackformat = false;
267 if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
268 if ($postedvalue == -1) { // -1 means no grade
269 $finalgrade = null;
270 } else {
271 $finalgrade = $postedvalue;
272 }
273 } else {
274 $finalgrade = unformat_float($postedvalue);
275 }
29a5680e 276
30793ea3 277 $errorstr = '';
09171b95
FM
278 $skip = false;
279
280 $dategraded = $oldvalue->get_dategraded();
281 if (!empty($dategraded) && $timepageload < $dategraded) {
282 // Warn if the grade was updated while we were editing this form.
283 $errorstr = 'gradewasmodifiedduringediting';
284 $skip = true;
285 } else if (!is_null($finalgrade)) {
286 // Warn if the grade is out of bounds.
30793ea3
PN
287 $bounded = $gradeitem->bounded_grade($finalgrade);
288 if ($bounded > $finalgrade) {
01da2d36 289 $errorstr = 'lessthanmin';
30793ea3
PN
290 } else if ($bounded < $finalgrade) {
291 $errorstr = 'morethanmax';
292 }
293 }
09171b95 294
30793ea3 295 if ($errorstr) {
12b4487e
AG
296 $userfields = 'id, ' . get_all_user_name_fields(true);
297 $user = $DB->get_record('user', array('id' => $userid), $userfields);
30793ea3 298 $gradestr = new stdClass();
20b2bbb9 299 $gradestr->username = fullname($user, $viewfullnames);
30793ea3
PN
300 $gradestr->itemname = $gradeitem->get_name();
301 $warnings[] = get_string($errorstr, 'grades', $gradestr);
09171b95
FM
302 if ($skip) {
303 // Skipping the update of this grade it failed the tests above.
304 continue;
305 }
30793ea3 306 }
4ba9941c 307
30793ea3
PN
308 } else if ($datatype == 'feedback') {
309 $finalgrade = false;
310 $trimmed = trim($postedvalue);
311 if (empty($trimmed)) {
02d1a0a5 312 $feedback = null;
30793ea3
PN
313 } else {
314 $feedback = $postedvalue;
315 }
4ba9941c 316 }
79eabc2a 317
30793ea3
PN
318 // group access control
319 if ($separategroups) {
320 // note: we can not use $this->currentgroup because it would fail badly
321 // when having two browser windows each with different group
322 $sharinggroup = false;
02d1a0a5 323 foreach ($mygroups as $groupid) {
30793ea3
PN
324 if (groups_is_member($groupid, $userid)) {
325 $sharinggroup = true;
326 break;
327 }
328 }
329 if (!$sharinggroup) {
330 // either group membership changed or somebody is hacking grades of other group
331 $warnings[] = get_string('errorsavegrade', 'grades');
332 continue;
333 }
78946b9b 334 }
0a2c8485 335
30793ea3 336 $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
4ba9941c 337
30793ea3
PN
338 // We can update feedback without reloading the grade item as it doesn't affect grade calculations
339 if ($datatype === 'feedback') {
340 $this->grades[$userid][$itemid]->feedback = $feedback;
30ebb74f 341 }
342 }
8233747e 343 }
4ba9941c 344 }
345
a740a0ad
AD
346 if ($changedgrades) {
347 // If a final grade was overriden reload grades so dependent grades like course total will be correct
348 $this->grades = null;
349 }
350
75674470 351 return $warnings;
4ba9941c 352 }
353
4ba9941c 354
355 /**
356 * Setting the sort order, this depends on last state
357 * all this should be in the new table class that we might need to use
358 * for displaying grades.
359 */
d24832f9 360 private function setup_sortitemid() {
63d6efa2 361
362 global $SESSION;
363
54352ac9
PS
364 if (!isset($SESSION->gradeuserreport)) {
365 $SESSION->gradeuserreport = new stdClass();
366 }
367
4ba9941c 368 if ($this->sortitemid) {
369 if (!isset($SESSION->gradeuserreport->sort)) {
a80112f0 370 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
371 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
372 } else {
373 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
374 }
4ba9941c 375 } else {
376 // this is the first sort, i.e. by last name
377 if (!isset($SESSION->gradeuserreport->sortitemid)) {
a80112f0 378 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
d24832f9 379 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
a80112f0 380 } else {
381 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
382 }
4ba9941c 383 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
384 // same as last sort
385 if ($SESSION->gradeuserreport->sort == 'ASC') {
386 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
387 } else {
388 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
389 }
390 } else {
a80112f0 391 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
392 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
393 } else {
394 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
395 }
4ba9941c 396 }
397 }
398 $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
399 } else {
400 // not requesting sort, use last setting (for paging)
401
402 if (isset($SESSION->gradeuserreport->sortitemid)) {
403 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
02d1a0a5 404 } else {
d20737e8 405 $this->sortitemid = 'lastname';
4ba9941c 406 }
d20737e8 407
4ba9941c 408 if (isset($SESSION->gradeuserreport->sort)) {
409 $this->sortorder = $SESSION->gradeuserreport->sort;
410 } else {
411 $this->sortorder = 'ASC';
412 }
413 }
414 }
415
4ba9941c 416 /**
b50371da 417 * pulls out the userids of the users to be display, and sorts them
4ba9941c 418 */
d24832f9 419 public function load_users() {
420 global $CFG, $DB;
b50371da 421
8233747e
AD
422 if (!empty($this->users)) {
423 return;
424 }
8e4bf6cc 425 $this->setup_users();
8233747e 426
41877849 427 // Limit to users with a gradeable role.
ef8f084c 428 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
4ba9941c 429
fe89cb8c
FM
430 // Check the status of showing only active enrolments.
431 $coursecontext = $this->context->get_course_context(true);
432 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
433 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
434 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
435
4e829d48 436 // Limit to users with an active enrollment.
fe89cb8c 437 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
ef8f084c 438
4e829d48 439 // Fields we need from the user table.
ef8c793d 440 $userfields = user_picture::fields('u', get_extra_user_fields($this->context));
ef8f084c 441
4e829d48
MN
442 // We want to query both the current context and parent contexts.
443 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
656d17c2 444
4e829d48 445 // If the user has clicked one of the sort asc/desc arrows.
4ba9941c 446 if (is_numeric($this->sortitemid)) {
02d1a0a5
MA
447 $params = array_merge(array('gitemid' => $this->sortitemid), $gradebookrolesparams, $this->userwheresql_params,
448 $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
09d0ef21 449
656d17c2 450 $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
0a0e2843 451 $sort = "g.finalgrade $this->sortorder, u.idnumber, u.lastname, u.firstname, u.email";
4ba9941c 452 } else {
656d17c2 453 $sortjoin = '';
09d0ef21 454 switch($this->sortitemid) {
455 case 'lastname':
0a0e2843 456 $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder, u.idnumber, u.email";
656d17c2 457 break;
09d0ef21 458 case 'firstname':
0a0e2843 459 $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder, u.idnumber, u.email";
656d17c2 460 break;
69101b43 461 case 'email':
0a0e2843 462 $sort = "u.email $this->sortorder, u.firstname, u.lastname, u.idnumber";
69101b43 463 break;
09d0ef21 464 case 'idnumber':
465 default:
0a0e2843 466 $sort = "u.idnumber $this->sortorder, u.firstname, u.lastname, u.email";
656d17c2 467 break;
c421ad4b 468 }
4ba9941c 469
8e4bf6cc 470 $params = array_merge($gradebookrolesparams, $this->userwheresql_params, $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
4ba9941c 471 }
472
656d17c2
AD
473 $sql = "SELECT $userfields
474 FROM {user} u
475 JOIN ($enrolledsql) je ON je.id = u.id
476 $this->groupsql
477 $sortjoin
478 JOIN (
479 SELECT DISTINCT ra.userid
480 FROM {role_assignments} ra
481 WHERE ra.roleid IN ($this->gradebookroles)
4e829d48 482 AND ra.contextid $relatedctxsql
656d17c2
AD
483 ) rainner ON rainner.userid = u.id
484 AND u.deleted = 0
8e4bf6cc 485 $this->userwheresql
656d17c2
AD
486 $this->groupwheresql
487 ORDER BY $sort";
d3b698a4
AD
488 $studentsperpage = $this->get_students_per_page();
489 $this->users = $DB->get_records_sql($sql, $params, $studentsperpage * $this->page, $studentsperpage);
09d0ef21 490
4ba9941c 491 if (empty($this->users)) {
492 $this->userselect = '';
493 $this->users = array();
0a695c36 494 $this->userselect_params = array();
4ba9941c 495 } else {
3aafffc0 496 list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
d24832f9 497 $this->userselect = "AND g.userid $usql";
3aafffc0
AD
498 $this->userselect_params = $uparams;
499
fe89cb8c 500 // First flag everyone as not suspended.
3aafffc0 501 foreach ($this->users as $user) {
fe89cb8c
FM
502 $this->users[$user->id]->suspendedenrolment = false;
503 }
504
505 // If we want to mix both suspended and not suspended users, let's find out who is suspended.
506 if (!$showonlyactiveenrol) {
507 $sql = "SELECT ue.userid
508 FROM {user_enrolments} ue
509 JOIN {enrol} e ON e.id = ue.enrolid
510 WHERE ue.userid $usql
511 AND ue.status = :uestatus
512 AND e.status = :estatus
513 AND e.courseid = :courseid
514 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
515 GROUP BY ue.userid";
516
517 $time = time();
518 $params = array_merge($uparams, array('estatus' => ENROL_INSTANCE_ENABLED, 'uestatus' => ENROL_USER_ACTIVE,
519 'courseid' => $coursecontext->instanceid, 'now1' => $time, 'now2' => $time));
520 $useractiveenrolments = $DB->get_records_sql($sql, $params);
521
522 foreach ($this->users as $user) {
38c1dd19
RT
523 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments);
524 }
3aafffc0 525 }
4ba9941c 526 }
4ba9941c 527 return $this->users;
528 }
529
bba75cb1
AA
530 /**
531 * Load all grade items.
532 */
533 protected function get_allgradeitems() {
534 if (!empty($this->allgradeitems)) {
535 return $this->allgradeitems;
536 }
537 $allgradeitems = grade_item::fetch_all(array('courseid' => $this->courseid));
538 // But hang on - don't include ones which are set to not show the grade at all.
539 $this->allgradeitems = array_filter($allgradeitems, function($item) {
540 return $item->gradetype != GRADE_TYPE_NONE;
541 });
542
543 return $this->allgradeitems;
544 }
545
4ba9941c 546 /**
547 * we supply the userids in this query, and get all the grades
548 * pulls out all the grades, this does not need to worry about paging
549 */
d24832f9 550 public function load_final_grades() {
551 global $CFG, $DB;
4ba9941c 552
8233747e
AD
553 if (!empty($this->grades)) {
554 return;
555 }
556
8e4bf6cc
MA
557 if (empty($this->users)) {
558 return;
559 }
560
6ef4878b 561 // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
b50371da 562 $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
b89a70ce 563 $sql = "SELECT g.*
d24832f9 564 FROM {grade_items} gi,
565 {grade_grades} g
b50371da 566 WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
b89a70ce 567
568 $userids = array_keys($this->users);
6c6bd6e1 569 $allgradeitems = $this->get_allgradeitems();
4ba9941c 570
d24832f9 571 if ($grades = $DB->get_records_sql($sql, $params)) {
b89a70ce 572 foreach ($grades as $graderec) {
20180b31 573 $grade = new grade_grade($graderec, false);
6c6bd6e1
AA
574 if (!empty($allgradeitems[$graderec->itemid])) {
575 // Note: Filter out grades which have a grade type of GRADE_TYPE_NONE.
576 // Only grades without this type are present in $allgradeitems.
577 $this->allgrades[$graderec->userid][$graderec->itemid] = $grade;
578 }
d24832f9 579 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
20180b31 580 $this->grades[$graderec->userid][$graderec->itemid] = $grade;
54352ac9 581 $this->grades[$graderec->userid][$graderec->itemid]->grade_item = $this->gtree->get_item($graderec->itemid); // db caching
b89a70ce 582 }
583 }
584 }
585
586 // prefil grades that do not exist yet
587 foreach ($userids as $userid) {
02d1a0a5 588 foreach ($this->gtree->get_items() as $itemid => $unused) {
b89a70ce 589 if (!isset($this->grades[$userid][$itemid])) {
590 $this->grades[$userid][$itemid] = new grade_grade();
478f4322 591 $this->grades[$userid][$itemid]->itemid = $itemid;
3b34f698 592 $this->grades[$userid][$itemid]->userid = $userid;
54352ac9 593 $this->grades[$userid][$itemid]->grade_item = $this->gtree->get_item($itemid); // db caching
20180b31
MN
594
595 $this->allgrades[$userid][$itemid] = $this->grades[$userid][$itemid];
b89a70ce 596 }
4ba9941c 597 }
598 }
bba75cb1
AA
599
600 // Pre fill grades for any remaining items which might be collapsed.
bba75cb1
AA
601 foreach ($userids as $userid) {
602 foreach ($allgradeitems as $itemid => $gradeitem) {
603 if (!isset($this->allgrades[$userid][$itemid])) {
604 $this->allgrades[$userid][$itemid] = new grade_grade();
605 $this->allgrades[$userid][$itemid]->itemid = $itemid;
606 $this->allgrades[$userid][$itemid]->userid = $userid;
607 $this->allgrades[$userid][$itemid]->grade_item = $gradeitem;
608 }
609 }
610 }
4ba9941c 611 }
612
613 /**
02d1a0a5 614 * Gets html toggle
33564ffb 615 * @deprecated since Moodle 2.4 as it appears not to be used any more.
4ba9941c 616 */
d24832f9 617 public function get_toggles_html() {
33564ffb 618 throw new coding_exception('get_toggles_html() can not be used any more');
4ba9941c 619 }
620
621 /**
02d1a0a5 622 * Prints html toggle
33564ffb 623 * @deprecated since 2.4 as it appears not to be used any more.
02d1a0a5 624 * @param unknown $type
33564ffb 625 */
319770d7 626 public function print_toggle($type) {
33564ffb 627 throw new coding_exception('print_toggle() can not be used any more');
4ba9941c 628 }
629
630 /**
6c096a49
NC
631 * Builds and returns the rows that will make up the left part of the grader report
632 * This consists of student names and icons, links to user reports and id numbers, as well
633 * as header cells for these columns. It also includes the fillers required for the
634 * categories displayed on the right side of the report.
2b267d31 635 * @param boolean $displayaverages whether to display average rows in the table
6c096a49 636 * @return array Array of html_table_row objects
4ba9941c 637 */
cbe8e5b3 638 public function get_left_rows($displayaverages) {
319770d7 639 global $CFG, $USER, $OUTPUT;
4ba9941c 640
6c096a49
NC
641 $rows = array();
642
643 $showuserimage = $this->get_pref('showuserimage');
2811831a
DP
644 // FIXME: MDL-52678 This get_capability_info is hacky and we should have an API for inserting grade row links instead.
645 $canseeuserreport = false;
646 $canseesingleview = false;
647 if (get_capability_info('gradereport/'.$CFG->grade_profilereport.':view')) {
648 $canseeuserreport = has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context);
649 }
650 if (get_capability_info('gradereport/singleview:view')) {
651 $canseesingleview = has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall',
4ae71e93 652 'moodle/grade:edit'), $this->context);
2811831a 653 }
1c733bd6 654 $hasuserreportcell = $canseeuserreport || $canseesingleview;
20b2bbb9 655 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
203b7e2e 656
6c096a49
NC
657 $strfeedback = $this->get_lang_string("feedback");
658 $strgrade = $this->get_lang_string('grade');
203b7e2e 659
e4aec5be 660 $extrafields = get_extra_user_fields($this->context);
6c096a49 661
e4aec5be 662 $arrows = $this->get_sort_arrows($extrafields);
6c096a49 663
1c733bd6 664 $colspan = 1 + $hasuserreportcell + count($extrafields);
6c096a49
NC
665
666 $levels = count($this->gtree->levels) - 1;
667
6929b68b
JC
668 $fillercell = new html_table_cell();
669 $fillercell->header = true;
670 $fillercell->attributes['scope'] = 'col';
671 $fillercell->attributes['class'] = 'cell topleft';
672 $fillercell->text = html_writer::span(get_string('participants'), 'accesshide');
673 $fillercell->colspan = $colspan;
674 $fillercell->rowspan = $levels;
675 $row = new html_table_row(array($fillercell));
676 $rows[] = $row;
677
678 for ($i = 1; $i < $levels; $i++) {
679 $row = new html_table_row();
6c096a49
NC
680 $rows[] = $row;
681 }
682
683 $headerrow = new html_table_row();
16be8974 684 $headerrow->attributes['class'] = 'heading';
6c096a49
NC
685
686 $studentheader = new html_table_cell();
16be8974 687 $studentheader->attributes['class'] = 'header';
6c096a49
NC
688 $studentheader->scope = 'col';
689 $studentheader->header = true;
690 $studentheader->id = 'studentheader';
1c733bd6 691 if ($hasuserreportcell) {
6c096a49
NC
692 $studentheader->colspan = 2;
693 }
694 $studentheader->text = $arrows['studentname'];
695
696 $headerrow->cells[] = $studentheader;
697
e4aec5be 698 foreach ($extrafields as $field) {
699 $fieldheader = new html_table_cell();
700 $fieldheader->attributes['class'] = 'header userfield user' . $field;
701 $fieldheader->scope = 'col';
702 $fieldheader->header = true;
703 $fieldheader->text = $arrows[$field];
6c096a49 704
e4aec5be 705 $headerrow->cells[] = $fieldheader;
6c096a49
NC
706 }
707
708 $rows[] = $headerrow;
709
710 $rows = $this->get_left_icons_row($rows, $colspan);
711
3aafffc0 712 $suspendedstring = null;
6c096a49
NC
713 foreach ($this->users as $userid => $user) {
714 $userrow = new html_table_row();
fe213365 715 $userrow->id = 'fixed_user_'.$userid;
6c096a49
NC
716
717 $usercell = new html_table_cell();
6929b68b 718 $usercell->attributes['class'] = 'header user';
3aafffc0 719
6c096a49
NC
720 $usercell->header = true;
721 $usercell->scope = 'row';
6c096a49
NC
722
723 if ($showuserimage) {
6929b68b 724 $usercell->text = $OUTPUT->user_picture($user, array('visibletoscreenreaders' => false));
203b7e2e 725 }
726
20b2bbb9 727 $fullname = fullname($user, $viewfullnames);
feb0014b
AN
728 $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), $fullname, array(
729 'class' => 'username',
730 ));
6c096a49 731
3aafffc0
AD
732 if (!empty($user->suspendedenrolment)) {
733 $usercell->attributes['class'] .= ' usersuspended';
734
735 //may be lots of suspended users so only get the string once
736 if (empty($suspendedstring)) {
737 $suspendedstring = get_string('userenrolmentsuspended', 'grades');
738 }
663640f5
DW
739 $icon = $OUTPUT->pix_icon('i/enrolmentsuspended', $suspendedstring);
740 $usercell->text .= html_writer::tag('span', $icon, array('class'=>'usersuspendedicon'));
3aafffc0
AD
741 }
742
6c096a49
NC
743 $userrow->cells[] = $usercell;
744
0a55da57
AB
745 $userreportcell = new html_table_cell();
746 $userreportcell->attributes['class'] = 'userreport';
6929b68b 747 $userreportcell->header = false;
1c733bd6 748 if ($canseeuserreport) {
ace9051c 749 $a = new stdClass();
b21b32a4 750 $a->user = $fullname;
6c096a49 751 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
a6855934 752 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
0a55da57
AB
753 $userreportcell->text .= $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
754 }
755
1c733bd6 756 if ($canseesingleview) {
92c61fee
ZD
757 $url = new moodle_url('/grade/report/singleview/index.php', array('id' => $this->course->id, 'itemid' => $user->id, 'item' => 'user'));
758 $singleview = $OUTPUT->action_icon($url, new pix_icon('t/editstring', get_string('singleview', 'grades', $fullname)));
0a55da57
AB
759 $userreportcell->text .= $singleview;
760 }
761
762 if ($userreportcell->text) {
6c096a49 763 $userrow->cells[] = $userreportcell;
203b7e2e 764 }
765
e4aec5be 766 foreach ($extrafields as $field) {
767 $fieldcell = new html_table_cell();
6929b68b
JC
768 $fieldcell->attributes['class'] = 'userfield user' . $field;
769 $fieldcell->header = false;
e4aec5be 770 $fieldcell->text = $user->{$field};
771 $userrow->cells[] = $fieldcell;
6c096a49
NC
772 }
773
feb0014b 774 $userrow->attributes['data-uid'] = $userid;
6c096a49 775 $rows[] = $userrow;
203b7e2e 776 }
4ba9941c 777
6c096a49 778 $rows = $this->get_left_range_row($rows, $colspan);
cbe8e5b3
MA
779 if ($displayaverages) {
780 $rows = $this->get_left_avg_row($rows, $colspan, true);
781 $rows = $this->get_left_avg_row($rows, $colspan);
782 }
4ba9941c 783
6c096a49
NC
784 return $rows;
785 }
786
787 /**
788 * Builds and returns the rows that will make up the right part of the grader report
2b267d31 789 * @param boolean $displayaverages whether to display average rows in the table
6c096a49
NC
790 * @return array Array of html_table_row objects
791 */
cbe8e5b3 792 public function get_right_rows($displayaverages) {
fe213365 793 global $CFG, $USER, $OUTPUT, $DB, $PAGE;
4ba9941c 794
6c096a49
NC
795 $rows = array();
796 $this->rowcount = 0;
797 $numrows = count($this->gtree->get_levels());
798 $numusers = count($this->users);
799 $gradetabindex = 1;
319770d7 800 $columnstounset = array();
6c096a49 801 $strgrade = $this->get_lang_string('grade');
fe213365 802 $strfeedback = $this->get_lang_string("feedback");
6c096a49 803 $arrows = $this->get_sort_arrows();
cb7fe7b4 804
fe213365 805 $jsarguments = array(
fe213365
SH
806 'cfg' => array('ajaxenabled'=>false),
807 'items' => array(),
808 'users' => array(),
df65120a 809 'feedback' => array(),
12f946d9 810 'grades' => array()
fe213365
SH
811 );
812 $jsscales = array();
813
b21b32a4
AN
814 // Get preferences once.
815 $showactivityicons = $this->get_pref('showactivityicons');
816 $quickgrading = $this->get_pref('quickgrading');
817 $showquickfeedback = $this->get_pref('showquickfeedback');
818 $enableajax = $this->get_pref('enableajax');
819 $showanalysisicon = $this->get_pref('showanalysisicon');
820
821 // Get strings which are re-used inside the loop.
822 $strftimedatetimeshort = get_string('strftimedatetimeshort');
823 $strexcludedgrades = get_string('excluded', 'grades');
824 $strerror = get_string('error');
b21b32a4 825
20b2bbb9
SR
826 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
827
02d1a0a5 828 foreach ($this->gtree->get_levels() as $key => $row) {
6c096a49 829 $headingrow = new html_table_row();
16be8974 830 $headingrow->attributes['class'] = 'heading_name_row';
4ba9941c 831
cb7fe7b4 832 foreach ($row as $columnkey => $element) {
319770d7 833 $sortlink = clone($this->baseurl);
2e3987a9 834 if (isset($element['object']->id)) {
319770d7 835 $sortlink->param('sortitemid', $element['object']->id);
2e3987a9 836 }
837
cb7fe7b4 838 $eid = $element['eid'];
839 $object = $element['object'];
840 $type = $element['type'];
438a5aa9 841 $categorystate = @$element['categorystate'];
8c5a416e 842
4ba9941c 843 if (!empty($element['colspan'])) {
6c096a49 844 $colspan = $element['colspan'];
4ba9941c 845 } else {
6c096a49 846 $colspan = 1;
4ba9941c 847 }
848
849 if (!empty($element['depth'])) {
6c096a49 850 $catlevel = 'catlevel'.$element['depth'];
4ba9941c 851 } else {
852 $catlevel = '';
853 }
854
02d1a0a5 855 // Element is a filler
4ba9941c 856 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
6c096a49 857 $fillercell = new html_table_cell();
16be8974 858 $fillercell->attributes['class'] = $type . ' ' . $catlevel;
6c096a49
NC
859 $fillercell->colspan = $colspan;
860 $fillercell->text = '&nbsp;';
6929b68b
JC
861
862 // This is a filler cell; don't use a <th>, it'll confuse screen readers.
863 $fillercell->header = false;
6c096a49 864 $headingrow->cells[] = $fillercell;
02d1a0a5 865 } else if ($type == 'category') {
825a3fa9
JP
866 // Make sure the grade category has a grade total or at least has child grade items.
867 if (grade_tree::can_output_item($element)) {
868 // Element is a category.
869 $categorycell = new html_table_cell();
870 $categorycell->attributes['class'] = 'category ' . $catlevel;
871 $categorycell->colspan = $colspan;
872 $categorycell->text = $this->get_course_header($element);
873 $categorycell->header = true;
874 $categorycell->scope = 'col';
875
876 // Print icons.
877 if ($USER->gradeediting[$this->courseid]) {
878 $categorycell->text .= $this->get_icons($element);
879 }
4ba9941c 880
825a3fa9
JP
881 $headingrow->cells[] = $categorycell;
882 }
02d1a0a5
MA
883 } else {
884 // Element is a grade_item
4ba9941c 885 if ($element['object']->id == $this->sortitemid) {
886 if ($this->sortorder == 'ASC') {
319770d7 887 $arrow = $this->get_sort_arrow('up', $sortlink);
4ba9941c 888 } else {
319770d7 889 $arrow = $this->get_sort_arrow('down', $sortlink);
4ba9941c 890 }
891 } else {
319770d7 892 $arrow = $this->get_sort_arrow('move', $sortlink);
4ba9941c 893 }
894
41e62a90 895 $headerlink = $this->gtree->get_element_header($element, true, $showactivityicons, false, false, true);
6c096a49
NC
896
897 $itemcell = new html_table_cell();
edb7d5ad 898 $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable'. ' i'. $element['object']->id;
6ad1af09 899 $itemcell->attributes['data-itemid'] = $element['object']->id;
6c096a49 900
4ba9941c 901 if ($element['object']->is_hidden()) {
834f4ea6 902 $itemcell->attributes['class'] .= ' dimmed_text';
4ba9941c 903 }
904
92c61fee 905 $singleview = '';
2811831a
DP
906
907 // FIXME: MDL-52678 This is extremely hacky we should have an API for inserting grade column links.
908 if (get_capability_info('gradereport/singleview:view')) {
909 if (has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall',
910 'moodle/grade:edit'), $this->context)) {
911
912 $url = new moodle_url('/grade/report/singleview/index.php', array(
913 'id' => $this->course->id,
914 'item' => 'grade',
915 'itemid' => $element['object']->id));
916 $singleview = $OUTPUT->action_icon(
917 $url,
918 new pix_icon('t/editstring', get_string('singleview', 'grades', $element['object']->get_name()))
919 );
920 }
92c61fee
ZD
921 }
922
6c096a49 923 $itemcell->colspan = $colspan;
89eacee7 924 $itemcell->text = $headerlink . $arrow . $singleview;
6c096a49
NC
925 $itemcell->header = true;
926 $itemcell->scope = 'col';
6c096a49
NC
927
928 $headingrow->cells[] = $itemcell;
4ba9941c 929 }
4ba9941c 930 }
6c096a49 931 $rows[] = $headingrow;
4ba9941c 932 }
4ba9941c 933
6c096a49 934 $rows = $this->get_right_icons_row($rows);
4ba9941c 935
f17bb885 936 // Preload scale objects for items with a scaleid and initialize tab indices
319770d7 937 $scaleslist = array();
c0c1e7c2 938 $tabindices = array();
d297269d 939
02d1a0a5 940 foreach ($this->gtree->get_items() as $itemid => $item) {
fe213365 941 $scale = null;
388234f4 942 if (!empty($item->scaleid)) {
319770d7 943 $scaleslist[] = $item->scaleid;
fe213365
SH
944 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
945 } else {
946 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
388234f4 947 }
c0c1e7c2 948 $tabindices[$item->id]['grade'] = $gradetabindex;
949 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
950 $gradetabindex += $numusers * 2;
388234f4 951 }
319770d7 952 $scalesarray = array();
388234f4 953
319770d7 954 if (!empty($scaleslist)) {
955 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
388234f4 956 }
fe213365 957 $jsscales = $scalesarray;
d24832f9 958
20180b31
MN
959 // Get all the grade items if the user can not view hidden grade items.
960 // It is possible that the user is simply viewing the 'Course total' by switching to the 'Aggregates only' view
961 // and that this user does not have the ability to view hidden items. In this case we still need to pass all the
962 // grade items (in case one has been hidden) as the course total shown needs to be adjusted for this particular
963 // user.
964 if (!$this->canviewhidden) {
bba75cb1 965 $allgradeitems = $this->get_allgradeitems();
20180b31
MN
966 }
967
4ba9941c 968 foreach ($this->users as $userid => $user) {
b89a70ce 969
57068674 970 if ($this->canviewhidden) {
d297269d 971 $altered = array();
972 $unknown = array();
b89a70ce 973 } else {
20180b31
MN
974 $usergrades = $this->allgrades[$userid];
975 $hidingaffected = grade_grade::get_hiding_affected($usergrades, $allgradeitems);
319770d7 976 $altered = $hidingaffected['altered'];
20060b3b 977 $unknown = $hidingaffected['unknowngrades'];
319770d7 978 unset($hidingaffected);
b89a70ce 979 }
980
6c096a49 981 $itemrow = new html_table_row();
fe213365 982 $itemrow->id = 'user_'.$userid;
9d35e66e 983
20b2bbb9 984 $fullname = fullname($user, $viewfullnames);
b21b32a4 985 $jsarguments['users'][$userid] = $fullname;
fe213365 986
02d1a0a5 987 foreach ($this->gtree->items as $itemid => $unused) {
dc482cfa 988 $item =& $this->gtree->items[$itemid];
d297269d 989 $grade = $this->grades[$userid][$item->id];
b89a70ce 990
6c096a49
NC
991 $itemcell = new html_table_cell();
992
fe213365 993 $itemcell->id = 'u'.$userid.'i'.$itemid;
6ad1af09 994 $itemcell->attributes['data-itemid'] = $itemid;
fe213365 995
e50ce569 996 // Get the decimal points preference for this item
31a6c06c 997 $decimalpoints = $item->get_decimals();
4ba9941c 998
be85f0cf 999 if (array_key_exists($itemid, $unknown)) {
d297269d 1000 $gradeval = null;
1001 } else if (array_key_exists($itemid, $altered)) {
1002 $gradeval = $altered[$itemid];
1003 } else {
1004 $gradeval = $grade->finalgrade;
1005 }
a740a0ad 1006 if (!empty($grade->finalgrade)) {
02d1a0a5 1007 $gradevalforjs = null;
a740a0ad 1008 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
02d1a0a5 1009 $gradevalforjs = (int)$gradeval;
a740a0ad 1010 } else {
02d1a0a5 1011 $gradevalforjs = format_float($gradeval, $decimalpoints);
a740a0ad 1012 }
02d1a0a5 1013 $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforjs);
a740a0ad 1014 }
4ba9941c 1015
00374cc5 1016 // MDL-11274
1017 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
57068674 1018 if (!$this->canviewhidden and $grade->is_hidden()) {
6cc3e350 1019 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
d297269d 1020 // 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
b21b32a4
AN
1021 $itemcell->text = "<span class='datesubmitted'>" .
1022 userdate($grade->get_datesubmitted(), $strftimedatetimeshort) . "</span>";
bb49f77b 1023 } else {
6c096a49 1024 $itemcell->text = '-';
00374cc5 1025 }
6c096a49 1026 $itemrow->cells[] = $itemcell;
a5b8be62 1027 continue;
00374cc5 1028 }
1029
2cc773f5 1030 // emulate grade element
d3c3da1b 1031 $eid = $this->gtree->get_grade_eid($grade);
1032 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
2cc773f5 1033
edb7d5ad 1034 $itemcell->attributes['class'] .= ' grade i'.$itemid;
dff9d94d 1035 if ($item->is_category_item()) {
16be8974 1036 $itemcell->attributes['class'] .= ' cat';
b89a70ce 1037 }
dff9d94d 1038 if ($item->is_course_item()) {
16be8974 1039 $itemcell->attributes['class'] .= ' course';
b89a70ce 1040 }
4ba9941c 1041 if ($grade->is_overridden()) {
16be8974 1042 $itemcell->attributes['class'] .= ' overridden';
6ad1af09 1043 $itemcell->attributes['aria-label'] = get_string('overriddengrade', 'gradereport_grader');
4ba9941c 1044 }
85db09fb 1045
fe213365 1046 if (!empty($grade->feedback)) {
feb0014b
AN
1047 $feedback = wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br>');
1048 $itemcell->attributes['data-feedback'] = $feedback;
1049 $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content' => $feedback);
653a8648 1050 }
1051
23207a1a 1052 if ($grade->is_excluded()) {
d688ee6d
FM
1053 // Adding white spaces before and after to prevent a screenreader from
1054 // thinking that the words are attached to the next/previous <span> or text.
1055 $itemcell->text .= " <span class='excludedfloater'>" . $strexcludedgrades . "</span> ";
23207a1a 1056 }
1057
4ba9941c 1058 // Do not show any icons if no grade (no record in DB to match)
d3c3da1b 1059 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
6c096a49 1060 $itemcell->text .= $this->get_icons($element);
4ba9941c 1061 }
1062
80fb1cf9 1063 $hidden = '';
1064 if ($grade->is_hidden()) {
cff613f0 1065 $hidden = ' dimmed_text ';
80fb1cf9 1066 }
6cc3e350 1067
d24832f9 1068 $gradepass = ' gradefail ';
46e6df89 1069 if ($grade->is_passed($item)) {
1070 $gradepass = ' gradepass ';
02d1a0a5 1071 } else if (is_null($grade->is_passed($item))) {
e6477988 1072 $gradepass = '';
46e6df89 1073 }
1074
6ef4878b 1075 // if in editing mode, we need to print either a text box
4ba9941c 1076 // or a drop down (for scales)
4ba9941c 1077 // grades in item of type grade category or course are not directly editable
d14ae855 1078 if ($item->needsupdate) {
b21b32a4 1079 $itemcell->text .= "<span class='gradingerror{$hidden}'>" . $strerror . "</span>";
d14ae855 1080
2cc773f5 1081 } else if ($USER->gradeediting[$this->courseid]) {
4ba9941c 1082
12f946d9
EM
1083 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1084 $itemcell->attributes['class'] .= ' grade_type_scale';
1085 } else if ($item->gradetype == GRADE_TYPE_VALUE) {
1086 $itemcell->attributes['class'] .= ' grade_type_value';
1087 } else if ($item->gradetype == GRADE_TYPE_TEXT) {
1088 $itemcell->attributes['class'] .= ' grade_type_text';
1089 }
1090
319770d7 1091 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1092 $scale = $scalesarray[$item->scaleid];
99ccfda8 1093 $gradeval = (int)$gradeval; // scales use only integers
388234f4 1094 $scales = explode(",", $scale->scale);
1095 // reindex because scale is off 1
9d35e66e 1096
914ea002 1097 // MDL-12104 some previous scales might have taken up part of the array
1098 // so this needs to be reset
d48ebf97 1099 $scaleopt = array();
388234f4 1100 $i = 0;
1101 foreach ($scales as $scaleoption) {
1102 $i++;
1103 $scaleopt[$i] = $scaleoption;
1104 }
1105
b21b32a4 1106 if ($quickgrading and $grade->is_editable()) {
0658afc9 1107 $oldval = empty($gradeval) ? -1 : $gradeval;
1108 if (empty($item->outcomeid)) {
d4795a07 1109 $nogradestr = $this->get_lang_string('nograde');
0658afc9 1110 } else {
d4795a07 1111 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
0658afc9 1112 }
fe213365 1113 $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
ccdda855 1114 $gradelabel = $fullname . ' ' . $item->get_name(true);
3087835a
JO
1115 $itemcell->text .= html_writer::label(
1116 get_string('useractivitygrade', 'gradereport_grader', $gradelabel), $attributes['id'], false,
b21b32a4 1117 array('class' => 'accesshide'));
30793ea3 1118 $itemcell->text .= html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']', $gradeval, array(-1=>$nogradestr), $attributes);
02d1a0a5 1119 } else if (!empty($scale)) {
4ba9941c 1120 $scales = explode(",", $scale->scale);
4ba9941c 1121
388234f4 1122 // invalid grade if gradeval < 1
99ccfda8 1123 if ($gradeval < 1) {
b21b32a4 1124 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>-</span>";
4ba9941c 1125 } else {
653a8648 1126 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
b21b32a4 1127 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>{$scales[$gradeval - 1]}</span>";
4ba9941c 1128 }
1129 }
79eabc2a 1130
bb384a8e 1131 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
b21b32a4 1132 if ($quickgrading and $grade->is_editable()) {
76317c73 1133 $value = format_float($gradeval, $decimalpoints);
ccdda855 1134 $gradelabel = $fullname . ' ' . $item->get_name(true);
7400be1b
RT
1135 $itemcell->text .= '<label class="accesshide" for="grade_'.$userid.'_'.$item->id.'">'
1136 .get_string('useractivitygrade', 'gradereport_grader', $gradelabel).'</label>';
6c096a49 1137 $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
30793ea3
PN
1138 . '" type="text" class="text" title="'. $strgrade .'" name="grade['
1139 .$userid.'][' .$item->id.']" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
4ba9941c 1140 } else {
b21b32a4
AN
1141 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>" .
1142 format_float($gradeval, $decimalpoints) . "</span>";
4ba9941c 1143 }
1144 }
1145
4ba9941c 1146 // If quickfeedback is on, print an input element
b21b32a4 1147 if ($showquickfeedback and $grade->is_editable()) {
9566b021 1148 $feedbacklabel = $fullname . ' ' . $item->get_name(true);
7400be1b
RT
1149 $itemcell->text .= '<label class="accesshide" for="feedback_'.$userid.'_'.$item->id.'">'
1150 .get_string('useractivityfeedback', 'gradereport_grader', $feedbacklabel).'</label>';
fe213365 1151 $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
30793ea3 1152 . '" size="6" title="' . $strfeedback . '" type="text" name="feedback['.$userid.']['.$item->id.']" value="' . s($grade->feedback) . '" />';
4ba9941c 1153 }
1154
78a2d9f0 1155 } else { // Not editing
41f22daa 1156 $gradedisplaytype = $item->get_displaytype();
e50ce569 1157
fe213365 1158 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
16be8974 1159 $itemcell->attributes['class'] .= ' grade_type_scale';
12f946d9
EM
1160 } else if ($item->gradetype == GRADE_TYPE_VALUE) {
1161 $itemcell->attributes['class'] .= ' grade_type_value';
1162 } else if ($item->gradetype == GRADE_TYPE_TEXT) {
16be8974 1163 $itemcell->attributes['class'] .= ' grade_type_text';
fe213365 1164 }
4ba9941c 1165
12f946d9
EM
1166 // Only allow edting if the grade is editable (not locked, not in a unoverridable category, etc).
1167 if ($enableajax && $grade->is_editable()) {
1168 // If a grade item is type text, and we don't have show quick feedback on, it can't be edited.
1169 if ($item->gradetype != GRADE_TYPE_TEXT || $showquickfeedback) {
0e999796
AD
1170 $itemcell->attributes['class'] .= ' clickable';
1171 }
6712973f
AD
1172 }
1173
d14ae855 1174 if ($item->needsupdate) {
b21b32a4 1175 $itemcell->text .= "<span class='gradingerror{$hidden}{$gradepass}'>" . $error . "</span>";
4ba9941c 1176 } else {
5a59aeb1
DW
1177 // The max and min for an aggregation may be different to the grade_item.
1178 if (!is_null($gradeval)) {
ebea19cb
FM
1179 $item->grademax = $grade->get_grade_max();
1180 $item->grademin = $grade->get_grade_min();
5a59aeb1
DW
1181 }
1182
b21b32a4
AN
1183 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>" .
1184 grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null) . "</span>";
1185 if ($showanalysisicon) {
f17bb885 1186 $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
bb17ac1e 1187 }
4ba9941c 1188 }
4ba9941c 1189 }
1190
245f45f4
PN
1191 // Enable keyboard navigation if the grade is editable (not locked, not in a unoverridable category, etc).
1192 if ($enableajax && $grade->is_editable()) {
1193 // If a grade item is type text, and we don't have show quick feedback on, it can't be edited.
1194 if ($item->gradetype != GRADE_TYPE_TEXT || $showquickfeedback) {
1195 $itemcell->attributes['class'] .= ' gbnavigable';
1196 }
1197 }
1198
4ba9941c 1199 if (!empty($this->gradeserror[$item->id][$userid])) {
6c096a49 1200 $itemcell->text .= $this->gradeserror[$item->id][$userid];
4ba9941c 1201 }
1202
6c096a49 1203 $itemrow->cells[] = $itemcell;
4ba9941c 1204 }
6c096a49 1205 $rows[] = $itemrow;
4ba9941c 1206 }
4ba9941c 1207
b21b32a4 1208 if ($enableajax) {
fe213365
SH
1209 $jsarguments['cfg']['ajaxenabled'] = true;
1210 $jsarguments['cfg']['scales'] = array();
1211 foreach ($jsscales as $scale) {
12f946d9
EM
1212 // Trim the scale values, as they may have a space that is ommitted from values later.
1213 $jsarguments['cfg']['scales'][$scale->id] = array_map('trim', explode(',', $scale->scale));
fe213365
SH
1214 }
1215 $jsarguments['cfg']['feedbacktrunclength'] = $this->feedback_trunc_length;
92ff6236 1216
a740a0ad 1217 // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades']
fe213365
SH
1218 }
1219 $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
b21b32a4
AN
1220 $jsarguments['cfg']['courseid'] = $this->courseid;
1221 $jsarguments['cfg']['studentsperpage'] = $this->get_students_per_page();
1222 $jsarguments['cfg']['showquickfeedback'] = (bool) $showquickfeedback;
fe213365
SH
1223
1224 $module = array(
1225 'name' => 'gradereport_grader',
1226 'fullpath' => '/grade/report/grader/module.js',
227e9023 1227 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
fe213365
SH
1228 );
1229 $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
02d1a0a5
MA
1230 $PAGE->requires->strings_for_js(array('addfeedback', 'feedback', 'grade'), 'grades');
1231 $PAGE->requires->strings_for_js(array('ajaxchoosescale', 'ajaxclicktoclose', 'ajaxerror', 'ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
b21b32a4 1232 if (!$enableajax && $USER->gradeediting[$this->courseid]) {
0f204015
AO
1233 $PAGE->requires->yui_module('moodle-core-formchangechecker',
1234 'M.core_formchangechecker.init',
1235 array(array(
1236 'formid' => 'gradereport_grader'
1237 ))
1238 );
1239 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
1240 }
fe213365 1241
6c096a49 1242 $rows = $this->get_right_range_row($rows);
cbe8e5b3
MA
1243 if ($displayaverages) {
1244 $rows = $this->get_right_avg_row($rows, true);
1245 $rows = $this->get_right_avg_row($rows);
1246 }
dc482cfa 1247
6c096a49
NC
1248 return $rows;
1249 }
dc482cfa 1250
6c096a49
NC
1251 /**
1252 * Depending on the style of report (fixedstudents vs traditional one-table),
1253 * arranges the rows of data in one or two tables, and returns the output of
1254 * these tables in HTML
2b267d31 1255 * @param boolean $displayaverages whether to display average rows in the table
6c096a49
NC
1256 * @return string HTML
1257 */
cbe8e5b3 1258 public function get_grade_table($displayaverages = false) {
6c096a49 1259 global $OUTPUT;
cbe8e5b3
MA
1260 $leftrows = $this->get_left_rows($displayaverages);
1261 $rightrows = $this->get_right_rows($displayaverages);
dc482cfa 1262
6c096a49 1263 $html = '';
dc482cfa 1264
8c037a91 1265 $fulltable = new html_table();
31819e89 1266 $fulltable->attributes['class'] = 'gradereport-grader-table';
8c037a91 1267 $fulltable->id = 'user-grades';
6929b68b 1268 $fulltable->summary = get_string('summarygrader', 'gradereport_grader');
319770d7 1269
8c037a91
AN
1270 // Extract rows from each side (left and right) and collate them into one row each
1271 foreach ($leftrows as $key => $row) {
1272 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1273 $fulltable->data[] = $row;
6c096a49 1274 }
8c037a91 1275 $html .= html_writer::table($fulltable);
6c096a49
NC
1276 return $OUTPUT->container($html, 'gradeparent');
1277 }
dc482cfa 1278
6c096a49
NC
1279 /**
1280 * Builds and return the row of icons for the left side of the report.
1281 * It only has one cell that says "Controls"
1282 * @param array $rows The Array of rows for the left part of the report
1283 * @param int $colspan The number of columns this cell has to span
1284 * @return array Array of rows for the left part of the report
1285 */
1286 public function get_left_icons_row($rows=array(), $colspan=1) {
1287 global $USER;
dc482cfa 1288
6c096a49
NC
1289 if ($USER->gradeediting[$this->courseid]) {
1290 $controlsrow = new html_table_row();
16be8974 1291 $controlsrow->attributes['class'] = 'controls';
6c096a49 1292 $controlscell = new html_table_cell();
16be8974 1293 $controlscell->attributes['class'] = 'header controls';
6c096a49 1294 $controlscell->colspan = $colspan;
02d1a0a5 1295 $controlscell->text = $this->get_lang_string('controls', 'grades');
6c096a49
NC
1296
1297 $controlsrow->cells[] = $controlscell;
1298 $rows[] = $controlsrow;
1299 }
1300 return $rows;
1301 }
dc482cfa 1302
6c096a49
NC
1303 /**
1304 * Builds and return the header for the row of ranges, for the left part of the grader report.
1305 * @param array $rows The Array of rows for the left part of the report
1306 * @param int $colspan The number of columns this cell has to span
1307 * @return array Array of rows for the left part of the report
1308 */
1309 public function get_left_range_row($rows=array(), $colspan=1) {
1310 global $CFG, $USER;
bb9b58a6 1311
6c096a49
NC
1312 if ($this->get_pref('showranges')) {
1313 $rangerow = new html_table_row();
16be8974 1314 $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
6c096a49 1315 $rangecell = new html_table_cell();
16be8974 1316 $rangecell->attributes['class'] = 'header range';
6c096a49
NC
1317 $rangecell->colspan = $colspan;
1318 $rangecell->header = true;
1319 $rangecell->scope = 'row';
02d1a0a5 1320 $rangecell->text = $this->get_lang_string('range', 'grades');
6c096a49
NC
1321 $rangerow->cells[] = $rangecell;
1322 $rows[] = $rangerow;
1323 }
dc482cfa 1324
6c096a49
NC
1325 return $rows;
1326 }
dc482cfa 1327
6c096a49
NC
1328 /**
1329 * Builds and return the headers for the rows of averages, for the left part of the grader report.
1330 * @param array $rows The Array of rows for the left part of the report
1331 * @param int $colspan The number of columns this cell has to span
1332 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1333 * @return array Array of rows for the left part of the report
1334 */
1335 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1336 if (!$this->canviewhidden) {
1337 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1338 // better not show them at all if user can not see all hideen grades
1339 return $rows;
1340 }
dc482cfa 1341
6c096a49
NC
1342 $showaverages = $this->get_pref('showaverages');
1343 $showaveragesgroup = $this->currentgroup && $showaverages;
1344 $straveragegroup = get_string('groupavg', 'grades');
319770d7 1345
6c096a49 1346 if ($groupavg) {
319770d7 1347 if ($showaveragesgroup) {
1348 $groupavgrow = new html_table_row();
16be8974 1349 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
319770d7 1350 $groupavgcell = new html_table_cell();
16be8974 1351 $groupavgcell->attributes['class'] = 'header range';
319770d7 1352 $groupavgcell->colspan = $colspan;
1353 $groupavgcell->header = true;
1354 $groupavgcell->scope = 'row';
1355 $groupavgcell->text = $straveragegroup;
1356 $groupavgrow->cells[] = $groupavgcell;
6c096a49 1357 $rows[] = $groupavgrow;
203b7e2e 1358 }
6c096a49
NC
1359 } else {
1360 $straverage = get_string('overallaverage', 'grades');
dc482cfa 1361
203b7e2e 1362 if ($showaverages) {
319770d7 1363 $avgrow = new html_table_row();
16be8974 1364 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
319770d7 1365 $avgcell = new html_table_cell();
16be8974 1366 $avgcell->attributes['class'] = 'header range';
319770d7 1367 $avgcell->colspan = $colspan;
1368 $avgcell->header = true;
1369 $avgcell->scope = 'row';
1370 $avgcell->text = $straverage;
1371 $avgrow->cells[] = $avgcell;
6c096a49 1372 $rows[] = $avgrow;
203b7e2e 1373 }
6c096a49 1374 }
203b7e2e 1375
6c096a49
NC
1376 return $rows;
1377 }
dc482cfa 1378
6c096a49
NC
1379 /**
1380 * Builds and return the row of icons when editing is on, for the right part of the grader report.
1381 * @param array $rows The Array of rows for the right part of the report
1382 * @return array Array of rows for the right part of the report
1383 */
1384 public function get_right_icons_row($rows=array()) {
1385 global $USER;
1386 if ($USER->gradeediting[$this->courseid]) {
1387 $iconsrow = new html_table_row();
16be8974 1388 $iconsrow->attributes['class'] = 'controls';
6c096a49 1389
02d1a0a5 1390 foreach ($this->gtree->items as $itemid => $unused) {
6c096a49 1391 // emulate grade element
e2bb3c92 1392 $item = $this->gtree->get_item($itemid);
6c096a49
NC
1393
1394 $eid = $this->gtree->get_item_eid($item);
1395 $element = $this->gtree->locate_element($eid);
1396 $itemcell = new html_table_cell();
edb7d5ad 1397 $itemcell->attributes['class'] = 'controls icons i'.$itemid;
6c096a49
NC
1398 $itemcell->text = $this->get_icons($element);
1399 $iconsrow->cells[] = $itemcell;
1400 }
1401 $rows[] = $iconsrow;
1402 }
1403 return $rows;
dc482cfa 1404 }
1405
18a00359 1406 /**
6c096a49
NC
1407 * Builds and return the row of ranges for the right part of the grader report.
1408 * @param array $rows The Array of rows for the right part of the report
1409 * @return array Array of rows for the right part of the report
18a00359 1410 */
6c096a49
NC
1411 public function get_right_range_row($rows=array()) {
1412 global $OUTPUT;
18a00359 1413
6c096a49
NC
1414 if ($this->get_pref('showranges')) {
1415 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
1416 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1417 $rangerow = new html_table_row();
16be8974 1418 $rangerow->attributes['class'] = 'heading range';
18a00359 1419
02d1a0a5 1420 foreach ($this->gtree->items as $itemid => $unused) {
6c096a49
NC
1421 $item =& $this->gtree->items[$itemid];
1422 $itemcell = new html_table_cell();
edb7d5ad 1423 $itemcell->attributes['class'] .= ' range i'. $itemid;
6c096a49
NC
1424
1425 $hidden = '';
1426 if ($item->is_hidden()) {
cff613f0 1427 $hidden = ' dimmed_text ';
6c096a49
NC
1428 }
1429
1430 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1431
1432 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1433 $rangerow->cells[] = $itemcell;
1434 }
1435 $rows[] = $rangerow;
18a00359 1436 }
6c096a49 1437 return $rows;
18a00359 1438 }
1439
4ba9941c 1440 /**
6c096a49
NC
1441 * Builds and return the row of averages for the right part of the grader report.
1442 * @param array $rows Whether to return only group averages or all averages.
1443 * @param bool $grouponly Whether to return only group averages or all averages.
1444 * @return array Array of rows for the right part of the report
4ba9941c 1445 */
6c096a49 1446 public function get_right_avg_row($rows=array(), $grouponly=false) {
c288300c 1447 global $USER, $DB, $OUTPUT, $CFG;
4ba9941c 1448
57068674 1449 if (!$this->canviewhidden) {
4e829d48
MN
1450 // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1451 // better not show them at all if user can not see all hidden grades.
6c096a49 1452 return $rows;
57068674 1453 }
1454
5b508a08 1455 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
1456 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
098042ba 1457 $meanselection = $this->get_pref('meanselection');
1458 $shownumberofgrades = $this->get_pref('shownumberofgrades');
1459
5b508a08 1460 if ($grouponly) {
35079f53 1461 $showaverages = $this->currentgroup && $this->get_pref('showaverages');
5b508a08 1462 $groupsql = $this->groupsql;
1463 $groupwheresql = $this->groupwheresql;
319770d7 1464 $groupwheresqlparams = $this->groupwheresql_params;
3446013d 1465 } else {
5b508a08 1466 $showaverages = $this->get_pref('showaverages');
0dba6cb2 1467 $groupsql = "";
1468 $groupwheresql = "";
319770d7 1469 $groupwheresqlparams = array();
3446013d 1470 }
1471
4e829d48
MN
1472 if ($showaverages) {
1473 $totalcount = $this->get_numusers($grouponly);
a5b8be62 1474
4e829d48
MN
1475 // Limit to users with a gradeable role.
1476 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
04259694 1477
4e829d48 1478 // Limit to users with an active enrollment.
c288300c
RL
1479 $coursecontext = $this->context->get_course_context(true);
1480 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
1481 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
1482 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
1483 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
387815db 1484
4e829d48
MN
1485 // We want to query both the current context and parent contexts.
1486 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
d24832f9 1487
4e829d48 1488 $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams);
04259694 1489
4e829d48 1490 // Find sums of all grade items in course.
656d17c2 1491 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
d24832f9 1492 FROM {grade_items} gi
656d17c2
AD
1493 JOIN {grade_grades} g ON g.itemid = gi.id
1494 JOIN {user} u ON u.id = g.userid
1495 JOIN ($enrolledsql) je ON je.id = u.id
1496 JOIN (
1497 SELECT DISTINCT ra.userid
1498 FROM {role_assignments} ra
1499 WHERE ra.roleid $gradebookrolessql
4e829d48 1500 AND ra.contextid $relatedctxsql
656d17c2 1501 ) rainner ON rainner.userid = u.id
25081b95 1502 $groupsql
b50371da 1503 WHERE gi.courseid = :courseid
656d17c2
AD
1504 AND u.deleted = 0
1505 AND g.finalgrade IS NOT NULL
1506 $groupwheresql
1507 GROUP BY g.itemid";
319770d7 1508 $sumarray = array();
656d17c2 1509 if ($sums = $DB->get_records_sql($sql, $params)) {
ab3444d7 1510 foreach ($sums as $itemid => $csum) {
319770d7 1511 $sumarray[$itemid] = $csum->sum;
7b61efbe 1512 }
4ba9941c 1513 }
66ef0471 1514
883187d0 1515 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1516 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
656d17c2 1517 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
d24832f9 1518 FROM {grade_items} gi
25081b95
SH
1519 CROSS JOIN {user} u
1520 JOIN ($enrolledsql) je
1521 ON je.id = u.id
1522 JOIN {role_assignments} ra
1523 ON ra.userid = u.id
1524 LEFT OUTER JOIN {grade_grades} g
1525 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1526 $groupsql
b50371da 1527 WHERE gi.courseid = :courseid
387815db 1528 AND ra.roleid $gradebookrolessql
4e829d48 1529 AND ra.contextid $relatedctxsql
656d17c2 1530 AND u.deleted = 0
828af11c 1531 AND g.id IS NULL
1532 $groupwheresql
883187d0 1533 GROUP BY gi.id";
828af11c 1534
656d17c2 1535 $ungradedcounts = $DB->get_records_sql($sql, $params);
883187d0 1536
6c096a49 1537 $avgrow = new html_table_row();
16be8974 1538 $avgrow->attributes['class'] = 'avg';
653a8648 1539
02d1a0a5 1540 foreach ($this->gtree->items as $itemid => $unused) {
b89a70ce 1541 $item =& $this->gtree->items[$itemid];
1542
67881aa8 1543 if ($item->needsupdate) {
6c096a49 1544 $avgcell = new html_table_cell();
edb7d5ad 1545 $avgcell->attributes['class'] = 'i'. $itemid;
6c096a49
NC
1546 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1547 $avgrow->cells[] = $avgcell;
67881aa8 1548 continue;
1549 }
1550
319770d7 1551 if (!isset($sumarray[$item->id])) {
1552 $sumarray[$item->id] = 0;
33a34cd4 1553 }
883187d0 1554
319770d7 1555 if (empty($ungradedcounts[$itemid])) {
1556 $ungradedcount = 0;
828af11c 1557 } else {
319770d7 1558 $ungradedcount = $ungradedcounts[$itemid]->count;
d1556c09 1559 }
33a34cd4 1560
c2efb501 1561 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
319770d7 1562 $meancount = $totalcount - $ungradedcount;
33a34cd4 1563 } else { // Bump up the sum by the number of ungraded items * grademin
319770d7 1564 $sumarray[$item->id] += $ungradedcount * $item->grademin;
1565 $meancount = $totalcount;
33a34cd4 1566 }
1567
bb384a8e 1568 // Determine which display type to use for this average
2cc773f5 1569 if ($USER->gradeediting[$this->courseid]) {
1796708d 1570 $displaytype = GRADE_DISPLAY_TYPE_REAL;
d622930b 1571
e0724506 1572 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
d622930b 1573 $displaytype = $item->get_displaytype();
1574
1575 } else {
bb384a8e 1576 $displaytype = $averagesdisplaytype;
1577 }
1578
31a6c06c 1579 // Override grade_item setting if a display preference (not inherit) was set for the averages
e0724506 1580 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
d622930b 1581 $decimalpoints = $item->get_decimals();
1582
1583 } else {
5b508a08 1584 $decimalpoints = $averagesdecimalpoints;
1585 }
1586
319770d7 1587 if (!isset($sumarray[$item->id]) || $meancount == 0) {
6c096a49 1588 $avgcell = new html_table_cell();
edb7d5ad 1589 $avgcell->attributes['class'] = 'i'. $itemid;
6c096a49
NC
1590 $avgcell->text = '-';
1591 $avgrow->cells[] = $avgcell;
1592
4ba9941c 1593 } else {
319770d7 1594 $sum = $sumarray[$item->id];
1595 $avgradeval = $sum/$meancount;
d622930b 1596 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
bb384a8e 1597
098042ba 1598 $numberofgrades = '';
098042ba 1599 if ($shownumberofgrades) {
319770d7 1600 $numberofgrades = " ($meancount)";
098042ba 1601 }
1602
6c096a49 1603 $avgcell = new html_table_cell();
edb7d5ad 1604 $avgcell->attributes['class'] = 'i'. $itemid;
6c096a49
NC
1605 $avgcell->text = $gradehtml.$numberofgrades;
1606 $avgrow->cells[] = $avgcell;
80fb1cf9 1607 }
9ecd4386 1608 }
6c096a49 1609 $rows[] = $avgrow;
9ecd4386 1610 }
6c096a49 1611 return $rows;
9ecd4386 1612 }
4ba9941c 1613
2350b3f4
ZD
1614 /**
1615 * Given element category, create a collapsible icon and
1616 * course header.
1617 *
6611780e 1618 * @param array $element
2350b3f4
ZD
1619 * @return string HTML
1620 */
1621 protected function get_course_header($element) {
1622 global $OUTPUT;
1623
1624 $icon = '';
1625 // If object is a category, display expand/contract icon.
1626 if ($element['type'] == 'category') {
1627 // Load language strings.
1628 $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1629 $strswitchplus = $this->get_lang_string('gradesonly', 'grades');
1630 $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1631
1632 $url = new moodle_url($this->gpr->get_return_url(null, array('target' => $element['eid'], 'sesskey' => sesskey())));
1633
1634 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1635 $url->param('action', 'switch_plus');
1636 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus), null, null);
1637 $showing = get_string('showingaggregatesonly', 'grades');
1638 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1639 $url->param('action', 'switch_whole');
1640 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole), null, null);
1641 $showing = get_string('showinggradesonly', 'grades');
1642 } else {
1643 $url->param('action', 'switch_minus');
1644 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus), null, null);
1645 $showing = get_string('showingfullmode', 'grades');
1646 }
1647 }
1648
0cfeb014 1649 $name = $element['object']->get_name();
7b287e09 1650 $courseheaderid = 'courseheader_' . clean_param($name, PARAM_ALPHANUMEXT);
0cfeb014
JB
1651 $courseheader = html_writer::tag('span', $name, array('id' => $courseheaderid,
1652 'title' => $name, 'class' => 'gradeitemheader'));
7b287e09 1653 $courseheader .= html_writer::label($showing, $courseheaderid, false, array('class' => 'accesshide'));
2350b3f4
ZD
1654 $courseheader .= $icon;
1655
1656 return $courseheader;
1657 }
1658
4ba9941c 1659 /**
1660 * Given a grade_category, grade_item or grade_grade, this function
1661 * figures out the state of the object and builds then returns a div
1662 * with the icons needed for the grader report.
1663 *
02d1a0a5 1664 * @param array $element
4ba9941c 1665 * @return string HTML
1666 */
d24832f9 1667 protected function get_icons($element) {
319770d7 1668 global $CFG, $USER, $OUTPUT;
4ba9941c 1669
2cc773f5 1670 if (!$USER->gradeediting[$this->courseid]) {
1671 return '<div class="grade_icons" />';
79eabc2a 1672 }
4ba9941c 1673
2cc773f5 1674 // Init all icons
319770d7 1675 $editicon = '';
dc482cfa 1676
0e999796
AD
1677 $editable = true;
1678
1679 if ($element['type'] == 'grade') {
1680 $item = $element['object']->grade_item;
1681 if ($item->is_course_item() or $item->is_category_item()) {
1682 $editable = $this->overridecat;
1683 }
1684 }
1685
1686 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) {
319770d7 1687 $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
dc482cfa 1688 }
1689
319770d7 1690 $editcalculationicon = '';
1691 $showhideicon = '';
1692 $lockunlockicon = '';
4ba9941c 1693
a5b8be62 1694 if (has_capability('moodle/grade:manage', $this->context)) {
a5b8be62 1695 if ($this->get_pref('showcalculations')) {
319770d7 1696 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
a5b8be62 1697 }
1698
1699 if ($this->get_pref('showeyecons')) {
02d1a0a5 1700 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
a5b8be62 1701 }
4ba9941c 1702
a5b8be62 1703 if ($this->get_pref('showlocks')) {
319770d7 1704 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
a5b8be62 1705 }
c97933ff
MG
1706
1707 }
1708
1709 $gradeanalysisicon = '';
1710 if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1711 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
4ba9941c 1712 }
1713
c97933ff 1714 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
4faf5f99 1715 }
1716
1717 /**
1718 * Given a category element returns collapsing +/- icon if available
2350b3f4
ZD
1719 *
1720 * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more.
4faf5f99 1721 */
d24832f9 1722 protected function get_collapsing_icon($element) {
7481f422 1723 throw new coding_exception('get_collapsing_icon() can not be used any more, please use get_course_header() instead.');
4ba9941c 1724 }
48b5d8f3 1725
02d1a0a5
MA
1726 /**
1727 * Processes a single action against a category, grade_item or grade.
1728 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1729 * @param string $action Which action to take (edit, delete etc...)
1730 * @return
1731 */
1e88baa0 1732 public function process_action($target, $action) {
9fe5a1b8
MG
1733 return self::do_process_action($target, $action, $this->course->id);
1734 }
1735
1736 /**
1737 * From the list of categories that this user prefers to collapse choose ones that belong to the current course.
1738 *
1739 * This function serves two purposes.
1740 * Mainly it helps migrating from user preference style when all courses were stored in one preference.
1741 * Also it helps to remove the settings for categories that were removed if the array for one course grows too big.
1742 *
1743 * @param int $courseid
1744 * @param array $collapsed
1745 * @return array
1746 */
1747 protected static function filter_collapsed_categories($courseid, $collapsed) {
1748 global $DB;
1749 if (empty($collapsed)) {
1750 $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1751 }
1752 if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) {
1753 return $collapsed;
1754 }
1755 $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid));
1756 $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats));
1757 $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats));
1758 return $collapsed;
1759 }
1760
1761 /**
1762 * Returns the list of categories that this user wants to collapse or display aggregatesonly
1763 *
1764 * This method also migrates on request from the old format of storing user preferences when they were stored
1765 * in one preference for all courses causing DB error when trying to insert very big value.
1766 *
1767 * @param int $courseid
1768 * @return array
1769 */
1770 protected static function get_collapsed_preferences($courseid) {
1771 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) {
1772 return json_decode($collapsed, true);
1773 }
1774
1775 // Try looking for old location of user setting that used to store all courses in one serialized user preference.
1776 if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) {
6e65554e 1777 if ($collapsedall = unserialize_array($oldcollapsedpref)) {
9fe5a1b8
MG
1778 // We found the old-style preference, filter out only categories that belong to this course and update the prefs.
1779 $collapsed = static::filter_collapsed_categories($courseid, $collapsedall);
1780 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1781 static::set_collapsed_preferences($courseid, $collapsed);
1782 $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']);
1783 $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']);
1784 if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) {
1785 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall));
1786 } else {
1787 unset_user_preference('grade_report_grader_collapsed_categories');
1788 }
1789 }
1790 } else {
1791 // We found the old-style preference, but it is unreadable, discard it.
1792 unset_user_preference('grade_report_grader_collapsed_categories');
1793 }
1794 } else {
1795 $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1796 }
1797 return $collapsed;
1798 }
1799
1800 /**
1801 * Sets the list of categories that user wants to see collapsed in user preferences
1802 *
1803 * This method may filter or even trim the list if it does not fit in DB field.
1804 *
1805 * @param int $courseid
1806 * @param array $collapsed
1807 */
1808 protected static function set_collapsed_preferences($courseid, $collapsed) {
1809 global $DB;
1810 // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size,
1811 // try to filter the list of categories since array may contain categories that were deleted.
1812 if (strlen(json_encode($collapsed)) >= 1333) {
1813 $collapsed = static::filter_collapsed_categories($courseid, $collapsed);
1814 }
1815
1816 // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information.
1817 while (strlen(json_encode($collapsed)) >= 1333) {
1818 if (count($collapsed['aggregatesonly'])) {
1819 array_pop($collapsed['aggregatesonly']);
1820 }
1821 if (count($collapsed['gradesonly'])) {
1822 array_pop($collapsed['gradesonly']);
1823 }
1824 }
1825
1826 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1827 set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed));
1828 } else {
1829 unset_user_preference('grade_report_grader_collapsed_categories'.$courseid);
1830 }
1e88baa0
TH
1831 }
1832
48b5d8f3 1833 /**
1834 * Processes a single action against a category, grade_item or grade.
1835 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1836 * @param string $action Which action to take (edit, delete etc...)
9fe5a1b8 1837 * @param int $courseid affected course.
48b5d8f3 1838 * @return
1839 */
9fe5a1b8
MG
1840 public static function do_process_action($target, $action, $courseid = null) {
1841 global $DB;
4faf5f99 1842 // TODO: this code should be in some grade_tree static method
165cdaba
MG
1843 $targettype = substr($target, 0, 2);
1844 $targetid = substr($target, 2);
4faf5f99 1845 // TODO: end
1846
165cdaba 1847 if ($targettype !== 'cg') {
9fe5a1b8
MG
1848 // The following code only works with categories.
1849 return true;
1850 }
1851
1852 if (!$courseid) {
1853 debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid',
1854 DEBUG_DEVELOPER);
1855 if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) {
1856 return true;
1857 }
4faf5f99 1858 }
1859
9fe5a1b8
MG
1860 $collapsed = static::get_collapsed_preferences($courseid);
1861
48b5d8f3 1862 switch ($action) {
384960dd 1863 case 'switch_minus': // Add category to array of aggregatesonly
1864 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1865 $collapsed['aggregatesonly'][] = $targetid;
9fe5a1b8 1866 static::set_collapsed_preferences($courseid, $collapsed);
4faf5f99 1867 }
48b5d8f3 1868 break;
4faf5f99 1869
384960dd 1870 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1871 $key = array_search($targetid, $collapsed['aggregatesonly']);
4faf5f99 1872 if ($key !== false) {
384960dd 1873 unset($collapsed['aggregatesonly'][$key]);
4faf5f99 1874 }
384960dd 1875 if (!in_array($targetid, $collapsed['gradesonly'])) {
1876 $collapsed['gradesonly'][] = $targetid;
1877 }
9fe5a1b8 1878 static::set_collapsed_preferences($courseid, $collapsed);
48b5d8f3 1879 break;
384960dd 1880 case 'switch_whole': // Remove the category from the array of collapsed cats
1881 $key = array_search($targetid, $collapsed['gradesonly']);
1882 if ($key !== false) {
1883 unset($collapsed['gradesonly'][$key]);
9fe5a1b8 1884 static::set_collapsed_preferences($courseid, $collapsed);
384960dd 1885 }
4faf5f99 1886
384960dd 1887 break;
48b5d8f3 1888 default:
1889 break;
1890 }
1891
1892 return true;
1893 }
03fcc729 1894
6c096a49
NC
1895 /**
1896 * Refactored function for generating HTML of sorting links with matching arrows.
1897 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1898 * to inject into a table header cell.
e4aec5be 1899 * @param array $extrafields Array of extra fields being displayed, such as
1900 * user idnumber
6c096a49
NC
1901 * @return array An associative array of HTML sorting links+arrows
1902 */
e4aec5be 1903 public function get_sort_arrows(array $extrafields = array()) {
727d3d70 1904 global $OUTPUT, $CFG;
6c096a49
NC
1905 $arrows = array();
1906
1907 $strsortasc = $this->get_lang_string('sortasc', 'grades');
1908 $strsortdesc = $this->get_lang_string('sortdesc', 'grades');
0cddd851
FM
1909 $iconasc = $OUTPUT->pix_icon('t/sort_asc', $strsortasc, '', array('class' => 'iconsmall sorticon'));
1910 $icondesc = $OUTPUT->pix_icon('t/sort_desc', $strsortdesc, '', array('class' => 'iconsmall sorticon'));
6c096a49 1911
727d3d70
P
1912 // Sourced from tablelib.php
1913 // Check the full name display for sortable fields.
1dcb2445 1914 if (has_capability('moodle/site:viewfullnames', $this->context)) {
727d3d70
P
1915 $nameformat = $CFG->alternativefullnameformat;
1916 } else {
1917 $nameformat = $CFG->fullnamedisplay;
6c096a49
NC
1918 }
1919
727d3d70
P
1920 if ($nameformat == 'language') {
1921 $nameformat = get_string('fullnamedisplay');
1922 }
6c096a49 1923
727d3d70
P
1924 $arrows['studentname'] = '';
1925 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1926 if (!empty($requirednames)) {
1927 foreach ($requirednames as $name) {
1928 $arrows['studentname'] .= html_writer::link(
1929 new moodle_url($this->baseurl, array('sortitemid' => $name)), $this->get_lang_string($name)
1930 );
1931 if ($this->sortitemid == $name) {
1932 $arrows['studentname'] .= $this->sortorder == 'ASC' ? $iconasc : $icondesc;
1933 }
1934 $arrows['studentname'] .= ' / ';
6c096a49 1935 }
727d3d70
P
1936
1937 $arrows['studentname'] = substr($arrows['studentname'], 0, -3);
6c096a49
NC
1938 }
1939
e4aec5be 1940 foreach ($extrafields as $field) {
1941 $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1942 array('sortitemid'=>$field)), get_user_field_name($field));
1943 $arrows[$field] = $fieldlink;
6c096a49 1944
e4aec5be 1945 if ($field == $this->sortitemid) {
1946 if ($this->sortorder == 'ASC') {
0cddd851 1947 $arrows[$field] .= $iconasc;
e4aec5be 1948 } else {
0cddd851 1949 $arrows[$field] .= $icondesc;
e4aec5be 1950 }
6c096a49
NC
1951 }
1952 }
1953
1954 return $arrows;
1955 }
d3b698a4
AD
1956
1957 /**
a740a0ad 1958 * Returns the maximum number of students to be displayed on each page
d3b698a4 1959 *
a740a0ad 1960 * @return int The maximum number of students to display per page
d3b698a4 1961 */
a740a0ad 1962 public function get_students_per_page() {
a3777547 1963 return $this->get_pref('studentsperpage');
d3b698a4 1964 }
4ba9941c 1965}
6c3ef410 1966