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