MDL-79062 gradereport_grader: Set numeric type for grade value inputs
[moodle.git] / grade / report / grader / lib.php
blob9be062ec4a088903681ef53fc2dd2cabe1a9c3a3
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 $rows = [];
626 $showuserimage = $this->get_pref('showuserimage');
627 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
629 $extrafields = \core_user\fields::get_identity_fields($this->context);
631 $arrows = $this->get_sort_arrows($extrafields);
633 $colspan = 1 + count($extrafields);
635 $levels = count($this->gtree->levels) - 1;
637 $fillercell = new html_table_cell();
638 $fillercell->header = true;
639 $fillercell->attributes['scope'] = 'col';
640 $fillercell->attributes['class'] = 'cell topleft';
641 $fillercell->text = html_writer::span(get_string('participants'), 'accesshide');
642 $fillercell->colspan = $colspan;
643 $fillercell->rowspan = $levels;
644 $row = new html_table_row(array($fillercell));
645 $rows[] = $row;
647 for ($i = 1; $i < $levels; $i++) {
648 $row = new html_table_row();
649 $rows[] = $row;
652 $headerrow = new html_table_row();
653 $headerrow->attributes['class'] = 'heading';
655 $studentheader = new html_table_cell();
656 // The browser's scrollbar may partly cover (in certain operative systems) the content in the student header
657 // when horizontally scrolling through the table contents (most noticeable when in RTL mode).
658 // Therefore, add slight padding on the left or right when using RTL mode.
659 $studentheader->attributes['class'] = "header pl-3";
660 $studentheader->scope = 'col';
661 $studentheader->header = true;
662 $studentheader->id = 'studentheader';
663 $element = ['type' => 'userfield', 'name' => 'fullname'];
664 $studentheader->text = $arrows['studentname'] .
665 $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr, $this->baseurl);
667 $headerrow->cells[] = $studentheader;
669 foreach ($extrafields as $field) {
670 $fieldheader = new html_table_cell();
671 $fieldheader->attributes['class'] = 'userfield user' . $field;
672 $fieldheader->attributes['data-col'] = $field;
673 $fieldheader->scope = 'col';
674 $fieldheader->header = true;
676 $collapsecontext = ['field' => $field, 'name' => $field];
678 $collapsedicon = $OUTPUT->render_from_template('gradereport_grader/collapse/icon', $collapsecontext);
679 // Need to wrap the button into a div with our hooking element for user items, gradeitems already have this.
680 $collapsedicon = html_writer::div($collapsedicon, 'd-none', ['data-collapse' => 'expandbutton']);
682 $element = ['type' => 'userfield', 'name' => $field];
683 $fieldheader->text = $arrows[$field] .
684 $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr, $this->baseurl) . $collapsedicon;
685 $headerrow->cells[] = $fieldheader;
688 $rows[] = $headerrow;
690 $suspendedstring = null;
692 $usercount = 0;
693 foreach ($this->users as $userid => $user) {
694 $userrow = new html_table_row();
695 $userrow->id = 'fixed_user_'.$userid;
696 $userrow->attributes['class'] = ($usercount % 2) ? 'userrow even' : 'userrow odd';
698 $usercell = new html_table_cell();
699 $usercell->attributes['class'] = ($usercount % 2) ? 'header user even' : 'header user odd';
700 $usercount++;
702 $usercell->header = true;
703 $usercell->scope = 'row';
705 if ($showuserimage) {
706 $usercell->text = $OUTPUT->user_picture($user, ['link' => false, 'visibletoscreenreaders' => false]);
709 $fullname = fullname($user, $viewfullnames);
710 $usercell->text = html_writer::link(
711 new moodle_url('/user/view.php', ['id' => $user->id, 'course' => $this->course->id]),
712 $usercell->text . $fullname,
713 ['class' => 'username']
716 if (!empty($user->suspendedenrolment)) {
717 $usercell->attributes['class'] .= ' usersuspended';
719 //may be lots of suspended users so only get the string once
720 if (empty($suspendedstring)) {
721 $suspendedstring = get_string('userenrolmentsuspended', 'grades');
723 $icon = $OUTPUT->pix_icon('i/enrolmentsuspended', $suspendedstring);
724 $usercell->text .= html_writer::tag('span', $icon, array('class'=>'usersuspendedicon'));
726 // The browser's scrollbar may partly cover (in certain operative systems) the content in the user cells
727 // when horizontally scrolling through the table contents (most noticeable when in RTL mode).
728 // Therefore, add slight padding on the left or right when using RTL mode.
729 $usercell->attributes['class'] .= ' pl-3';
730 $usercell->text .= $this->gtree->get_cell_action_menu(['userid' => $userid], 'user', $this->gpr);
732 $userrow->cells[] = $usercell;
734 foreach ($extrafields as $field) {
735 $fieldcell = new html_table_cell();
736 $fieldcell->attributes['class'] = 'userfield user' . $field;
737 $fieldcell->attributes['data-col'] = $field;
738 $fieldcell->header = false;
739 $fieldcell->text = html_writer::tag('div', s($user->{$field}), [
740 'data-collapse' => 'content'
743 $userrow->cells[] = $fieldcell;
746 $userrow->attributes['data-uid'] = $userid;
747 $rows[] = $userrow;
750 $rows = $this->get_left_range_row($rows, $colspan);
751 if ($displayaverages) {
752 $rows = $this->get_left_avg_row($rows, $colspan, true);
753 $rows = $this->get_left_avg_row($rows, $colspan);
756 return $rows;
760 * Builds and returns the rows that will make up the right part of the grader report
761 * @param boolean $displayaverages whether to display average rows in the table
762 * @return array Array of html_table_row objects
764 public function get_right_rows(bool $displayaverages) : array {
765 global $CFG, $USER, $OUTPUT, $DB, $PAGE;
767 $rows = [];
768 $this->rowcount = 0;
769 $strgrade = \grade_helper::get_lang_string('gradenoun');
770 $this->get_sort_arrows();
772 // Get preferences once.
773 $quickgrading = $this->get_pref('quickgrading');
775 // Get strings which are re-used inside the loop.
776 $strftimedatetimeshort = get_string('strftimedatetimeshort');
777 $strerror = get_string('error');
778 $stroverridengrade = get_string('overridden', 'grades');
779 $strfail = get_string('fail', 'grades');
780 $strpass = get_string('pass', 'grades');
781 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
783 // Preload scale objects for items with a scaleid and initialize tab indices.
784 $scaleslist = [];
786 foreach ($this->gtree->get_items() as $itemid => $item) {
787 if (!empty($item->scaleid)) {
788 $scaleslist[] = $item->scaleid;
792 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'gradereport_grader', 'scales');
793 $scalesarray = $cache->get(get_class($this));
794 if (!$scalesarray) {
795 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
796 // Save to cache.
797 $cache->set(get_class($this), $scalesarray);
800 foreach ($this->gtree->get_levels() as $row) {
801 $headingrow = new html_table_row();
802 $headingrow->attributes['class'] = 'heading_name_row';
804 foreach ($row as $element) {
805 $sortlink = clone($this->baseurl);
806 if (isset($element['object']->id)) {
807 $sortlink->param('sortitemid', $element['object']->id);
810 $type = $element['type'];
812 if (!empty($element['colspan'])) {
813 $colspan = $element['colspan'];
814 } else {
815 $colspan = 1;
818 if (!empty($element['depth'])) {
819 $catlevel = 'catlevel'.$element['depth'];
820 } else {
821 $catlevel = '';
824 // Element is a filler.
825 if ($type == 'filler' || $type == 'fillerfirst' || $type == 'fillerlast') {
826 $fillercell = new html_table_cell();
827 $fillercell->attributes['class'] = $type . ' ' . $catlevel;
828 $fillercell->colspan = $colspan;
829 $fillercell->text = '&nbsp;';
831 // This is a filler cell; don't use a <th>, it'll confuse screen readers.
832 $fillercell->header = false;
833 $headingrow->cells[] = $fillercell;
834 } else if ($type == 'category') {
835 // Make sure the grade category has a grade total or at least has child grade items.
836 if (grade_tree::can_output_item($element)) {
837 // Element is a category.
838 $categorycell = new html_table_cell();
839 $categorycell->attributes['class'] = 'category ' . $catlevel;
840 $categorycell->colspan = $colspan;
841 $categorycell->header = true;
842 $categorycell->scope = 'col';
844 $statusicons = $this->gtree->set_grade_status_icons($element);
845 if ($statusicons) {
846 $categorycell->attributes['class'] .= ' statusicons';
849 $context = new stdClass();
850 $context->courseheader = $this->get_course_header($element);
851 $context->actionmenu = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr);
852 $context->statusicons = $statusicons;
853 $categorycell->text = $OUTPUT->render_from_template('gradereport_grader/categorycell', $context);
855 $headingrow->cells[] = $categorycell;
857 } else {
858 // Element is a grade_item.
860 $arrow = '';
861 if ($element['object']->id == $this->sortitemid) {
862 if ($this->sortorder == 'ASC') {
863 $arrow = $this->get_sort_arrow('down', $sortlink);
864 } else {
865 $arrow = $this->get_sort_arrow('up', $sortlink);
869 $collapsecontext = [
870 'field' => $element['object']->id,
871 'name' => $element['object']->get_name(),
873 $collapsedicon = '';
874 // We do not want grade category total items to be hidden away as it is controlled by something else.
875 if (!$element['object']->is_aggregate_item()) {
876 $collapsedicon = $OUTPUT->render_from_template('gradereport_grader/collapse/icon', $collapsecontext);
878 $headerlink = $this->gtree->get_element_header($element, true,
879 true, false, false, true, $sortlink);
881 $itemcell = new html_table_cell();
882 $itemcell->attributes['class'] = $type . ' ' . $catlevel .
883 ' highlightable'. ' i'. $element['object']->id;
884 $itemcell->attributes['data-itemid'] = $element['object']->id;
886 $singleview = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr, $this->baseurl);
887 $statusicons = $this->gtree->set_grade_status_icons($element);
888 if ($statusicons) {
889 $itemcell->attributes['class'] .= ' statusicons';
892 $itemcell->attributes['class'] .= $this->get_cell_display_class($element['object']);
894 $itemcell->colspan = $colspan;
895 $itemcell->header = true;
896 $itemcell->scope = 'col';
898 $context = new stdClass();
899 $context->headerlink = $headerlink;
900 $context->arrow = $arrow;
901 $context->singleview = $singleview;
902 $context->statusicons = $statusicons;
903 $context->collapsedicon = $collapsedicon;
905 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/headercell', $context);
907 $headingrow->cells[] = $itemcell;
910 $rows[] = $headingrow;
913 // Get all the grade items if the user can not view hidden grade items.
914 // It is possible that the user is simply viewing the 'Course total' by switching to the 'Aggregates only' view
915 // and that this user does not have the ability to view hidden items. In this case we still need to pass all the
916 // grade items (in case one has been hidden) as the course total shown needs to be adjusted for this particular
917 // user.
918 if (!$this->canviewhidden) {
919 $allgradeitems = $this->get_allgradeitems();
922 foreach ($this->users as $userid => $user) {
924 if ($this->canviewhidden) {
925 $altered = [];
926 $unknown = [];
927 } else {
928 $usergrades = $this->allgrades[$userid];
929 $hidingaffected = grade_grade::get_hiding_affected($usergrades, $allgradeitems);
930 $altered = $hidingaffected['altered'];
931 $unknown = $hidingaffected['unknowngrades'];
932 unset($hidingaffected);
935 $itemrow = new html_table_row();
936 $itemrow->id = 'user_'.$userid;
938 $fullname = fullname($user, $viewfullnames);
940 foreach ($this->gtree->items as $itemid => $unused) {
941 $item =& $this->gtree->items[$itemid];
942 $grade = $this->grades[$userid][$item->id];
944 $itemcell = new html_table_cell();
946 $itemcell->id = 'u' . $userid . 'i' . $itemid;
947 $itemcell->attributes['data-itemid'] = $itemid;
948 $itemcell->attributes['class'] = 'gradecell';
950 // Get the decimal points preference for this item.
951 $decimalpoints = $item->get_decimals();
953 if (array_key_exists($itemid, $unknown)) {
954 $gradeval = null;
955 } else if (array_key_exists($itemid, $altered)) {
956 $gradeval = $altered[$itemid];
957 } else {
958 $gradeval = $grade->finalgrade;
961 $context = new stdClass();
963 // MDL-11274: Hide grades in the grader report if the current grader
964 // doesn't have 'moodle/grade:viewhidden'.
965 if (!$this->canviewhidden && $grade->is_hidden()) {
966 if (!empty($CFG->grade_hiddenasdate) && $grade->get_datesubmitted()
967 && !$item->is_category_item() && !$item->is_course_item()) {
968 // The problem here is that we do not have the time when grade value was modified,
969 // 'timemodified' is general modification date for grade_grades records.
970 $context->text = userdate($grade->get_datesubmitted(), $strftimedatetimeshort);
971 $context->extraclasses = 'datesubmitted';
972 } else {
973 $context->text = '-';
975 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/cell', $context);
976 $itemrow->cells[] = $itemcell;
977 continue;
980 // Emulate grade element.
981 $eid = $this->gtree->get_grade_eid($grade);
982 $element = ['eid' => $eid, 'object' => $grade, 'type' => 'grade'];
984 $itemcell->attributes['class'] .= ' grade i' . $itemid;
985 if ($item->is_category_item()) {
986 $itemcell->attributes['class'] .= ' cat';
988 if ($item->is_course_item()) {
989 $itemcell->attributes['class'] .= ' course';
991 if ($grade->is_overridden()) {
992 $itemcell->attributes['class'] .= ' overridden';
993 $itemcell->attributes['aria-label'] = $stroverridengrade;
996 $hidden = '';
997 if ($grade->is_hidden()) {
998 $hidden = ' dimmed_text ';
1000 $gradepass = ' gradefail ';
1001 $context->gradepassicon = $OUTPUT->pix_icon('i/invalid', $strfail);
1002 if ($grade->is_passed($item)) {
1003 $gradepass = ' gradepass ';
1004 $context->gradepassicon = $OUTPUT->pix_icon('i/valid', $strpass);
1005 } else if (is_null($grade->is_passed($item))) {
1006 $gradepass = '';
1007 $context->gradepassicon = '';
1009 $context->statusicons = $this->gtree->set_grade_status_icons($element);
1011 // If in editing mode, we need to print either a text box or a drop down (for scales)
1012 // grades in item of type grade category or course are not directly editable.
1013 if ($item->needsupdate) {
1014 $context->text = $strerror;
1015 $context->extraclasses = 'gradingerror';
1016 } else if (!empty($USER->editing)) {
1017 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1018 $itemcell->attributes['class'] .= ' grade_type_scale';
1019 } else if ($item->gradetype == GRADE_TYPE_VALUE) {
1020 $itemcell->attributes['class'] .= ' grade_type_value';
1021 } else if ($item->gradetype == GRADE_TYPE_TEXT) {
1022 $itemcell->attributes['class'] .= ' grade_type_text';
1025 if ($grade->is_locked()) {
1026 $itemcell->attributes['class'] .= ' locked';
1029 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1030 $context->scale = true;
1032 $scale = $scalesarray[$item->scaleid];
1033 $gradeval = (int)$gradeval; // Scales use only integers.
1034 $scales = explode(",", $scale->scale);
1035 // Reindex because scale is off 1.
1037 // MDL-12104 some previous scales might have taken up part of the array
1038 // so this needs to be reset.
1039 $scaleopt = [];
1040 $i = 0;
1041 foreach ($scales as $scaleoption) {
1042 $i++;
1043 $scaleopt[$i] = $scaleoption;
1046 if ($quickgrading && $grade->is_editable()) {
1047 $context->iseditable = true;
1048 if (empty($item->outcomeid)) {
1049 $nogradestr = \grade_helper::get_lang_string('nograde');
1050 } else {
1051 $nogradestr = \grade_helper::get_lang_string('nooutcome', 'grades');
1053 $attributes = [
1054 'id' => 'grade_' . $userid . '_' . $item->id
1056 $gradelabel = $fullname . ' ' . $item->get_name(true);
1058 if ($context->statusicons) {
1059 $attributes['class'] = 'statusicons';
1062 $context->label = html_writer::label(
1063 get_string('useractivitygrade', 'gradereport_grader', $gradelabel),
1064 $attributes['id'], false, ['class' => 'accesshide']);
1065 $context->select = html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']',
1066 $gradeval, [-1 => $nogradestr], $attributes);
1067 } else if (!empty($scale)) {
1068 $scales = explode(",", $scale->scale);
1070 $context->extraclasses = 'gradevalue' . $hidden . $gradepass;
1071 // Invalid grade if gradeval < 1.
1072 if ($gradeval < 1) {
1073 $context->text = '-';
1074 } else {
1075 // Just in case somebody changes scale.
1076 $gradeval = $grade->grade_item->bounded_grade($gradeval);
1077 $context->text = $scales[$gradeval - 1];
1081 } else if ($item->gradetype != GRADE_TYPE_TEXT) {
1082 // Value type.
1083 if ($quickgrading and $grade->is_editable()) {
1084 $context->iseditable = true;
1086 // Set this input field with type="number" if the decimal separator for current language is set to
1087 // a period. Other decimal separators may not be recognised by browsers yet which may cause issues
1088 // when entering grades.
1089 $decsep = get_string('decsep', 'core_langconfig');
1090 $context->isnumeric = $decsep === '.';
1091 // If we're rendering this as a number field, set min/max attributes, if applicable.
1092 if ($context->isnumeric) {
1093 $context->minvalue = $item->grademin ?? null;
1094 $context->maxvalue = $item->grademax ?? null;
1097 $value = format_float($gradeval, $decimalpoints);
1098 $gradelabel = $fullname . ' ' . $item->get_name(true);
1100 $context->id = 'grade_' . $userid . '_' . $item->id;
1101 $context->name = 'grade[' . $userid . '][' . $item->id .']';
1102 $context->value = $value;
1103 $context->label = get_string('useractivitygrade', 'gradereport_grader', $gradelabel);
1104 $context->title = $strgrade;
1105 $context->extraclasses = 'form-control';
1106 if ($context->statusicons) {
1107 $context->extraclasses .= ' statusicons';
1109 } else {
1110 $context->extraclasses = 'gradevalue' . $hidden . $gradepass;
1111 $context->text = format_float($gradeval, $decimalpoints);
1115 } else {
1116 // Not editing.
1117 $gradedisplaytype = $item->get_displaytype();
1119 // Letter grades, scales and text grades are left aligned.
1120 $textgrade = false;
1121 $textgrades = [GRADE_DISPLAY_TYPE_LETTER,
1122 GRADE_DISPLAY_TYPE_REAL_LETTER,
1123 GRADE_DISPLAY_TYPE_LETTER_REAL,
1124 GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE,
1125 GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER];
1126 if (in_array($gradedisplaytype, $textgrades)) {
1127 $textgrade = true;
1130 if ($textgrade || ($item->gradetype == GRADE_TYPE_TEXT)) {
1131 $itemcell->attributes['class'] .= ' grade_type_text';
1132 } else if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1133 if ($gradedisplaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) {
1134 $itemcell->attributes['class'] .= ' grade_type_value';
1135 } else {
1136 $itemcell->attributes['class'] .= ' grade_type_scale';
1138 } else {
1139 $itemcell->attributes['class'] .= ' grade_type_value';
1142 if ($item->needsupdate) {
1143 $context->text = $strerror;
1144 $context->extraclasses = 'gradingerror' . $hidden . $gradepass;
1145 } else {
1146 // The max and min for an aggregation may be different to the grade_item.
1147 if (!is_null($gradeval)) {
1148 $item->grademax = $grade->get_grade_max();
1149 $item->grademin = $grade->get_grade_min();
1152 $context->extraclasses = 'gradevalue ' . $hidden . $gradepass;
1153 $context->text = grade_format_gradevalue($gradeval, $item, true,
1154 $gradedisplaytype, null);
1158 if ($item->gradetype == GRADE_TYPE_TEXT && !empty($grade->feedback)) {
1159 $context->text = html_writer::span(shorten_text(strip_tags($grade->feedback), 20), '',
1160 ['data-action' => 'feedback', 'role' => 'button', 'data-courseid' => $this->courseid]);
1163 if (!$item->needsupdate && !($item->gradetype == GRADE_TYPE_TEXT && empty($USER->editing))) {
1164 $context->actionmenu = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr);
1167 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/cell', $context);
1169 if (!empty($this->gradeserror[$item->id][$userid])) {
1170 $itemcell->text .= $this->gradeserror[$item->id][$userid];
1173 $itemrow->cells[] = $itemcell;
1175 $rows[] = $itemrow;
1178 if (!empty($USER->editing)) {
1179 $PAGE->requires->js_call_amd('core_form/changechecker',
1180 'watchFormById', ['gradereport_grader']);
1183 $rows = $this->get_right_range_row($rows);
1184 if ($displayaverages) {
1185 $rows = $this->get_right_avg_row($rows, true);
1186 $rows = $this->get_right_avg_row($rows);
1189 return $rows;
1193 * Depending on the style of report (fixedstudents vs traditional one-table),
1194 * arranges the rows of data in one or two tables, and returns the output of
1195 * these tables in HTML
1196 * @param boolean $displayaverages whether to display average rows in the table
1197 * @return string HTML
1199 public function get_grade_table($displayaverages = false) {
1200 global $OUTPUT;
1201 $leftrows = $this->get_left_rows($displayaverages);
1202 $rightrows = $this->get_right_rows($displayaverages);
1204 $html = '';
1206 $fulltable = new html_table();
1207 $fulltable->attributes['class'] = 'gradereport-grader-table d-none';
1208 $fulltable->id = 'user-grades';
1209 $fulltable->caption = get_string('summarygrader', 'gradereport_grader');
1210 $fulltable->captionhide = true;
1211 // We don't want the table to be enclosed within in a .table-responsive div as it is heavily customised.
1212 $fulltable->responsive = false;
1214 // Extract rows from each side (left and right) and collate them into one row each
1215 foreach ($leftrows as $key => $row) {
1216 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1217 $fulltable->data[] = $row;
1219 $html .= html_writer::table($fulltable);
1220 return $OUTPUT->container($html, 'gradeparent');
1224 * Builds and return the row of icons for the left side of the report.
1225 * It only has one cell that says "Controls"
1226 * @param array $rows The Array of rows for the left part of the report
1227 * @param int $colspan The number of columns this cell has to span
1228 * @return array Array of rows for the left part of the report
1229 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1230 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1232 public function get_left_icons_row($rows=array(), $colspan=1) {
1233 global $USER;
1235 debugging('The function get_left_icons_row() is deprecated, please do not use it anymore.',
1236 DEBUG_DEVELOPER);
1238 if (!empty($USER->editing)) {
1239 $controlsrow = new html_table_row();
1240 $controlsrow->attributes['class'] = 'controls';
1241 $controlscell = new html_table_cell();
1242 $controlscell->attributes['class'] = 'header controls';
1243 $controlscell->header = true;
1244 $controlscell->colspan = $colspan;
1245 $controlscell->text = \grade_helper::get_lang_string('controls', 'grades');
1246 $controlsrow->cells[] = $controlscell;
1248 $rows[] = $controlsrow;
1250 return $rows;
1254 * Builds and return the header for the row of ranges, for the left part of the grader report.
1255 * @param array $rows The Array of rows for the left part of the report
1256 * @param int $colspan The number of columns this cell has to span
1257 * @return array Array of rows for the left part of the report
1259 public function get_left_range_row($rows=array(), $colspan=1) {
1260 global $CFG, $USER;
1262 if ($this->get_pref('showranges')) {
1263 $rangerow = new html_table_row();
1264 $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1265 $rangecell = new html_table_cell();
1266 $rangecell->attributes['class'] = 'header range';
1267 $rangecell->colspan = $colspan;
1268 $rangecell->header = true;
1269 $rangecell->scope = 'row';
1270 $rangecell->text = \grade_helper::get_lang_string('range', 'grades');
1271 $rangerow->cells[] = $rangecell;
1272 $rows[] = $rangerow;
1275 return $rows;
1279 * Builds and return the headers for the rows of averages, for the left part of the grader report.
1280 * @param array $rows The Array of rows for the left part of the report
1281 * @param int $colspan The number of columns this cell has to span
1282 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1283 * @return array Array of rows for the left part of the report
1285 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1286 if (!$this->canviewhidden) {
1287 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1288 // better not show them at all if user can not see all hideen grades
1289 return $rows;
1292 $showaverages = $this->get_pref('showaverages');
1293 $showaveragesgroup = $this->currentgroup && $showaverages;
1294 $straveragegroup = get_string('groupavg', 'grades');
1296 if ($groupavg) {
1297 if ($showaveragesgroup) {
1298 $groupavgrow = new html_table_row();
1299 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1300 $groupavgcell = new html_table_cell();
1301 $groupavgcell->attributes['class'] = 'header range';
1302 $groupavgcell->colspan = $colspan;
1303 $groupavgcell->header = true;
1304 $groupavgcell->scope = 'row';
1305 $groupavgcell->text = $straveragegroup;
1306 $groupavgrow->cells[] = $groupavgcell;
1307 $rows[] = $groupavgrow;
1309 } else {
1310 $straverage = get_string('overallaverage', 'grades');
1312 if ($showaverages) {
1313 $avgrow = new html_table_row();
1314 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1315 $avgcell = new html_table_cell();
1316 $avgcell->attributes['class'] = 'header range';
1317 $avgcell->colspan = $colspan;
1318 $avgcell->header = true;
1319 $avgcell->scope = 'row';
1320 $avgcell->text = $straverage;
1321 $avgrow->cells[] = $avgcell;
1322 $rows[] = $avgrow;
1326 return $rows;
1330 * Builds and return the row of icons when editing is on, for the right part of the grader report.
1331 * @param array $rows The Array of rows for the right part of the report
1332 * @return array Array of rows for the right part of the report
1333 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1334 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1336 public function get_right_icons_row($rows=array()) {
1337 global $USER;
1338 debugging('The function get_right_icons_row() is deprecated, please do not use it anymore.',
1339 DEBUG_DEVELOPER);
1341 if (!empty($USER->editing)) {
1342 $iconsrow = new html_table_row();
1343 $iconsrow->attributes['class'] = 'controls';
1345 foreach ($this->gtree->items as $itemid => $unused) {
1346 // emulate grade element
1347 $item = $this->gtree->get_item($itemid);
1349 $eid = $this->gtree->get_item_eid($item);
1350 $element = $this->gtree->locate_element($eid);
1351 $itemcell = new html_table_cell();
1352 $itemcell->attributes['class'] = 'controls icons i'.$itemid;
1353 $itemcell->text = $this->get_icons($element);
1354 $iconsrow->cells[] = $itemcell;
1356 $rows[] = $iconsrow;
1358 return $rows;
1362 * Builds and return the row of ranges for the right part of the grader report.
1363 * @param array $rows The Array of rows for the right part of the report
1364 * @return array Array of rows for the right part of the report
1366 public function get_right_range_row($rows=array()) {
1368 if ($this->get_pref('showranges')) {
1369 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
1370 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1371 $rangerow = new html_table_row();
1372 $rangerow->attributes['class'] = 'heading range';
1374 foreach ($this->gtree->items as $itemid => $unused) {
1375 $item =& $this->gtree->items[$itemid];
1376 $itemcell = new html_table_cell();
1377 $itemcell->attributes['class'] .= ' range i'. $itemid;
1378 $itemcell->attributes['class'] .= $this->get_cell_display_class($item);
1380 $hidden = '';
1381 if ($item->is_hidden()) {
1382 $hidden = ' dimmed_text ';
1385 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1387 $itemcell->attributes['data-itemid'] = $itemid;
1388 $itemcell->text = html_writer::div($formattedrange, 'rangevalues' . $hidden,
1389 ['data-collapse' => 'rangerowcell']);
1390 $rangerow->cells[] = $itemcell;
1392 $rows[] = $rangerow;
1394 return $rows;
1398 * Builds and return the row of averages for the right part of the grader report.
1399 * @param array $rows Whether to return only group averages or all averages.
1400 * @param bool $grouponly Whether to return only group averages or all averages.
1401 * @return array Array of rows for the right part of the report
1403 public function get_right_avg_row($rows=array(), $grouponly=false) {
1404 global $USER, $DB, $OUTPUT, $CFG;
1405 if (!$this->canviewhidden) {
1406 // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1407 // better not show them at all if user can not see all hidden grades.
1408 return $rows;
1411 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
1412 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1413 $meanselection = $this->get_pref('meanselection');
1414 $shownumberofgrades = $this->get_pref('shownumberofgrades');
1416 if ($grouponly) {
1417 $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1418 $groupsql = $this->groupsql;
1419 $groupwheresql = $this->groupwheresql;
1420 $groupwheresqlparams = $this->groupwheresql_params;
1421 } else {
1422 $showaverages = $this->get_pref('showaverages');
1423 $groupsql = "";
1424 $groupwheresql = "";
1425 $groupwheresqlparams = array();
1428 if ($showaverages) {
1429 $totalcount = $this->get_numusers($grouponly);
1431 // Limit to users with a gradeable role.
1432 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1434 // Limit to users with an active enrollment.
1435 $coursecontext = $this->context->get_course_context(true);
1436 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
1437 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
1438 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
1439 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
1441 // We want to query both the current context and parent contexts.
1442 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
1444 $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams);
1446 // Find sums of all grade items in course.
1447 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1448 FROM {grade_items} gi
1449 JOIN {grade_grades} g ON g.itemid = gi.id
1450 JOIN {user} u ON u.id = g.userid
1451 JOIN ($enrolledsql) je ON je.id = u.id
1452 JOIN (
1453 SELECT DISTINCT ra.userid
1454 FROM {role_assignments} ra
1455 WHERE ra.roleid $gradebookrolessql
1456 AND ra.contextid $relatedctxsql
1457 ) rainner ON rainner.userid = u.id
1458 $groupsql
1459 WHERE gi.courseid = :courseid
1460 AND u.deleted = 0
1461 AND g.finalgrade IS NOT NULL
1462 $groupwheresql
1463 GROUP BY g.itemid";
1464 $sumarray = array();
1465 if ($sums = $DB->get_records_sql($sql, $params)) {
1466 foreach ($sums as $itemid => $csum) {
1467 $sumarray[$itemid] = $csum->sum;
1471 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1472 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1473 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1474 FROM {grade_items} gi
1475 CROSS JOIN ($enrolledsql) u
1476 JOIN {role_assignments} ra
1477 ON ra.userid = u.id
1478 LEFT OUTER JOIN {grade_grades} g
1479 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1480 $groupsql
1481 WHERE gi.courseid = :courseid
1482 AND ra.roleid $gradebookrolessql
1483 AND ra.contextid $relatedctxsql
1484 AND g.id IS NULL
1485 $groupwheresql
1486 GROUP BY gi.id";
1488 $ungradedcounts = $DB->get_records_sql($sql, $params);
1490 $avgrow = new html_table_row();
1491 $avgrow->attributes['class'] = 'avg';
1493 foreach ($this->gtree->items as $itemid => $unused) {
1494 $item =& $this->gtree->items[$itemid];
1496 if ($item->needsupdate) {
1497 $avgcell = new html_table_cell();
1498 $avgcell->attributes['class'] = 'i'. $itemid;
1499 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1500 $avgrow->cells[] = $avgcell;
1501 continue;
1504 if (!isset($sumarray[$item->id])) {
1505 $sumarray[$item->id] = 0;
1508 if (empty($ungradedcounts[$itemid])) {
1509 $ungradedcount = 0;
1510 } else {
1511 $ungradedcount = $ungradedcounts[$itemid]->count;
1514 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1515 $meancount = $totalcount - $ungradedcount;
1516 } else { // Bump up the sum by the number of ungraded items * grademin
1517 $sumarray[$item->id] += $ungradedcount * $item->grademin;
1518 $meancount = $totalcount;
1521 // Determine which display type to use for this average
1522 if (!empty($USER->editing)) {
1523 $displaytype = GRADE_DISPLAY_TYPE_REAL;
1525 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1526 $displaytype = $item->get_displaytype();
1528 } else {
1529 $displaytype = $averagesdisplaytype;
1532 // Override grade_item setting if a display preference (not inherit) was set for the averages
1533 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1534 $decimalpoints = $item->get_decimals();
1536 } else {
1537 $decimalpoints = $averagesdecimalpoints;
1540 $gradetypeclass = $this->get_cell_display_class($item);
1542 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1543 $avgcell = new html_table_cell();
1544 $avgcell->attributes['class'] = $gradetypeclass . ' i'. $itemid;
1545 $avgcell->attributes['data-itemid'] = $itemid;
1546 $avgcell->text = html_writer::div('-', '', ['data-collapse' => 'avgrowcell']);
1547 $avgrow->cells[] = $avgcell;
1548 } else {
1549 $sum = $sumarray[$item->id];
1550 $avgradeval = $sum/$meancount;
1551 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1553 $numberofgrades = '';
1554 if ($shownumberofgrades) {
1555 $numberofgrades = " ($meancount)";
1558 $avgcell = new html_table_cell();
1559 $avgcell->attributes['class'] = $gradetypeclass . ' i'. $itemid;
1560 $avgcell->attributes['data-itemid'] = $itemid;
1561 $avgcell->text = html_writer::div($gradehtml.$numberofgrades, '', ['data-collapse' => 'avgrowcell']);
1562 $avgrow->cells[] = $avgcell;
1565 $rows[] = $avgrow;
1567 return $rows;
1571 * Given element category, create a collapsible icon and
1572 * course header.
1574 * @param array $element
1575 * @return string HTML
1577 protected function get_course_header($element) {
1578 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1579 $showing = get_string('showingaggregatesonly', 'grades');
1580 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1581 $showing = get_string('showinggradesonly', 'grades');
1582 } else {
1583 $showing = get_string('showingfullmode', 'grades');
1586 $name = $element['object']->get_name();
1587 $nameunescaped = $element['object']->get_name(false);
1588 $describedbyid = uniqid();
1589 $courseheader = html_writer::tag('span', $name, [
1590 'title' => $nameunescaped,
1591 'class' => 'gradeitemheader',
1592 'aria-describedby' => $describedbyid
1594 $courseheader .= html_writer::div($showing, 'sr-only', [
1595 'id' => $describedbyid
1598 return $courseheader;
1602 * Given a grade_category, grade_item or grade_grade, this function
1603 * figures out the state of the object and builds then returns a div
1604 * with the icons needed for the grader report.
1606 * @param array $element
1607 * @return string HTML
1608 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1609 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1611 protected function get_icons($element) {
1612 global $CFG, $USER, $OUTPUT;
1613 debugging('The function get_icons() is deprecated, please do not use it anymore.',
1614 DEBUG_DEVELOPER);
1616 if (empty($USER->editing)) {
1617 return '<div class="grade_icons" />';
1620 // Init all icons
1621 $editicon = '';
1623 $editable = true;
1625 if ($element['type'] == 'grade') {
1626 $item = $element['object']->grade_item;
1627 if ($item->is_course_item() or $item->is_category_item()) {
1628 $editable = $this->overridecat;
1632 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) {
1633 $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1636 $editcalculationicon = '';
1637 $showhideicon = '';
1638 $lockunlockicon = '';
1640 if (has_capability('moodle/grade:manage', $this->context)) {
1641 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1643 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1645 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1648 $gradeanalysisicon = '';
1649 if ($element['type'] == 'grade') {
1650 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
1653 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
1657 * Given a category element returns collapsing +/- icon if available
1659 * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more.
1661 protected function get_collapsing_icon($element) {
1662 throw new coding_exception('get_collapsing_icon() can not be used any more, please use get_course_header() instead.');
1666 * Processes a single action against a category, grade_item or grade.
1667 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1668 * @param string $action Which action to take (edit, delete etc...)
1669 * @return
1671 public function process_action($target, $action) {
1672 return self::do_process_action($target, $action, $this->course->id);
1676 * From the list of categories that this user prefers to collapse choose ones that belong to the current course.
1678 * This function serves two purposes.
1679 * Mainly it helps migrating from user preference style when all courses were stored in one preference.
1680 * Also it helps to remove the settings for categories that were removed if the array for one course grows too big.
1682 * @param int $courseid
1683 * @param array $collapsed
1684 * @return array
1686 protected static function filter_collapsed_categories($courseid, $collapsed) {
1687 global $DB;
1688 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1689 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? [];
1690 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? [];
1692 if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) {
1693 return $collapsed;
1695 $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid));
1696 $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats));
1697 $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats));
1698 return $collapsed;
1702 * Returns the list of categories that this user wants to collapse or display aggregatesonly
1704 * This method also migrates on request from the old format of storing user preferences when they were stored
1705 * in one preference for all courses causing DB error when trying to insert very big value.
1707 * @param int $courseid
1708 * @return array
1710 protected static function get_collapsed_preferences($courseid) {
1711 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) {
1712 $collapsed = json_decode($collapsed, true);
1713 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1714 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? [];
1715 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? [];
1716 return $collapsed;
1719 // Try looking for old location of user setting that used to store all courses in one serialized user preference.
1720 $collapsed = ['aggregatesonly' => [], 'gradesonly' => []]; // Use this if old settings are not found.
1721 $collapsedall = [];
1722 $oldprefexists = false;
1723 if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) {
1724 $oldprefexists = true;
1725 if ($collapsedall = unserialize_array($oldcollapsedpref)) {
1726 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1727 $collapsedall['aggregatesonly'] = $collapsedall['aggregatesonly'] ?? [];
1728 $collapsedall['gradesonly'] = $collapsedall['gradesonly'] ?? [];
1729 // We found the old-style preference, filter out only categories that belong to this course and update the prefs.
1730 $collapsed = static::filter_collapsed_categories($courseid, $collapsedall);
1731 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1732 static::set_collapsed_preferences($courseid, $collapsed);
1733 $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']);
1734 $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']);
1735 if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) {
1736 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall));
1742 // Arrived here, if the old pref exists and it doesn't contain
1743 // more information, it means that the migration of all the
1744 // data to new, by course, preferences is completed, so
1745 // the old one can be safely deleted.
1746 if ($oldprefexists &&
1747 empty($collapsedall['aggregatesonly']) &&
1748 empty($collapsedall['gradesonly'])) {
1749 unset_user_preference('grade_report_grader_collapsed_categories');
1752 return $collapsed;
1756 * Sets the list of categories that user wants to see collapsed in user preferences
1758 * This method may filter or even trim the list if it does not fit in DB field.
1760 * @param int $courseid
1761 * @param array $collapsed
1763 protected static function set_collapsed_preferences($courseid, $collapsed) {
1764 global $DB;
1765 // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size,
1766 // try to filter the list of categories since array may contain categories that were deleted.
1767 if (strlen(json_encode($collapsed)) >= 1333) {
1768 $collapsed = static::filter_collapsed_categories($courseid, $collapsed);
1771 // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information.
1772 while (strlen(json_encode($collapsed)) >= 1333) {
1773 if (count($collapsed['aggregatesonly'])) {
1774 array_pop($collapsed['aggregatesonly']);
1776 if (count($collapsed['gradesonly'])) {
1777 array_pop($collapsed['gradesonly']);
1781 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1782 set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed));
1783 } else {
1784 unset_user_preference('grade_report_grader_collapsed_categories'.$courseid);
1789 * Processes a single action against a category, grade_item or grade.
1790 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1791 * @param string $action Which action to take (edit, delete etc...)
1792 * @param int $courseid affected course.
1793 * @return
1795 public static function do_process_action($target, $action, $courseid = null) {
1796 global $DB;
1797 // TODO: this code should be in some grade_tree static method
1798 $targettype = substr($target, 0, 2);
1799 $targetid = substr($target, 2);
1800 // TODO: end
1802 if ($targettype !== 'cg') {
1803 // The following code only works with categories.
1804 return true;
1807 if (!$courseid) {
1808 debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid',
1809 DEBUG_DEVELOPER);
1810 if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) {
1811 return true;
1815 $collapsed = static::get_collapsed_preferences($courseid);
1817 switch ($action) {
1818 case 'switch_minus': // Add category to array of aggregatesonly
1819 $key = array_search($targetid, $collapsed['gradesonly']);
1820 if ($key !== false) {
1821 unset($collapsed['gradesonly'][$key]);
1823 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1824 $collapsed['aggregatesonly'][] = $targetid;
1825 static::set_collapsed_preferences($courseid, $collapsed);
1827 break;
1829 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1830 $key = array_search($targetid, $collapsed['aggregatesonly']);
1831 if ($key !== false) {
1832 unset($collapsed['aggregatesonly'][$key]);
1834 if (!in_array($targetid, $collapsed['gradesonly'])) {
1835 $collapsed['gradesonly'][] = $targetid;
1837 static::set_collapsed_preferences($courseid, $collapsed);
1838 break;
1839 case 'switch_whole': // Remove the category from the array of collapsed cats
1840 $key = array_search($targetid, $collapsed['gradesonly']);
1841 if ($key !== false) {
1842 unset($collapsed['gradesonly'][$key]);
1843 static::set_collapsed_preferences($courseid, $collapsed);
1846 $key = array_search($targetid, $collapsed['aggregatesonly']);
1847 if ($key !== false) {
1848 unset($collapsed['aggregatesonly'][$key]);
1849 static::set_collapsed_preferences($courseid, $collapsed);
1851 break;
1852 default:
1853 break;
1856 return true;
1860 * Refactored function for generating HTML of sorting links with matching arrows.
1861 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1862 * to inject into a table header cell.
1863 * @param array $extrafields Array of extra fields being displayed, such as
1864 * user idnumber
1865 * @return array An associative array of HTML sorting links+arrows
1867 public function get_sort_arrows(array $extrafields = []) {
1868 global $CFG;
1869 $arrows = array();
1870 $sortlink = clone($this->baseurl);
1872 // Sourced from tablelib.php
1873 // Check the full name display for sortable fields.
1874 if (has_capability('moodle/site:viewfullnames', $this->context)) {
1875 $nameformat = $CFG->alternativefullnameformat;
1876 } else {
1877 $nameformat = $CFG->fullnamedisplay;
1880 if ($nameformat == 'language') {
1881 $nameformat = get_string('fullnamedisplay');
1884 $arrows['studentname'] = '';
1885 $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat);
1886 if (!empty($requirednames)) {
1887 foreach ($requirednames as $name) {
1888 $arrows['studentname'] .= html_writer::link(
1889 new moodle_url($this->baseurl, array('sortitemid' => $name)), \grade_helper::get_lang_string($name)
1891 if ($this->sortitemid == $name) {
1892 $sortlink->param('sortitemid', $name);
1893 if ($this->sortorder == 'ASC') {
1894 $sorticon = $this->get_sort_arrow('down', $sortlink);
1895 } else {
1896 $sorticon = $this->get_sort_arrow('up', $sortlink);
1898 $arrows['studentname'] .= $sorticon;
1900 $arrows['studentname'] .= ' / ';
1903 $arrows['studentname'] = substr($arrows['studentname'], 0, -3);
1906 foreach ($extrafields as $field) {
1907 $attributes = [
1908 'data-collapse' => 'content'
1910 // With additional user profile fields, we can't grab the name via WS, so conditionally add it to rip out of the DOM.
1911 if (preg_match(\core_user\fields::PROFILE_FIELD_REGEX, $field)) {
1912 $attributes['data-collapse-name'] = \core_user\fields::get_display_name($field);
1914 $fieldlink = html_writer::link(new moodle_url($this->baseurl, ['sortitemid' => $field]),
1915 \core_user\fields::get_display_name($field), $attributes);
1916 $arrows[$field] = $fieldlink;
1918 if ($field == $this->sortitemid) {
1919 $sortlink->param('sortitemid', $field);
1921 if ($this->sortorder == 'ASC') {
1922 $sorticon = $this->get_sort_arrow('down', $sortlink);
1923 } else {
1924 $sorticon = $this->get_sort_arrow('up', $sortlink);
1926 $arrows[$field] .= $sorticon;
1930 return $arrows;
1934 * Returns the maximum number of students to be displayed on each page
1936 * @return int The maximum number of students to display per page
1938 public function get_students_per_page(): int {
1939 // Default to the lowest available option.
1940 return (int) get_user_preferences('grade_report_studentsperpage', min(static::PAGINATION_OPTIONS));
1944 * Returns link to change category view mode.
1946 * @param moodle_url $url Url to grader report page
1947 * @param string $title Menu item title
1948 * @param string $action View mode to change to
1949 * @param bool $active Whether link is active in dropdown
1951 * @return string|null
1953 public function get_category_view_mode_link(moodle_url $url, string $title, string $action, bool $active = false): ?string {
1954 $urlnew = $url;
1955 $urlnew->param('action', $action);
1956 $active = $active ? 'true' : 'false';
1957 return html_writer::link($urlnew, $title,
1958 ['class' => 'dropdown-item', 'aria-label' => $title, 'aria-current' => $active, 'role' => 'menuitem']);
1962 * Return the link to allow the field to collapse from the users view.
1964 * @return string Dropdown menu link that'll trigger the collapsing functionality.
1965 * @throws coding_exception
1966 * @throws moodle_exception
1968 public function get_hide_show_link(): string {
1969 $link = new moodle_url('#', []);
1970 return html_writer::link(
1971 $link->out(false),
1972 get_string('collapse'),
1973 ['class' => 'dropdown-item', 'data-hider' => 'hide', 'aria-label' => get_string('collapse'), 'role' => 'menuitem'],
1978 * Return the base report link with some default sorting applied.
1980 * @return string
1981 * @throws moodle_exception
1983 public function get_default_sortable(): string {
1984 $sortlink = new moodle_url('/grade/report/grader/index.php', [
1985 'id' => $this->courseid,
1986 'sortitemid' => 'firstname',
1987 'sort' => 'asc'
1989 $this->gpr->add_url_params($sortlink);
1990 return $sortlink->out(false);
1994 * Return class used for text alignment.
1996 * @param grade_item $item Can be grade item or grade
1997 * @return string class name used for text alignment
1999 public function get_cell_display_class(grade_item $item): string {
2000 global $USER;
2002 $gradetypeclass = '';
2003 if (!empty($USER->editing)) {
2004 switch ($item->gradetype) {
2005 case GRADE_TYPE_SCALE:
2006 $gradetypeclass = ' grade_type_scale';
2007 break;
2008 case GRADE_TYPE_VALUE:
2009 $gradetypeclass = ' grade_type_value';
2010 break;
2011 case GRADE_TYPE_TEXT:
2012 $gradetypeclass = ' grade_type_text';
2013 break;
2015 } else {
2016 $gradedisplaytype = $item->get_displaytype();
2018 // Letter grades, scales and text grades are left aligned.
2019 $textgrade = false;
2020 $textgrades = [GRADE_DISPLAY_TYPE_LETTER,
2021 GRADE_DISPLAY_TYPE_REAL_LETTER,
2022 GRADE_DISPLAY_TYPE_LETTER_REAL,
2023 GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE,
2024 GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER];
2025 if (in_array($gradedisplaytype, $textgrades)) {
2026 $textgrade = true;
2029 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'gradereport_grader', 'scales');
2030 $scalesarray = $cache->get(get_class($this));
2032 if ($textgrade || ($item->gradetype == GRADE_TYPE_TEXT)) {
2033 $gradetypeclass = ' grade_type_text';
2034 } else if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
2035 if ($gradedisplaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) {
2036 $gradetypeclass = ' grade_type_value';
2037 } else {
2038 $gradetypeclass = ' grade_type_scale';
2040 } else {
2041 $gradetypeclass = ' grade_type_value';
2044 return $gradetypeclass;
2049 * Adds report specific context variable
2051 * @param context_course $context Course context
2052 * @param int $courseid Course ID
2053 * @param array $element An array representing an element in the grade_tree
2054 * @param grade_plugin_return $gpr A grade_plugin_return object
2055 * @param string $mode Not used
2056 * @param stdClass|null $templatecontext Template context
2057 * @return stdClass|null
2059 function gradereport_grader_get_report_link(context_course $context, int $courseid,
2060 array $element, grade_plugin_return $gpr, string $mode, ?stdClass $templatecontext): ?stdClass {
2062 static $report = null;
2063 if (!$report) {
2064 $report = new grade_report_grader($courseid, $gpr, $context);
2067 if ($mode == 'category') {
2068 if (!isset($templatecontext)) {
2069 $templatecontext = new stdClass();
2072 $categoryid = $element['object']->id;
2074 // Load language strings.
2075 $strswitchminus = grade_helper::get_lang_string('aggregatesonly', 'grades');
2076 $strswitchplus = grade_helper::get_lang_string('gradesonly', 'grades');
2077 $strswitchwhole = grade_helper::get_lang_string('fullmode', 'grades');
2079 $url = new moodle_url($gpr->get_return_url(null, ['target' => $element['eid'], 'sesskey' => sesskey()]));
2081 $gradesonly = false;
2082 $aggregatesonly = false;
2083 $fullmode = false;
2084 if (in_array($categoryid, $report->collapsed['gradesonly'])) {
2085 $gradesonly = true;
2086 } else if (in_array($categoryid, $report->collapsed['aggregatesonly'])) {
2087 $aggregatesonly = true;
2088 } else {
2089 $fullmode = true;
2091 $templatecontext->gradesonlyurl =
2092 $report->get_category_view_mode_link($url, $strswitchplus, 'switch_plus', $gradesonly);
2093 $templatecontext->aggregatesonlyurl =
2094 $report->get_category_view_mode_link($url, $strswitchminus, 'switch_minus', $aggregatesonly);
2095 $templatecontext->fullmodeurl =
2096 $report->get_category_view_mode_link($url, $strswitchwhole, 'switch_whole', $fullmode);
2097 return $templatecontext;
2098 } else if ($mode == 'gradeitem') {
2099 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) {
2100 $templatecontext->columncollapse = $report->get_hide_show_link();
2101 $templatecontext->dataid = $element['name'];
2104 // We do not want grade category total items to be hidden away as it is controlled by something else.
2105 if (isset($element['object']->id) && !$element['object']->is_aggregate_item()) {
2106 $templatecontext->columncollapse = $report->get_hide_show_link();
2108 return $templatecontext;
2110 return null;