MDL-79062 gradereport_grader: Remove setting of tabindex >= 1
[moodle.git] / grade / report / grader / lib.php
blob884cbc608a0c8d59beea7904f63ae9d82229423b
1 <?php
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.
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/>.
17 /**
18 * Definition of the grader report class
20 * @package gradereport_grader
21 * @copyright 2007 Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->dirroot . '/grade/report/lib.php');
26 require_once($CFG->libdir.'/tablelib.php');
28 /**
29 * Class providing an API for the grader report building and displaying.
30 * @uses grade_report
31 * @copyright 2007 Nicolas Connault
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 class grade_report_grader extends grade_report {
35 /**
36 * The final grades.
37 * @var array $grades
39 public $grades;
41 /**
42 * Contains all the grades for the course - even the ones not displayed in the grade tree.
44 * @var array $allgrades
46 private $allgrades;
48 /**
49 * Contains all grade items expect GRADE_TYPE_NONE.
51 * @var array $allgradeitems
53 private $allgradeitems;
55 /**
56 * Array of errors for bulk grades updating.
57 * @var array $gradeserror
59 public $gradeserror = array();
61 // SQL-RELATED
63 /**
64 * The id of the grade_item by which this report will be sorted.
65 * @var int $sortitemid
67 public $sortitemid;
69 /**
70 * Sortorder used in the SQL selections.
71 * @var int $sortorder
73 public $sortorder;
75 /**
76 * An SQL fragment affecting the search for users.
77 * @var string $userselect
79 public $userselect;
81 /**
82 * The bound params for $userselect
83 * @var array $userselectparams
85 public $userselectparams = array();
87 /**
88 * List of collapsed categories from user preference
89 * @var array $collapsed
91 public $collapsed;
93 /**
94 * A count of the rows, used for css classes.
95 * @var int $rowcount
97 public $rowcount = 0;
99 /**
100 * Capability check caching
101 * @var boolean $canviewhidden
103 public $canviewhidden;
105 /** @var int Maximum number of students that can be shown on one page */
106 public const MAX_STUDENTS_PER_PAGE = 5000;
108 /** @var int[] List of available options on the pagination dropdown */
109 public const PAGINATION_OPTIONS = [20, 100];
112 * Allow category grade overriding
113 * @var bool $overridecat
115 protected $overridecat;
117 /** @var array of objects, or empty array if no records were found. */
118 protected $users = [];
121 * Constructor. Sets local copies of user preferences and initialises grade_tree.
122 * @param int $courseid
123 * @param object $gpr grade plugin return tracking object
124 * @param string $context
125 * @param int $page The current page being viewed (when report is paged)
126 * @param int $sortitemid The id of the grade_item by which to sort the table
127 * @param string $sort Sorting direction
129 public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null, string $sort = '') {
130 global $CFG;
131 parent::__construct($courseid, $gpr, $context, $page);
133 $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->course->id));
135 // load collapsed settings for this report
136 $this->collapsed = static::get_collapsed_preferences($this->course->id);
138 if (empty($CFG->enableoutcomes)) {
139 $nooutcomes = false;
140 } else {
141 $nooutcomes = get_user_preferences('grade_report_shownooutcomes');
144 // if user report preference set or site report setting set use it, otherwise use course or site setting
145 $switch = $this->get_pref('aggregationposition');
146 if ($switch == '') {
147 $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
150 // Grab the grade_tree for this course
151 $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes);
153 $this->sortitemid = $sortitemid;
155 // base url for sorting by first/last name
157 $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
159 $studentsperpage = $this->get_students_per_page();
160 if (!empty($this->page) && !empty($studentsperpage)) {
161 $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
164 $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid));
166 $this->setup_groups();
167 $this->setup_users();
168 $this->setup_sortitemid($sort);
170 $this->overridecat = (bool)get_config('moodle', 'grade_overridecat');
174 * Processes the data sent by the form (grades).
175 * Caller is responsible for all access control checks
176 * @param array $data form submission (with magic quotes)
177 * @return array empty array if success, array of warnings if something fails.
179 public function process_data($data) {
180 global $DB;
181 $warnings = array();
183 $separategroups = false;
184 $mygroups = array();
185 if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
186 $separategroups = true;
187 $mygroups = groups_get_user_groups($this->course->id);
188 $mygroups = $mygroups[0]; // ignore groupings
189 // reorder the groups fro better perf below
190 $current = array_search($this->currentgroup, $mygroups);
191 if ($current !== false) {
192 unset($mygroups[$current]);
193 array_unshift($mygroups, $this->currentgroup);
196 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
198 // always initialize all arrays
199 $queue = array();
201 $this->load_users();
202 $this->load_final_grades();
204 // Were any changes made?
205 $changedgrades = false;
206 $timepageload = clean_param($data->timepageload, PARAM_INT);
208 foreach ($data as $varname => $students) {
210 $needsupdate = false;
212 // Skip, not a grade.
213 if (strpos($varname, 'grade') === 0) {
214 $datatype = 'grade';
215 } else {
216 continue;
219 foreach ($students as $userid => $items) {
220 $userid = clean_param($userid, PARAM_INT);
221 foreach ($items as $itemid => $postedvalue) {
222 $itemid = clean_param($itemid, PARAM_INT);
224 // Was change requested?
225 $oldvalue = $this->grades[$userid][$itemid];
226 if ($datatype === 'grade') {
227 // If there was no grade and there still isn't
228 if (is_null($oldvalue->finalgrade) && $postedvalue == -1) {
229 // -1 means no grade
230 continue;
233 // If the grade item uses a custom scale
234 if (!empty($oldvalue->grade_item->scaleid)) {
236 if ((int)$oldvalue->finalgrade === (int)$postedvalue) {
237 continue;
239 } else {
240 // The grade item uses a numeric scale
242 // Format the finalgrade from the DB so that it matches the grade from the client
243 if ($postedvalue === format_float($oldvalue->finalgrade, $oldvalue->grade_item->get_decimals())) {
244 continue;
248 $changedgrades = true;
251 if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) {
252 throw new \moodle_exception('invalidgradeitemid');
255 // Pre-process grade
256 if ($datatype == 'grade') {
257 if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
258 if ($postedvalue == -1) { // -1 means no grade
259 $finalgrade = null;
260 } else {
261 $finalgrade = $postedvalue;
263 } else {
264 $finalgrade = unformat_float($postedvalue);
267 $errorstr = '';
268 $skip = false;
270 $dategraded = $oldvalue->get_dategraded();
271 if (!empty($dategraded) && $timepageload < $dategraded) {
272 // Warn if the grade was updated while we were editing this form.
273 $errorstr = 'gradewasmodifiedduringediting';
274 $skip = true;
275 } else if (!is_null($finalgrade)) {
276 // Warn if the grade is out of bounds.
277 $bounded = $gradeitem->bounded_grade($finalgrade);
278 if ($bounded > $finalgrade) {
279 $errorstr = 'lessthanmin';
280 } else if ($bounded < $finalgrade) {
281 $errorstr = 'morethanmax';
285 if ($errorstr) {
286 $userfieldsapi = \core_user\fields::for_name();
287 $userfields = 'id, ' . $userfieldsapi->get_sql('', false, '', '', false)->selects;
288 $user = $DB->get_record('user', array('id' => $userid), $userfields);
289 $gradestr = new stdClass();
290 $gradestr->username = fullname($user, $viewfullnames);
291 $gradestr->itemname = $gradeitem->get_name();
292 $warnings[] = get_string($errorstr, 'grades', $gradestr);
293 if ($skip) {
294 // Skipping the update of this grade it failed the tests above.
295 continue;
300 // group access control
301 if ($separategroups) {
302 // note: we can not use $this->currentgroup because it would fail badly
303 // when having two browser windows each with different group
304 $sharinggroup = false;
305 foreach ($mygroups as $groupid) {
306 if (groups_is_member($groupid, $userid)) {
307 $sharinggroup = true;
308 break;
311 if (!$sharinggroup) {
312 // either group membership changed or somebody is hacking grades of other group
313 $warnings[] = get_string('errorsavegrade', 'grades');
314 continue;
318 $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', false,
319 FORMAT_MOODLE, null, null, true);
324 if ($changedgrades) {
325 // If a final grade was overriden reload grades so dependent grades like course total will be correct
326 $this->grades = null;
329 return $warnings;
334 * Setting the sort order, this depends on last state
335 * all this should be in the new table class that we might need to use
336 * for displaying grades.
338 * @param string $sort sorting direction
340 private function setup_sortitemid(string $sort = '') {
342 global $SESSION;
344 if (!isset($SESSION->gradeuserreport)) {
345 $SESSION->gradeuserreport = new stdClass();
348 if ($this->sortitemid) {
349 if (!isset($SESSION->gradeuserreport->sort)) {
350 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
351 } else if (!$sort) {
352 // this is the first sort, i.e. by last name
353 if (!isset($SESSION->gradeuserreport->sortitemid)) {
354 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
355 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
356 // same as last sort
357 if ($SESSION->gradeuserreport->sort == 'ASC') {
358 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
359 } else {
360 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
362 } else {
363 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
366 $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
367 } else {
368 // not requesting sort, use last setting (for paging)
370 if (isset($SESSION->gradeuserreport->sortitemid)) {
371 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
372 } else {
373 $this->sortitemid = 'lastname';
376 if (isset($SESSION->gradeuserreport->sort)) {
377 $this->sortorder = $SESSION->gradeuserreport->sort;
378 } else {
379 $this->sortorder = 'ASC';
383 // If explicit sorting direction exists.
384 if ($sort) {
385 $this->sortorder = $sort;
386 $SESSION->gradeuserreport->sort = $sort;
391 * pulls out the userids of the users to be display, and sorts them
393 * @param bool $allusers If we are getting the users within the report, we want them all irrespective of paging.
395 public function load_users(bool $allusers = false) {
396 global $CFG, $DB;
398 if (!empty($this->users)) {
399 return;
401 $this->setup_users();
403 // Limit to users with a gradeable role.
404 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
406 // Check the status of showing only active enrolments.
407 $coursecontext = $this->context->get_course_context(true);
408 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
409 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
410 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
412 // Limit to users with an active enrollment.
413 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
415 // Fields we need from the user table.
416 $userfieldsapi = \core_user\fields::for_identity($this->context)->with_userpic();
417 $userfieldssql = $userfieldsapi->get_sql('u', true, '', '', false);
419 // We want to query both the current context and parent contexts.
420 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
422 // If the user has clicked one of the sort asc/desc arrows.
423 if (is_numeric($this->sortitemid)) {
424 $params = array_merge(array('gitemid' => $this->sortitemid), $gradebookrolesparams, $this->userwheresql_params,
425 $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
427 $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
429 if ($this->sortorder == 'ASC') {
430 $sort = $DB->sql_order_by_null('g.finalgrade');
431 } else {
432 $sort = $DB->sql_order_by_null('g.finalgrade', SORT_DESC);
434 $sort .= ", u.idnumber, u.lastname, u.firstname, u.email";
435 } else {
436 $sortjoin = '';
438 // The default sort will be that provided by the site for users, unless a valid user field is requested,
439 // the value of which takes precedence.
440 [$sort] = users_order_by_sql('u', null, $this->context, $userfieldssql->mappings);
441 if (array_key_exists($this->sortitemid, $userfieldssql->mappings)) {
443 // Ensure user sort field doesn't duplicate one of the default sort fields.
444 $usersortfield = $userfieldssql->mappings[$this->sortitemid];
445 $defaultsortfields = array_diff(explode(', ', $sort), [$usersortfield]);
447 $sort = "{$usersortfield} {$this->sortorder}, " . implode(', ', $defaultsortfields);
450 $params = array_merge($gradebookrolesparams, $this->userwheresql_params, $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
452 $params = array_merge($userfieldssql->params, $params);
453 $sql = "SELECT {$userfieldssql->selects}
454 FROM {user} u
455 {$userfieldssql->joins}
456 JOIN ($enrolledsql) je ON je.id = u.id
457 $this->groupsql
458 $sortjoin
459 JOIN (
460 SELECT DISTINCT ra.userid
461 FROM {role_assignments} ra
462 WHERE ra.roleid IN ($this->gradebookroles)
463 AND ra.contextid $relatedctxsql
464 ) rainner ON rainner.userid = u.id
465 AND u.deleted = 0
466 $this->userwheresql
467 $this->groupwheresql
468 ORDER BY $sort";
469 // We never work with unlimited result. Limit the number of records by MAX_STUDENTS_PER_PAGE if no other limit is specified.
470 $studentsperpage = ($this->get_students_per_page() && !$allusers) ?
471 $this->get_students_per_page() : static::MAX_STUDENTS_PER_PAGE;
472 $this->users = $DB->get_records_sql($sql, $params, $studentsperpage * $this->page, $studentsperpage);
474 if (empty($this->users)) {
475 $this->userselect = '';
476 $this->users = array();
477 $this->userselectparams = array();
478 } else {
479 list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
480 $this->userselect = "AND g.userid $usql";
481 $this->userselectparams = $uparams;
483 // First flag everyone as not suspended.
484 foreach ($this->users as $user) {
485 $this->users[$user->id]->suspendedenrolment = false;
488 // If we want to mix both suspended and not suspended users, let's find out who is suspended.
489 if (!$showonlyactiveenrol) {
490 $sql = "SELECT ue.userid
491 FROM {user_enrolments} ue
492 JOIN {enrol} e ON e.id = ue.enrolid
493 WHERE ue.userid $usql
494 AND ue.status = :uestatus
495 AND e.status = :estatus
496 AND e.courseid = :courseid
497 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
498 GROUP BY ue.userid";
500 $time = time();
501 $params = array_merge($uparams, array('estatus' => ENROL_INSTANCE_ENABLED, 'uestatus' => ENROL_USER_ACTIVE,
502 'courseid' => $coursecontext->instanceid, 'now1' => $time, 'now2' => $time));
503 $useractiveenrolments = $DB->get_records_sql($sql, $params);
505 foreach ($this->users as $user) {
506 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments);
510 return $this->users;
514 * Load all grade items.
516 protected function get_allgradeitems() {
517 if (!empty($this->allgradeitems)) {
518 return $this->allgradeitems;
520 $allgradeitems = grade_item::fetch_all(array('courseid' => $this->courseid));
521 // But hang on - don't include ones which are set to not show the grade at all.
522 $this->allgradeitems = array_filter($allgradeitems, function($item) {
523 return $item->gradetype != GRADE_TYPE_NONE;
526 return $this->allgradeitems;
530 * we supply the userids in this query, and get all the grades
531 * pulls out all the grades, this does not need to worry about paging
533 public function load_final_grades() {
534 global $CFG, $DB;
536 if (!empty($this->grades)) {
537 return;
540 if (empty($this->users)) {
541 return;
544 // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
545 $params = array_merge(array('courseid'=>$this->courseid), $this->userselectparams);
546 $sql = "SELECT g.*
547 FROM {grade_items} gi,
548 {grade_grades} g
549 WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
551 $userids = array_keys($this->users);
552 $allgradeitems = $this->get_allgradeitems();
554 if ($grades = $DB->get_records_sql($sql, $params)) {
555 foreach ($grades as $graderec) {
556 $grade = new grade_grade($graderec, false);
557 if (!empty($allgradeitems[$graderec->itemid])) {
558 // Note: Filter out grades which have a grade type of GRADE_TYPE_NONE.
559 // Only grades without this type are present in $allgradeitems.
560 $this->allgrades[$graderec->userid][$graderec->itemid] = $grade;
562 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
563 $this->grades[$graderec->userid][$graderec->itemid] = $grade;
564 $this->grades[$graderec->userid][$graderec->itemid]->grade_item = $this->gtree->get_item($graderec->itemid); // db caching
569 // prefil grades that do not exist yet
570 foreach ($userids as $userid) {
571 foreach ($this->gtree->get_items() as $itemid => $unused) {
572 if (!isset($this->grades[$userid][$itemid])) {
573 $this->grades[$userid][$itemid] = new grade_grade();
574 $this->grades[$userid][$itemid]->itemid = $itemid;
575 $this->grades[$userid][$itemid]->userid = $userid;
576 $this->grades[$userid][$itemid]->grade_item = $this->gtree->get_item($itemid); // db caching
578 $this->allgrades[$userid][$itemid] = $this->grades[$userid][$itemid];
583 // Pre fill grades for any remaining items which might be collapsed.
584 foreach ($userids as $userid) {
585 foreach ($allgradeitems as $itemid => $gradeitem) {
586 if (!isset($this->allgrades[$userid][$itemid])) {
587 $this->allgrades[$userid][$itemid] = new grade_grade();
588 $this->allgrades[$userid][$itemid]->itemid = $itemid;
589 $this->allgrades[$userid][$itemid]->userid = $userid;
590 $this->allgrades[$userid][$itemid]->grade_item = $gradeitem;
597 * Gets html toggle
598 * @deprecated since Moodle 2.4 as it appears not to be used any more.
600 public function get_toggles_html() {
601 throw new coding_exception('get_toggles_html() can not be used any more');
605 * Prints html toggle
606 * @deprecated since 2.4 as it appears not to be used any more.
607 * @param unknown $type
609 public function print_toggle($type) {
610 throw new coding_exception('print_toggle() can not be used any more');
614 * Builds and returns the rows that will make up the left part of the grader report
615 * This consists of student names and icons, links to user reports and id numbers, as well
616 * as header cells for these columns. It also includes the fillers required for the
617 * categories displayed on the right side of the report.
618 * @param boolean $displayaverages whether to display average rows in the table
619 * @return array Array of html_table_row objects
621 public function get_left_rows($displayaverages) {
622 global $CFG, $OUTPUT;
624 // Course context to determine how the user details should be displayed.
625 $coursecontext = context_course::instance($this->courseid);
627 $rows = [];
629 $showuserimage = $this->get_pref('showuserimage');
630 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
632 $extrafields = \core_user\fields::get_identity_fields($this->context);
634 $arrows = $this->get_sort_arrows($extrafields);
636 $colspan = 1 + count($extrafields);
638 $levels = count($this->gtree->levels) - 1;
640 $fillercell = new html_table_cell();
641 $fillercell->header = true;
642 $fillercell->attributes['scope'] = 'col';
643 $fillercell->attributes['class'] = 'cell topleft';
644 $fillercell->text = html_writer::span(get_string('participants'), 'accesshide');
645 $fillercell->colspan = $colspan;
646 $fillercell->rowspan = $levels;
647 $row = new html_table_row(array($fillercell));
648 $rows[] = $row;
650 for ($i = 1; $i < $levels; $i++) {
651 $row = new html_table_row();
652 $rows[] = $row;
655 $headerrow = new html_table_row();
656 $headerrow->attributes['class'] = 'heading';
658 $studentheader = new html_table_cell();
659 // The browser's scrollbar may partly cover (in certain operative systems) the content in the student header
660 // when horizontally scrolling through the table contents (most noticeable when in RTL mode).
661 // Therefore, add slight padding on the left or right when using RTL mode.
662 $studentheader->attributes['class'] = "header pl-3";
663 $studentheader->scope = 'col';
664 $studentheader->header = true;
665 $studentheader->id = 'studentheader';
666 $element = ['type' => 'userfield', 'name' => 'fullname'];
667 $studentheader->text = $arrows['studentname'] .
668 $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr, $this->baseurl);
670 $headerrow->cells[] = $studentheader;
672 foreach ($extrafields as $field) {
673 $fieldheader = new html_table_cell();
674 $fieldheader->attributes['class'] = 'userfield user' . $field;
675 $fieldheader->attributes['data-col'] = $field;
676 $fieldheader->scope = 'col';
677 $fieldheader->header = true;
679 $collapsecontext = ['field' => $field, 'name' => $field];
681 $collapsedicon = $OUTPUT->render_from_template('gradereport_grader/collapse/icon', $collapsecontext);
682 // Need to wrap the button into a div with our hooking element for user items, gradeitems already have this.
683 $collapsedicon = html_writer::div($collapsedicon, 'd-none', ['data-collapse' => 'expandbutton']);
685 $element = ['type' => 'userfield', 'name' => $field];
686 $fieldheader->text = $arrows[$field] .
687 $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr, $this->baseurl) . $collapsedicon;
688 $headerrow->cells[] = $fieldheader;
691 $rows[] = $headerrow;
693 $suspendedstring = null;
695 $usercount = 0;
696 foreach ($this->users as $userid => $user) {
697 $userrow = new html_table_row();
698 $userrow->id = 'fixed_user_'.$userid;
699 $userrow->attributes['class'] = ($usercount % 2) ? 'userrow even' : 'userrow odd';
701 $usercell = new html_table_cell();
702 $usercell->attributes['class'] = ($usercount % 2) ? 'header user even' : 'header user odd';
703 $usercount++;
705 $usercell->header = true;
706 $usercell->scope = 'row';
708 if ($showuserimage) {
709 $usercell->text = $OUTPUT->render(\core_user::get_profile_picture($user, $coursecontext, [
710 'link' => false, 'visibletoscreenreaders' => false
711 ]));
714 $fullname = fullname($user, $viewfullnames);
715 $usercell->text = html_writer::link(
716 \core_user::get_profile_url($user, $coursecontext),
717 $usercell->text . $fullname,
718 ['class' => 'username']
721 if (!empty($user->suspendedenrolment)) {
722 $usercell->attributes['class'] .= ' usersuspended';
724 //may be lots of suspended users so only get the string once
725 if (empty($suspendedstring)) {
726 $suspendedstring = get_string('userenrolmentsuspended', 'grades');
728 $icon = $OUTPUT->pix_icon('i/enrolmentsuspended', $suspendedstring);
729 $usercell->text .= html_writer::tag('span', $icon, array('class'=>'usersuspendedicon'));
731 // The browser's scrollbar may partly cover (in certain operative systems) the content in the user cells
732 // when horizontally scrolling through the table contents (most noticeable when in RTL mode).
733 // Therefore, add slight padding on the left or right when using RTL mode.
734 $usercell->attributes['class'] .= ' pl-3';
735 $usercell->text .= $this->gtree->get_cell_action_menu(['userid' => $userid], 'user', $this->gpr);
737 $userrow->cells[] = $usercell;
739 foreach ($extrafields as $field) {
740 $fieldcell = new html_table_cell();
741 $fieldcell->attributes['class'] = 'userfield user' . $field;
742 $fieldcell->attributes['data-col'] = $field;
743 $fieldcell->header = false;
744 $fieldcell->text = html_writer::tag('div', s($user->{$field}), [
745 'data-collapse' => 'content'
748 $userrow->cells[] = $fieldcell;
751 $userrow->attributes['data-uid'] = $userid;
752 $rows[] = $userrow;
755 $rows = $this->get_left_range_row($rows, $colspan);
756 if ($displayaverages) {
757 $rows = $this->get_left_avg_row($rows, $colspan, true);
758 $rows = $this->get_left_avg_row($rows, $colspan);
761 return $rows;
765 * Builds and returns the rows that will make up the right part of the grader report
766 * @param boolean $displayaverages whether to display average rows in the table
767 * @return array Array of html_table_row objects
769 public function get_right_rows(bool $displayaverages) : array {
770 global $CFG, $USER, $OUTPUT, $DB, $PAGE;
772 $rows = [];
773 $this->rowcount = 0;
774 $strgrade = get_string('gradenoun');
775 $this->get_sort_arrows();
777 // Get preferences once.
778 $quickgrading = $this->get_pref('quickgrading');
780 // Get strings which are re-used inside the loop.
781 $strftimedatetimeshort = get_string('strftimedatetimeshort');
782 $strerror = get_string('error');
783 $stroverridengrade = get_string('overridden', 'grades');
784 $strfail = get_string('fail', 'grades');
785 $strpass = get_string('pass', 'grades');
786 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
788 // Preload scale objects for items with a scaleid and initialize tab indices.
789 $scaleslist = [];
791 foreach ($this->gtree->get_items() as $itemid => $item) {
792 if (!empty($item->scaleid)) {
793 $scaleslist[] = $item->scaleid;
797 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'gradereport_grader', 'scales');
798 $scalesarray = $cache->get(get_class($this));
799 if (!$scalesarray) {
800 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
801 // Save to cache.
802 $cache->set(get_class($this), $scalesarray);
805 foreach ($this->gtree->get_levels() as $row) {
806 $headingrow = new html_table_row();
807 $headingrow->attributes['class'] = 'heading_name_row';
809 foreach ($row as $element) {
810 $sortlink = clone($this->baseurl);
811 if (isset($element['object']->id)) {
812 $sortlink->param('sortitemid', $element['object']->id);
815 $type = $element['type'];
817 if (!empty($element['colspan'])) {
818 $colspan = $element['colspan'];
819 } else {
820 $colspan = 1;
823 if (!empty($element['depth'])) {
824 $catlevel = 'catlevel'.$element['depth'];
825 } else {
826 $catlevel = '';
829 // Element is a filler.
830 if ($type == 'filler' || $type == 'fillerfirst' || $type == 'fillerlast') {
831 $fillercell = new html_table_cell();
832 $fillercell->attributes['class'] = $type . ' ' . $catlevel;
833 $fillercell->colspan = $colspan;
834 $fillercell->text = '&nbsp;';
836 // This is a filler cell; don't use a <th>, it'll confuse screen readers.
837 $fillercell->header = false;
838 $headingrow->cells[] = $fillercell;
839 } else if ($type == 'category') {
840 // Make sure the grade category has a grade total or at least has child grade items.
841 if (grade_tree::can_output_item($element)) {
842 // Element is a category.
843 $categorycell = new html_table_cell();
844 $categorycell->attributes['class'] = 'category ' . $catlevel;
845 $categorycell->colspan = $colspan;
846 $categorycell->header = true;
847 $categorycell->scope = 'col';
849 $statusicons = $this->gtree->set_grade_status_icons($element);
850 if ($statusicons) {
851 $categorycell->attributes['class'] .= ' statusicons';
854 $context = new stdClass();
855 $context->courseheader = $this->get_course_header($element);
856 $context->actionmenu = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr);
857 $context->statusicons = $statusicons;
858 $categorycell->text = $OUTPUT->render_from_template('gradereport_grader/categorycell', $context);
860 $headingrow->cells[] = $categorycell;
862 } else {
863 // Element is a grade_item.
865 $arrow = '';
866 if ($element['object']->id == $this->sortitemid) {
867 if ($this->sortorder == 'ASC') {
868 $arrow = $this->get_sort_arrow('down', $sortlink);
869 } else {
870 $arrow = $this->get_sort_arrow('up', $sortlink);
874 $collapsecontext = [
875 'field' => $element['object']->id,
876 'name' => $element['object']->get_name(),
878 $collapsedicon = '';
879 // We do not want grade category total items to be hidden away as it is controlled by something else.
880 if (!$element['object']->is_aggregate_item()) {
881 $collapsedicon = $OUTPUT->render_from_template('gradereport_grader/collapse/icon', $collapsecontext);
883 $headerlink = $this->gtree->get_element_header($element, true,
884 true, false, false, true, $sortlink);
886 $itemcell = new html_table_cell();
887 $itemcell->attributes['class'] = $type . ' ' . $catlevel .
888 ' highlightable'. ' i'. $element['object']->id;
889 $itemcell->attributes['data-itemid'] = $element['object']->id;
891 $singleview = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr, $this->baseurl);
892 $statusicons = $this->gtree->set_grade_status_icons($element);
893 if ($statusicons) {
894 $itemcell->attributes['class'] .= ' statusicons';
897 $itemcell->attributes['class'] .= $this->get_cell_display_class($element['object']);
899 $itemcell->colspan = $colspan;
900 $itemcell->header = true;
901 $itemcell->scope = 'col';
903 $context = new stdClass();
904 $context->headerlink = $headerlink;
905 $context->arrow = $arrow;
906 $context->singleview = $singleview;
907 $context->statusicons = $statusicons;
908 $context->collapsedicon = $collapsedicon;
910 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/headercell', $context);
912 $headingrow->cells[] = $itemcell;
915 $rows[] = $headingrow;
918 // Get all the grade items if the user can not view hidden grade items.
919 // It is possible that the user is simply viewing the 'Course total' by switching to the 'Aggregates only' view
920 // and that this user does not have the ability to view hidden items. In this case we still need to pass all the
921 // grade items (in case one has been hidden) as the course total shown needs to be adjusted for this particular
922 // user.
923 if (!$this->canviewhidden) {
924 $allgradeitems = $this->get_allgradeitems();
927 foreach ($this->users as $userid => $user) {
929 if ($this->canviewhidden) {
930 $altered = [];
931 $unknown = [];
932 } else {
933 $usergrades = $this->allgrades[$userid];
934 $hidingaffected = grade_grade::get_hiding_affected($usergrades, $allgradeitems);
935 $altered = $hidingaffected['altered'];
936 $unknown = $hidingaffected['unknowngrades'];
937 unset($hidingaffected);
940 $itemrow = new html_table_row();
941 $itemrow->id = 'user_'.$userid;
943 $fullname = fullname($user, $viewfullnames);
945 foreach ($this->gtree->items as $itemid => $unused) {
946 $item =& $this->gtree->items[$itemid];
947 $grade = $this->grades[$userid][$item->id];
949 $itemcell = new html_table_cell();
951 $itemcell->id = 'u' . $userid . 'i' . $itemid;
952 $itemcell->attributes['data-itemid'] = $itemid;
953 $itemcell->attributes['class'] = 'gradecell';
955 // Get the decimal points preference for this item.
956 $decimalpoints = $item->get_decimals();
958 if (array_key_exists($itemid, $unknown)) {
959 $gradeval = null;
960 } else if (array_key_exists($itemid, $altered)) {
961 $gradeval = $altered[$itemid];
962 } else {
963 $gradeval = $grade->finalgrade;
966 $context = new stdClass();
968 // MDL-11274: Hide grades in the grader report if the current grader
969 // doesn't have 'moodle/grade:viewhidden'.
970 if (!$this->canviewhidden && $grade->is_hidden()) {
971 if (!empty($CFG->grade_hiddenasdate) && $grade->get_datesubmitted()
972 && !$item->is_category_item() && !$item->is_course_item()) {
973 // The problem here is that we do not have the time when grade value was modified,
974 // 'timemodified' is general modification date for grade_grades records.
975 $context->text = userdate($grade->get_datesubmitted(), $strftimedatetimeshort);
976 $context->extraclasses = 'datesubmitted';
977 } else {
978 $context->text = '-';
980 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/cell', $context);
981 $itemrow->cells[] = $itemcell;
982 continue;
985 // Emulate grade element.
986 $eid = $this->gtree->get_grade_eid($grade);
987 $element = ['eid' => $eid, 'object' => $grade, 'type' => 'grade'];
989 $itemcell->attributes['class'] .= ' grade i' . $itemid;
990 if ($item->is_category_item()) {
991 $itemcell->attributes['class'] .= ' cat';
993 if ($item->is_course_item()) {
994 $itemcell->attributes['class'] .= ' course';
996 if ($grade->is_overridden()) {
997 $itemcell->attributes['class'] .= ' overridden';
998 $itemcell->attributes['aria-label'] = $stroverridengrade;
1001 $hidden = '';
1002 if ($grade->is_hidden()) {
1003 $hidden = ' dimmed_text ';
1005 $gradepass = ' gradefail ';
1006 $context->gradepassicon = $OUTPUT->pix_icon('i/invalid', $strfail);
1007 if ($grade->is_passed($item)) {
1008 $gradepass = ' gradepass ';
1009 $context->gradepassicon = $OUTPUT->pix_icon('i/valid', $strpass);
1010 } else if (is_null($grade->is_passed($item))) {
1011 $gradepass = '';
1012 $context->gradepassicon = '';
1014 $context->statusicons = $this->gtree->set_grade_status_icons($element);
1016 // If in editing mode, we need to print either a text box or a drop down (for scales)
1017 // grades in item of type grade category or course are not directly editable.
1018 if ($item->needsupdate) {
1019 $context->text = $strerror;
1020 $context->extraclasses = 'gradingerror';
1021 } else if (!empty($USER->editing)) {
1022 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1023 $itemcell->attributes['class'] .= ' grade_type_scale';
1024 } else if ($item->gradetype == GRADE_TYPE_VALUE) {
1025 $itemcell->attributes['class'] .= ' grade_type_value';
1026 } else if ($item->gradetype == GRADE_TYPE_TEXT) {
1027 $itemcell->attributes['class'] .= ' grade_type_text';
1030 if ($grade->is_locked()) {
1031 $itemcell->attributes['class'] .= ' locked';
1034 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1035 $context->scale = true;
1037 $scale = $scalesarray[$item->scaleid];
1038 $gradeval = (int)$gradeval; // Scales use only integers.
1039 $scales = explode(",", $scale->scale);
1040 // Reindex because scale is off 1.
1042 // MDL-12104 some previous scales might have taken up part of the array
1043 // so this needs to be reset.
1044 $scaleopt = [];
1045 $i = 0;
1046 foreach ($scales as $scaleoption) {
1047 $i++;
1048 $scaleopt[$i] = $scaleoption;
1051 if ($quickgrading && $grade->is_editable()) {
1052 $context->iseditable = true;
1053 if (empty($item->outcomeid)) {
1054 $nogradestr = get_string('nograde');
1055 } else {
1056 $nogradestr = get_string('nooutcome', 'grades');
1058 $attributes = [
1059 'id' => 'grade_' . $userid . '_' . $item->id
1061 $gradelabel = $fullname . ' ' . $item->get_name(true);
1063 if ($context->statusicons) {
1064 $attributes['class'] = 'statusicons';
1067 $context->label = html_writer::label(
1068 get_string('useractivitygrade', 'gradereport_grader', $gradelabel),
1069 $attributes['id'], false, ['class' => 'accesshide']);
1070 $context->select = html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']',
1071 $gradeval, [-1 => $nogradestr], $attributes);
1072 } else if (!empty($scale)) {
1073 $scales = explode(",", $scale->scale);
1075 $context->extraclasses = 'gradevalue' . $hidden . $gradepass;
1076 // Invalid grade if gradeval < 1.
1077 if ($gradeval < 1) {
1078 $context->text = '-';
1079 } else {
1080 // Just in case somebody changes scale.
1081 $gradeval = $grade->grade_item->bounded_grade($gradeval);
1082 $context->text = $scales[$gradeval - 1];
1086 } else if ($item->gradetype != GRADE_TYPE_TEXT) {
1087 // Value type.
1088 if ($quickgrading and $grade->is_editable()) {
1089 $context->iseditable = true;
1090 $value = format_float($gradeval, $decimalpoints);
1091 $gradelabel = $fullname . ' ' . $item->get_name(true);
1093 $context->id = 'grade_' . $userid . '_' . $item->id;
1094 $context->name = 'grade[' . $userid . '][' . $item->id .']';
1095 $context->value = $value;
1096 $context->label = get_string('useractivitygrade', 'gradereport_grader', $gradelabel);
1097 $context->title = $strgrade;
1098 $context->extraclasses = 'form-control';
1099 if ($context->statusicons) {
1100 $context->extraclasses .= ' statusicons';
1102 } else {
1103 $context->extraclasses = 'gradevalue' . $hidden . $gradepass;
1104 $context->text = format_float($gradeval, $decimalpoints);
1108 } else {
1109 // Not editing.
1110 $gradedisplaytype = $item->get_displaytype();
1112 // Letter grades, scales and text grades are left aligned.
1113 $textgrade = false;
1114 $textgrades = [GRADE_DISPLAY_TYPE_LETTER,
1115 GRADE_DISPLAY_TYPE_REAL_LETTER,
1116 GRADE_DISPLAY_TYPE_LETTER_REAL,
1117 GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE,
1118 GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER];
1119 if (in_array($gradedisplaytype, $textgrades)) {
1120 $textgrade = true;
1123 if ($textgrade || ($item->gradetype == GRADE_TYPE_TEXT)) {
1124 $itemcell->attributes['class'] .= ' grade_type_text';
1125 } else if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1126 if ($gradedisplaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) {
1127 $itemcell->attributes['class'] .= ' grade_type_value';
1128 } else {
1129 $itemcell->attributes['class'] .= ' grade_type_scale';
1131 } else {
1132 $itemcell->attributes['class'] .= ' grade_type_value';
1135 if ($item->needsupdate) {
1136 $context->text = $strerror;
1137 $context->extraclasses = 'gradingerror' . $hidden . $gradepass;
1138 } else {
1139 // The max and min for an aggregation may be different to the grade_item.
1140 if (!is_null($gradeval)) {
1141 $item->grademax = $grade->get_grade_max();
1142 $item->grademin = $grade->get_grade_min();
1145 $context->extraclasses = 'gradevalue ' . $hidden . $gradepass;
1146 $context->text = grade_format_gradevalue($gradeval, $item, true,
1147 $gradedisplaytype, null);
1151 if ($item->gradetype == GRADE_TYPE_TEXT && !empty($grade->feedback)) {
1152 $context->text = html_writer::span(shorten_text(strip_tags($grade->feedback), 20), '',
1153 ['data-action' => 'feedback', 'role' => 'button', 'data-courseid' => $this->courseid]);
1156 if (!$item->needsupdate && !($item->gradetype == GRADE_TYPE_TEXT && empty($USER->editing))) {
1157 $context->actionmenu = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr);
1160 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/cell', $context);
1162 if (!empty($this->gradeserror[$item->id][$userid])) {
1163 $itemcell->text .= $this->gradeserror[$item->id][$userid];
1166 $itemrow->cells[] = $itemcell;
1168 $rows[] = $itemrow;
1171 if (!empty($USER->editing)) {
1172 $PAGE->requires->js_call_amd('core_form/changechecker',
1173 'watchFormById', ['gradereport_grader']);
1176 $rows = $this->get_right_range_row($rows);
1177 if ($displayaverages) {
1178 $rows = $this->get_right_avg_row($rows, true);
1179 $rows = $this->get_right_avg_row($rows);
1182 return $rows;
1186 * Depending on the style of report (fixedstudents vs traditional one-table),
1187 * arranges the rows of data in one or two tables, and returns the output of
1188 * these tables in HTML
1189 * @param boolean $displayaverages whether to display average rows in the table
1190 * @return string HTML
1192 public function get_grade_table($displayaverages = false) {
1193 global $OUTPUT;
1194 $leftrows = $this->get_left_rows($displayaverages);
1195 $rightrows = $this->get_right_rows($displayaverages);
1197 $html = '';
1199 $fulltable = new html_table();
1200 $fulltable->attributes['class'] = 'gradereport-grader-table d-none';
1201 $fulltable->id = 'user-grades';
1202 $fulltable->caption = get_string('summarygrader', 'gradereport_grader');
1203 $fulltable->captionhide = true;
1204 // We don't want the table to be enclosed within in a .table-responsive div as it is heavily customised.
1205 $fulltable->responsive = false;
1207 // Extract rows from each side (left and right) and collate them into one row each
1208 foreach ($leftrows as $key => $row) {
1209 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1210 $fulltable->data[] = $row;
1212 $html .= html_writer::table($fulltable);
1213 return $OUTPUT->container($html, 'gradeparent');
1217 * Builds and return the row of icons for the left side of the report.
1218 * It only has one cell that says "Controls"
1219 * @param array $rows The Array of rows for the left part of the report
1220 * @param int $colspan The number of columns this cell has to span
1221 * @return array Array of rows for the left part of the report
1222 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1223 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1225 public function get_left_icons_row($rows=array(), $colspan=1) {
1226 global $USER;
1228 debugging('The function get_left_icons_row() is deprecated, please do not use it anymore.',
1229 DEBUG_DEVELOPER);
1231 if (!empty($USER->editing)) {
1232 $controlsrow = new html_table_row();
1233 $controlsrow->attributes['class'] = 'controls';
1234 $controlscell = new html_table_cell();
1235 $controlscell->attributes['class'] = 'header controls';
1236 $controlscell->header = true;
1237 $controlscell->colspan = $colspan;
1238 $controlscell->text = get_string('controls', 'grades');
1239 $controlsrow->cells[] = $controlscell;
1241 $rows[] = $controlsrow;
1243 return $rows;
1247 * Builds and return the header for the row of ranges, for the left part of the grader report.
1248 * @param array $rows The Array of rows for the left part of the report
1249 * @param int $colspan The number of columns this cell has to span
1250 * @return array Array of rows for the left part of the report
1252 public function get_left_range_row($rows=array(), $colspan=1) {
1253 global $CFG, $USER;
1255 if ($this->get_pref('showranges')) {
1256 $rangerow = new html_table_row();
1257 $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1258 $rangecell = new html_table_cell();
1259 $rangecell->attributes['class'] = 'header range';
1260 $rangecell->colspan = $colspan;
1261 $rangecell->header = true;
1262 $rangecell->scope = 'row';
1263 $rangecell->text = get_string('range', 'grades');
1264 $rangerow->cells[] = $rangecell;
1265 $rows[] = $rangerow;
1268 return $rows;
1272 * Builds and return the headers for the rows of averages, for the left part of the grader report.
1273 * @param array $rows The Array of rows for the left part of the report
1274 * @param int $colspan The number of columns this cell has to span
1275 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1276 * @return array Array of rows for the left part of the report
1278 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1279 if (!$this->canviewhidden) {
1280 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1281 // better not show them at all if user can not see all hideen grades
1282 return $rows;
1285 $showaverages = $this->get_pref('showaverages');
1286 $showaveragesgroup = $this->currentgroup && $showaverages;
1287 $straveragegroup = get_string('groupavg', 'grades');
1289 if ($groupavg) {
1290 if ($showaveragesgroup) {
1291 $groupavgrow = new html_table_row();
1292 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1293 $groupavgcell = new html_table_cell();
1294 $groupavgcell->attributes['class'] = 'header range';
1295 $groupavgcell->colspan = $colspan;
1296 $groupavgcell->header = true;
1297 $groupavgcell->scope = 'row';
1298 $groupavgcell->text = $straveragegroup;
1299 $groupavgrow->cells[] = $groupavgcell;
1300 $rows[] = $groupavgrow;
1302 } else {
1303 $straverage = get_string('overallaverage', 'grades');
1305 if ($showaverages) {
1306 $avgrow = new html_table_row();
1307 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1308 $avgcell = new html_table_cell();
1309 $avgcell->attributes['class'] = 'header range';
1310 $avgcell->colspan = $colspan;
1311 $avgcell->header = true;
1312 $avgcell->scope = 'row';
1313 $avgcell->text = $straverage;
1314 $avgrow->cells[] = $avgcell;
1315 $rows[] = $avgrow;
1319 return $rows;
1323 * Builds and return the row of icons when editing is on, for the right part of the grader report.
1324 * @param array $rows The Array of rows for the right part of the report
1325 * @return array Array of rows for the right part of the report
1326 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1327 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1329 public function get_right_icons_row($rows=array()) {
1330 global $USER;
1331 debugging('The function get_right_icons_row() is deprecated, please do not use it anymore.',
1332 DEBUG_DEVELOPER);
1334 if (!empty($USER->editing)) {
1335 $iconsrow = new html_table_row();
1336 $iconsrow->attributes['class'] = 'controls';
1338 foreach ($this->gtree->items as $itemid => $unused) {
1339 // emulate grade element
1340 $item = $this->gtree->get_item($itemid);
1342 $eid = $this->gtree->get_item_eid($item);
1343 $element = $this->gtree->locate_element($eid);
1344 $itemcell = new html_table_cell();
1345 $itemcell->attributes['class'] = 'controls icons i'.$itemid;
1346 $itemcell->text = $this->get_icons($element);
1347 $iconsrow->cells[] = $itemcell;
1349 $rows[] = $iconsrow;
1351 return $rows;
1355 * Builds and return the row of ranges for the right part of the grader report.
1356 * @param array $rows The Array of rows for the right part of the report
1357 * @return array Array of rows for the right part of the report
1359 public function get_right_range_row($rows=array()) {
1361 if ($this->get_pref('showranges')) {
1362 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
1363 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1364 $rangerow = new html_table_row();
1365 $rangerow->attributes['class'] = 'heading range';
1367 foreach ($this->gtree->items as $itemid => $unused) {
1368 $item =& $this->gtree->items[$itemid];
1369 $itemcell = new html_table_cell();
1370 $itemcell->attributes['class'] .= ' range i'. $itemid;
1371 $itemcell->attributes['class'] .= $this->get_cell_display_class($item);
1373 $hidden = '';
1374 if ($item->is_hidden()) {
1375 $hidden = ' dimmed_text ';
1378 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1380 $itemcell->attributes['data-itemid'] = $itemid;
1381 $itemcell->text = html_writer::div($formattedrange, 'rangevalues' . $hidden,
1382 ['data-collapse' => 'rangerowcell']);
1383 $rangerow->cells[] = $itemcell;
1385 $rows[] = $rangerow;
1387 return $rows;
1391 * Builds and return the row of averages for the right part of the grader report.
1392 * @param array $rows Whether to return only group averages or all averages.
1393 * @param bool $grouponly Whether to return only group averages or all averages.
1394 * @return array Array of rows for the right part of the report
1396 public function get_right_avg_row($rows=array(), $grouponly=false) {
1397 global $USER, $DB, $OUTPUT, $CFG;
1398 if (!$this->canviewhidden) {
1399 // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1400 // better not show them at all if user can not see all hidden grades.
1401 return $rows;
1404 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
1405 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1406 $meanselection = $this->get_pref('meanselection');
1407 $shownumberofgrades = $this->get_pref('shownumberofgrades');
1409 if ($grouponly) {
1410 $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1411 $groupsql = $this->groupsql;
1412 $groupwheresql = $this->groupwheresql;
1413 $groupwheresqlparams = $this->groupwheresql_params;
1414 } else {
1415 $showaverages = $this->get_pref('showaverages');
1416 $groupsql = "";
1417 $groupwheresql = "";
1418 $groupwheresqlparams = array();
1421 if ($showaverages) {
1422 $totalcount = $this->get_numusers($grouponly);
1424 // Limit to users with a gradeable role.
1425 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1427 // Limit to users with an active enrollment.
1428 $coursecontext = $this->context->get_course_context(true);
1429 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
1430 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
1431 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
1432 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
1434 // We want to query both the current context and parent contexts.
1435 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
1437 $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams);
1439 // Find sums of all grade items in course.
1440 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1441 FROM {grade_items} gi
1442 JOIN {grade_grades} g ON g.itemid = gi.id
1443 JOIN {user} u ON u.id = g.userid
1444 JOIN ($enrolledsql) je ON je.id = u.id
1445 JOIN (
1446 SELECT DISTINCT ra.userid
1447 FROM {role_assignments} ra
1448 WHERE ra.roleid $gradebookrolessql
1449 AND ra.contextid $relatedctxsql
1450 ) rainner ON rainner.userid = u.id
1451 $groupsql
1452 WHERE gi.courseid = :courseid
1453 AND u.deleted = 0
1454 AND g.finalgrade IS NOT NULL
1455 $groupwheresql
1456 GROUP BY g.itemid";
1457 $sumarray = array();
1458 if ($sums = $DB->get_records_sql($sql, $params)) {
1459 foreach ($sums as $itemid => $csum) {
1460 $sumarray[$itemid] = $csum->sum;
1464 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1465 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1466 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1467 FROM {grade_items} gi
1468 CROSS JOIN ($enrolledsql) u
1469 JOIN {role_assignments} ra
1470 ON ra.userid = u.id
1471 LEFT OUTER JOIN {grade_grades} g
1472 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1473 $groupsql
1474 WHERE gi.courseid = :courseid
1475 AND ra.roleid $gradebookrolessql
1476 AND ra.contextid $relatedctxsql
1477 AND g.id IS NULL
1478 $groupwheresql
1479 GROUP BY gi.id";
1481 $ungradedcounts = $DB->get_records_sql($sql, $params);
1483 $avgrow = new html_table_row();
1484 $avgrow->attributes['class'] = 'avg';
1486 foreach ($this->gtree->items as $itemid => $unused) {
1487 $item =& $this->gtree->items[$itemid];
1489 if ($item->needsupdate) {
1490 $avgcell = new html_table_cell();
1491 $avgcell->attributes['class'] = 'i'. $itemid;
1492 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1493 $avgrow->cells[] = $avgcell;
1494 continue;
1497 if (!isset($sumarray[$item->id])) {
1498 $sumarray[$item->id] = 0;
1501 if (empty($ungradedcounts[$itemid])) {
1502 $ungradedcount = 0;
1503 } else {
1504 $ungradedcount = $ungradedcounts[$itemid]->count;
1507 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1508 $meancount = $totalcount - $ungradedcount;
1509 } else { // Bump up the sum by the number of ungraded items * grademin
1510 $sumarray[$item->id] += $ungradedcount * $item->grademin;
1511 $meancount = $totalcount;
1514 // Determine which display type to use for this average
1515 if (!empty($USER->editing)) {
1516 $displaytype = GRADE_DISPLAY_TYPE_REAL;
1518 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1519 $displaytype = $item->get_displaytype();
1521 } else {
1522 $displaytype = $averagesdisplaytype;
1525 // Override grade_item setting if a display preference (not inherit) was set for the averages
1526 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1527 $decimalpoints = $item->get_decimals();
1529 } else {
1530 $decimalpoints = $averagesdecimalpoints;
1533 $gradetypeclass = $this->get_cell_display_class($item);
1535 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1536 $avgcell = new html_table_cell();
1537 $avgcell->attributes['class'] = $gradetypeclass . ' i'. $itemid;
1538 $avgcell->attributes['data-itemid'] = $itemid;
1539 $avgcell->text = html_writer::div('-', '', ['data-collapse' => 'avgrowcell']);
1540 $avgrow->cells[] = $avgcell;
1541 } else {
1542 $sum = $sumarray[$item->id];
1543 $avgradeval = $sum/$meancount;
1544 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1546 $numberofgrades = '';
1547 if ($shownumberofgrades) {
1548 $numberofgrades = " ($meancount)";
1551 $avgcell = new html_table_cell();
1552 $avgcell->attributes['class'] = $gradetypeclass . ' i'. $itemid;
1553 $avgcell->attributes['data-itemid'] = $itemid;
1554 $avgcell->text = html_writer::div($gradehtml.$numberofgrades, '', ['data-collapse' => 'avgrowcell']);
1555 $avgrow->cells[] = $avgcell;
1558 $rows[] = $avgrow;
1560 return $rows;
1564 * Given element category, create a collapsible icon and
1565 * course header.
1567 * @param array $element
1568 * @return string HTML
1570 protected function get_course_header($element) {
1571 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1572 $showing = get_string('showingaggregatesonly', 'grades');
1573 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1574 $showing = get_string('showinggradesonly', 'grades');
1575 } else {
1576 $showing = get_string('showingfullmode', 'grades');
1579 $name = $element['object']->get_name();
1580 $nameunescaped = $element['object']->get_name(false);
1581 $describedbyid = uniqid();
1582 $courseheader = html_writer::tag('span', $name, [
1583 'title' => $nameunescaped,
1584 'class' => 'gradeitemheader',
1585 'aria-describedby' => $describedbyid
1587 $courseheader .= html_writer::div($showing, 'sr-only', [
1588 'id' => $describedbyid
1591 return $courseheader;
1595 * Given a grade_category, grade_item or grade_grade, this function
1596 * figures out the state of the object and builds then returns a div
1597 * with the icons needed for the grader report.
1599 * @param array $element
1600 * @return string HTML
1601 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1602 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1604 protected function get_icons($element) {
1605 global $CFG, $USER, $OUTPUT;
1606 debugging('The function get_icons() is deprecated, please do not use it anymore.',
1607 DEBUG_DEVELOPER);
1609 if (empty($USER->editing)) {
1610 return '<div class="grade_icons" />';
1613 // Init all icons
1614 $editicon = '';
1616 $editable = true;
1618 if ($element['type'] == 'grade') {
1619 $item = $element['object']->grade_item;
1620 if ($item->is_course_item() or $item->is_category_item()) {
1621 $editable = $this->overridecat;
1625 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) {
1626 $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1629 $editcalculationicon = '';
1630 $showhideicon = '';
1631 $lockunlockicon = '';
1633 if (has_capability('moodle/grade:manage', $this->context)) {
1634 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1636 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1638 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1641 $gradeanalysisicon = '';
1642 if ($element['type'] == 'grade') {
1643 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
1646 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
1650 * Given a category element returns collapsing +/- icon if available
1652 * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more.
1654 protected function get_collapsing_icon($element) {
1655 throw new coding_exception('get_collapsing_icon() can not be used any more, please use get_course_header() instead.');
1659 * Processes a single action against a category, grade_item or grade.
1660 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1661 * @param string $action Which action to take (edit, delete etc...)
1662 * @return
1664 public function process_action($target, $action) {
1665 return self::do_process_action($target, $action, $this->course->id);
1669 * From the list of categories that this user prefers to collapse choose ones that belong to the current course.
1671 * This function serves two purposes.
1672 * Mainly it helps migrating from user preference style when all courses were stored in one preference.
1673 * Also it helps to remove the settings for categories that were removed if the array for one course grows too big.
1675 * @param int $courseid
1676 * @param array $collapsed
1677 * @return array
1679 protected static function filter_collapsed_categories($courseid, $collapsed) {
1680 global $DB;
1681 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1682 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? [];
1683 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? [];
1685 if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) {
1686 return $collapsed;
1688 $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid));
1689 $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats));
1690 $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats));
1691 return $collapsed;
1695 * Returns the list of categories that this user wants to collapse or display aggregatesonly
1697 * This method also migrates on request from the old format of storing user preferences when they were stored
1698 * in one preference for all courses causing DB error when trying to insert very big value.
1700 * @param int $courseid
1701 * @return array
1703 protected static function get_collapsed_preferences($courseid) {
1704 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) {
1705 $collapsed = json_decode($collapsed, true);
1706 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1707 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? [];
1708 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? [];
1709 return $collapsed;
1712 // Try looking for old location of user setting that used to store all courses in one serialized user preference.
1713 $collapsed = ['aggregatesonly' => [], 'gradesonly' => []]; // Use this if old settings are not found.
1714 $collapsedall = [];
1715 $oldprefexists = false;
1716 if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) {
1717 $oldprefexists = true;
1718 if ($collapsedall = unserialize_array($oldcollapsedpref)) {
1719 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1720 $collapsedall['aggregatesonly'] = $collapsedall['aggregatesonly'] ?? [];
1721 $collapsedall['gradesonly'] = $collapsedall['gradesonly'] ?? [];
1722 // We found the old-style preference, filter out only categories that belong to this course and update the prefs.
1723 $collapsed = static::filter_collapsed_categories($courseid, $collapsedall);
1724 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1725 static::set_collapsed_preferences($courseid, $collapsed);
1726 $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']);
1727 $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']);
1728 if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) {
1729 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall));
1735 // Arrived here, if the old pref exists and it doesn't contain
1736 // more information, it means that the migration of all the
1737 // data to new, by course, preferences is completed, so
1738 // the old one can be safely deleted.
1739 if ($oldprefexists &&
1740 empty($collapsedall['aggregatesonly']) &&
1741 empty($collapsedall['gradesonly'])) {
1742 unset_user_preference('grade_report_grader_collapsed_categories');
1745 return $collapsed;
1749 * Sets the list of categories that user wants to see collapsed in user preferences
1751 * This method may filter or even trim the list if it does not fit in DB field.
1753 * @param int $courseid
1754 * @param array $collapsed
1756 protected static function set_collapsed_preferences($courseid, $collapsed) {
1757 global $DB;
1758 // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size,
1759 // try to filter the list of categories since array may contain categories that were deleted.
1760 if (strlen(json_encode($collapsed)) >= 1333) {
1761 $collapsed = static::filter_collapsed_categories($courseid, $collapsed);
1764 // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information.
1765 while (strlen(json_encode($collapsed)) >= 1333) {
1766 if (count($collapsed['aggregatesonly'])) {
1767 array_pop($collapsed['aggregatesonly']);
1769 if (count($collapsed['gradesonly'])) {
1770 array_pop($collapsed['gradesonly']);
1774 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1775 set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed));
1776 } else {
1777 unset_user_preference('grade_report_grader_collapsed_categories'.$courseid);
1782 * Processes a single action against a category, grade_item or grade.
1783 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1784 * @param string $action Which action to take (edit, delete etc...)
1785 * @param int $courseid affected course.
1786 * @return
1788 public static function do_process_action($target, $action, $courseid = null) {
1789 global $DB;
1790 // TODO: this code should be in some grade_tree static method
1791 $targettype = substr($target, 0, 2);
1792 $targetid = substr($target, 2);
1793 // TODO: end
1795 if ($targettype !== 'cg') {
1796 // The following code only works with categories.
1797 return true;
1800 if (!$courseid) {
1801 debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid',
1802 DEBUG_DEVELOPER);
1803 if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) {
1804 return true;
1808 $collapsed = static::get_collapsed_preferences($courseid);
1810 switch ($action) {
1811 case 'switch_minus': // Add category to array of aggregatesonly
1812 $key = array_search($targetid, $collapsed['gradesonly']);
1813 if ($key !== false) {
1814 unset($collapsed['gradesonly'][$key]);
1816 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1817 $collapsed['aggregatesonly'][] = $targetid;
1818 static::set_collapsed_preferences($courseid, $collapsed);
1820 break;
1822 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1823 $key = array_search($targetid, $collapsed['aggregatesonly']);
1824 if ($key !== false) {
1825 unset($collapsed['aggregatesonly'][$key]);
1827 if (!in_array($targetid, $collapsed['gradesonly'])) {
1828 $collapsed['gradesonly'][] = $targetid;
1830 static::set_collapsed_preferences($courseid, $collapsed);
1831 break;
1832 case 'switch_whole': // Remove the category from the array of collapsed cats
1833 $key = array_search($targetid, $collapsed['gradesonly']);
1834 if ($key !== false) {
1835 unset($collapsed['gradesonly'][$key]);
1836 static::set_collapsed_preferences($courseid, $collapsed);
1839 $key = array_search($targetid, $collapsed['aggregatesonly']);
1840 if ($key !== false) {
1841 unset($collapsed['aggregatesonly'][$key]);
1842 static::set_collapsed_preferences($courseid, $collapsed);
1844 break;
1845 default:
1846 break;
1849 return true;
1853 * Refactored function for generating HTML of sorting links with matching arrows.
1854 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1855 * to inject into a table header cell.
1856 * @param array $extrafields Array of extra fields being displayed, such as
1857 * user idnumber
1858 * @return array An associative array of HTML sorting links+arrows
1860 public function get_sort_arrows(array $extrafields = []) {
1861 global $CFG;
1862 $arrows = array();
1863 $sortlink = clone($this->baseurl);
1865 // Sourced from tablelib.php
1866 // Check the full name display for sortable fields.
1867 if (has_capability('moodle/site:viewfullnames', $this->context)) {
1868 $nameformat = $CFG->alternativefullnameformat;
1869 } else {
1870 $nameformat = $CFG->fullnamedisplay;
1873 if ($nameformat == 'language') {
1874 $nameformat = get_string('fullnamedisplay');
1877 $arrows['studentname'] = '';
1878 $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat);
1879 if (!empty($requirednames)) {
1880 foreach ($requirednames as $name) {
1881 $arrows['studentname'] .= html_writer::link(
1882 new moodle_url($this->baseurl, array('sortitemid' => $name)), get_string($name)
1884 if ($this->sortitemid == $name) {
1885 $sortlink->param('sortitemid', $name);
1886 if ($this->sortorder == 'ASC') {
1887 $sorticon = $this->get_sort_arrow('down', $sortlink);
1888 } else {
1889 $sorticon = $this->get_sort_arrow('up', $sortlink);
1891 $arrows['studentname'] .= $sorticon;
1893 $arrows['studentname'] .= ' / ';
1896 $arrows['studentname'] = substr($arrows['studentname'], 0, -3);
1899 foreach ($extrafields as $field) {
1900 $attributes = [
1901 'data-collapse' => 'content'
1903 // With additional user profile fields, we can't grab the name via WS, so conditionally add it to rip out of the DOM.
1904 if (preg_match(\core_user\fields::PROFILE_FIELD_REGEX, $field)) {
1905 $attributes['data-collapse-name'] = \core_user\fields::get_display_name($field);
1907 $fieldlink = html_writer::link(new moodle_url($this->baseurl, ['sortitemid' => $field]),
1908 \core_user\fields::get_display_name($field), $attributes);
1909 $arrows[$field] = $fieldlink;
1911 if ($field == $this->sortitemid) {
1912 $sortlink->param('sortitemid', $field);
1914 if ($this->sortorder == 'ASC') {
1915 $sorticon = $this->get_sort_arrow('down', $sortlink);
1916 } else {
1917 $sorticon = $this->get_sort_arrow('up', $sortlink);
1919 $arrows[$field] .= $sorticon;
1923 return $arrows;
1927 * Returns the maximum number of students to be displayed on each page
1929 * @return int The maximum number of students to display per page
1931 public function get_students_per_page(): int {
1932 // Default to the lowest available option.
1933 return (int) get_user_preferences('grade_report_studentsperpage', min(static::PAGINATION_OPTIONS));
1937 * Returns link to change category view mode.
1939 * @param moodle_url $url Url to grader report page
1940 * @param string $title Menu item title
1941 * @param string $action View mode to change to
1942 * @param bool $active Whether link is active in dropdown
1944 * @return string|null
1946 public function get_category_view_mode_link(moodle_url $url, string $title, string $action, bool $active = false): ?string {
1947 $urlnew = $url;
1948 $urlnew->param('action', $action);
1949 $active = $active ? 'true' : 'false';
1950 return html_writer::link($urlnew, $title,
1951 ['class' => 'dropdown-item', 'aria-label' => $title, 'aria-current' => $active, 'role' => 'menuitem']);
1955 * Return the link to allow the field to collapse from the users view.
1957 * @return string Dropdown menu link that'll trigger the collapsing functionality.
1958 * @throws coding_exception
1959 * @throws moodle_exception
1961 public function get_hide_show_link(): string {
1962 $link = new moodle_url('#', []);
1963 return html_writer::link(
1964 $link->out(false),
1965 get_string('collapse'),
1966 ['class' => 'dropdown-item', 'data-hider' => 'hide', 'aria-label' => get_string('collapse'), 'role' => 'menuitem'],
1971 * Return the base report link with some default sorting applied.
1973 * @return string
1974 * @throws moodle_exception
1976 public function get_default_sortable(): string {
1977 $sortlink = new moodle_url('/grade/report/grader/index.php', [
1978 'id' => $this->courseid,
1979 'sortitemid' => 'firstname',
1980 'sort' => 'asc'
1982 $this->gpr->add_url_params($sortlink);
1983 return $sortlink->out(false);
1987 * Return class used for text alignment.
1989 * @param grade_item $item Can be grade item or grade
1990 * @return string class name used for text alignment
1992 public function get_cell_display_class(grade_item $item): string {
1993 global $USER;
1995 $gradetypeclass = '';
1996 if (!empty($USER->editing)) {
1997 switch ($item->gradetype) {
1998 case GRADE_TYPE_SCALE:
1999 $gradetypeclass = ' grade_type_scale';
2000 break;
2001 case GRADE_TYPE_VALUE:
2002 $gradetypeclass = ' grade_type_value';
2003 break;
2004 case GRADE_TYPE_TEXT:
2005 $gradetypeclass = ' grade_type_text';
2006 break;
2008 } else {
2009 $gradedisplaytype = $item->get_displaytype();
2011 // Letter grades, scales and text grades are left aligned.
2012 $textgrade = false;
2013 $textgrades = [GRADE_DISPLAY_TYPE_LETTER,
2014 GRADE_DISPLAY_TYPE_REAL_LETTER,
2015 GRADE_DISPLAY_TYPE_LETTER_REAL,
2016 GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE,
2017 GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER];
2018 if (in_array($gradedisplaytype, $textgrades)) {
2019 $textgrade = true;
2022 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'gradereport_grader', 'scales');
2023 $scalesarray = $cache->get(get_class($this));
2025 if ($textgrade || ($item->gradetype == GRADE_TYPE_TEXT)) {
2026 $gradetypeclass = ' grade_type_text';
2027 } else if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
2028 if ($gradedisplaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) {
2029 $gradetypeclass = ' grade_type_value';
2030 } else {
2031 $gradetypeclass = ' grade_type_scale';
2033 } else {
2034 $gradetypeclass = ' grade_type_value';
2037 return $gradetypeclass;
2042 * Adds report specific context variable
2044 * @param context_course $context Course context
2045 * @param int $courseid Course ID
2046 * @param array $element An array representing an element in the grade_tree
2047 * @param grade_plugin_return $gpr A grade_plugin_return object
2048 * @param string $mode Not used
2049 * @param stdClass|null $templatecontext Template context
2050 * @return stdClass|null
2052 function gradereport_grader_get_report_link(context_course $context, int $courseid,
2053 array $element, grade_plugin_return $gpr, string $mode, ?stdClass $templatecontext): ?stdClass {
2055 static $report = null;
2056 if (!$report) {
2057 $report = new grade_report_grader($courseid, $gpr, $context);
2060 if ($mode == 'category') {
2061 if (!isset($templatecontext)) {
2062 $templatecontext = new stdClass();
2065 $categoryid = $element['object']->id;
2067 // Load language strings.
2068 $strswitchminus = get_string('aggregatesonly', 'grades');
2069 $strswitchplus = get_string('gradesonly', 'grades');
2070 $strswitchwhole = get_string('fullmode', 'grades');
2072 $url = new moodle_url($gpr->get_return_url(null, ['target' => $element['eid'], 'sesskey' => sesskey()]));
2074 $gradesonly = false;
2075 $aggregatesonly = false;
2076 $fullmode = false;
2077 if (in_array($categoryid, $report->collapsed['gradesonly'])) {
2078 $gradesonly = true;
2079 } else if (in_array($categoryid, $report->collapsed['aggregatesonly'])) {
2080 $aggregatesonly = true;
2081 } else {
2082 $fullmode = true;
2084 $templatecontext->gradesonlyurl =
2085 $report->get_category_view_mode_link($url, $strswitchplus, 'switch_plus', $gradesonly);
2086 $templatecontext->aggregatesonlyurl =
2087 $report->get_category_view_mode_link($url, $strswitchminus, 'switch_minus', $aggregatesonly);
2088 $templatecontext->fullmodeurl =
2089 $report->get_category_view_mode_link($url, $strswitchwhole, 'switch_whole', $fullmode);
2090 return $templatecontext;
2091 } else if ($mode == 'gradeitem') {
2092 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) {
2093 $templatecontext->columncollapse = $report->get_hide_show_link();
2094 $templatecontext->dataid = $element['name'];
2097 // We do not want grade category total items to be hidden away as it is controlled by something else.
2098 if (isset($element['object']->id) && !$element['object']->is_aggregate_item()) {
2099 $templatecontext->columncollapse = $report->get_hide_show_link();
2101 return $templatecontext;
2103 return null;