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