MDL-36559 usability: Gradebook CSS styling for new icons
[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
4cf69ee3 520 * @deprecated since 2.4 as it appears not to be used any more.
4ba9941c 521 */
d24832f9 522 public function get_toggles_html() {
319770d7 523 global $CFG, $USER, $COURSE, $OUTPUT;
4cf69ee3 524 debugging('Call to deprecated function grade_report_grader::get_toggles_html().', DEBUG_DEVELOPER);
319770d7 525 $html = '';
2cc773f5 526 if ($USER->gradeediting[$this->courseid]) {
527 if (has_capability('moodle/grade:manage', $this->context) or has_capability('moodle/grade:hide', $this->context)) {
319770d7 528 $html .= $this->print_toggle('eyecons');
2cc773f5 529 }
530 if (has_capability('moodle/grade:manage', $this->context)
531 or has_capability('moodle/grade:lock', $this->context)
532 or has_capability('moodle/grade:unlock', $this->context)) {
319770d7 533 $html .= $this->print_toggle('locks');
2cc773f5 534 }
2ca093fa 535 if (has_capability('moodle/grade:manage', $this->context)) {
319770d7 536 $html .= $this->print_toggle('quickfeedback');
2ca093fa 537 }
538
2cc773f5 539 if (has_capability('moodle/grade:manage', $this->context)) {
319770d7 540 $html .= $this->print_toggle('calculations');
2cc773f5 541 }
4ba9941c 542 }
543
57068674 544 if ($this->canviewhidden) {
319770d7 545 $html .= $this->print_toggle('averages');
57068674 546 }
aae94377 547
319770d7 548 $html .= $this->print_toggle('ranges');
aea4df41 549 if (!empty($CFG->enableoutcomes)) {
319770d7 550 $html .= $this->print_toggle('nooutcomes');
aea4df41 551 }
319770d7 552
553 return $OUTPUT->container($html, 'grade-report-toggles');
4ba9941c 554 }
555
556 /**
557 * Shortcut function for printing the grader report toggles.
558 * @param string $type The type of toggle
559 * @param bool $return Whether to return the HTML string rather than printing it
560 * @return void
4cf69ee3 561 * @deprecated since 2.4 as it appears not to be used any more.
4ba9941c 562 */
319770d7 563 public function print_toggle($type) {
e63f88c9 564 global $CFG, $OUTPUT;
4cf69ee3 565 debugging('Call to deprecated function grade_report_grader::print_toggle().', DEBUG_DEVELOPER);
319770d7 566 $icons = array('eyecons' => 't/hide',
567 'calculations' => 't/calc',
568 'locks' => 't/lock',
569 'averages' => 't/mean',
570 'quickfeedback' => 't/feedback',
571 'nooutcomes' => 't/outcomes');
4ba9941c 572
319770d7 573 $prefname = 'grade_report_show' . $type;
aea4df41 574
319770d7 575 if (array_key_exists($prefname, $CFG)) {
576 $showpref = get_user_preferences($prefname, $CFG->$prefname);
aea4df41 577 } else {
319770d7 578 $showpref = get_user_preferences($prefname);
aea4df41 579 }
4ba9941c 580
388234f4 581 $strshow = $this->get_lang_string('show' . $type, 'grades');
582 $strhide = $this->get_lang_string('hide' . $type, 'grades');
4ba9941c 583
319770d7 584 $showhide = 'show';
585 $toggleaction = 1;
4ba9941c 586
319770d7 587 if ($showpref) {
588 $showhide = 'hide';
589 $toggleaction = 0;
4ba9941c 590 }
591
592 if (array_key_exists($type, $icons)) {
319770d7 593 $imagename = $icons[$type];
4ba9941c 594 } else {
b11681e0 595 $imagename = "t/$type";
4ba9941c 596 }
597
319770d7 598 $string = ${'str' . $showhide};
4ba9941c 599
e1513ca9 600 $url = new moodle_url($this->baseurl, array('toggle' => $toggleaction, 'toggle_type' => $type));
4ba9941c 601
c63923bd 602 $retval = $OUTPUT->container($OUTPUT->action_icon($url, new pix_icon($imagename, $string))); // TODO: this container looks wrong here
4ba9941c 603
319770d7 604 return $retval;
4ba9941c 605 }
606
607 /**
6c096a49
NC
608 * Builds and returns the rows that will make up the left part of the grader report
609 * This consists of student names and icons, links to user reports and id numbers, as well
610 * as header cells for these columns. It also includes the fillers required for the
611 * categories displayed on the right side of the report.
612 * @return array Array of html_table_row objects
4ba9941c 613 */
6c096a49 614 public function get_left_rows() {
319770d7 615 global $CFG, $USER, $OUTPUT;
4ba9941c 616
6c096a49
NC
617 $rows = array();
618
619 $showuserimage = $this->get_pref('showuserimage');
203b7e2e 620
6c096a49
NC
621 $strfeedback = $this->get_lang_string("feedback");
622 $strgrade = $this->get_lang_string('grade');
203b7e2e 623
e4aec5be 624 $extrafields = get_extra_user_fields($this->context);
6c096a49 625
e4aec5be 626 $arrows = $this->get_sort_arrows($extrafields);
6c096a49 627
e4aec5be 628 $colspan = 1;
3e7ca6b3 629 if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
6c096a49
NC
630 $colspan++;
631 }
e4aec5be 632 $colspan += count($extrafields);
6c096a49
NC
633
634 $levels = count($this->gtree->levels) - 1;
635
636 for ($i = 0; $i < $levels; $i++) {
637 $fillercell = new html_table_cell();
16be8974 638 $fillercell->attributes['class'] = 'fixedcolumn cell topleft';
6c096a49
NC
639 $fillercell->text = ' ';
640 $fillercell->colspan = $colspan;
8cea545e 641 $row = new html_table_row(array($fillercell));
6c096a49
NC
642 $rows[] = $row;
643 }
644
645 $headerrow = new html_table_row();
16be8974 646 $headerrow->attributes['class'] = 'heading';
6c096a49
NC
647
648 $studentheader = new html_table_cell();
16be8974 649 $studentheader->attributes['class'] = 'header';
6c096a49
NC
650 $studentheader->scope = 'col';
651 $studentheader->header = true;
652 $studentheader->id = 'studentheader';
3e7ca6b3 653 if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
6c096a49
NC
654 $studentheader->colspan = 2;
655 }
656 $studentheader->text = $arrows['studentname'];
657
658 $headerrow->cells[] = $studentheader;
659
e4aec5be 660 foreach ($extrafields as $field) {
661 $fieldheader = new html_table_cell();
662 $fieldheader->attributes['class'] = 'header userfield user' . $field;
663 $fieldheader->scope = 'col';
664 $fieldheader->header = true;
665 $fieldheader->text = $arrows[$field];
6c096a49 666
e4aec5be 667 $headerrow->cells[] = $fieldheader;
6c096a49
NC
668 }
669
670 $rows[] = $headerrow;
671
672 $rows = $this->get_left_icons_row($rows, $colspan);
673
674 $rowclasses = array('even', 'odd');
675
3aafffc0 676 $suspendedstring = null;
6c096a49
NC
677 foreach ($this->users as $userid => $user) {
678 $userrow = new html_table_row();
fe213365 679 $userrow->id = 'fixed_user_'.$userid;
abfe77ea 680 $userrow->attributes['class'] = 'r'.$this->rowcount++.' '.$rowclasses[$this->rowcount % 2];
6c096a49
NC
681
682 $usercell = new html_table_cell();
16be8974 683 $usercell->attributes['class'] = 'user';
3aafffc0 684
6c096a49
NC
685 $usercell->header = true;
686 $usercell->scope = 'row';
6c096a49
NC
687
688 if ($showuserimage) {
bea2086c 689 $usercell->text = $OUTPUT->user_picture($user);
203b7e2e 690 }
691
a6855934 692 $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
6c096a49 693
3aafffc0
AD
694 if (!empty($user->suspendedenrolment)) {
695 $usercell->attributes['class'] .= ' usersuspended';
696
697 //may be lots of suspended users so only get the string once
698 if (empty($suspendedstring)) {
699 $suspendedstring = get_string('userenrolmentsuspended', 'grades');
700 }
701 $usercell->text .= html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('i/enrolmentsuspended'), 'title'=>$suspendedstring, 'alt'=>$suspendedstring, 'class'=>'usersuspendedicon'));
702 }
703
6c096a49
NC
704 $userrow->cells[] = $usercell;
705
3e7ca6b3 706 if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
6c096a49 707 $userreportcell = new html_table_cell();
16be8974 708 $userreportcell->attributes['class'] = 'userreport';
6c096a49 709 $userreportcell->header = true;
ace9051c 710 $a = new stdClass();
6c096a49
NC
711 $a->user = fullname($user);
712 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
a6855934 713 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
c63923bd 714 $userreportcell->text = $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
6c096a49 715 $userrow->cells[] = $userreportcell;
203b7e2e 716 }
717
e4aec5be 718 foreach ($extrafields as $field) {
719 $fieldcell = new html_table_cell();
720 $fieldcell->attributes['class'] = 'header userfield user' . $field;
721 $fieldcell->header = true;
722 $fieldcell->scope = 'row';
723 $fieldcell->text = $user->{$field};
724 $userrow->cells[] = $fieldcell;
6c096a49
NC
725 }
726
727 $rows[] = $userrow;
203b7e2e 728 }
4ba9941c 729
6c096a49
NC
730 $rows = $this->get_left_range_row($rows, $colspan);
731 $rows = $this->get_left_avg_row($rows, $colspan, true);
732 $rows = $this->get_left_avg_row($rows, $colspan);
4ba9941c 733
6c096a49
NC
734 return $rows;
735 }
736
737 /**
738 * Builds and returns the rows that will make up the right part of the grader report
739 * @return array Array of html_table_row objects
740 */
741 public function get_right_rows() {
fe213365 742 global $CFG, $USER, $OUTPUT, $DB, $PAGE;
4ba9941c 743
6c096a49
NC
744 $rows = array();
745 $this->rowcount = 0;
746 $numrows = count($this->gtree->get_levels());
747 $numusers = count($this->users);
748 $gradetabindex = 1;
319770d7 749 $columnstounset = array();
6c096a49 750 $strgrade = $this->get_lang_string('grade');
fe213365 751 $strfeedback = $this->get_lang_string("feedback");
6c096a49 752 $arrows = $this->get_sort_arrows();
cb7fe7b4 753
fe213365
SH
754 $jsarguments = array(
755 'id' => '#fixed_column',
756 'cfg' => array('ajaxenabled'=>false),
757 'items' => array(),
758 'users' => array(),
759 'feedback' => array()
760 );
761 $jsscales = array();
762
d24832f9 763 foreach ($this->gtree->get_levels() as $key=>$row) {
4ba9941c 764 if ($key == 0) {
cb7fe7b4 765 // do not display course grade category
4ba9941c 766 // continue;
767 }
768
6c096a49 769 $headingrow = new html_table_row();
16be8974 770 $headingrow->attributes['class'] = 'heading_name_row';
4ba9941c 771
cb7fe7b4 772 foreach ($row as $columnkey => $element) {
319770d7 773 $sortlink = clone($this->baseurl);
2e3987a9 774 if (isset($element['object']->id)) {
319770d7 775 $sortlink->param('sortitemid', $element['object']->id);
2e3987a9 776 }
777
cb7fe7b4 778 $eid = $element['eid'];
779 $object = $element['object'];
780 $type = $element['type'];
438a5aa9 781 $categorystate = @$element['categorystate'];
8c5a416e 782
4ba9941c 783 if (!empty($element['colspan'])) {
6c096a49 784 $colspan = $element['colspan'];
4ba9941c 785 } else {
6c096a49 786 $colspan = 1;
4ba9941c 787 }
788
789 if (!empty($element['depth'])) {
6c096a49 790 $catlevel = 'catlevel'.$element['depth'];
4ba9941c 791 } else {
792 $catlevel = '';
793 }
794
cb7fe7b4 795// Element is a filler
4ba9941c 796 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
6c096a49 797 $fillercell = new html_table_cell();
16be8974 798 $fillercell->attributes['class'] = $type . ' ' . $catlevel;
6c096a49
NC
799 $fillercell->colspan = $colspan;
800 $fillercell->text = '&nbsp;';
801 $fillercell->header = true;
802 $fillercell->scope = 'col';
803 $headingrow->cells[] = $fillercell;
cb7fe7b4 804 }
805// Element is a category
4faf5f99 806 else if ($type == 'category') {
6c096a49 807 $categorycell = new html_table_cell();
16be8974 808 $categorycell->attributes['class'] = 'category ' . $catlevel;
6c096a49
NC
809 $categorycell->colspan = $colspan;
810 $categorycell->text = shorten_text($element['object']->get_name());
811 $categorycell->text .= $this->get_collapsing_icon($element);
812 $categorycell->header = true;
813 $categorycell->scope = 'col';
4ba9941c 814
815 // Print icons
2cc773f5 816 if ($USER->gradeediting[$this->courseid]) {
6c096a49 817 $categorycell->text .= $this->get_icons($element);
4ba9941c 818 }
819
6c096a49 820 $headingrow->cells[] = $categorycell;
cb7fe7b4 821 }
822// Element is a grade_item
4faf5f99 823 else {
7bac3777
AD
824 //$itemmodule = $element['object']->itemmodule;
825 //$iteminstance = $element['object']->iteminstance;
2e3987a9 826
4ba9941c 827 if ($element['object']->id == $this->sortitemid) {
828 if ($this->sortorder == 'ASC') {
319770d7 829 $arrow = $this->get_sort_arrow('up', $sortlink);
4ba9941c 830 } else {
319770d7 831 $arrow = $this->get_sort_arrow('down', $sortlink);
4ba9941c 832 }
833 } else {
319770d7 834 $arrow = $this->get_sort_arrow('move', $sortlink);
4ba9941c 835 }
836
6c096a49
NC
837 $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
838
839 $itemcell = new html_table_cell();
13aa8f0e 840 $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable';
6c096a49 841
4ba9941c 842 if ($element['object']->is_hidden()) {
16be8974 843 $itemcell->attributes['class'] .= ' hidden';
4ba9941c 844 }
845
6c096a49
NC
846 $itemcell->colspan = $colspan;
847 $itemcell->text = shorten_text($headerlink) . $arrow;
848 $itemcell->header = true;
849 $itemcell->scope = 'col';
6c096a49
NC
850
851 $headingrow->cells[] = $itemcell;
4ba9941c 852 }
4ba9941c 853 }
6c096a49 854 $rows[] = $headingrow;
4ba9941c 855 }
4ba9941c 856
6c096a49 857 $rows = $this->get_right_icons_row($rows);
4ba9941c 858
f17bb885 859 // Preload scale objects for items with a scaleid and initialize tab indices
319770d7 860 $scaleslist = array();
c0c1e7c2 861 $tabindices = array();
d297269d 862
fe213365
SH
863 foreach ($this->gtree->get_items() as $itemid=>$item) {
864 $scale = null;
388234f4 865 if (!empty($item->scaleid)) {
319770d7 866 $scaleslist[] = $item->scaleid;
fe213365
SH
867 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
868 } else {
869 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
388234f4 870 }
c0c1e7c2 871 $tabindices[$item->id]['grade'] = $gradetabindex;
872 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
873 $gradetabindex += $numusers * 2;
388234f4 874 }
319770d7 875 $scalesarray = array();
388234f4 876
319770d7 877 if (!empty($scaleslist)) {
878 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
388234f4 879 }
fe213365 880 $jsscales = $scalesarray;
d24832f9 881
6c096a49 882 $rowclasses = array('even', 'odd');
a47d38f2 883
4ba9941c 884 foreach ($this->users as $userid => $user) {
b89a70ce 885
57068674 886 if ($this->canviewhidden) {
d297269d 887 $altered = array();
888 $unknown = array();
b89a70ce 889 } else {
319770d7 890 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
891 $altered = $hidingaffected['altered'];
892 $unknown = $hidingaffected['unknown'];
893 unset($hidingaffected);
b89a70ce 894 }
895
bb9b58a6 896
6c096a49 897 $itemrow = new html_table_row();
fe213365 898 $itemrow->id = 'user_'.$userid;
16be8974 899 $itemrow->attributes['class'] = $rowclasses[$this->rowcount % 2];
9d35e66e 900
fe213365
SH
901 $jsarguments['users'][$userid] = fullname($user);
902
dc482cfa 903 foreach ($this->gtree->items as $itemid=>$unused) {
904 $item =& $this->gtree->items[$itemid];
d297269d 905 $grade = $this->grades[$userid][$item->id];
b89a70ce 906
6c096a49
NC
907 $itemcell = new html_table_cell();
908
fe213365
SH
909 $itemcell->id = 'u'.$userid.'i'.$itemid;
910
e50ce569 911 // Get the decimal points preference for this item
31a6c06c 912 $decimalpoints = $item->get_decimals();
4ba9941c 913
d297269d 914 if (in_array($itemid, $unknown)) {
915 $gradeval = null;
916 } else if (array_key_exists($itemid, $altered)) {
917 $gradeval = $altered[$itemid];
918 } else {
919 $gradeval = $grade->finalgrade;
920 }
a740a0ad
AD
921 if (!empty($grade->finalgrade)) {
922 $gradevalforJS = null;
923 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
924 $gradevalforJS = (int)$gradeval;
925 } else {
926 $gradevalforJS = format_float($gradeval, $decimalpoints);
927 }
928 $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforJS);
929 }
4ba9941c 930
00374cc5 931 // MDL-11274
932 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
57068674 933 if (!$this->canviewhidden and $grade->is_hidden()) {
6cc3e350 934 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
d297269d 935 // 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 936 $itemcell->text = html_writer::tag('span', userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), array('class'=>'datesubmitted'));
bb49f77b 937 } else {
6c096a49 938 $itemcell->text = '-';
00374cc5 939 }
6c096a49 940 $itemrow->cells[] = $itemcell;
a5b8be62 941 continue;
00374cc5 942 }
943
2cc773f5 944 // emulate grade element
d3c3da1b 945 $eid = $this->gtree->get_grade_eid($grade);
946 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
2cc773f5 947
16be8974 948 $itemcell->attributes['class'] .= ' grade';
dff9d94d 949 if ($item->is_category_item()) {
16be8974 950 $itemcell->attributes['class'] .= ' cat';
b89a70ce 951 }
dff9d94d 952 if ($item->is_course_item()) {
16be8974 953 $itemcell->attributes['class'] .= ' course';
b89a70ce 954 }
4ba9941c 955 if ($grade->is_overridden()) {
16be8974 956 $itemcell->attributes['class'] .= ' overridden';
4ba9941c 957 }
85db09fb 958
5ebce7bb 959 if ($grade->is_excluded()) {
16be8974 960 // $itemcell->attributes['class'] .= ' excluded';
5ebce7bb 961 }
4ba9941c 962
fe213365 963 if (!empty($grade->feedback)) {
92ff6236 964 //should we be truncating feedback? ie $short_feedback = shorten_text($feedback, $this->feedback_trunc_length);
fe213365 965 $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content'=>wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'));
653a8648 966 }
967
23207a1a 968 if ($grade->is_excluded()) {
26acc814 969 $itemcell->text .= html_writer::tag('span', get_string('excluded', 'grades'), array('class'=>'excludedfloater'));
23207a1a 970 }
971
4ba9941c 972 // Do not show any icons if no grade (no record in DB to match)
d3c3da1b 973 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
6c096a49 974 $itemcell->text .= $this->get_icons($element);
4ba9941c 975 }
976
80fb1cf9 977 $hidden = '';
978 if ($grade->is_hidden()) {
979 $hidden = ' hidden ';
980 }
6cc3e350 981
d24832f9 982 $gradepass = ' gradefail ';
46e6df89 983 if ($grade->is_passed($item)) {
984 $gradepass = ' gradepass ';
e6477988 985 } elseif (is_null($grade->is_passed($item))) {
986 $gradepass = '';
46e6df89 987 }
988
6ef4878b 989 // if in editing mode, we need to print either a text box
4ba9941c 990 // or a drop down (for scales)
4ba9941c 991 // grades in item of type grade category or course are not directly editable
d14ae855 992 if ($item->needsupdate) {
26acc814 993 $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden"));
d14ae855 994
2cc773f5 995 } else if ($USER->gradeediting[$this->courseid]) {
4ba9941c 996
319770d7 997 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
998 $scale = $scalesarray[$item->scaleid];
99ccfda8 999 $gradeval = (int)$gradeval; // scales use only integers
388234f4 1000 $scales = explode(",", $scale->scale);
1001 // reindex because scale is off 1
9d35e66e 1002
914ea002 1003 // MDL-12104 some previous scales might have taken up part of the array
1004 // so this needs to be reset
d48ebf97 1005 $scaleopt = array();
388234f4 1006 $i = 0;
1007 foreach ($scales as $scaleoption) {
1008 $i++;
1009 $scaleopt[$i] = $scaleoption;
1010 }
1011
1012 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
0658afc9 1013 $oldval = empty($gradeval) ? -1 : $gradeval;
1014 if (empty($item->outcomeid)) {
d4795a07 1015 $nogradestr = $this->get_lang_string('nograde');
0658afc9 1016 } else {
d4795a07 1017 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
0658afc9 1018 }
fe213365 1019 $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
29bea634
RW
1020 $itemcell->text .= html_writer::label(get_string('typescale', 'grades'), $attributes['id'], false, array('class' => 'accesshide'));
1021 $itemcell->text .= html_writer::select($scaleopt, 'grade_'.$userid.'_'.$item->id, $gradeval, array(-1=>$nogradestr), $attributes);
388234f4 1022 } elseif(!empty($scale)) {
4ba9941c 1023 $scales = explode(",", $scale->scale);
4ba9941c 1024
388234f4 1025 // invalid grade if gradeval < 1
99ccfda8 1026 if ($gradeval < 1) {
26acc814 1027 $itemcell->text .= html_writer::tag('span', '-', array('class'=>"gradevalue$hidden$gradepass"));
4ba9941c 1028 } else {
653a8648 1029 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
26acc814 1030 $itemcell->text .= html_writer::tag('span', $scales[$gradeval-1], array('class'=>"gradevalue$hidden$gradepass"));
4ba9941c 1031 }
388234f4 1032 } else {
1033 // no such scale, throw error?
4ba9941c 1034 }
79eabc2a 1035
bb384a8e 1036 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
936f1350 1037 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
76317c73 1038 $value = format_float($gradeval, $decimalpoints);
b1fec412 1039 $gradelabel = fullname($user) . ' ' . $item->itemname;
7400be1b
RT
1040 $itemcell->text .= '<label class="accesshide" for="grade_'.$userid.'_'.$item->id.'">'
1041 .get_string('useractivitygrade', 'gradereport_grader', $gradelabel).'</label>';
6c096a49 1042 $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
319770d7 1043 . '" type="text" class="text" title="'. $strgrade .'" name="grade_'
fe213365 1044 .$userid.'_' .$item->id.'" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
4ba9941c 1045 } else {
26acc814 1046 $itemcell->text .= html_writer::tag('span', format_float($gradeval, $decimalpoints), array('class'=>"gradevalue$hidden$gradepass"));
4ba9941c 1047 }
1048 }
1049
1050
1051 // If quickfeedback is on, print an input element
2ca093fa 1052 if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
b1fec412 1053 $feedbacklabel = fullname($user) . ' ' . $item->itemname;
7400be1b
RT
1054 $itemcell->text .= '<label class="accesshide" for="feedback_'.$userid.'_'.$item->id.'">'
1055 .get_string('useractivityfeedback', 'gradereport_grader', $feedbacklabel).'</label>';
fe213365
SH
1056 $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
1057 . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
4ba9941c 1058 }
1059
78a2d9f0 1060 } else { // Not editing
41f22daa 1061 $gradedisplaytype = $item->get_displaytype();
e50ce569 1062
fe213365 1063 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
16be8974 1064 $itemcell->attributes['class'] .= ' grade_type_scale';
fe213365 1065 } else if ($item->gradetype != GRADE_TYPE_TEXT) {
16be8974 1066 $itemcell->attributes['class'] .= ' grade_type_text';
fe213365 1067 }
4ba9941c 1068
6712973f
AD
1069 if ($this->get_pref('enableajax')) {
1070 $itemcell->attributes['class'] .= ' clickable';
1071 }
1072
d14ae855 1073 if ($item->needsupdate) {
26acc814 1074 $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden$gradepass"));
4ba9941c 1075 } else {
26acc814 1076 $itemcell->text .= html_writer::tag('span', grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), array('class'=>"gradevalue$hidden$gradepass"));
c97933ff 1077 if ($this->get_pref('showanalysisicon')) {
f17bb885 1078 $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
bb17ac1e 1079 }
4ba9941c 1080 }
4ba9941c 1081 }
1082
1083 if (!empty($this->gradeserror[$item->id][$userid])) {
6c096a49 1084 $itemcell->text .= $this->gradeserror[$item->id][$userid];
4ba9941c 1085 }
1086
6c096a49 1087 $itemrow->cells[] = $itemcell;
4ba9941c 1088 }
6c096a49 1089 $rows[] = $itemrow;
4ba9941c 1090 }
4ba9941c 1091
fe213365
SH
1092 if ($this->get_pref('enableajax')) {
1093 $jsarguments['cfg']['ajaxenabled'] = true;
1094 $jsarguments['cfg']['scales'] = array();
1095 foreach ($jsscales as $scale) {
1096 $jsarguments['cfg']['scales'][$scale->id] = explode(',',$scale->scale);
1097 }
1098 $jsarguments['cfg']['feedbacktrunclength'] = $this->feedback_trunc_length;
92ff6236 1099
a740a0ad 1100 // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades']
fe213365
SH
1101 }
1102 $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
1103 $jsarguments['cfg']['courseid'] = $this->courseid;
d3b698a4 1104 $jsarguments['cfg']['studentsperpage'] = $this->get_students_per_page();
fe213365
SH
1105 $jsarguments['cfg']['showquickfeedback'] = (bool)$this->get_pref('showquickfeedback');
1106
1107 $module = array(
1108 'name' => 'gradereport_grader',
1109 'fullpath' => '/grade/report/grader/module.js',
227e9023 1110 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
fe213365
SH
1111 );
1112 $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
1113 $PAGE->requires->strings_for_js(array('addfeedback','feedback', 'grade'), 'grades');
1114 $PAGE->requires->strings_for_js(array('ajaxchoosescale','ajaxclicktoclose','ajaxerror','ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
1115
6c096a49
NC
1116 $rows = $this->get_right_range_row($rows);
1117 $rows = $this->get_right_avg_row($rows, true);
1118 $rows = $this->get_right_avg_row($rows);
dc482cfa 1119
6c096a49
NC
1120 return $rows;
1121 }
dc482cfa 1122
6c096a49
NC
1123 /**
1124 * Depending on the style of report (fixedstudents vs traditional one-table),
1125 * arranges the rows of data in one or two tables, and returns the output of
1126 * these tables in HTML
1127 * @return string HTML
1128 */
1129 public function get_grade_table() {
1130 global $OUTPUT;
1131 $fixedstudents = $this->is_fixed_students();
dc482cfa 1132
6c096a49
NC
1133 $leftrows = $this->get_left_rows();
1134 $rightrows = $this->get_right_rows();
dc482cfa 1135
6c096a49 1136 $html = '';
dc482cfa 1137
fe213365 1138
203b7e2e 1139 if ($fixedstudents) {
319770d7 1140 $fixedcolumntable = new html_table();
1141 $fixedcolumntable->id = 'fixed_column';
6c096a49 1142 $fixedcolumntable->data = $leftrows;
16be8974 1143 $html .= $OUTPUT->container(html_writer::table($fixedcolumntable), 'left_scroller');
dc482cfa 1144
6c096a49
NC
1145 $righttable = new html_table();
1146 $righttable->id = 'user-grades';
6c096a49 1147 $righttable->data = $rightrows;
319770d7 1148
16be8974 1149 $html .= $OUTPUT->container(html_writer::table($righttable), 'right_scroller');
6c096a49
NC
1150 } else {
1151 $fulltable = new html_table();
16be8974 1152 $fulltable->attributes['class'] = 'gradestable flexible boxaligncenter generaltable';
6c096a49
NC
1153 $fulltable->id = 'user-grades';
1154
1155 // Extract rows from each side (left and right) and collate them into one row each
1156 foreach ($leftrows as $key => $row) {
1157 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1158 $fulltable->data[] = $row;
203b7e2e 1159 }
16be8974 1160 $html .= html_writer::table($fulltable);
6c096a49
NC
1161 }
1162 return $OUTPUT->container($html, 'gradeparent');
1163 }
dc482cfa 1164
6c096a49
NC
1165 /**
1166 * Builds and return the row of icons for the left side of the report.
1167 * It only has one cell that says "Controls"
1168 * @param array $rows The Array of rows for the left part of the report
1169 * @param int $colspan The number of columns this cell has to span
1170 * @return array Array of rows for the left part of the report
1171 */
1172 public function get_left_icons_row($rows=array(), $colspan=1) {
1173 global $USER;
dc482cfa 1174
6c096a49
NC
1175 if ($USER->gradeediting[$this->courseid]) {
1176 $controlsrow = new html_table_row();
16be8974 1177 $controlsrow->attributes['class'] = 'controls';
6c096a49 1178 $controlscell = new html_table_cell();
16be8974 1179 $controlscell->attributes['class'] = 'header controls';
6c096a49
NC
1180 $controlscell->colspan = $colspan;
1181 $controlscell->text = $this->get_lang_string('controls','grades');
1182
1183 $controlsrow->cells[] = $controlscell;
1184 $rows[] = $controlsrow;
1185 }
1186 return $rows;
1187 }
dc482cfa 1188
6c096a49
NC
1189 /**
1190 * Builds and return the header for the row of ranges, for the left part of the grader report.
1191 * @param array $rows The Array of rows for the left part of the report
1192 * @param int $colspan The number of columns this cell has to span
1193 * @return array Array of rows for the left part of the report
1194 */
1195 public function get_left_range_row($rows=array(), $colspan=1) {
1196 global $CFG, $USER;
bb9b58a6 1197
6c096a49
NC
1198 if ($this->get_pref('showranges')) {
1199 $rangerow = new html_table_row();
16be8974 1200 $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
6c096a49 1201 $rangecell = new html_table_cell();
16be8974 1202 $rangecell->attributes['class'] = 'header range';
6c096a49
NC
1203 $rangecell->colspan = $colspan;
1204 $rangecell->header = true;
1205 $rangecell->scope = 'row';
1206 $rangecell->text = $this->get_lang_string('range','grades');
1207 $rangerow->cells[] = $rangecell;
1208 $rows[] = $rangerow;
1209 }
dc482cfa 1210
6c096a49
NC
1211 return $rows;
1212 }
dc482cfa 1213
6c096a49
NC
1214 /**
1215 * Builds and return the headers for the rows of averages, for the left part of the grader report.
1216 * @param array $rows The Array of rows for the left part of the report
1217 * @param int $colspan The number of columns this cell has to span
1218 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1219 * @return array Array of rows for the left part of the report
1220 */
1221 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1222 if (!$this->canviewhidden) {
1223 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1224 // better not show them at all if user can not see all hideen grades
1225 return $rows;
1226 }
dc482cfa 1227
6c096a49
NC
1228 $showaverages = $this->get_pref('showaverages');
1229 $showaveragesgroup = $this->currentgroup && $showaverages;
1230 $straveragegroup = get_string('groupavg', 'grades');
319770d7 1231
6c096a49 1232 if ($groupavg) {
319770d7 1233 if ($showaveragesgroup) {
1234 $groupavgrow = new html_table_row();
16be8974 1235 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
319770d7 1236 $groupavgcell = new html_table_cell();
16be8974 1237 $groupavgcell->attributes['class'] = 'header range';
319770d7 1238 $groupavgcell->colspan = $colspan;
1239 $groupavgcell->header = true;
1240 $groupavgcell->scope = 'row';
1241 $groupavgcell->text = $straveragegroup;
1242 $groupavgrow->cells[] = $groupavgcell;
6c096a49 1243 $rows[] = $groupavgrow;
203b7e2e 1244 }
6c096a49
NC
1245 } else {
1246 $straverage = get_string('overallaverage', 'grades');
dc482cfa 1247
203b7e2e 1248 if ($showaverages) {
319770d7 1249 $avgrow = new html_table_row();
16be8974 1250 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
319770d7 1251 $avgcell = new html_table_cell();
16be8974 1252 $avgcell->attributes['class'] = 'header range';
319770d7 1253 $avgcell->colspan = $colspan;
1254 $avgcell->header = true;
1255 $avgcell->scope = 'row';
1256 $avgcell->text = $straverage;
1257 $avgrow->cells[] = $avgcell;
6c096a49 1258 $rows[] = $avgrow;
203b7e2e 1259 }
6c096a49 1260 }
203b7e2e 1261
6c096a49
NC
1262 return $rows;
1263 }
dc482cfa 1264
6c096a49
NC
1265 /**
1266 * Builds and return the row of icons when editing is on, for the right part of the grader report.
1267 * @param array $rows The Array of rows for the right part of the report
1268 * @return array Array of rows for the right part of the report
1269 */
1270 public function get_right_icons_row($rows=array()) {
1271 global $USER;
1272 if ($USER->gradeediting[$this->courseid]) {
1273 $iconsrow = new html_table_row();
16be8974 1274 $iconsrow->attributes['class'] = 'controls';
6c096a49 1275
6c096a49
NC
1276 foreach ($this->gtree->items as $itemid=>$unused) {
1277 // emulate grade element
e2bb3c92 1278 $item = $this->gtree->get_item($itemid);
6c096a49
NC
1279
1280 $eid = $this->gtree->get_item_eid($item);
1281 $element = $this->gtree->locate_element($eid);
1282 $itemcell = new html_table_cell();
16be8974 1283 $itemcell->attributes['class'] = 'controls icons';
6c096a49
NC
1284 $itemcell->text = $this->get_icons($element);
1285 $iconsrow->cells[] = $itemcell;
1286 }
1287 $rows[] = $iconsrow;
1288 }
1289 return $rows;
dc482cfa 1290 }
1291
18a00359 1292 /**
6c096a49
NC
1293 * Builds and return the row of ranges for the right part of the grader report.
1294 * @param array $rows The Array of rows for the right part of the report
1295 * @return array Array of rows for the right part of the report
18a00359 1296 */
6c096a49
NC
1297 public function get_right_range_row($rows=array()) {
1298 global $OUTPUT;
18a00359 1299
6c096a49
NC
1300 if ($this->get_pref('showranges')) {
1301 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
1302 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1303 $rangerow = new html_table_row();
16be8974 1304 $rangerow->attributes['class'] = 'heading range';
18a00359 1305
6c096a49
NC
1306 foreach ($this->gtree->items as $itemid=>$unused) {
1307 $item =& $this->gtree->items[$itemid];
1308 $itemcell = new html_table_cell();
1309 $itemcell->header = true;
16be8974 1310 $itemcell->attributes['class'] .= ' header range';
6c096a49
NC
1311
1312 $hidden = '';
1313 if ($item->is_hidden()) {
1314 $hidden = ' hidden ';
1315 }
1316
1317 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1318
1319 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1320 $rangerow->cells[] = $itemcell;
1321 }
1322 $rows[] = $rangerow;
18a00359 1323 }
6c096a49 1324 return $rows;
18a00359 1325 }
1326
4ba9941c 1327 /**
6c096a49
NC
1328 * Builds and return the row of averages for the right part of the grader report.
1329 * @param array $rows Whether to return only group averages or all averages.
1330 * @param bool $grouponly Whether to return only group averages or all averages.
1331 * @return array Array of rows for the right part of the report
4ba9941c 1332 */
6c096a49
NC
1333 public function get_right_avg_row($rows=array(), $grouponly=false) {
1334 global $CFG, $USER, $DB, $OUTPUT;
4ba9941c 1335
57068674 1336 if (!$this->canviewhidden) {
1337 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
6ef4878b 1338 // better not show them at all if user can not see all hidden grades
6c096a49 1339 return $rows;
57068674 1340 }
1341
6c096a49
NC
1342 $showaverages = $this->get_pref('showaverages');
1343 $showaveragesgroup = $this->currentgroup && $showaverages;
1344
5b508a08 1345 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
1346 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
098042ba 1347 $meanselection = $this->get_pref('meanselection');
1348 $shownumberofgrades = $this->get_pref('shownumberofgrades');
1349
5b508a08 1350 $avghtml = '';
aae94377 1351 $avgcssclass = 'avg';
3446013d 1352
5b508a08 1353 if ($grouponly) {
1354 $straverage = get_string('groupavg', 'grades');
35079f53 1355 $showaverages = $this->currentgroup && $this->get_pref('showaverages');
5b508a08 1356 $groupsql = $this->groupsql;
1357 $groupwheresql = $this->groupwheresql;
319770d7 1358 $groupwheresqlparams = $this->groupwheresql_params;
aae94377 1359 $avgcssclass = 'groupavg';
3446013d 1360 } else {
6308b91c 1361 $straverage = get_string('overallaverage', 'grades');
5b508a08 1362 $showaverages = $this->get_pref('showaverages');
0dba6cb2 1363 $groupsql = "";
1364 $groupwheresql = "";
319770d7 1365 $groupwheresqlparams = array();
3446013d 1366 }
1367
a5b8be62 1368 if ($shownumberofgrades) {
1369 $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1370 }
1371
f8ae1f86 1372 $totalcount = $this->get_numusers($grouponly);
04259694 1373
387815db 1374 //limit to users with a gradeable role
1375 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1376
1377 //limit to users with an active enrollment
1378 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
d24832f9 1379
5b508a08 1380 if ($showaverages) {
387815db 1381 $params = array_merge(array('courseid'=>$this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams);
04259694 1382
828af11c 1383 // find sums of all grade items in course
656d17c2 1384 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
d24832f9 1385 FROM {grade_items} gi
656d17c2
AD
1386 JOIN {grade_grades} g ON g.itemid = gi.id
1387 JOIN {user} u ON u.id = g.userid
1388 JOIN ($enrolledsql) je ON je.id = u.id
1389 JOIN (
1390 SELECT DISTINCT ra.userid
1391 FROM {role_assignments} ra
1392 WHERE ra.roleid $gradebookrolessql
1393 AND ra.contextid " . get_related_contexts_string($this->context) . "
1394 ) rainner ON rainner.userid = u.id
25081b95 1395 $groupsql
b50371da 1396 WHERE gi.courseid = :courseid
656d17c2
AD
1397 AND u.deleted = 0
1398 AND g.finalgrade IS NOT NULL
1399 $groupwheresql
1400 GROUP BY g.itemid";
319770d7 1401 $sumarray = array();
656d17c2 1402 if ($sums = $DB->get_records_sql($sql, $params)) {
ab3444d7 1403 foreach ($sums as $itemid => $csum) {
319770d7 1404 $sumarray[$itemid] = $csum->sum;
7b61efbe 1405 }
4ba9941c 1406 }
66ef0471 1407
883187d0 1408 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1409 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
656d17c2 1410 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
d24832f9 1411 FROM {grade_items} gi
25081b95
SH
1412 CROSS JOIN {user} u
1413 JOIN ($enrolledsql) je
1414 ON je.id = u.id
1415 JOIN {role_assignments} ra
1416 ON ra.userid = u.id
1417 LEFT OUTER JOIN {grade_grades} g
1418 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1419 $groupsql
b50371da 1420 WHERE gi.courseid = :courseid
387815db 1421 AND ra.roleid $gradebookrolessql
828af11c 1422 AND ra.contextid ".get_related_contexts_string($this->context)."
656d17c2 1423 AND u.deleted = 0
828af11c 1424 AND g.id IS NULL
1425 $groupwheresql
883187d0 1426 GROUP BY gi.id";
828af11c 1427
656d17c2 1428 $ungradedcounts = $DB->get_records_sql($sql, $params);
883187d0 1429
6c096a49 1430 $avgrow = new html_table_row();
16be8974 1431 $avgrow->attributes['class'] = 'avg';
653a8648 1432
b89a70ce 1433 foreach ($this->gtree->items as $itemid=>$unused) {
1434 $item =& $this->gtree->items[$itemid];
1435
67881aa8 1436 if ($item->needsupdate) {
6c096a49
NC
1437 $avgcell = new html_table_cell();
1438 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1439 $avgrow->cells[] = $avgcell;
67881aa8 1440 continue;
1441 }
1442
319770d7 1443 if (!isset($sumarray[$item->id])) {
1444 $sumarray[$item->id] = 0;
33a34cd4 1445 }
883187d0 1446
319770d7 1447 if (empty($ungradedcounts[$itemid])) {
1448 $ungradedcount = 0;
828af11c 1449 } else {
319770d7 1450 $ungradedcount = $ungradedcounts[$itemid]->count;
d1556c09 1451 }
33a34cd4 1452
c2efb501 1453 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
319770d7 1454 $meancount = $totalcount - $ungradedcount;
33a34cd4 1455 } else { // Bump up the sum by the number of ungraded items * grademin
319770d7 1456 $sumarray[$item->id] += $ungradedcount * $item->grademin;
1457 $meancount = $totalcount;
33a34cd4 1458 }
1459
31a6c06c 1460 $decimalpoints = $item->get_decimals();
41f22daa 1461
bb384a8e 1462 // Determine which display type to use for this average
2cc773f5 1463 if ($USER->gradeediting[$this->courseid]) {
1796708d 1464 $displaytype = GRADE_DISPLAY_TYPE_REAL;
d622930b 1465
e0724506 1466 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
d622930b 1467 $displaytype = $item->get_displaytype();
1468
1469 } else {
bb384a8e 1470 $displaytype = $averagesdisplaytype;
1471 }
1472
31a6c06c 1473 // Override grade_item setting if a display preference (not inherit) was set for the averages
e0724506 1474 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
d622930b 1475 $decimalpoints = $item->get_decimals();
1476
1477 } else {
5b508a08 1478 $decimalpoints = $averagesdecimalpoints;
1479 }
1480
319770d7 1481 if (!isset($sumarray[$item->id]) || $meancount == 0) {
6c096a49
NC
1482 $avgcell = new html_table_cell();
1483 $avgcell->text = '-';
1484 $avgrow->cells[] = $avgcell;
1485
4ba9941c 1486 } else {
319770d7 1487 $sum = $sumarray[$item->id];
1488 $avgradeval = $sum/$meancount;
d622930b 1489 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
bb384a8e 1490
098042ba 1491 $numberofgrades = '';
098042ba 1492 if ($shownumberofgrades) {
319770d7 1493 $numberofgrades = " ($meancount)";
098042ba 1494 }
1495
6c096a49
NC
1496 $avgcell = new html_table_cell();
1497 $avgcell->text = $gradehtml.$numberofgrades;
1498 $avgrow->cells[] = $avgcell;
80fb1cf9 1499 }
9ecd4386 1500 }
6c096a49 1501 $rows[] = $avgrow;
9ecd4386 1502 }
6c096a49 1503 return $rows;
9ecd4386 1504 }
4ba9941c 1505
1506 /**
1507 * Given a grade_category, grade_item or grade_grade, this function
1508 * figures out the state of the object and builds then returns a div
1509 * with the icons needed for the grader report.
1510 *
c97933ff 1511 * @param array $object
4ba9941c 1512 * @return string HTML
1513 */
d24832f9 1514 protected function get_icons($element) {
319770d7 1515 global $CFG, $USER, $OUTPUT;
4ba9941c 1516
2cc773f5 1517 if (!$USER->gradeediting[$this->courseid]) {
1518 return '<div class="grade_icons" />';
79eabc2a 1519 }
4ba9941c 1520
2cc773f5 1521 // Init all icons
319770d7 1522 $editicon = '';
dc482cfa 1523
1524 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
319770d7 1525 $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
dc482cfa 1526 }
1527
319770d7 1528 $editcalculationicon = '';
1529 $showhideicon = '';
1530 $lockunlockicon = '';
4ba9941c 1531
a5b8be62 1532 if (has_capability('moodle/grade:manage', $this->context)) {
a5b8be62 1533 if ($this->get_pref('showcalculations')) {
319770d7 1534 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
a5b8be62 1535 }
1536
1537 if ($this->get_pref('showeyecons')) {
319770d7 1538 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
a5b8be62 1539 }
4ba9941c 1540
a5b8be62 1541 if ($this->get_pref('showlocks')) {
319770d7 1542 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
a5b8be62 1543 }
c97933ff
MG
1544
1545 }
1546
1547 $gradeanalysisicon = '';
1548 if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1549 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
4ba9941c 1550 }
1551
c97933ff 1552 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
4faf5f99 1553 }
1554
1555 /**
1556 * Given a category element returns collapsing +/- icon if available
1557 * @param object $object
1558 * @return string HTML
1559 */
d24832f9 1560 protected function get_collapsing_icon($element) {
5d3b9994 1561 global $OUTPUT;
4faf5f99 1562
319770d7 1563 $icon = '';
2cc773f5 1564 // If object is a category, display expand/contract icon
384960dd 1565 if ($element['type'] == 'category') {
2cc773f5 1566 // Load language strings
319770d7 1567 $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1568 $strswitchplus = $this->get_lang_string('gradesonly', 'grades');
1569 $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
384960dd 1570
8ae8bf8a 1571 $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
48b5d8f3 1572
384960dd 1573 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
8ae8bf8a 1574 $url->param('action', 'switch_plus');
c63923bd 1575 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
8ae8bf8a
PS
1576
1577 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1578 $url->param('action', 'switch_whole');
c63923bd 1579 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
8ae8bf8a
PS
1580
1581 } else {
1582 $url->param('action', 'switch_minus');
c63923bd 1583 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
2cc773f5 1584 }
4ba9941c 1585 }
319770d7 1586 return $icon;
4ba9941c 1587 }
48b5d8f3 1588
1e88baa0
TH
1589 public function process_action($target, $action) {
1590 return self::do_process_action($target, $action);
1591 }
1592
48b5d8f3 1593 /**
1594 * Processes a single action against a category, grade_item or grade.
1595 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1596 * @param string $action Which action to take (edit, delete etc...)
1597 * @return
1598 */
1e88baa0 1599 public static function do_process_action($target, $action) {
4faf5f99 1600 // TODO: this code should be in some grade_tree static method
48b5d8f3 1601 $targettype = substr($target, 0, 1);
1602 $targetid = substr($target, 1);
4faf5f99 1603 // TODO: end
1604
1605 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1606 $collapsed = unserialize($collapsed);
1607 } else {
384960dd 1608 $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
4faf5f99 1609 }
1610
48b5d8f3 1611 switch ($action) {
384960dd 1612 case 'switch_minus': // Add category to array of aggregatesonly
1613 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1614 $collapsed['aggregatesonly'][] = $targetid;
4faf5f99 1615 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1616 }
48b5d8f3 1617 break;
4faf5f99 1618
384960dd 1619 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1620 $key = array_search($targetid, $collapsed['aggregatesonly']);
4faf5f99 1621 if ($key !== false) {
384960dd 1622 unset($collapsed['aggregatesonly'][$key]);
4faf5f99 1623 }
384960dd 1624 if (!in_array($targetid, $collapsed['gradesonly'])) {
1625 $collapsed['gradesonly'][] = $targetid;
1626 }
1627 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
48b5d8f3 1628 break;
384960dd 1629 case 'switch_whole': // Remove the category from the array of collapsed cats
1630 $key = array_search($targetid, $collapsed['gradesonly']);
1631 if ($key !== false) {
1632 unset($collapsed['gradesonly'][$key]);
1633 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1634 }
4faf5f99 1635
384960dd 1636 break;
48b5d8f3 1637 default:
1638 break;
1639 }
1640
1641 return true;
1642 }
03fcc729 1643
795b745a 1644 /**
1645 * Returns whether or not to display fixed students column.
1646 * Includes a browser check, because IE6 doesn't support the scrollbar.
1647 *
1648 * @return bool
1649 */
1650 public function is_fixed_students() {
1651 global $USER, $CFG;
19db454f 1652 return $CFG->grade_report_fixedstudents &&
03fcc729 1653 (check_browser_version('MSIE', '7.0') ||
795b745a 1654 check_browser_version('Firefox', '2.0') ||
1655 check_browser_version('Gecko', '2006010100') ||
1656 check_browser_version('Camino', '1.0') ||
1657 check_browser_version('Opera', '6.0') ||
06671035
PS
1658 check_browser_version('Chrome', '6') ||
1659 check_browser_version('Safari', '300'));
795b745a 1660 }
6c096a49
NC
1661
1662 /**
1663 * Refactored function for generating HTML of sorting links with matching arrows.
1664 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1665 * to inject into a table header cell.
e4aec5be 1666 * @param array $extrafields Array of extra fields being displayed, such as
1667 * user idnumber
6c096a49
NC
1668 * @return array An associative array of HTML sorting links+arrows
1669 */
e4aec5be 1670 public function get_sort_arrows(array $extrafields = array()) {
6c096a49
NC
1671 global $OUTPUT;
1672 $arrows = array();
1673
1674 $strsortasc = $this->get_lang_string('sortasc', 'grades');
1675 $strsortdesc = $this->get_lang_string('sortdesc', 'grades');
1676 $strfirstname = $this->get_lang_string('firstname');
1677 $strlastname = $this->get_lang_string('lastname');
0cddd851
FM
1678 $iconasc = $OUTPUT->pix_icon('t/sort_asc', $strsortasc, '', array('class' => 'iconsmall sorticon'));
1679 $icondesc = $OUTPUT->pix_icon('t/sort_desc', $strsortdesc, '', array('class' => 'iconsmall sorticon'));
6c096a49 1680
0f4c64b7
PS
1681 $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1682 $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
6c096a49 1683
0f4c64b7 1684 $arrows['studentname'] = $lastlink;
6c096a49
NC
1685
1686 if ($this->sortitemid === 'lastname') {
1687 if ($this->sortorder == 'ASC') {
0cddd851 1688 $arrows['studentname'] .= $iconasc;
6c096a49 1689 } else {
0cddd851 1690 $arrows['studentname'] .= $icondesc;
6c096a49
NC
1691 }
1692 }
1693
0f4c64b7 1694 $arrows['studentname'] .= ' ' . $firstlink;
6c096a49
NC
1695
1696 if ($this->sortitemid === 'firstname') {
1697 if ($this->sortorder == 'ASC') {
0cddd851 1698 $arrows['studentname'] .= $iconasc;
6c096a49 1699 } else {
0cddd851 1700 $arrows['studentname'] .= $icondesc;
6c096a49
NC
1701 }
1702 }
1703
e4aec5be 1704 foreach ($extrafields as $field) {
1705 $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1706 array('sortitemid'=>$field)), get_user_field_name($field));
1707 $arrows[$field] = $fieldlink;
6c096a49 1708
e4aec5be 1709 if ($field == $this->sortitemid) {
1710 if ($this->sortorder == 'ASC') {
0cddd851 1711 $arrows[$field] .= $iconasc;
e4aec5be 1712 } else {
0cddd851 1713 $arrows[$field] .= $icondesc;
e4aec5be 1714 }
6c096a49
NC
1715 }
1716 }
1717
1718 return $arrows;
1719 }
d3b698a4
AD
1720
1721 /**
a740a0ad 1722 * Returns the maximum number of students to be displayed on each page
d3b698a4
AD
1723 *
1724 * Takes into account the 'studentsperpage' user preference and the 'max_input_vars'
1725 * PHP setting. Too many fields is only a problem when submitting grades but
1726 * we respect 'max_input_vars' even when viewing grades to prevent students disappearing
1727 * when toggling editing on and off.
1728 *
a740a0ad 1729 * @return int The maximum number of students to display per page
d3b698a4 1730 */
a740a0ad 1731 public function get_students_per_page() {
d3b698a4
AD
1732 global $USER;
1733 static $studentsperpage = null;
1734
1735 if ($studentsperpage === null) {
a740a0ad 1736 $originalstudentsperpage = $studentsperpage = $this->get_pref('studentsperpage');
d3b698a4
AD
1737
1738 // Will this number of students result in more fields that we are allowed?
1739 $maxinputvars = ini_get('max_input_vars');
1740 if ($maxinputvars !== false) {
1741 $fieldspergradeitem = 0; // The number of fields output per grade item for each student
1742
1743 if ($this->get_pref('quickgrading')) {
8233747e
AD
1744 // One grade field
1745 $fieldspergradeitem ++;
d3b698a4
AD
1746 }
1747 if ($this->get_pref('showquickfeedback')) {
8233747e
AD
1748 // One feedback field
1749 $fieldspergradeitem ++;
d3b698a4
AD
1750 }
1751
1752 $fieldsperstudent = $fieldspergradeitem * count($this->gtree->get_items());
1753 $fieldsrequired = $studentsperpage * $fieldsperstudent;
d3b698a4
AD
1754 if ($fieldsrequired > $maxinputvars) {
1755 $studentsperpage = floor($maxinputvars / $fieldsperstudent);
1756 if ($studentsperpage<1) {
1757 // Make sure students per page doesn't fall below 1
1758 // PHP max_input_vars could potentially be reached with 1 student
8233747e 1759 // if there are >500 grade items and quickgrading and showquickfeedback are on
d3b698a4
AD
1760 $studentsperpage = 1;
1761 }
a740a0ad
AD
1762
1763 $a = new stdClass();
1764 $a->originalstudentsperpage = $originalstudentsperpage;
1765 $a->studentsperpage = $studentsperpage;
1766 $a->maxinputvars = $maxinputvars;
1767 debugging(get_string('studentsperpagereduced', 'grades', $a));
d3b698a4
AD
1768 }
1769 }
1770 }
1771
1772 return $studentsperpage;
1773 }
4ba9941c 1774}
6c3ef410 1775