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