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