MDL-49826 grade: hide singleview links when no permissions
[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
fe89cb8c
FM
415 // Check the status of showing only active enrolments.
416 $coursecontext = $this->context->get_course_context(true);
417 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
418 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
419 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
420
4e829d48 421 // Limit to users with an active enrollment.
fe89cb8c 422 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
ef8f084c 423
4e829d48 424 // Fields we need from the user table.
ef8c793d 425 $userfields = user_picture::fields('u', get_extra_user_fields($this->context));
ef8f084c 426
4e829d48
MN
427 // We want to query both the current context and parent contexts.
428 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
656d17c2 429
4e829d48 430 // If the user has clicked one of the sort asc/desc arrows.
4ba9941c 431 if (is_numeric($this->sortitemid)) {
02d1a0a5
MA
432 $params = array_merge(array('gitemid' => $this->sortitemid), $gradebookrolesparams, $this->userwheresql_params,
433 $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
09d0ef21 434
656d17c2
AD
435 $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
436 $sort = "g.finalgrade $this->sortorder";
4ba9941c 437 } else {
656d17c2 438 $sortjoin = '';
09d0ef21 439 switch($this->sortitemid) {
440 case 'lastname':
656d17c2
AD
441 $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder";
442 break;
09d0ef21 443 case 'firstname':
656d17c2
AD
444 $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder";
445 break;
69101b43
IT
446 case 'email':
447 $sort = "u.email $this->sortorder";
448 break;
09d0ef21 449 case 'idnumber':
450 default:
656d17c2
AD
451 $sort = "u.idnumber $this->sortorder";
452 break;
c421ad4b 453 }
4ba9941c 454
8e4bf6cc 455 $params = array_merge($gradebookrolesparams, $this->userwheresql_params, $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
4ba9941c 456 }
457
656d17c2
AD
458 $sql = "SELECT $userfields
459 FROM {user} u
460 JOIN ($enrolledsql) je ON je.id = u.id
461 $this->groupsql
462 $sortjoin
463 JOIN (
464 SELECT DISTINCT ra.userid
465 FROM {role_assignments} ra
466 WHERE ra.roleid IN ($this->gradebookroles)
4e829d48 467 AND ra.contextid $relatedctxsql
656d17c2
AD
468 ) rainner ON rainner.userid = u.id
469 AND u.deleted = 0
8e4bf6cc 470 $this->userwheresql
656d17c2
AD
471 $this->groupwheresql
472 ORDER BY $sort";
d3b698a4
AD
473 $studentsperpage = $this->get_students_per_page();
474 $this->users = $DB->get_records_sql($sql, $params, $studentsperpage * $this->page, $studentsperpage);
09d0ef21 475
4ba9941c 476 if (empty($this->users)) {
477 $this->userselect = '';
478 $this->users = array();
0a695c36 479 $this->userselect_params = array();
4ba9941c 480 } else {
3aafffc0 481 list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
d24832f9 482 $this->userselect = "AND g.userid $usql";
3aafffc0
AD
483 $this->userselect_params = $uparams;
484
fe89cb8c 485 // First flag everyone as not suspended.
3aafffc0 486 foreach ($this->users as $user) {
fe89cb8c
FM
487 $this->users[$user->id]->suspendedenrolment = false;
488 }
489
490 // If we want to mix both suspended and not suspended users, let's find out who is suspended.
491 if (!$showonlyactiveenrol) {
492 $sql = "SELECT ue.userid
493 FROM {user_enrolments} ue
494 JOIN {enrol} e ON e.id = ue.enrolid
495 WHERE ue.userid $usql
496 AND ue.status = :uestatus
497 AND e.status = :estatus
498 AND e.courseid = :courseid
499 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
500 GROUP BY ue.userid";
501
502 $time = time();
503 $params = array_merge($uparams, array('estatus' => ENROL_INSTANCE_ENABLED, 'uestatus' => ENROL_USER_ACTIVE,
504 'courseid' => $coursecontext->instanceid, 'now1' => $time, 'now2' => $time));
505 $useractiveenrolments = $DB->get_records_sql($sql, $params);
506
507 foreach ($this->users as $user) {
38c1dd19
RT
508 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments);
509 }
3aafffc0 510 }
4ba9941c 511 }
4ba9941c 512 return $this->users;
513 }
514
4ba9941c 515 /**
516 * we supply the userids in this query, and get all the grades
517 * pulls out all the grades, this does not need to worry about paging
518 */
d24832f9 519 public function load_final_grades() {
520 global $CFG, $DB;
4ba9941c 521
8233747e
AD
522 if (!empty($this->grades)) {
523 return;
524 }
525
8e4bf6cc
MA
526 if (empty($this->users)) {
527 return;
528 }
529
6ef4878b 530 // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
b50371da 531 $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
b89a70ce 532 $sql = "SELECT g.*
d24832f9 533 FROM {grade_items} gi,
534 {grade_grades} g
b50371da 535 WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
b89a70ce 536
537 $userids = array_keys($this->users);
4ba9941c 538
d24832f9 539 if ($grades = $DB->get_records_sql($sql, $params)) {
b89a70ce 540 foreach ($grades as $graderec) {
d24832f9 541 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
b89a70ce 542 $this->grades[$graderec->userid][$graderec->itemid] = new grade_grade($graderec, false);
54352ac9 543 $this->grades[$graderec->userid][$graderec->itemid]->grade_item = $this->gtree->get_item($graderec->itemid); // db caching
b89a70ce 544 }
545 }
546 }
547
548 // prefil grades that do not exist yet
549 foreach ($userids as $userid) {
02d1a0a5 550 foreach ($this->gtree->get_items() as $itemid => $unused) {
b89a70ce 551 if (!isset($this->grades[$userid][$itemid])) {
552 $this->grades[$userid][$itemid] = new grade_grade();
478f4322 553 $this->grades[$userid][$itemid]->itemid = $itemid;
3b34f698 554 $this->grades[$userid][$itemid]->userid = $userid;
54352ac9 555 $this->grades[$userid][$itemid]->grade_item = $this->gtree->get_item($itemid); // db caching
b89a70ce 556 }
4ba9941c 557 }
558 }
559 }
560
561 /**
02d1a0a5 562 * Gets html toggle
33564ffb 563 * @deprecated since Moodle 2.4 as it appears not to be used any more.
4ba9941c 564 */
d24832f9 565 public function get_toggles_html() {
33564ffb 566 throw new coding_exception('get_toggles_html() can not be used any more');
4ba9941c 567 }
568
569 /**
02d1a0a5 570 * Prints html toggle
33564ffb 571 * @deprecated since 2.4 as it appears not to be used any more.
02d1a0a5 572 * @param unknown $type
33564ffb 573 */
319770d7 574 public function print_toggle($type) {
33564ffb 575 throw new coding_exception('print_toggle() can not be used any more');
4ba9941c 576 }
577
578 /**
6c096a49
NC
579 * Builds and returns the rows that will make up the left part of the grader report
580 * This consists of student names and icons, links to user reports and id numbers, as well
581 * as header cells for these columns. It also includes the fillers required for the
582 * categories displayed on the right side of the report.
2b267d31 583 * @param boolean $displayaverages whether to display average rows in the table
6c096a49 584 * @return array Array of html_table_row objects
4ba9941c 585 */
cbe8e5b3 586 public function get_left_rows($displayaverages) {
319770d7 587 global $CFG, $USER, $OUTPUT;
4ba9941c 588
6c096a49
NC
589 $rows = array();
590
591 $showuserimage = $this->get_pref('showuserimage');
1c733bd6 592 $canseeuserreport = has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context);
4ae71e93
DP
593 $canseesingleview = has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall',
594 'moodle/grade:edit'), $this->context);
1c733bd6 595 $hasuserreportcell = $canseeuserreport || $canseesingleview;
203b7e2e 596
6c096a49
NC
597 $strfeedback = $this->get_lang_string("feedback");
598 $strgrade = $this->get_lang_string('grade');
203b7e2e 599
e4aec5be 600 $extrafields = get_extra_user_fields($this->context);
6c096a49 601
e4aec5be 602 $arrows = $this->get_sort_arrows($extrafields);
6c096a49 603
1c733bd6 604 $colspan = 1 + $hasuserreportcell + count($extrafields);
6c096a49
NC
605
606 $levels = count($this->gtree->levels) - 1;
607
6929b68b
JC
608 $fillercell = new html_table_cell();
609 $fillercell->header = true;
610 $fillercell->attributes['scope'] = 'col';
611 $fillercell->attributes['class'] = 'cell topleft';
612 $fillercell->text = html_writer::span(get_string('participants'), 'accesshide');
613 $fillercell->colspan = $colspan;
614 $fillercell->rowspan = $levels;
615 $row = new html_table_row(array($fillercell));
616 $rows[] = $row;
617
618 for ($i = 1; $i < $levels; $i++) {
619 $row = new html_table_row();
6c096a49
NC
620 $rows[] = $row;
621 }
622
623 $headerrow = new html_table_row();
16be8974 624 $headerrow->attributes['class'] = 'heading';
6c096a49
NC
625
626 $studentheader = new html_table_cell();
16be8974 627 $studentheader->attributes['class'] = 'header';
6c096a49
NC
628 $studentheader->scope = 'col';
629 $studentheader->header = true;
630 $studentheader->id = 'studentheader';
1c733bd6 631 if ($hasuserreportcell) {
6c096a49
NC
632 $studentheader->colspan = 2;
633 }
634 $studentheader->text = $arrows['studentname'];
635
636 $headerrow->cells[] = $studentheader;
637
e4aec5be 638 foreach ($extrafields as $field) {
639 $fieldheader = new html_table_cell();
640 $fieldheader->attributes['class'] = 'header userfield user' . $field;
641 $fieldheader->scope = 'col';
642 $fieldheader->header = true;
643 $fieldheader->text = $arrows[$field];
6c096a49 644
e4aec5be 645 $headerrow->cells[] = $fieldheader;
6c096a49
NC
646 }
647
648 $rows[] = $headerrow;
649
650 $rows = $this->get_left_icons_row($rows, $colspan);
651
3aafffc0 652 $suspendedstring = null;
6c096a49
NC
653 foreach ($this->users as $userid => $user) {
654 $userrow = new html_table_row();
fe213365 655 $userrow->id = 'fixed_user_'.$userid;
6c096a49
NC
656
657 $usercell = new html_table_cell();
6929b68b 658 $usercell->attributes['class'] = 'header user';
3aafffc0 659
6c096a49
NC
660 $usercell->header = true;
661 $usercell->scope = 'row';
6c096a49
NC
662
663 if ($showuserimage) {
6929b68b 664 $usercell->text = $OUTPUT->user_picture($user, array('visibletoscreenreaders' => false));
203b7e2e 665 }
666
b21b32a4 667 $fullname = fullname($user);
feb0014b
AN
668 $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), $fullname, array(
669 'class' => 'username',
670 ));
6c096a49 671
3aafffc0
AD
672 if (!empty($user->suspendedenrolment)) {
673 $usercell->attributes['class'] .= ' usersuspended';
674
675 //may be lots of suspended users so only get the string once
676 if (empty($suspendedstring)) {
677 $suspendedstring = get_string('userenrolmentsuspended', 'grades');
678 }
02d1a0a5
MA
679 $usercell->text .= html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('i/enrolmentsuspended'), 'title'=>$suspendedstring,
680 'alt'=>$suspendedstring, 'class'=>'usersuspendedicon'));
3aafffc0
AD
681 }
682
6c096a49
NC
683 $userrow->cells[] = $usercell;
684
0a55da57
AB
685 $userreportcell = new html_table_cell();
686 $userreportcell->attributes['class'] = 'userreport';
6929b68b 687 $userreportcell->header = false;
1c733bd6 688 if ($canseeuserreport) {
ace9051c 689 $a = new stdClass();
b21b32a4 690 $a->user = $fullname;
6c096a49 691 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
a6855934 692 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
0a55da57
AB
693 $userreportcell->text .= $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
694 }
695
1c733bd6 696 if ($canseesingleview) {
92c61fee
ZD
697 $url = new moodle_url('/grade/report/singleview/index.php', array('id' => $this->course->id, 'itemid' => $user->id, 'item' => 'user'));
698 $singleview = $OUTPUT->action_icon($url, new pix_icon('t/editstring', get_string('singleview', 'grades', $fullname)));
0a55da57
AB
699 $userreportcell->text .= $singleview;
700 }
701
702 if ($userreportcell->text) {
6c096a49 703 $userrow->cells[] = $userreportcell;
203b7e2e 704 }
705
e4aec5be 706 foreach ($extrafields as $field) {
707 $fieldcell = new html_table_cell();
6929b68b
JC
708 $fieldcell->attributes['class'] = 'userfield user' . $field;
709 $fieldcell->header = false;
e4aec5be 710 $fieldcell->text = $user->{$field};
711 $userrow->cells[] = $fieldcell;
6c096a49
NC
712 }
713
feb0014b 714 $userrow->attributes['data-uid'] = $userid;
6c096a49 715 $rows[] = $userrow;
203b7e2e 716 }
4ba9941c 717
6c096a49 718 $rows = $this->get_left_range_row($rows, $colspan);
cbe8e5b3
MA
719 if ($displayaverages) {
720 $rows = $this->get_left_avg_row($rows, $colspan, true);
721 $rows = $this->get_left_avg_row($rows, $colspan);
722 }
4ba9941c 723
6c096a49
NC
724 return $rows;
725 }
726
727 /**
728 * Builds and returns the rows that will make up the right part of the grader report
2b267d31 729 * @param boolean $displayaverages whether to display average rows in the table
6c096a49
NC
730 * @return array Array of html_table_row objects
731 */
cbe8e5b3 732 public function get_right_rows($displayaverages) {
fe213365 733 global $CFG, $USER, $OUTPUT, $DB, $PAGE;
4ba9941c 734
6c096a49
NC
735 $rows = array();
736 $this->rowcount = 0;
737 $numrows = count($this->gtree->get_levels());
738 $numusers = count($this->users);
739 $gradetabindex = 1;
319770d7 740 $columnstounset = array();
6c096a49 741 $strgrade = $this->get_lang_string('grade');
fe213365 742 $strfeedback = $this->get_lang_string("feedback");
6c096a49 743 $arrows = $this->get_sort_arrows();
cb7fe7b4 744
fe213365 745 $jsarguments = array(
fe213365
SH
746 'cfg' => array('ajaxenabled'=>false),
747 'items' => array(),
748 'users' => array(),
749 'feedback' => array()
750 );
751 $jsscales = array();
752
b21b32a4
AN
753 // Get preferences once.
754 $showactivityicons = $this->get_pref('showactivityicons');
755 $quickgrading = $this->get_pref('quickgrading');
756 $showquickfeedback = $this->get_pref('showquickfeedback');
757 $enableajax = $this->get_pref('enableajax');
758 $showanalysisicon = $this->get_pref('showanalysisicon');
759
760 // Get strings which are re-used inside the loop.
761 $strftimedatetimeshort = get_string('strftimedatetimeshort');
762 $strexcludedgrades = get_string('excluded', 'grades');
763 $strerror = get_string('error');
b21b32a4 764
02d1a0a5 765 foreach ($this->gtree->get_levels() as $key => $row) {
6c096a49 766 $headingrow = new html_table_row();
16be8974 767 $headingrow->attributes['class'] = 'heading_name_row';
4ba9941c 768
cb7fe7b4 769 foreach ($row as $columnkey => $element) {
319770d7 770 $sortlink = clone($this->baseurl);
2e3987a9 771 if (isset($element['object']->id)) {
319770d7 772 $sortlink->param('sortitemid', $element['object']->id);
2e3987a9 773 }
774
cb7fe7b4 775 $eid = $element['eid'];
776 $object = $element['object'];
777 $type = $element['type'];
438a5aa9 778 $categorystate = @$element['categorystate'];
8c5a416e 779
4ba9941c 780 if (!empty($element['colspan'])) {
6c096a49 781 $colspan = $element['colspan'];
4ba9941c 782 } else {
6c096a49 783 $colspan = 1;
4ba9941c 784 }
785
786 if (!empty($element['depth'])) {
6c096a49 787 $catlevel = 'catlevel'.$element['depth'];
4ba9941c 788 } else {
789 $catlevel = '';
790 }
791
02d1a0a5 792 // Element is a filler
4ba9941c 793 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
6c096a49 794 $fillercell = new html_table_cell();
16be8974 795 $fillercell->attributes['class'] = $type . ' ' . $catlevel;
6c096a49
NC
796 $fillercell->colspan = $colspan;
797 $fillercell->text = '&nbsp;';
6929b68b
JC
798
799 // This is a filler cell; don't use a <th>, it'll confuse screen readers.
800 $fillercell->header = false;
6c096a49 801 $headingrow->cells[] = $fillercell;
02d1a0a5
MA
802 } else if ($type == 'category') {
803 // Element is a category
6c096a49 804 $categorycell = new html_table_cell();
16be8974 805 $categorycell->attributes['class'] = 'category ' . $catlevel;
6c096a49 806 $categorycell->colspan = $colspan;
2350b3f4 807 $categorycell->text = $this->get_course_header($element);
6c096a49
NC
808 $categorycell->header = true;
809 $categorycell->scope = 'col';
4ba9941c 810
811 // Print icons
2cc773f5 812 if ($USER->gradeediting[$this->courseid]) {
6c096a49 813 $categorycell->text .= $this->get_icons($element);
4ba9941c 814 }
815
6c096a49 816 $headingrow->cells[] = $categorycell;
02d1a0a5
MA
817 } else {
818 // Element is a grade_item
4ba9941c 819 if ($element['object']->id == $this->sortitemid) {
820 if ($this->sortorder == 'ASC') {
319770d7 821 $arrow = $this->get_sort_arrow('up', $sortlink);
4ba9941c 822 } else {
319770d7 823 $arrow = $this->get_sort_arrow('down', $sortlink);
4ba9941c 824 }
825 } else {
319770d7 826 $arrow = $this->get_sort_arrow('move', $sortlink);
4ba9941c 827 }
828
41e62a90 829 $headerlink = $this->gtree->get_element_header($element, true, $showactivityicons, false, false, true);
6c096a49
NC
830
831 $itemcell = new html_table_cell();
edb7d5ad 832 $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable'. ' i'. $element['object']->id;
6ad1af09 833 $itemcell->attributes['data-itemid'] = $element['object']->id;
6c096a49 834
4ba9941c 835 if ($element['object']->is_hidden()) {
834f4ea6 836 $itemcell->attributes['class'] .= ' dimmed_text';
4ba9941c 837 }
838
92c61fee 839 $singleview = '';
4ae71e93
DP
840 if (has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall',
841 'moodle/grade:edit'), $this->context)) {
842
92c61fee
ZD
843 $url = new moodle_url('/grade/report/singleview/index.php', array(
844 'id' => $this->course->id,
845 'item' => 'grade',
846 'itemid' => $element['object']->id));
2350b3f4
ZD
847 $singleview = $OUTPUT->action_icon(
848 $url,
1be1c66a 849 new pix_icon('t/editstring', get_string('singleview', 'grades', $element['object']->get_name()))
2350b3f4 850 );
92c61fee
ZD
851 }
852
6c096a49 853 $itemcell->colspan = $colspan;
92c61fee 854 $itemcell->text = shorten_text($headerlink) . $arrow . $singleview;
6c096a49
NC
855 $itemcell->header = true;
856 $itemcell->scope = 'col';
6c096a49
NC
857
858 $headingrow->cells[] = $itemcell;
4ba9941c 859 }
4ba9941c 860 }
6c096a49 861 $rows[] = $headingrow;
4ba9941c 862 }
4ba9941c 863
6c096a49 864 $rows = $this->get_right_icons_row($rows);
4ba9941c 865
f17bb885 866 // Preload scale objects for items with a scaleid and initialize tab indices
319770d7 867 $scaleslist = array();
c0c1e7c2 868 $tabindices = array();
d297269d 869
02d1a0a5 870 foreach ($this->gtree->get_items() as $itemid => $item) {
fe213365 871 $scale = null;
388234f4 872 if (!empty($item->scaleid)) {
319770d7 873 $scaleslist[] = $item->scaleid;
fe213365
SH
874 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
875 } else {
876 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
388234f4 877 }
c0c1e7c2 878 $tabindices[$item->id]['grade'] = $gradetabindex;
879 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
880 $gradetabindex += $numusers * 2;
388234f4 881 }
319770d7 882 $scalesarray = array();
388234f4 883
319770d7 884 if (!empty($scaleslist)) {
885 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
388234f4 886 }
fe213365 887 $jsscales = $scalesarray;
d24832f9 888
4ba9941c 889 foreach ($this->users as $userid => $user) {
b89a70ce 890
57068674 891 if ($this->canviewhidden) {
d297269d 892 $altered = array();
893 $unknown = array();
b89a70ce 894 } else {
319770d7 895 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
896 $altered = $hidingaffected['altered'];
897 $unknown = $hidingaffected['unknown'];
898 unset($hidingaffected);
b89a70ce 899 }
900
6c096a49 901 $itemrow = new html_table_row();
fe213365 902 $itemrow->id = 'user_'.$userid;
9d35e66e 903
b21b32a4
AN
904 $fullname = fullname($user);
905 $jsarguments['users'][$userid] = $fullname;
fe213365 906
02d1a0a5 907 foreach ($this->gtree->items as $itemid => $unused) {
dc482cfa 908 $item =& $this->gtree->items[$itemid];
d297269d 909 $grade = $this->grades[$userid][$item->id];
b89a70ce 910
6c096a49
NC
911 $itemcell = new html_table_cell();
912
fe213365 913 $itemcell->id = 'u'.$userid.'i'.$itemid;
6ad1af09 914 $itemcell->attributes['data-itemid'] = $itemid;
fe213365 915
e50ce569 916 // Get the decimal points preference for this item
31a6c06c 917 $decimalpoints = $item->get_decimals();
4ba9941c 918
d297269d 919 if (in_array($itemid, $unknown)) {
920 $gradeval = null;
921 } else if (array_key_exists($itemid, $altered)) {
922 $gradeval = $altered[$itemid];
923 } else {
924 $gradeval = $grade->finalgrade;
925 }
a740a0ad 926 if (!empty($grade->finalgrade)) {
02d1a0a5 927 $gradevalforjs = null;
a740a0ad 928 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
02d1a0a5 929 $gradevalforjs = (int)$gradeval;
a740a0ad 930 } else {
02d1a0a5 931 $gradevalforjs = format_float($gradeval, $decimalpoints);
a740a0ad 932 }
02d1a0a5 933 $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforjs);
a740a0ad 934 }
4ba9941c 935
00374cc5 936 // MDL-11274
937 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
57068674 938 if (!$this->canviewhidden and $grade->is_hidden()) {
6cc3e350 939 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
d297269d 940 // 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
941 $itemcell->text = "<span class='datesubmitted'>" .
942 userdate($grade->get_datesubmitted(), $strftimedatetimeshort) . "</span>";
bb49f77b 943 } else {
6c096a49 944 $itemcell->text = '-';
00374cc5 945 }
6c096a49 946 $itemrow->cells[] = $itemcell;
a5b8be62 947 continue;
00374cc5 948 }
949
2cc773f5 950 // emulate grade element
d3c3da1b 951 $eid = $this->gtree->get_grade_eid($grade);
952 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
2cc773f5 953
edb7d5ad 954 $itemcell->attributes['class'] .= ' grade i'.$itemid;
dff9d94d 955 if ($item->is_category_item()) {
16be8974 956 $itemcell->attributes['class'] .= ' cat';
b89a70ce 957 }
dff9d94d 958 if ($item->is_course_item()) {
16be8974 959 $itemcell->attributes['class'] .= ' course';
b89a70ce 960 }
4ba9941c 961 if ($grade->is_overridden()) {
16be8974 962 $itemcell->attributes['class'] .= ' overridden';
6ad1af09 963 $itemcell->attributes['aria-label'] = get_string('overriddengrade', 'gradereport_grader');
4ba9941c 964 }
85db09fb 965
fe213365 966 if (!empty($grade->feedback)) {
feb0014b
AN
967 $feedback = wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br>');
968 $itemcell->attributes['data-feedback'] = $feedback;
969 $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content' => $feedback);
653a8648 970 }
971
23207a1a 972 if ($grade->is_excluded()) {
d688ee6d
FM
973 // Adding white spaces before and after to prevent a screenreader from
974 // thinking that the words are attached to the next/previous <span> or text.
975 $itemcell->text .= " <span class='excludedfloater'>" . $strexcludedgrades . "</span> ";
23207a1a 976 }
977
4ba9941c 978 // Do not show any icons if no grade (no record in DB to match)
d3c3da1b 979 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
6c096a49 980 $itemcell->text .= $this->get_icons($element);
4ba9941c 981 }
982
80fb1cf9 983 $hidden = '';
984 if ($grade->is_hidden()) {
cff613f0 985 $hidden = ' dimmed_text ';
80fb1cf9 986 }
6cc3e350 987
d24832f9 988 $gradepass = ' gradefail ';
46e6df89 989 if ($grade->is_passed($item)) {
990 $gradepass = ' gradepass ';
02d1a0a5 991 } else if (is_null($grade->is_passed($item))) {
e6477988 992 $gradepass = '';
46e6df89 993 }
994
6ef4878b 995 // if in editing mode, we need to print either a text box
4ba9941c 996 // or a drop down (for scales)
4ba9941c 997 // grades in item of type grade category or course are not directly editable
d14ae855 998 if ($item->needsupdate) {
b21b32a4 999 $itemcell->text .= "<span class='gradingerror{$hidden}'>" . $strerror . "</span>";
d14ae855 1000
2cc773f5 1001 } else if ($USER->gradeediting[$this->courseid]) {
4ba9941c 1002
319770d7 1003 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1004 $scale = $scalesarray[$item->scaleid];
99ccfda8 1005 $gradeval = (int)$gradeval; // scales use only integers
388234f4 1006 $scales = explode(",", $scale->scale);
1007 // reindex because scale is off 1
9d35e66e 1008
914ea002 1009 // MDL-12104 some previous scales might have taken up part of the array
1010 // so this needs to be reset
d48ebf97 1011 $scaleopt = array();
388234f4 1012 $i = 0;
1013 foreach ($scales as $scaleoption) {
1014 $i++;
1015 $scaleopt[$i] = $scaleoption;
1016 }
1017
b21b32a4 1018 if ($quickgrading and $grade->is_editable()) {
0658afc9 1019 $oldval = empty($gradeval) ? -1 : $gradeval;
1020 if (empty($item->outcomeid)) {
d4795a07 1021 $nogradestr = $this->get_lang_string('nograde');
0658afc9 1022 } else {
d4795a07 1023 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
0658afc9 1024 }
fe213365 1025 $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
3087835a
JO
1026 $gradelabel = $fullname . ' ' . $item->itemname;
1027 $itemcell->text .= html_writer::label(
1028 get_string('useractivitygrade', 'gradereport_grader', $gradelabel), $attributes['id'], false,
b21b32a4 1029 array('class' => 'accesshide'));
30793ea3 1030 $itemcell->text .= html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']', $gradeval, array(-1=>$nogradestr), $attributes);
02d1a0a5 1031 } else if (!empty($scale)) {
4ba9941c 1032 $scales = explode(",", $scale->scale);
4ba9941c 1033
388234f4 1034 // invalid grade if gradeval < 1
99ccfda8 1035 if ($gradeval < 1) {
b21b32a4 1036 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>-</span>";
4ba9941c 1037 } else {
653a8648 1038 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
b21b32a4 1039 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>{$scales[$gradeval - 1]}</span>";
4ba9941c 1040 }
1041 }
79eabc2a 1042
bb384a8e 1043 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
b21b32a4 1044 if ($quickgrading and $grade->is_editable()) {
76317c73 1045 $value = format_float($gradeval, $decimalpoints);
b21b32a4 1046 $gradelabel = $fullname . ' ' . $item->itemname;
7400be1b
RT
1047 $itemcell->text .= '<label class="accesshide" for="grade_'.$userid.'_'.$item->id.'">'
1048 .get_string('useractivitygrade', 'gradereport_grader', $gradelabel).'</label>';
6c096a49 1049 $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
30793ea3
PN
1050 . '" type="text" class="text" title="'. $strgrade .'" name="grade['
1051 .$userid.'][' .$item->id.']" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
4ba9941c 1052 } else {
b21b32a4
AN
1053 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>" .
1054 format_float($gradeval, $decimalpoints) . "</span>";
4ba9941c 1055 }
1056 }
1057
4ba9941c 1058 // If quickfeedback is on, print an input element
b21b32a4
AN
1059 if ($showquickfeedback and $grade->is_editable()) {
1060 $feedbacklabel = $fullname . ' ' . $item->itemname;
7400be1b
RT
1061 $itemcell->text .= '<label class="accesshide" for="feedback_'.$userid.'_'.$item->id.'">'
1062 .get_string('useractivityfeedback', 'gradereport_grader', $feedbacklabel).'</label>';
fe213365 1063 $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
30793ea3 1064 . '" size="6" title="' . $strfeedback . '" type="text" name="feedback['.$userid.']['.$item->id.']" value="' . s($grade->feedback) . '" />';
4ba9941c 1065 }
1066
78a2d9f0 1067 } else { // Not editing
41f22daa 1068 $gradedisplaytype = $item->get_displaytype();
e50ce569 1069
fe213365 1070 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
16be8974 1071 $itemcell->attributes['class'] .= ' grade_type_scale';
fe213365 1072 } else if ($item->gradetype != GRADE_TYPE_TEXT) {
16be8974 1073 $itemcell->attributes['class'] .= ' grade_type_text';
fe213365 1074 }
4ba9941c 1075
b21b32a4 1076 if ($enableajax) {
0e999796
AD
1077 $canoverride = true;
1078 if ($item->is_category_item() || $item->is_course_item()) {
1079 $canoverride = (bool) get_config('moodle', 'grade_overridecat');
1080 }
1081 if ($canoverride) {
1082 $itemcell->attributes['class'] .= ' clickable';
1083 }
6712973f
AD
1084 }
1085
d14ae855 1086 if ($item->needsupdate) {
b21b32a4 1087 $itemcell->text .= "<span class='gradingerror{$hidden}{$gradepass}'>" . $error . "</span>";
4ba9941c 1088 } else {
5a59aeb1
DW
1089 // The max and min for an aggregation may be different to the grade_item.
1090 if (!is_null($gradeval)) {
ebea19cb
FM
1091 $item->grademax = $grade->get_grade_max();
1092 $item->grademin = $grade->get_grade_min();
5a59aeb1
DW
1093 }
1094
b21b32a4
AN
1095 $itemcell->text .= "<span class='gradevalue{$hidden}{$gradepass}'>" .
1096 grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null) . "</span>";
1097 if ($showanalysisicon) {
f17bb885 1098 $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
bb17ac1e 1099 }
4ba9941c 1100 }
4ba9941c 1101 }
1102
1103 if (!empty($this->gradeserror[$item->id][$userid])) {
6c096a49 1104 $itemcell->text .= $this->gradeserror[$item->id][$userid];
4ba9941c 1105 }
1106
6c096a49 1107 $itemrow->cells[] = $itemcell;
4ba9941c 1108 }
6c096a49 1109 $rows[] = $itemrow;
4ba9941c 1110 }
4ba9941c 1111
b21b32a4 1112 if ($enableajax) {
fe213365
SH
1113 $jsarguments['cfg']['ajaxenabled'] = true;
1114 $jsarguments['cfg']['scales'] = array();
1115 foreach ($jsscales as $scale) {
02d1a0a5 1116 $jsarguments['cfg']['scales'][$scale->id] = explode(',', $scale->scale);
fe213365
SH
1117 }
1118 $jsarguments['cfg']['feedbacktrunclength'] = $this->feedback_trunc_length;
92ff6236 1119
a740a0ad 1120 // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades']
fe213365
SH
1121 }
1122 $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
b21b32a4
AN
1123 $jsarguments['cfg']['courseid'] = $this->courseid;
1124 $jsarguments['cfg']['studentsperpage'] = $this->get_students_per_page();
1125 $jsarguments['cfg']['showquickfeedback'] = (bool) $showquickfeedback;
fe213365
SH
1126
1127 $module = array(
1128 'name' => 'gradereport_grader',
1129 'fullpath' => '/grade/report/grader/module.js',
227e9023 1130 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
fe213365
SH
1131 );
1132 $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
02d1a0a5
MA
1133 $PAGE->requires->strings_for_js(array('addfeedback', 'feedback', 'grade'), 'grades');
1134 $PAGE->requires->strings_for_js(array('ajaxchoosescale', 'ajaxclicktoclose', 'ajaxerror', 'ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
b21b32a4 1135 if (!$enableajax && $USER->gradeediting[$this->courseid]) {
0f204015
AO
1136 $PAGE->requires->yui_module('moodle-core-formchangechecker',
1137 'M.core_formchangechecker.init',
1138 array(array(
1139 'formid' => 'gradereport_grader'
1140 ))
1141 );
1142 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
1143 }
fe213365 1144
6c096a49 1145 $rows = $this->get_right_range_row($rows);
cbe8e5b3
MA
1146 if ($displayaverages) {
1147 $rows = $this->get_right_avg_row($rows, true);
1148 $rows = $this->get_right_avg_row($rows);
1149 }
dc482cfa 1150
6c096a49
NC
1151 return $rows;
1152 }
dc482cfa 1153
6c096a49
NC
1154 /**
1155 * Depending on the style of report (fixedstudents vs traditional one-table),
1156 * arranges the rows of data in one or two tables, and returns the output of
1157 * these tables in HTML
2b267d31 1158 * @param boolean $displayaverages whether to display average rows in the table
6c096a49
NC
1159 * @return string HTML
1160 */
cbe8e5b3 1161 public function get_grade_table($displayaverages = false) {
6c096a49 1162 global $OUTPUT;
cbe8e5b3
MA
1163 $leftrows = $this->get_left_rows($displayaverages);
1164 $rightrows = $this->get_right_rows($displayaverages);
dc482cfa 1165
6c096a49 1166 $html = '';
dc482cfa 1167
8c037a91 1168 $fulltable = new html_table();
31819e89 1169 $fulltable->attributes['class'] = 'gradereport-grader-table';
8c037a91 1170 $fulltable->id = 'user-grades';
6929b68b 1171 $fulltable->summary = get_string('summarygrader', 'gradereport_grader');
319770d7 1172
8c037a91
AN
1173 // Extract rows from each side (left and right) and collate them into one row each
1174 foreach ($leftrows as $key => $row) {
1175 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1176 $fulltable->data[] = $row;
6c096a49 1177 }
8c037a91 1178 $html .= html_writer::table($fulltable);
6c096a49
NC
1179 return $OUTPUT->container($html, 'gradeparent');
1180 }
dc482cfa 1181
6c096a49
NC
1182 /**
1183 * Builds and return the row of icons for the left side of the report.
1184 * It only has one cell that says "Controls"
1185 * @param array $rows The Array of rows for the left part of the report
1186 * @param int $colspan The number of columns this cell has to span
1187 * @return array Array of rows for the left part of the report
1188 */
1189 public function get_left_icons_row($rows=array(), $colspan=1) {
1190 global $USER;
dc482cfa 1191
6c096a49
NC
1192 if ($USER->gradeediting[$this->courseid]) {
1193 $controlsrow = new html_table_row();
16be8974 1194 $controlsrow->attributes['class'] = 'controls';
6c096a49 1195 $controlscell = new html_table_cell();
16be8974 1196 $controlscell->attributes['class'] = 'header controls';
6c096a49 1197 $controlscell->colspan = $colspan;
02d1a0a5 1198 $controlscell->text = $this->get_lang_string('controls', 'grades');
6c096a49
NC
1199
1200 $controlsrow->cells[] = $controlscell;
1201 $rows[] = $controlsrow;
1202 }
1203 return $rows;
1204 }
dc482cfa 1205
6c096a49
NC
1206 /**
1207 * Builds and return the header for the row of ranges, for the left part of the grader report.
1208 * @param array $rows The Array of rows for the left part of the report
1209 * @param int $colspan The number of columns this cell has to span
1210 * @return array Array of rows for the left part of the report
1211 */
1212 public function get_left_range_row($rows=array(), $colspan=1) {
1213 global $CFG, $USER;
bb9b58a6 1214
6c096a49
NC
1215 if ($this->get_pref('showranges')) {
1216 $rangerow = new html_table_row();
16be8974 1217 $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
6c096a49 1218 $rangecell = new html_table_cell();
16be8974 1219 $rangecell->attributes['class'] = 'header range';
6c096a49
NC
1220 $rangecell->colspan = $colspan;
1221 $rangecell->header = true;
1222 $rangecell->scope = 'row';
02d1a0a5 1223 $rangecell->text = $this->get_lang_string('range', 'grades');
6c096a49
NC
1224 $rangerow->cells[] = $rangecell;
1225 $rows[] = $rangerow;
1226 }
dc482cfa 1227
6c096a49
NC
1228 return $rows;
1229 }
dc482cfa 1230
6c096a49
NC
1231 /**
1232 * Builds and return the headers for the rows of averages, for the left part of the grader report.
1233 * @param array $rows The Array of rows for the left part of the report
1234 * @param int $colspan The number of columns this cell has to span
1235 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1236 * @return array Array of rows for the left part of the report
1237 */
1238 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1239 if (!$this->canviewhidden) {
1240 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1241 // better not show them at all if user can not see all hideen grades
1242 return $rows;
1243 }
dc482cfa 1244
6c096a49
NC
1245 $showaverages = $this->get_pref('showaverages');
1246 $showaveragesgroup = $this->currentgroup && $showaverages;
1247 $straveragegroup = get_string('groupavg', 'grades');
319770d7 1248
6c096a49 1249 if ($groupavg) {
319770d7 1250 if ($showaveragesgroup) {
1251 $groupavgrow = new html_table_row();
16be8974 1252 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
319770d7 1253 $groupavgcell = new html_table_cell();
16be8974 1254 $groupavgcell->attributes['class'] = 'header range';
319770d7 1255 $groupavgcell->colspan = $colspan;
1256 $groupavgcell->header = true;
1257 $groupavgcell->scope = 'row';
1258 $groupavgcell->text = $straveragegroup;
1259 $groupavgrow->cells[] = $groupavgcell;
6c096a49 1260 $rows[] = $groupavgrow;
203b7e2e 1261 }
6c096a49
NC
1262 } else {
1263 $straverage = get_string('overallaverage', 'grades');
dc482cfa 1264
203b7e2e 1265 if ($showaverages) {
319770d7 1266 $avgrow = new html_table_row();
16be8974 1267 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
319770d7 1268 $avgcell = new html_table_cell();
16be8974 1269 $avgcell->attributes['class'] = 'header range';
319770d7 1270 $avgcell->colspan = $colspan;
1271 $avgcell->header = true;
1272 $avgcell->scope = 'row';
1273 $avgcell->text = $straverage;
1274 $avgrow->cells[] = $avgcell;
6c096a49 1275 $rows[] = $avgrow;
203b7e2e 1276 }
6c096a49 1277 }
203b7e2e 1278
6c096a49
NC
1279 return $rows;
1280 }
dc482cfa 1281
6c096a49
NC
1282 /**
1283 * Builds and return the row of icons when editing is on, for the right part of the grader report.
1284 * @param array $rows The Array of rows for the right part of the report
1285 * @return array Array of rows for the right part of the report
1286 */
1287 public function get_right_icons_row($rows=array()) {
1288 global $USER;
1289 if ($USER->gradeediting[$this->courseid]) {
1290 $iconsrow = new html_table_row();
16be8974 1291 $iconsrow->attributes['class'] = 'controls';
6c096a49 1292
02d1a0a5 1293 foreach ($this->gtree->items as $itemid => $unused) {
6c096a49 1294 // emulate grade element
e2bb3c92 1295 $item = $this->gtree->get_item($itemid);
6c096a49
NC
1296
1297 $eid = $this->gtree->get_item_eid($item);
1298 $element = $this->gtree->locate_element($eid);
1299 $itemcell = new html_table_cell();
edb7d5ad 1300 $itemcell->attributes['class'] = 'controls icons i'.$itemid;
6c096a49
NC
1301 $itemcell->text = $this->get_icons($element);
1302 $iconsrow->cells[] = $itemcell;
1303 }
1304 $rows[] = $iconsrow;
1305 }
1306 return $rows;
dc482cfa 1307 }
1308
18a00359 1309 /**
6c096a49
NC
1310 * Builds and return the row of ranges for the right part of the grader report.
1311 * @param array $rows The Array of rows for the right part of the report
1312 * @return array Array of rows for the right part of the report
18a00359 1313 */
6c096a49
NC
1314 public function get_right_range_row($rows=array()) {
1315 global $OUTPUT;
18a00359 1316
6c096a49
NC
1317 if ($this->get_pref('showranges')) {
1318 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
1319 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1320 $rangerow = new html_table_row();
16be8974 1321 $rangerow->attributes['class'] = 'heading range';
18a00359 1322
02d1a0a5 1323 foreach ($this->gtree->items as $itemid => $unused) {
6c096a49
NC
1324 $item =& $this->gtree->items[$itemid];
1325 $itemcell = new html_table_cell();
edb7d5ad 1326 $itemcell->attributes['class'] .= ' range i'. $itemid;
6c096a49
NC
1327
1328 $hidden = '';
1329 if ($item->is_hidden()) {
cff613f0 1330 $hidden = ' dimmed_text ';
6c096a49
NC
1331 }
1332
1333 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1334
1335 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1336 $rangerow->cells[] = $itemcell;
1337 }
1338 $rows[] = $rangerow;
18a00359 1339 }
6c096a49 1340 return $rows;
18a00359 1341 }
1342
4ba9941c 1343 /**
6c096a49
NC
1344 * Builds and return the row of averages for the right part of the grader report.
1345 * @param array $rows Whether to return only group averages or all averages.
1346 * @param bool $grouponly Whether to return only group averages or all averages.
1347 * @return array Array of rows for the right part of the report
4ba9941c 1348 */
6c096a49 1349 public function get_right_avg_row($rows=array(), $grouponly=false) {
c288300c 1350 global $USER, $DB, $OUTPUT, $CFG;
4ba9941c 1351
57068674 1352 if (!$this->canviewhidden) {
4e829d48
MN
1353 // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1354 // better not show them at all if user can not see all hidden grades.
6c096a49 1355 return $rows;
57068674 1356 }
1357
5b508a08 1358 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
1359 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
098042ba 1360 $meanselection = $this->get_pref('meanselection');
1361 $shownumberofgrades = $this->get_pref('shownumberofgrades');
1362
5b508a08 1363 if ($grouponly) {
35079f53 1364 $showaverages = $this->currentgroup && $this->get_pref('showaverages');
5b508a08 1365 $groupsql = $this->groupsql;
1366 $groupwheresql = $this->groupwheresql;
319770d7 1367 $groupwheresqlparams = $this->groupwheresql_params;
3446013d 1368 } else {
5b508a08 1369 $showaverages = $this->get_pref('showaverages');
0dba6cb2 1370 $groupsql = "";
1371 $groupwheresql = "";
319770d7 1372 $groupwheresqlparams = array();
3446013d 1373 }
1374
4e829d48
MN
1375 if ($showaverages) {
1376 $totalcount = $this->get_numusers($grouponly);
a5b8be62 1377
4e829d48
MN
1378 // Limit to users with a gradeable role.
1379 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
04259694 1380
4e829d48 1381 // Limit to users with an active enrollment.
c288300c
RL
1382 $coursecontext = $this->context->get_course_context(true);
1383 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
1384 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
1385 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
1386 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
387815db 1387
4e829d48
MN
1388 // We want to query both the current context and parent contexts.
1389 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
d24832f9 1390
4e829d48 1391 $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams);
04259694 1392
4e829d48 1393 // Find sums of all grade items in course.
656d17c2 1394 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
d24832f9 1395 FROM {grade_items} gi
656d17c2
AD
1396 JOIN {grade_grades} g ON g.itemid = gi.id
1397 JOIN {user} u ON u.id = g.userid
1398 JOIN ($enrolledsql) je ON je.id = u.id
1399 JOIN (
1400 SELECT DISTINCT ra.userid
1401 FROM {role_assignments} ra
1402 WHERE ra.roleid $gradebookrolessql
4e829d48 1403 AND ra.contextid $relatedctxsql
656d17c2 1404 ) rainner ON rainner.userid = u.id
25081b95 1405 $groupsql
b50371da 1406 WHERE gi.courseid = :courseid
656d17c2
AD
1407 AND u.deleted = 0
1408 AND g.finalgrade IS NOT NULL
1409 $groupwheresql
1410 GROUP BY g.itemid";
319770d7 1411 $sumarray = array();
656d17c2 1412 if ($sums = $DB->get_records_sql($sql, $params)) {
ab3444d7 1413 foreach ($sums as $itemid => $csum) {
319770d7 1414 $sumarray[$itemid] = $csum->sum;
7b61efbe 1415 }
4ba9941c 1416 }
66ef0471 1417
883187d0 1418 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1419 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
656d17c2 1420 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
d24832f9 1421 FROM {grade_items} gi
25081b95
SH
1422 CROSS JOIN {user} u
1423 JOIN ($enrolledsql) je
1424 ON je.id = u.id
1425 JOIN {role_assignments} ra
1426 ON ra.userid = u.id
1427 LEFT OUTER JOIN {grade_grades} g
1428 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1429 $groupsql
b50371da 1430 WHERE gi.courseid = :courseid
387815db 1431 AND ra.roleid $gradebookrolessql
4e829d48 1432 AND ra.contextid $relatedctxsql
656d17c2 1433 AND u.deleted = 0
828af11c 1434 AND g.id IS NULL
1435 $groupwheresql
883187d0 1436 GROUP BY gi.id";
828af11c 1437
656d17c2 1438 $ungradedcounts = $DB->get_records_sql($sql, $params);
883187d0 1439
6c096a49 1440 $avgrow = new html_table_row();
16be8974 1441 $avgrow->attributes['class'] = 'avg';
653a8648 1442
02d1a0a5 1443 foreach ($this->gtree->items as $itemid => $unused) {
b89a70ce 1444 $item =& $this->gtree->items[$itemid];
1445
67881aa8 1446 if ($item->needsupdate) {
6c096a49 1447 $avgcell = new html_table_cell();
edb7d5ad 1448 $avgcell->attributes['class'] = 'i'. $itemid;
6c096a49
NC
1449 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1450 $avgrow->cells[] = $avgcell;
67881aa8 1451 continue;
1452 }
1453
319770d7 1454 if (!isset($sumarray[$item->id])) {
1455 $sumarray[$item->id] = 0;
33a34cd4 1456 }
883187d0 1457
319770d7 1458 if (empty($ungradedcounts[$itemid])) {
1459 $ungradedcount = 0;
828af11c 1460 } else {
319770d7 1461 $ungradedcount = $ungradedcounts[$itemid]->count;
d1556c09 1462 }
33a34cd4 1463
c2efb501 1464 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
319770d7 1465 $meancount = $totalcount - $ungradedcount;
33a34cd4 1466 } else { // Bump up the sum by the number of ungraded items * grademin
319770d7 1467 $sumarray[$item->id] += $ungradedcount * $item->grademin;
1468 $meancount = $totalcount;
33a34cd4 1469 }
1470
bb384a8e 1471 // Determine which display type to use for this average
2cc773f5 1472 if ($USER->gradeediting[$this->courseid]) {
1796708d 1473 $displaytype = GRADE_DISPLAY_TYPE_REAL;
d622930b 1474
e0724506 1475 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
d622930b 1476 $displaytype = $item->get_displaytype();
1477
1478 } else {
bb384a8e 1479 $displaytype = $averagesdisplaytype;
1480 }
1481
31a6c06c 1482 // Override grade_item setting if a display preference (not inherit) was set for the averages
e0724506 1483 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
d622930b 1484 $decimalpoints = $item->get_decimals();
1485
1486 } else {
5b508a08 1487 $decimalpoints = $averagesdecimalpoints;
1488 }
1489
319770d7 1490 if (!isset($sumarray[$item->id]) || $meancount == 0) {
6c096a49 1491 $avgcell = new html_table_cell();
edb7d5ad 1492 $avgcell->attributes['class'] = 'i'. $itemid;
6c096a49
NC
1493 $avgcell->text = '-';
1494 $avgrow->cells[] = $avgcell;
1495
4ba9941c 1496 } else {
319770d7 1497 $sum = $sumarray[$item->id];
1498 $avgradeval = $sum/$meancount;
d622930b 1499 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
bb384a8e 1500
098042ba 1501 $numberofgrades = '';
098042ba 1502 if ($shownumberofgrades) {
319770d7 1503 $numberofgrades = " ($meancount)";
098042ba 1504 }
1505
6c096a49 1506 $avgcell = new html_table_cell();
edb7d5ad 1507 $avgcell->attributes['class'] = 'i'. $itemid;
6c096a49
NC
1508 $avgcell->text = $gradehtml.$numberofgrades;
1509 $avgrow->cells[] = $avgcell;
80fb1cf9 1510 }
9ecd4386 1511 }
6c096a49 1512 $rows[] = $avgrow;
9ecd4386 1513 }
6c096a49 1514 return $rows;
9ecd4386 1515 }
4ba9941c 1516
2350b3f4
ZD
1517 /**
1518 * Given element category, create a collapsible icon and
1519 * course header.
1520 *
6611780e 1521 * @param array $element
2350b3f4
ZD
1522 * @return string HTML
1523 */
1524 protected function get_course_header($element) {
1525 global $OUTPUT;
1526
1527 $icon = '';
1528 // If object is a category, display expand/contract icon.
1529 if ($element['type'] == 'category') {
1530 // Load language strings.
1531 $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1532 $strswitchplus = $this->get_lang_string('gradesonly', 'grades');
1533 $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1534
1535 $url = new moodle_url($this->gpr->get_return_url(null, array('target' => $element['eid'], 'sesskey' => sesskey())));
1536
1537 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1538 $url->param('action', 'switch_plus');
1539 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus), null, null);
1540 $showing = get_string('showingaggregatesonly', 'grades');
1541 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1542 $url->param('action', 'switch_whole');
1543 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole), null, null);
1544 $showing = get_string('showinggradesonly', 'grades');
1545 } else {
1546 $url->param('action', 'switch_minus');
1547 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus), null, null);
1548 $showing = get_string('showingfullmode', 'grades');
1549 }
1550 }
1551
1552 $name = shorten_text($element['object']->get_name());
1553 $courseheader = html_writer::tag('span', $name, array('id' => 'courseheader'));
1554 $courseheader .= html_writer::label($showing, 'courseheader', false, array('class' => 'accesshide'));
1555 $courseheader .= $icon;
1556
1557 return $courseheader;
1558 }
1559
4ba9941c 1560 /**
1561 * Given a grade_category, grade_item or grade_grade, this function
1562 * figures out the state of the object and builds then returns a div
1563 * with the icons needed for the grader report.
1564 *
02d1a0a5 1565 * @param array $element
4ba9941c 1566 * @return string HTML
1567 */
d24832f9 1568 protected function get_icons($element) {
319770d7 1569 global $CFG, $USER, $OUTPUT;
4ba9941c 1570
2cc773f5 1571 if (!$USER->gradeediting[$this->courseid]) {
1572 return '<div class="grade_icons" />';
79eabc2a 1573 }
4ba9941c 1574
2cc773f5 1575 // Init all icons
319770d7 1576 $editicon = '';
dc482cfa 1577
0e999796
AD
1578 $editable = true;
1579
1580 if ($element['type'] == 'grade') {
1581 $item = $element['object']->grade_item;
1582 if ($item->is_course_item() or $item->is_category_item()) {
1583 $editable = $this->overridecat;
1584 }
1585 }
1586
1587 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) {
319770d7 1588 $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
dc482cfa 1589 }
1590
319770d7 1591 $editcalculationicon = '';
1592 $showhideicon = '';
1593 $lockunlockicon = '';
4ba9941c 1594
a5b8be62 1595 if (has_capability('moodle/grade:manage', $this->context)) {
a5b8be62 1596 if ($this->get_pref('showcalculations')) {
319770d7 1597 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
a5b8be62 1598 }
1599
1600 if ($this->get_pref('showeyecons')) {
02d1a0a5 1601 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
a5b8be62 1602 }
4ba9941c 1603
a5b8be62 1604 if ($this->get_pref('showlocks')) {
319770d7 1605 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
a5b8be62 1606 }
c97933ff
MG
1607
1608 }
1609
1610 $gradeanalysisicon = '';
1611 if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1612 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
4ba9941c 1613 }
1614
c97933ff 1615 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
4faf5f99 1616 }
1617
1618 /**
1619 * Given a category element returns collapsing +/- icon if available
2350b3f4
ZD
1620 *
1621 * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more.
1622 * @todo MDL-49021 This will be deleted in Moodle 3.1
1623 * @see grade_report_grader::get_course_header()
02d1a0a5 1624 * @param object $element
4faf5f99 1625 * @return string HTML
1626 */
d24832f9 1627 protected function get_collapsing_icon($element) {
5d3b9994 1628 global $OUTPUT;
2350b3f4 1629 debugging('get_collapsing_icon is deprecated, please use get_course_header instead.', DEBUG_DEVELOPER);
4faf5f99 1630
319770d7 1631 $icon = '';
2cc773f5 1632 // If object is a category, display expand/contract icon
384960dd 1633 if ($element['type'] == 'category') {
2cc773f5 1634 // Load language strings
319770d7 1635 $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1636 $strswitchplus = $this->get_lang_string('gradesonly', 'grades');
1637 $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
384960dd 1638
8ae8bf8a 1639 $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
48b5d8f3 1640
384960dd 1641 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
8ae8bf8a 1642 $url->param('action', 'switch_plus');
c63923bd 1643 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
8ae8bf8a
PS
1644
1645 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1646 $url->param('action', 'switch_whole');
c63923bd 1647 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
8ae8bf8a
PS
1648
1649 } else {
1650 $url->param('action', 'switch_minus');
c63923bd 1651 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
2cc773f5 1652 }
4ba9941c 1653 }
319770d7 1654 return $icon;
4ba9941c 1655 }
48b5d8f3 1656
02d1a0a5
MA
1657 /**
1658 * Processes a single action against a category, grade_item or grade.
1659 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1660 * @param string $action Which action to take (edit, delete etc...)
1661 * @return
1662 */
1e88baa0 1663 public function process_action($target, $action) {
9fe5a1b8
MG
1664 return self::do_process_action($target, $action, $this->course->id);
1665 }
1666
1667 /**
1668 * From the list of categories that this user prefers to collapse choose ones that belong to the current course.
1669 *
1670 * This function serves two purposes.
1671 * Mainly it helps migrating from user preference style when all courses were stored in one preference.
1672 * Also it helps to remove the settings for categories that were removed if the array for one course grows too big.
1673 *
1674 * @param int $courseid
1675 * @param array $collapsed
1676 * @return array
1677 */
1678 protected static function filter_collapsed_categories($courseid, $collapsed) {
1679 global $DB;
1680 if (empty($collapsed)) {
1681 $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1682 }
1683 if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) {
1684 return $collapsed;
1685 }
1686 $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid));
1687 $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats));
1688 $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats));
1689 return $collapsed;
1690 }
1691
1692 /**
1693 * Returns the list of categories that this user wants to collapse or display aggregatesonly
1694 *
1695 * This method also migrates on request from the old format of storing user preferences when they were stored
1696 * in one preference for all courses causing DB error when trying to insert very big value.
1697 *
1698 * @param int $courseid
1699 * @return array
1700 */
1701 protected static function get_collapsed_preferences($courseid) {
1702 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) {
1703 return json_decode($collapsed, true);
1704 }
1705
1706 // Try looking for old location of user setting that used to store all courses in one serialized user preference.
1707 if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) {
1708 if ($collapsedall = @unserialize($oldcollapsedpref)) {
1709 // We found the old-style preference, filter out only categories that belong to this course and update the prefs.
1710 $collapsed = static::filter_collapsed_categories($courseid, $collapsedall);
1711 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1712 static::set_collapsed_preferences($courseid, $collapsed);
1713 $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']);
1714 $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']);
1715 if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) {
1716 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall));
1717 } else {
1718 unset_user_preference('grade_report_grader_collapsed_categories');
1719 }
1720 }
1721 } else {
1722 // We found the old-style preference, but it is unreadable, discard it.
1723 unset_user_preference('grade_report_grader_collapsed_categories');
1724 }
1725 } else {
1726 $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1727 }
1728 return $collapsed;
1729 }
1730
1731 /**
1732 * Sets the list of categories that user wants to see collapsed in user preferences
1733 *
1734 * This method may filter or even trim the list if it does not fit in DB field.
1735 *
1736 * @param int $courseid
1737 * @param array $collapsed
1738 */
1739 protected static function set_collapsed_preferences($courseid, $collapsed) {
1740 global $DB;
1741 // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size,
1742 // try to filter the list of categories since array may contain categories that were deleted.
1743 if (strlen(json_encode($collapsed)) >= 1333) {
1744 $collapsed = static::filter_collapsed_categories($courseid, $collapsed);
1745 }
1746
1747 // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information.
1748 while (strlen(json_encode($collapsed)) >= 1333) {
1749 if (count($collapsed['aggregatesonly'])) {
1750 array_pop($collapsed['aggregatesonly']);
1751 }
1752 if (count($collapsed['gradesonly'])) {
1753 array_pop($collapsed['gradesonly']);
1754 }
1755 }
1756
1757 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1758 set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed));
1759 } else {
1760 unset_user_preference('grade_report_grader_collapsed_categories'.$courseid);
1761 }
1e88baa0
TH
1762 }
1763
48b5d8f3 1764 /**
1765 * Processes a single action against a category, grade_item or grade.
1766 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1767 * @param string $action Which action to take (edit, delete etc...)
9fe5a1b8 1768 * @param int $courseid affected course.
48b5d8f3 1769 * @return
1770 */
9fe5a1b8
MG
1771 public static function do_process_action($target, $action, $courseid = null) {
1772 global $DB;
4faf5f99 1773 // TODO: this code should be in some grade_tree static method
165cdaba
MG
1774 $targettype = substr($target, 0, 2);
1775 $targetid = substr($target, 2);
4faf5f99 1776 // TODO: end
1777
165cdaba 1778 if ($targettype !== 'cg') {
9fe5a1b8
MG
1779 // The following code only works with categories.
1780 return true;
1781 }
1782
1783 if (!$courseid) {
1784 debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid',
1785 DEBUG_DEVELOPER);
1786 if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) {
1787 return true;
1788 }
4faf5f99 1789 }
1790
9fe5a1b8
MG
1791 $collapsed = static::get_collapsed_preferences($courseid);
1792
48b5d8f3 1793 switch ($action) {
384960dd 1794 case 'switch_minus': // Add category to array of aggregatesonly
1795 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1796 $collapsed['aggregatesonly'][] = $targetid;
9fe5a1b8 1797 static::set_collapsed_preferences($courseid, $collapsed);
4faf5f99 1798 }
48b5d8f3 1799 break;
4faf5f99 1800
384960dd 1801 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1802 $key = array_search($targetid, $collapsed['aggregatesonly']);
4faf5f99 1803 if ($key !== false) {
384960dd 1804 unset($collapsed['aggregatesonly'][$key]);
4faf5f99 1805 }
384960dd 1806 if (!in_array($targetid, $collapsed['gradesonly'])) {
1807 $collapsed['gradesonly'][] = $targetid;
1808 }
9fe5a1b8 1809 static::set_collapsed_preferences($courseid, $collapsed);
48b5d8f3 1810 break;
384960dd 1811 case 'switch_whole': // Remove the category from the array of collapsed cats
1812 $key = array_search($targetid, $collapsed['gradesonly']);
1813 if ($key !== false) {
1814 unset($collapsed['gradesonly'][$key]);
9fe5a1b8 1815 static::set_collapsed_preferences($courseid, $collapsed);
384960dd 1816 }
4faf5f99 1817
384960dd 1818 break;
48b5d8f3 1819 default:
1820 break;
1821 }
1822
1823 return true;
1824 }
03fcc729 1825
6c096a49
NC
1826 /**
1827 * Refactored function for generating HTML of sorting links with matching arrows.
1828 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1829 * to inject into a table header cell.
e4aec5be 1830 * @param array $extrafields Array of extra fields being displayed, such as
1831 * user idnumber
6c096a49
NC
1832 * @return array An associative array of HTML sorting links+arrows
1833 */
e4aec5be 1834 public function get_sort_arrows(array $extrafields = array()) {
6c096a49
NC
1835 global $OUTPUT;
1836 $arrows = array();
1837
1838 $strsortasc = $this->get_lang_string('sortasc', 'grades');
1839 $strsortdesc = $this->get_lang_string('sortdesc', 'grades');
1840 $strfirstname = $this->get_lang_string('firstname');
1841 $strlastname = $this->get_lang_string('lastname');
0cddd851
FM
1842 $iconasc = $OUTPUT->pix_icon('t/sort_asc', $strsortasc, '', array('class' => 'iconsmall sorticon'));
1843 $icondesc = $OUTPUT->pix_icon('t/sort_desc', $strsortdesc, '', array('class' => 'iconsmall sorticon'));
6c096a49 1844
0f4c64b7
PS
1845 $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1846 $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
6c096a49 1847
0f4c64b7 1848 $arrows['studentname'] = $lastlink;
6c096a49
NC
1849
1850 if ($this->sortitemid === 'lastname') {
1851 if ($this->sortorder == 'ASC') {
0cddd851 1852 $arrows['studentname'] .= $iconasc;
6c096a49 1853 } else {
0cddd851 1854 $arrows['studentname'] .= $icondesc;
6c096a49
NC
1855 }
1856 }
1857
0f4c64b7 1858 $arrows['studentname'] .= ' ' . $firstlink;
6c096a49
NC
1859
1860 if ($this->sortitemid === 'firstname') {
1861 if ($this->sortorder == 'ASC') {
0cddd851 1862 $arrows['studentname'] .= $iconasc;
6c096a49 1863 } else {
0cddd851 1864 $arrows['studentname'] .= $icondesc;
6c096a49
NC
1865 }
1866 }
1867
e4aec5be 1868 foreach ($extrafields as $field) {
1869 $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1870 array('sortitemid'=>$field)), get_user_field_name($field));
1871 $arrows[$field] = $fieldlink;
6c096a49 1872
e4aec5be 1873 if ($field == $this->sortitemid) {
1874 if ($this->sortorder == 'ASC') {
0cddd851 1875 $arrows[$field] .= $iconasc;
e4aec5be 1876 } else {
0cddd851 1877 $arrows[$field] .= $icondesc;
e4aec5be 1878 }
6c096a49
NC
1879 }
1880 }
1881
1882 return $arrows;
1883 }
d3b698a4
AD
1884
1885 /**
a740a0ad 1886 * Returns the maximum number of students to be displayed on each page
d3b698a4 1887 *
a740a0ad 1888 * @return int The maximum number of students to display per page
d3b698a4 1889 */
a740a0ad 1890 public function get_students_per_page() {
a3777547 1891 return $this->get_pref('studentsperpage');
d3b698a4 1892 }
4ba9941c 1893}
6c3ef410 1894