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