Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [Versions 402 and 403]
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. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17 /** 18 * Definition of the grader report class 19 * 20 * @package gradereport_grader 21 * @copyright 2007 Nicolas Connault 22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 */ 24 25 require_once($CFG->dirroot . '/grade/report/lib.php'); 26 require_once($CFG->libdir.'/tablelib.php'); 27 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 33 */ 34 class grade_report_grader extends grade_report { 35 /** 36 * The final grades. 37 * @var array $grades 38 */ 39 public $grades; 40 41 /** 42 * Contains all the grades for the course - even the ones not displayed in the grade tree. 43 * 44 * @var array $allgrades 45 */ 46 private $allgrades; 47 48 /** 49 * Contains all grade items expect GRADE_TYPE_NONE. 50 * 51 * @var array $allgradeitems 52 */ 53 private $allgradeitems; 54 55 /** 56 * Array of errors for bulk grades updating. 57 * @var array $gradeserror 58 */ 59 public $gradeserror = array(); 60 61 // SQL-RELATED 62 63 /** 64 * The id of the grade_item by which this report will be sorted. 65 * @var int $sortitemid 66 */ 67 public $sortitemid; 68 69 /** 70 * Sortorder used in the SQL selections. 71 * @var int $sortorder 72 */ 73 public $sortorder; 74 75 /** 76 * An SQL fragment affecting the search for users. 77 * @var string $userselect 78 */ 79 public $userselect; 80 81 /** 82 * The bound params for $userselect 83 * @var array $userselectparams 84 */ 85 public $userselectparams = array(); 86 87 /** 88 * List of collapsed categories from user preference 89 * @var array $collapsed 90 */ 91 public $collapsed; 92 93 /** 94 * A count of the rows, used for css classes. 95 * @var int $rowcount 96 */ 97 public $rowcount = 0; 98 99 /** 100 * Capability check caching 101 * @var boolean $canviewhidden 102 */ 103 public $canviewhidden; 104 105 /** @var int Maximum number of students that can be shown on one page */ 106 public const MAX_STUDENTS_PER_PAGE = 5000; 107 108 /** @var int[] List of available options on the pagination dropdown */ 109 public const PAGINATION_OPTIONS = [20, 100]; 110 111 /** 112 * Allow category grade overriding 113 * @var bool $overridecat 114 */ 115 protected $overridecat; 116 117 /** @var array of objects, or empty array if no records were found. */ 118 protected $users = []; 119 120 /** 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 128 */ 129 public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null, string $sort = '') { 130 global $CFG; 131 parent::__construct($courseid, $gpr, $context, $page); 132 133 $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->course->id)); 134 135 // load collapsed settings for this report 136 $this->collapsed = static::get_collapsed_preferences($this->course->id); 137 138 if (empty($CFG->enableoutcomes)) { 139 $nooutcomes = false; 140 } else { 141 $nooutcomes = get_user_preferences('grade_report_shownooutcomes'); 142 } 143 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); 148 } 149 150 // Grab the grade_tree for this course 151 $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes); 152 153 $this->sortitemid = $sortitemid; 154 155 // base url for sorting by first/last name 156 157 $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid)); 158 159 $studentsperpage = $this->get_students_per_page(); 160 if (!empty($this->page) && !empty($studentsperpage)) { 161 $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page)); 162 } 163 164 $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid)); 165 166 $this->setup_groups(); 167 $this->setup_users(); 168 $this->setup_sortitemid($sort); 169 170 $this->overridecat = (bool)get_config('moodle', 'grade_overridecat'); 171 } 172 173 /** 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. 178 */ 179 public function process_data($data) { 180 global $DB; 181 $warnings = array(); 182 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); 194 } 195 } 196 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context); 197 198 // always initialize all arrays 199 $queue = array(); 200 201 $this->load_users(); 202 $this->load_final_grades(); 203 204 // Were any changes made? 205 $changedgrades = false; 206 $timepageload = clean_param($data->timepageload, PARAM_INT); 207 208 foreach ($data as $varname => $students) { 209 210 $needsupdate = false; 211 212 // Skip, not a grade. 213 if (strpos($varname, 'grade') === 0) { 214 $datatype = 'grade'; 215 } else { 216 continue; 217 } 218 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); 223 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; 231 } 232 233 // If the grade item uses a custom scale 234 if (!empty($oldvalue->grade_item->scaleid)) { 235 236 if ((int)$oldvalue->finalgrade === (int)$postedvalue) { 237 continue; 238 } 239 } else { 240 // The grade item uses a numeric scale 241 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; 245 } 246 } 247 248 $changedgrades = true; 249 } 250 251 if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { 252 throw new \moodle_exception('invalidgradeitemid'); 253 } 254 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; 262 } 263 } else { 264 $finalgrade = unformat_float($postedvalue); 265 } 266 267 $errorstr = ''; 268 $skip = false; 269 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'; 282 } 283 } 284 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; 296 } 297 } 298 } 299 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; 309 } 310 } 311 if (!$sharinggroup) { 312 // either group membership changed or somebody is hacking grades of other group 313 $warnings[] = get_string('errorsavegrade', 'grades'); 314 continue; 315 } 316 } 317 318 $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', false, 319 FORMAT_MOODLE, null, null, true); 320 } 321 } 322 } 323 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; 327 } 328 329 return $warnings; 330 } 331 332 333 /** 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. 337 338 * @param string $sort sorting direction 339 */ 340 private function setup_sortitemid(string $sort = '') { 341 342 global $SESSION; 343 344 if (!isset($SESSION->gradeuserreport)) { 345 $SESSION->gradeuserreport = new stdClass(); 346 } 347 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'; 361 } 362 } else { 363 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC'; 364 } 365 } 366 $SESSION->gradeuserreport->sortitemid = $this->sortitemid; 367 } else { 368 // not requesting sort, use last setting (for paging) 369 370 if (isset($SESSION->gradeuserreport->sortitemid)) { 371 $this->sortitemid = $SESSION->gradeuserreport->sortitemid; 372 } else { 373 $this->sortitemid = 'lastname'; 374 } 375 376 if (isset($SESSION->gradeuserreport->sort)) { 377 $this->sortorder = $SESSION->gradeuserreport->sort; 378 } else { 379 $this->sortorder = 'ASC'; 380 } 381 } 382 383 // If explicit sorting direction exists. 384 if ($sort) { 385 $this->sortorder = $sort; 386 $SESSION->gradeuserreport->sort = $sort; 387 } 388 } 389 390 /** 391 * pulls out the userids of the users to be display, and sorts them 392 * 393 * @param bool $allusers If we are getting the users within the report, we want them all irrespective of paging. 394 */ 395 public function load_users(bool $allusers = false) { 396 global $CFG, $DB; 397 398 if (!empty($this->users)) { 399 return; 400 } 401 $this->setup_users(); 402 403 // Limit to users with a gradeable role. 404 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0'); 405 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); 411 412 // Limit to users with an active enrollment. 413 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol); 414 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); 418 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'); 421 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); 426 427 $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid"; 428 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); 433 } 434 $sort .= ", u.idnumber, u.lastname, u.firstname, u.email"; 435 } else { 436 $sortjoin = ''; 437 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)) { 442 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]); 446 447 $sort = "{$usersortfield} {$this->sortorder}, " . implode(', ', $defaultsortfields); 448 } 449 450 $params = array_merge($gradebookrolesparams, $this->userwheresql_params, $this->groupwheresql_params, $enrolledparams, $relatedctxparams); 451 } 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); 473 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; 482 483 // First flag everyone as not suspended. 484 foreach ($this->users as $user) { 485 $this->users[$user->id]->suspendedenrolment = false; 486 } 487 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"; 499 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); 504 505 foreach ($this->users as $user) { 506 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments); 507 } 508 } 509 } 510 return $this->users; 511 } 512 513 /** 514 * Load all grade items. 515 */ 516 protected function get_allgradeitems() { 517 if (!empty($this->allgradeitems)) { 518 return $this->allgradeitems; 519 } 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; 524 }); 525 526 return $this->allgradeitems; 527 } 528 529 /** 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 532 */ 533 public function load_final_grades() { 534 global $CFG, $DB; 535 536 if (!empty($this->grades)) { 537 return; 538 } 539 540 if (empty($this->users)) { 541 return; 542 } 543 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}"; 550 551 $userids = array_keys($this->users); 552 $allgradeitems = $this->get_allgradeitems(); 553 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; 561 } 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 565 } 566 } 567 } 568 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 577 578 $this->allgrades[$userid][$itemid] = $this->grades[$userid][$itemid]; 579 } 580 } 581 } 582 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; 591 } 592 } 593 } 594 } 595 596 /** 597 * Gets html toggle 598 * @deprecated since Moodle 2.4 as it appears not to be used any more. 599 */ 600 public function get_toggles_html() { 601 throw new coding_exception('get_toggles_html() can not be used any more'); 602 } 603 604 /** 605 * Prints html toggle 606 * @deprecated since 2.4 as it appears not to be used any more. 607 * @param unknown $type 608 */ 609 public function print_toggle($type) { 610 throw new coding_exception('print_toggle() can not be used any more'); 611 } 612 613 /** 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 620 */ 621 public function get_left_rows($displayaverages) { 622 global $CFG, $OUTPUT; 623 624 // Course context to determine how the user details should be displayed. 625 $coursecontext = context_course::instance($this->courseid); 626 627 $rows = []; 628 629 $showuserimage = $this->get_pref('showuserimage'); 630 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context); 631 632 $extrafields = \core_user\fields::get_identity_fields($this->context); 633 634 $arrows = $this->get_sort_arrows($extrafields); 635 636 $colspan = 1 + count($extrafields); 637 638 $levels = count($this->gtree->levels) - 1; 639 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; 649 650 for ($i = 1; $i < $levels; $i++) { 651 $row = new html_table_row(); 652 $rows[] = $row; 653 } 654 655 $headerrow = new html_table_row(); 656 $headerrow->attributes['class'] = 'heading'; 657 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); 669 670 $headerrow->cells[] = $studentheader; 671 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; 678 679 $collapsecontext = ['field' => $field, 'name' => $field]; 680 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']); 684 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; 689 } 690 691 $rows[] = $headerrow; 692 693 $suspendedstring = null; 694 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'; 700 701 $usercell = new html_table_cell(); 702 $usercell->attributes['class'] = ($usercount % 2) ? 'header user even' : 'header user odd'; 703 $usercount++; 704 705 $usercell->header = true; 706 $usercell->scope = 'row'; 707 708 if ($showuserimage) { 709 $usercell->text = $OUTPUT->render(\core_user::get_profile_picture($user, $coursecontext, [ 710 'link' => false, 'visibletoscreenreaders' => false 711 ])); 712 } 713 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'] 719 ); 720 721 if (!empty($user->suspendedenrolment)) { 722 $usercell->attributes['class'] .= ' usersuspended'; 723 724 //may be lots of suspended users so only get the string once 725 if (empty($suspendedstring)) { 726 $suspendedstring = get_string('userenrolmentsuspended', 'grades'); 727 } 728 $icon = $OUTPUT->pix_icon('i/enrolmentsuspended', $suspendedstring); 729 $usercell->text .= html_writer::tag('span', $icon, array('class'=>'usersuspendedicon')); 730 } 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); 736 737 $userrow->cells[] = $usercell; 738 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' 746 ]); 747 748 $userrow->cells[] = $fieldcell; 749 } 750 751 $userrow->attributes['data-uid'] = $userid; 752 $rows[] = $userrow; 753 } 754 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); 759 } 760 761 return $rows; 762 } 763 764 /** 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 768 */ 769 public function get_right_rows(bool $displayaverages) : array { 770 global $CFG, $USER, $OUTPUT, $DB, $PAGE; 771 772 $rows = []; 773 $this->rowcount = 0; 774 $strgrade = get_string('gradenoun'); 775 $this->get_sort_arrows(); 776 777 // Get preferences once. 778 $quickgrading = $this->get_pref('quickgrading'); 779 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); 787 788 // Preload scale objects for items with a scaleid and initialize tab indices. 789 $scaleslist = []; 790 791 foreach ($this->gtree->get_items() as $itemid => $item) { 792 if (!empty($item->scaleid)) { 793 $scaleslist[] = $item->scaleid; 794 } 795 } 796 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); 803 } 804 805 foreach ($this->gtree->get_levels() as $row) { 806 $headingrow = new html_table_row(); 807 $headingrow->attributes['class'] = 'heading_name_row'; 808 809 foreach ($row as $element) { 810 $sortlink = clone($this->baseurl); 811 if (isset($element['object']->id)) { 812 $sortlink->param('sortitemid', $element['object']->id); 813 } 814 815 $type = $element['type']; 816 817 if (!empty($element['colspan'])) { 818 $colspan = $element['colspan']; 819 } else { 820 $colspan = 1; 821 } 822 823 if (!empty($element['depth'])) { 824 $catlevel = 'catlevel'.$element['depth']; 825 } else { 826 $catlevel = ''; 827 } 828 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 = ' '; 835 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'; 848 849 $statusicons = $this->gtree->set_grade_status_icons($element); 850 if ($statusicons) { 851 $categorycell->attributes['class'] .= ' statusicons'; 852 } 853 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); 859 860 $headingrow->cells[] = $categorycell; 861 } 862 } else { 863 // Element is a grade_item. 864 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); 871 } 872 } 873 874 $collapsecontext = [ 875 'field' => $element['object']->id, 876 'name' => $element['object']->get_name(), 877 ]; 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); 882 } 883 $headerlink = $this->gtree->get_element_header($element, true, 884 true, false, false, true, $sortlink); 885 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; 890 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'; 895 } 896 897 $itemcell->attributes['class'] .= $this->get_cell_display_class($element['object']); 898 899 $itemcell->colspan = $colspan; 900 $itemcell->header = true; 901 $itemcell->scope = 'col'; 902 903 $context = new stdClass(); 904 $context->headerlink = $headerlink; 905 $context->arrow = $arrow; 906 $context->singleview = $singleview; 907 $context->statusicons = $statusicons; 908 $context->collapsedicon = $collapsedicon; 909 910 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/headercell', $context); 911 912 $headingrow->cells[] = $itemcell; 913 } 914 } 915 $rows[] = $headingrow; 916 } 917 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(); 925 } 926 927 foreach ($this->users as $userid => $user) { 928 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); 938 } 939 940 $itemrow = new html_table_row(); 941 $itemrow->id = 'user_'.$userid; 942 943 $fullname = fullname($user, $viewfullnames); 944 945 foreach ($this->gtree->items as $itemid => $unused) { 946 $item =& $this->gtree->items[$itemid]; 947 $grade = $this->grades[$userid][$item->id]; 948 949 $itemcell = new html_table_cell(); 950 951 $itemcell->id = 'u' . $userid . 'i' . $itemid; 952 $itemcell->attributes['data-itemid'] = $itemid; 953 $itemcell->attributes['class'] = 'gradecell'; 954 955 // Get the decimal points preference for this item. 956 $decimalpoints = $item->get_decimals(); 957 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; 964 } 965 966 $context = new stdClass(); 967 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 = '-'; 979 } 980 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/cell', $context); 981 $itemrow->cells[] = $itemcell; 982 continue; 983 } 984 985 // Emulate grade element. 986 $eid = $this->gtree->get_grade_eid($grade); 987 $element = ['eid' => $eid, 'object' => $grade, 'type' => 'grade']; 988 989 $itemcell->attributes['class'] .= ' grade i' . $itemid; 990 if ($item->is_category_item()) { 991 $itemcell->attributes['class'] .= ' cat'; 992 } 993 if ($item->is_course_item()) { 994 $itemcell->attributes['class'] .= ' course'; 995 } 996 if ($grade->is_overridden()) { 997 $itemcell->attributes['class'] .= ' overridden'; 998 $itemcell->attributes['aria-label'] = $stroverridengrade; 999 } 1000 1001 $hidden = ''; 1002 if ($grade->is_hidden()) { 1003 $hidden = ' dimmed_text '; 1004 } 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 = ''; 1013 } 1014 $context->statusicons = $this->gtree->set_grade_status_icons($element); 1015 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'; 1028 } 1029 1030 if ($grade->is_locked()) { 1031 $itemcell->attributes['class'] .= ' locked'; 1032 } 1033 1034 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 1035 $context->scale = true; 1036 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. 1041 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; 1049 } 1050 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'); 1057 } 1058 $attributes = [ 1059 'id' => 'grade_' . $userid . '_' . $item->id 1060 ]; 1061 $gradelabel = $fullname . ' ' . $item->get_name(true); 1062 1063 if ($context->statusicons) { 1064 $attributes['class'] = 'statusicons'; 1065 } 1066 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); 1074 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]; 1083 } 1084 } 1085 1086 } else if ($item->gradetype != GRADE_TYPE_TEXT) { 1087 // Value type. 1088 if ($quickgrading and $grade->is_editable()) { 1089 $context->iseditable = true; 1090 1091 // Set this input field with type="number" if the decimal separator for current language is set to 1092 // a period. Other decimal separators may not be recognised by browsers yet which may cause issues 1093 // when entering grades. 1094 $decsep = get_string('decsep', 'core_langconfig'); 1095 $context->isnumeric = $decsep === '.'; 1096 // If we're rendering this as a number field, set min/max attributes, if applicable. 1097 if ($context->isnumeric) { 1098 $context->minvalue = $item->grademin ?? null; 1099 $context->maxvalue = $item->grademax ?? null; 1100 } 1101 1102 $value = format_float($gradeval, $decimalpoints); 1103 $gradelabel = $fullname . ' ' . $item->get_name(true); 1104 1105 $context->id = 'grade_' . $userid . '_' . $item->id; 1106 $context->name = 'grade[' . $userid . '][' . $item->id .']'; 1107 $context->value = $value; 1108 $context->label = get_string('useractivitygrade', 'gradereport_grader', $gradelabel); 1109 $context->title = $strgrade; 1110 $context->extraclasses = 'form-control'; 1111 if ($context->statusicons) { 1112 $context->extraclasses .= ' statusicons'; 1113 } 1114 } else { 1115 $context->extraclasses = 'gradevalue' . $hidden . $gradepass; 1116 $context->text = format_float($gradeval, $decimalpoints); 1117 } 1118 } 1119 1120 } else { 1121 // Not editing. 1122 $gradedisplaytype = $item->get_displaytype(); 1123 1124 // Letter grades, scales and text grades are left aligned. 1125 $textgrade = false; 1126 $textgrades = [GRADE_DISPLAY_TYPE_LETTER, 1127 GRADE_DISPLAY_TYPE_REAL_LETTER, 1128 GRADE_DISPLAY_TYPE_LETTER_REAL, 1129 GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE, 1130 GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER]; 1131 if (in_array($gradedisplaytype, $textgrades)) { 1132 $textgrade = true; 1133 } 1134 1135 if ($textgrade || ($item->gradetype == GRADE_TYPE_TEXT)) { 1136 $itemcell->attributes['class'] .= ' grade_type_text'; 1137 } else if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 1138 if ($gradedisplaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) { 1139 $itemcell->attributes['class'] .= ' grade_type_value'; 1140 } else { 1141 $itemcell->attributes['class'] .= ' grade_type_scale'; 1142 } 1143 } else { 1144 $itemcell->attributes['class'] .= ' grade_type_value'; 1145 } 1146 1147 if ($item->needsupdate) { 1148 $context->text = $strerror; 1149 $context->extraclasses = 'gradingerror' . $hidden . $gradepass; 1150 } else { 1151 // The max and min for an aggregation may be different to the grade_item. 1152 if (!is_null($gradeval)) { 1153 $item->grademax = $grade->get_grade_max(); 1154 $item->grademin = $grade->get_grade_min(); 1155 } 1156 1157 $context->extraclasses = 'gradevalue ' . $hidden . $gradepass; 1158 $context->text = grade_format_gradevalue($gradeval, $item, true, 1159 $gradedisplaytype, null); 1160 } 1161 } 1162 1163 if ($item->gradetype == GRADE_TYPE_TEXT && !empty($grade->feedback)) { 1164 $context->text = html_writer::span(shorten_text(strip_tags($grade->feedback), 20), '', 1165 ['data-action' => 'feedback', 'role' => 'button', 'data-courseid' => $this->courseid]); 1166 } 1167 1168 if (!$item->needsupdate && !($item->gradetype == GRADE_TYPE_TEXT && empty($USER->editing))) { 1169 $context->actionmenu = $this->gtree->get_cell_action_menu($element, 'gradeitem', $this->gpr); 1170 } 1171 1172 $itemcell->text = $OUTPUT->render_from_template('gradereport_grader/cell', $context); 1173 1174 if (!empty($this->gradeserror[$item->id][$userid])) { 1175 $itemcell->text .= $this->gradeserror[$item->id][$userid]; 1176 } 1177 1178 $itemrow->cells[] = $itemcell; 1179 } 1180 $rows[] = $itemrow; 1181 } 1182 1183 if (!empty($USER->editing)) { 1184 $PAGE->requires->js_call_amd('core_form/changechecker', 1185 'watchFormById', ['gradereport_grader']); 1186 } 1187 1188 $rows = $this->get_right_range_row($rows); 1189 if ($displayaverages) { 1190 $rows = $this->get_right_avg_row($rows, true); 1191 $rows = $this->get_right_avg_row($rows); 1192 } 1193 1194 return $rows; 1195 } 1196 1197 /** 1198 * Depending on the style of report (fixedstudents vs traditional one-table), 1199 * arranges the rows of data in one or two tables, and returns the output of 1200 * these tables in HTML 1201 * @param boolean $displayaverages whether to display average rows in the table 1202 * @return string HTML 1203 */ 1204 public function get_grade_table($displayaverages = false) { 1205 global $OUTPUT; 1206 $leftrows = $this->get_left_rows($displayaverages); 1207 $rightrows = $this->get_right_rows($displayaverages); 1208 1209 $html = ''; 1210 1211 $fulltable = new html_table(); 1212 $fulltable->attributes['class'] = 'gradereport-grader-table d-none'; 1213 $fulltable->id = 'user-grades'; 1214 $fulltable->caption = get_string('summarygrader', 'gradereport_grader'); 1215 $fulltable->captionhide = true; 1216 // We don't want the table to be enclosed within in a .table-responsive div as it is heavily customised. 1217 $fulltable->responsive = false; 1218 1219 // Extract rows from each side (left and right) and collate them into one row each 1220 foreach ($leftrows as $key => $row) { 1221 $row->cells = array_merge($row->cells, $rightrows[$key]->cells); 1222 $fulltable->data[] = $row; 1223 } 1224 $html .= html_writer::table($fulltable); 1225 return $OUTPUT->container($html, 'gradeparent'); 1226 } 1227 1228 /** 1229 * Builds and return the row of icons for the left side of the report. 1230 * It only has one cell that says "Controls" 1231 * @param array $rows The Array of rows for the left part of the report 1232 * @param int $colspan The number of columns this cell has to span 1233 * @return array Array of rows for the left part of the report 1234 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu. 1235 * @todo MDL-77307 This will be deleted in Moodle 4.6. 1236 */ 1237 public function get_left_icons_row($rows=array(), $colspan=1) { 1238 global $USER; 1239 1240 debugging('The function get_left_icons_row() is deprecated, please do not use it anymore.', 1241 DEBUG_DEVELOPER); 1242 1243 if (!empty($USER->editing)) { 1244 $controlsrow = new html_table_row(); 1245 $controlsrow->attributes['class'] = 'controls'; 1246 $controlscell = new html_table_cell(); 1247 $controlscell->attributes['class'] = 'header controls'; 1248 $controlscell->header = true; 1249 $controlscell->colspan = $colspan; 1250 $controlscell->text = get_string('controls', 'grades'); 1251 $controlsrow->cells[] = $controlscell; 1252 1253 $rows[] = $controlsrow; 1254 } 1255 return $rows; 1256 } 1257 1258 /** 1259 * Builds and return the header for the row of ranges, for the left part of the grader report. 1260 * @param array $rows The Array of rows for the left part of the report 1261 * @param int $colspan The number of columns this cell has to span 1262 * @return array Array of rows for the left part of the report 1263 */ 1264 public function get_left_range_row($rows=array(), $colspan=1) { 1265 global $CFG, $USER; 1266 1267 if ($this->get_pref('showranges')) { 1268 $rangerow = new html_table_row(); 1269 $rangerow->attributes['class'] = 'range r'.$this->rowcount++; 1270 $rangecell = new html_table_cell(); 1271 $rangecell->attributes['class'] = 'header range'; 1272 $rangecell->colspan = $colspan; 1273 $rangecell->header = true; 1274 $rangecell->scope = 'row'; 1275 $rangecell->text = get_string('range', 'grades'); 1276 $rangerow->cells[] = $rangecell; 1277 $rows[] = $rangerow; 1278 } 1279 1280 return $rows; 1281 } 1282 1283 /** 1284 * Builds and return the headers for the rows of averages, for the left part of the grader report. 1285 * @param array $rows The Array of rows for the left part of the report 1286 * @param int $colspan The number of columns this cell has to span 1287 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages 1288 * @return array Array of rows for the left part of the report 1289 */ 1290 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) { 1291 if (!$this->canviewhidden) { 1292 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered 1293 // better not show them at all if user can not see all hideen grades 1294 return $rows; 1295 } 1296 1297 $showaverages = $this->get_pref('showaverages'); 1298 $showaveragesgroup = $this->currentgroup && $showaverages; 1299 $straveragegroup = get_string('groupavg', 'grades'); 1300 1301 if ($groupavg) { 1302 if ($showaveragesgroup) { 1303 $groupavgrow = new html_table_row(); 1304 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++; 1305 $groupavgcell = new html_table_cell(); 1306 $groupavgcell->attributes['class'] = 'header range'; 1307 $groupavgcell->colspan = $colspan; 1308 $groupavgcell->header = true; 1309 $groupavgcell->scope = 'row'; 1310 $groupavgcell->text = $straveragegroup; 1311 $groupavgrow->cells[] = $groupavgcell; 1312 $rows[] = $groupavgrow; 1313 } 1314 } else { 1315 $straverage = get_string('overallaverage', 'grades'); 1316 1317 if ($showaverages) { 1318 $avgrow = new html_table_row(); 1319 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++; 1320 $avgcell = new html_table_cell(); 1321 $avgcell->attributes['class'] = 'header range'; 1322 $avgcell->colspan = $colspan; 1323 $avgcell->header = true; 1324 $avgcell->scope = 'row'; 1325 $avgcell->text = $straverage; 1326 $avgrow->cells[] = $avgcell; 1327 $rows[] = $avgrow; 1328 } 1329 } 1330 1331 return $rows; 1332 } 1333 1334 /** 1335 * Builds and return the row of icons when editing is on, for the right part of the grader report. 1336 * @param array $rows The Array of rows for the right part of the report 1337 * @return array Array of rows for the right part of the report 1338 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu. 1339 * @todo MDL-77307 This will be deleted in Moodle 4.6. 1340 */ 1341 public function get_right_icons_row($rows=array()) { 1342 global $USER; 1343 debugging('The function get_right_icons_row() is deprecated, please do not use it anymore.', 1344 DEBUG_DEVELOPER); 1345 1346 if (!empty($USER->editing)) { 1347 $iconsrow = new html_table_row(); 1348 $iconsrow->attributes['class'] = 'controls'; 1349 1350 foreach ($this->gtree->items as $itemid => $unused) { 1351 // emulate grade element 1352 $item = $this->gtree->get_item($itemid); 1353 1354 $eid = $this->gtree->get_item_eid($item); 1355 $element = $this->gtree->locate_element($eid); 1356 $itemcell = new html_table_cell(); 1357 $itemcell->attributes['class'] = 'controls icons i'.$itemid; 1358 $itemcell->text = $this->get_icons($element); 1359 $iconsrow->cells[] = $itemcell; 1360 } 1361 $rows[] = $iconsrow; 1362 } 1363 return $rows; 1364 } 1365 1366 /** 1367 * Builds and return the row of ranges for the right part of the grader report. 1368 * @param array $rows The Array of rows for the right part of the report 1369 * @return array Array of rows for the right part of the report 1370 */ 1371 public function get_right_range_row($rows=array()) { 1372 1373 if ($this->get_pref('showranges')) { 1374 $rangesdisplaytype = $this->get_pref('rangesdisplaytype'); 1375 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints'); 1376 $rangerow = new html_table_row(); 1377 $rangerow->attributes['class'] = 'heading range'; 1378 1379 foreach ($this->gtree->items as $itemid => $unused) { 1380 $item =& $this->gtree->items[$itemid]; 1381 $itemcell = new html_table_cell(); 1382 $itemcell->attributes['class'] .= ' range i'. $itemid; 1383 $itemcell->attributes['class'] .= $this->get_cell_display_class($item); 1384 1385 $hidden = ''; 1386 if ($item->is_hidden()) { 1387 $hidden = ' dimmed_text '; 1388 } 1389 1390 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints); 1391 1392 $itemcell->attributes['data-itemid'] = $itemid; 1393 $itemcell->text = html_writer::div($formattedrange, 'rangevalues' . $hidden, 1394 ['data-collapse' => 'rangerowcell']); 1395 $rangerow->cells[] = $itemcell; 1396 } 1397 $rows[] = $rangerow; 1398 } 1399 return $rows; 1400 } 1401 1402 /** 1403 * Builds and return the row of averages for the right part of the grader report. 1404 * @param array $rows Whether to return only group averages or all averages. 1405 * @param bool $grouponly Whether to return only group averages or all averages. 1406 * @return array Array of rows for the right part of the report 1407 */ 1408 public function get_right_avg_row($rows=array(), $grouponly=false) { 1409 global $USER, $DB, $OUTPUT, $CFG; 1410 if (!$this->canviewhidden) { 1411 // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered 1412 // better not show them at all if user can not see all hidden grades. 1413 return $rows; 1414 } 1415 1416 $averagesdisplaytype = $this->get_pref('averagesdisplaytype'); 1417 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints'); 1418 $meanselection = $this->get_pref('meanselection'); 1419 $shownumberofgrades = $this->get_pref('shownumberofgrades'); 1420 1421 if ($grouponly) { 1422 $showaverages = $this->currentgroup && $this->get_pref('showaverages'); 1423 $groupsql = $this->groupsql; 1424 $groupwheresql = $this->groupwheresql; 1425 $groupwheresqlparams = $this->groupwheresql_params; 1426 } else { 1427 $showaverages = $this->get_pref('showaverages'); 1428 $groupsql = ""; 1429 $groupwheresql = ""; 1430 $groupwheresqlparams = array(); 1431 } 1432 1433 if ($showaverages) { 1434 $totalcount = $this->get_numusers($grouponly); 1435 1436 // Limit to users with a gradeable role. 1437 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0'); 1438 1439 // Limit to users with an active enrollment. 1440 $coursecontext = $this->context->get_course_context(true); 1441 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); 1442 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); 1443 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext); 1444 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol); 1445 1446 // We want to query both the current context and parent contexts. 1447 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx'); 1448 1449 $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams); 1450 1451 // Find sums of all grade items in course. 1452 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum 1453 FROM {grade_items} gi 1454 JOIN {grade_grades} g ON g.itemid = gi.id 1455 JOIN {user} u ON u.id = g.userid 1456 JOIN ($enrolledsql) je ON je.id = u.id 1457 JOIN ( 1458 SELECT DISTINCT ra.userid 1459 FROM {role_assignments} ra 1460 WHERE ra.roleid $gradebookrolessql 1461 AND ra.contextid $relatedctxsql 1462 ) rainner ON rainner.userid = u.id 1463 $groupsql 1464 WHERE gi.courseid = :courseid 1465 AND u.deleted = 0 1466 AND g.finalgrade IS NOT NULL 1467 $groupwheresql 1468 GROUP BY g.itemid"; 1469 $sumarray = array(); 1470 if ($sums = $DB->get_records_sql($sql, $params)) { 1471 foreach ($sums as $itemid => $csum) { 1472 $sumarray[$itemid] = $csum->sum; 1473 } 1474 } 1475 1476 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0 1477 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table) 1478 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count 1479 FROM {grade_items} gi 1480 CROSS JOIN ($enrolledsql) u 1481 JOIN {role_assignments} ra 1482 ON ra.userid = u.id 1483 LEFT OUTER JOIN {grade_grades} g 1484 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL) 1485 $groupsql 1486 WHERE gi.courseid = :courseid 1487 AND ra.roleid $gradebookrolessql 1488 AND ra.contextid $relatedctxsql 1489 AND g.id IS NULL 1490 $groupwheresql 1491 GROUP BY gi.id"; 1492 1493 $ungradedcounts = $DB->get_records_sql($sql, $params); 1494 1495 $avgrow = new html_table_row(); 1496 $avgrow->attributes['class'] = 'avg'; 1497 1498 foreach ($this->gtree->items as $itemid => $unused) { 1499 $item =& $this->gtree->items[$itemid]; 1500 1501 if ($item->needsupdate) { 1502 $avgcell = new html_table_cell(); 1503 $avgcell->attributes['class'] = 'i'. $itemid; 1504 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror'); 1505 $avgrow->cells[] = $avgcell; 1506 continue; 1507 } 1508 1509 if (!isset($sumarray[$item->id])) { 1510 $sumarray[$item->id] = 0; 1511 } 1512 1513 if (empty($ungradedcounts[$itemid])) { 1514 $ungradedcount = 0; 1515 } else { 1516 $ungradedcount = $ungradedcounts[$itemid]->count; 1517 } 1518 1519 if ($meanselection == GRADE_REPORT_MEAN_GRADED) { 1520 $meancount = $totalcount - $ungradedcount; 1521 } else { // Bump up the sum by the number of ungraded items * grademin 1522 $sumarray[$item->id] += $ungradedcount * $item->grademin; 1523 $meancount = $totalcount; 1524 } 1525 1526 // Determine which display type to use for this average 1527 if (!empty($USER->editing)) { 1528 $displaytype = GRADE_DISPLAY_TYPE_REAL; 1529 1530 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences 1531 $displaytype = $item->get_displaytype(); 1532 1533 } else { 1534 $displaytype = $averagesdisplaytype; 1535 } 1536 1537 // Override grade_item setting if a display preference (not inherit) was set for the averages 1538 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) { 1539 $decimalpoints = $item->get_decimals(); 1540 1541 } else { 1542 $decimalpoints = $averagesdecimalpoints; 1543 } 1544 1545 $gradetypeclass = $this->get_cell_display_class($item); 1546 1547 if (!isset($sumarray[$item->id]) || $meancount == 0) { 1548 $avgcell = new html_table_cell(); 1549 $avgcell->attributes['class'] = $gradetypeclass . ' i'. $itemid; 1550 $avgcell->attributes['data-itemid'] = $itemid; 1551 $avgcell->text = html_writer::div('-', '', ['data-collapse' => 'avgrowcell']); 1552 $avgrow->cells[] = $avgcell; 1553 } else { 1554 $sum = $sumarray[$item->id]; 1555 $avgradeval = $sum/$meancount; 1556 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints); 1557 1558 $numberofgrades = ''; 1559 if ($shownumberofgrades) { 1560 $numberofgrades = " ($meancount)"; 1561 } 1562 1563 $avgcell = new html_table_cell(); 1564 $avgcell->attributes['class'] = $gradetypeclass . ' i'. $itemid; 1565 $avgcell->attributes['data-itemid'] = $itemid; 1566 $avgcell->text = html_writer::div($gradehtml.$numberofgrades, '', ['data-collapse' => 'avgrowcell']); 1567 $avgrow->cells[] = $avgcell; 1568 } 1569 } 1570 $rows[] = $avgrow; 1571 } 1572 return $rows; 1573 } 1574 1575 /** 1576 * Given element category, create a collapsible icon and 1577 * course header. 1578 * 1579 * @param array $element 1580 * @return string HTML 1581 */ 1582 protected function get_course_header($element) { 1583 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) { 1584 $showing = get_string('showingaggregatesonly', 'grades'); 1585 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) { 1586 $showing = get_string('showinggradesonly', 'grades'); 1587 } else { 1588 $showing = get_string('showingfullmode', 'grades'); 1589 } 1590 1591 $name = $element['object']->get_name(); 1592 $nameunescaped = $element['object']->get_name(false); 1593 $describedbyid = uniqid(); 1594 $courseheader = html_writer::tag('span', $name, [ 1595 'title' => $nameunescaped, 1596 'class' => 'gradeitemheader', 1597 'aria-describedby' => $describedbyid 1598 ]); 1599 $courseheader .= html_writer::div($showing, 'sr-only', [ 1600 'id' => $describedbyid 1601 ]); 1602 1603 return $courseheader; 1604 } 1605 1606 /** 1607 * Given a grade_category, grade_item or grade_grade, this function 1608 * figures out the state of the object and builds then returns a div 1609 * with the icons needed for the grader report. 1610 * 1611 * @param array $element 1612 * @return string HTML 1613 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu. 1614 * @todo MDL-77307 This will be deleted in Moodle 4.6. 1615 */ 1616 protected function get_icons($element) { 1617 global $CFG, $USER, $OUTPUT; 1618 debugging('The function get_icons() is deprecated, please do not use it anymore.', 1619 DEBUG_DEVELOPER); 1620 1621 if (empty($USER->editing)) { 1622 return '<div class="grade_icons" />'; 1623 } 1624 1625 // Init all icons 1626 $editicon = ''; 1627 1628 $editable = true; 1629 1630 if ($element['type'] == 'grade') { 1631 $item = $element['object']->grade_item; 1632 if ($item->is_course_item() or $item->is_category_item()) { 1633 $editable = $this->overridecat; 1634 } 1635 } 1636 1637 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) { 1638 $editicon = $this->gtree->get_edit_icon($element, $this->gpr); 1639 } 1640 1641 $editcalculationicon = ''; 1642 $showhideicon = ''; 1643 $lockunlockicon = ''; 1644 1645 if (has_capability('moodle/grade:manage', $this->context)) { 1646 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr); 1647 1648 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr); 1649 1650 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr); 1651 } 1652 1653 $gradeanalysisicon = ''; 1654 if ($element['type'] == 'grade') { 1655 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']); 1656 } 1657 1658 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons'); 1659 } 1660 1661 /** 1662 * Given a category element returns collapsing +/- icon if available 1663 * 1664 * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more. 1665 */ 1666 protected function get_collapsing_icon($element) { 1667 throw new coding_exception('get_collapsing_icon() can not be used any more, please use get_course_header() instead.'); 1668 } 1669 1670 /** 1671 * Processes a single action against a category, grade_item or grade. 1672 * @param string $target eid ({type}{id}, e.g. c4 for category4) 1673 * @param string $action Which action to take (edit, delete etc...) 1674 * @return 1675 */ 1676 public function process_action($target, $action) { 1677 return self::do_process_action($target, $action, $this->course->id); 1678 } 1679 1680 /** 1681 * From the list of categories that this user prefers to collapse choose ones that belong to the current course. 1682 * 1683 * This function serves two purposes. 1684 * Mainly it helps migrating from user preference style when all courses were stored in one preference. 1685 * Also it helps to remove the settings for categories that were removed if the array for one course grows too big. 1686 * 1687 * @param int $courseid 1688 * @param array $collapsed 1689 * @return array 1690 */ 1691 protected static function filter_collapsed_categories($courseid, $collapsed) { 1692 global $DB; 1693 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty. 1694 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? []; 1695 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? []; 1696 1697 if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) { 1698 return $collapsed; 1699 } 1700 $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid)); 1701 $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats)); 1702 $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats)); 1703 return $collapsed; 1704 } 1705 1706 /** 1707 * Returns the list of categories that this user wants to collapse or display aggregatesonly 1708 * 1709 * This method also migrates on request from the old format of storing user preferences when they were stored 1710 * in one preference for all courses causing DB error when trying to insert very big value. 1711 * 1712 * @param int $courseid 1713 * @return array 1714 */ 1715 protected static function get_collapsed_preferences($courseid) { 1716 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) { 1717 $collapsed = json_decode($collapsed, true); 1718 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty. 1719 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? []; 1720 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? []; 1721 return $collapsed; 1722 } 1723 1724 // Try looking for old location of user setting that used to store all courses in one serialized user preference. 1725 $collapsed = ['aggregatesonly' => [], 'gradesonly' => []]; // Use this if old settings are not found. 1726 $collapsedall = []; 1727 $oldprefexists = false; 1728 if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) { 1729 $oldprefexists = true; 1730 if ($collapsedall = unserialize_array($oldcollapsedpref)) { 1731 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty. 1732 $collapsedall['aggregatesonly'] = $collapsedall['aggregatesonly'] ?? []; 1733 $collapsedall['gradesonly'] = $collapsedall['gradesonly'] ?? []; 1734 // We found the old-style preference, filter out only categories that belong to this course and update the prefs. 1735 $collapsed = static::filter_collapsed_categories($courseid, $collapsedall); 1736 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) { 1737 static::set_collapsed_preferences($courseid, $collapsed); 1738 $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']); 1739 $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']); 1740 if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) { 1741 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall)); 1742 } 1743 } 1744 } 1745 } 1746 1747 // Arrived here, if the old pref exists and it doesn't contain 1748 // more information, it means that the migration of all the 1749 // data to new, by course, preferences is completed, so 1750 // the old one can be safely deleted. 1751 if ($oldprefexists && 1752 empty($collapsedall['aggregatesonly']) && 1753 empty($collapsedall['gradesonly'])) { 1754 unset_user_preference('grade_report_grader_collapsed_categories'); 1755 } 1756 1757 return $collapsed; 1758 } 1759 1760 /** 1761 * Sets the list of categories that user wants to see collapsed in user preferences 1762 * 1763 * This method may filter or even trim the list if it does not fit in DB field. 1764 * 1765 * @param int $courseid 1766 * @param array $collapsed 1767 */ 1768 protected static function set_collapsed_preferences($courseid, $collapsed) { 1769 global $DB; 1770 // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size, 1771 // try to filter the list of categories since array may contain categories that were deleted. 1772 if (strlen(json_encode($collapsed)) >= 1333) { 1773 $collapsed = static::filter_collapsed_categories($courseid, $collapsed); 1774 } 1775 1776 // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information. 1777 while (strlen(json_encode($collapsed)) >= 1333) { 1778 if (count($collapsed['aggregatesonly'])) { 1779 array_pop($collapsed['aggregatesonly']); 1780 } 1781 if (count($collapsed['gradesonly'])) { 1782 array_pop($collapsed['gradesonly']); 1783 } 1784 } 1785 1786 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) { 1787 set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed)); 1788 } else { 1789 unset_user_preference('grade_report_grader_collapsed_categories'.$courseid); 1790 } 1791 } 1792 1793 /** 1794 * Processes a single action against a category, grade_item or grade. 1795 * @param string $target eid ({type}{id}, e.g. c4 for category4) 1796 * @param string $action Which action to take (edit, delete etc...) 1797 * @param int $courseid affected course. 1798 * @return 1799 */ 1800 public static function do_process_action($target, $action, $courseid = null) { 1801 global $DB; 1802 // TODO: this code should be in some grade_tree static method 1803 $targettype = substr($target, 0, 2); 1804 $targetid = substr($target, 2); 1805 // TODO: end 1806 1807 if ($targettype !== 'cg') { 1808 // The following code only works with categories. 1809 return true; 1810 } 1811 1812 if (!$courseid) { 1813 debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid', 1814 DEBUG_DEVELOPER); 1815 if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) { 1816 return true; 1817 } 1818 } 1819 1820 $collapsed = static::get_collapsed_preferences($courseid); 1821 1822 switch ($action) { 1823 case 'switch_minus': // Add category to array of aggregatesonly 1824 $key = array_search($targetid, $collapsed['gradesonly']); 1825 if ($key !== false) { 1826 unset($collapsed['gradesonly'][$key]); 1827 } 1828 if (!in_array($targetid, $collapsed['aggregatesonly'])) { 1829 $collapsed['aggregatesonly'][] = $targetid; 1830 static::set_collapsed_preferences($courseid, $collapsed); 1831 } 1832 break; 1833 1834 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly 1835 $key = array_search($targetid, $collapsed['aggregatesonly']); 1836 if ($key !== false) { 1837 unset($collapsed['aggregatesonly'][$key]); 1838 } 1839 if (!in_array($targetid, $collapsed['gradesonly'])) { 1840 $collapsed['gradesonly'][] = $targetid; 1841 } 1842 static::set_collapsed_preferences($courseid, $collapsed); 1843 break; 1844 case 'switch_whole': // Remove the category from the array of collapsed cats 1845 $key = array_search($targetid, $collapsed['gradesonly']); 1846 if ($key !== false) { 1847 unset($collapsed['gradesonly'][$key]); 1848 static::set_collapsed_preferences($courseid, $collapsed); 1849 } 1850 1851 $key = array_search($targetid, $collapsed['aggregatesonly']); 1852 if ($key !== false) { 1853 unset($collapsed['aggregatesonly'][$key]); 1854 static::set_collapsed_preferences($courseid, $collapsed); 1855 } 1856 break; 1857 default: 1858 break; 1859 } 1860 1861 return true; 1862 } 1863 1864 /** 1865 * Refactored function for generating HTML of sorting links with matching arrows. 1866 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready 1867 * to inject into a table header cell. 1868 * @param array $extrafields Array of extra fields being displayed, such as 1869 * user idnumber 1870 * @return array An associative array of HTML sorting links+arrows 1871 */ 1872 public function get_sort_arrows(array $extrafields = []) { 1873 global $CFG; 1874 $arrows = array(); 1875 $sortlink = clone($this->baseurl); 1876 1877 // Sourced from tablelib.php 1878 // Check the full name display for sortable fields. 1879 if (has_capability('moodle/site:viewfullnames', $this->context)) { 1880 $nameformat = $CFG->alternativefullnameformat; 1881 } else { 1882 $nameformat = $CFG->fullnamedisplay; 1883 } 1884 1885 if ($nameformat == 'language') { 1886 $nameformat = get_string('fullnamedisplay'); 1887 } 1888 1889 $arrows['studentname'] = ''; 1890 $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat); 1891 if (!empty($requirednames)) { 1892 foreach ($requirednames as $name) { 1893 $arrows['studentname'] .= html_writer::link( 1894 new moodle_url($this->baseurl, array('sortitemid' => $name)), get_string($name) 1895 ); 1896 if ($this->sortitemid == $name) { 1897 $sortlink->param('sortitemid', $name); 1898 if ($this->sortorder == 'ASC') { 1899 $sorticon = $this->get_sort_arrow('down', $sortlink); 1900 } else { 1901 $sorticon = $this->get_sort_arrow('up', $sortlink); 1902 } 1903 $arrows['studentname'] .= $sorticon; 1904 } 1905 $arrows['studentname'] .= ' / '; 1906 } 1907 1908 $arrows['studentname'] = substr($arrows['studentname'], 0, -3); 1909 } 1910 1911 foreach ($extrafields as $field) { 1912 $attributes = [ 1913 'data-collapse' => 'content' 1914 ]; 1915 // With additional user profile fields, we can't grab the name via WS, so conditionally add it to rip out of the DOM. 1916 if (preg_match(\core_user\fields::PROFILE_FIELD_REGEX, $field)) { 1917 $attributes['data-collapse-name'] = \core_user\fields::get_display_name($field); 1918 } 1919 $fieldlink = html_writer::link(new moodle_url($this->baseurl, ['sortitemid' => $field]), 1920 \core_user\fields::get_display_name($field), $attributes); 1921 $arrows[$field] = $fieldlink; 1922 1923 if ($field == $this->sortitemid) { 1924 $sortlink->param('sortitemid', $field); 1925 1926 if ($this->sortorder == 'ASC') { 1927 $sorticon = $this->get_sort_arrow('down', $sortlink); 1928 } else { 1929 $sorticon = $this->get_sort_arrow('up', $sortlink); 1930 } 1931 $arrows[$field] .= $sorticon; 1932 } 1933 } 1934 1935 return $arrows; 1936 } 1937 1938 /** 1939 * Returns the maximum number of students to be displayed on each page 1940 * 1941 * @return int The maximum number of students to display per page 1942 */ 1943 public function get_students_per_page(): int { 1944 // Default to the lowest available option. 1945 return (int) get_user_preferences('grade_report_studentsperpage', min(static::PAGINATION_OPTIONS)); 1946 } 1947 1948 /** 1949 * Returns link to change category view mode. 1950 * 1951 * @param moodle_url $url Url to grader report page 1952 * @param string $title Menu item title 1953 * @param string $action View mode to change to 1954 * @param bool $active Whether link is active in dropdown 1955 * 1956 * @return string|null 1957 */ 1958 public function get_category_view_mode_link(moodle_url $url, string $title, string $action, bool $active = false): ?string { 1959 $urlnew = $url; 1960 $urlnew->param('action', $action); 1961 $active = $active ? 'true' : 'false'; 1962 return html_writer::link($urlnew, $title, 1963 ['class' => 'dropdown-item', 'aria-label' => $title, 'aria-current' => $active, 'role' => 'menuitem']); 1964 } 1965 1966 /** 1967 * Return the link to allow the field to collapse from the users view. 1968 * 1969 * @return string Dropdown menu link that'll trigger the collapsing functionality. 1970 * @throws coding_exception 1971 * @throws moodle_exception 1972 */ 1973 public function get_hide_show_link(): string { 1974 $link = new moodle_url('#', []); 1975 return html_writer::link( 1976 $link->out(false), 1977 get_string('collapse'), 1978 ['class' => 'dropdown-item', 'data-hider' => 'hide', 'aria-label' => get_string('collapse'), 'role' => 'menuitem'], 1979 ); 1980 } 1981 1982 /** 1983 * Return the base report link with some default sorting applied. 1984 * 1985 * @return string 1986 * @throws moodle_exception 1987 */ 1988 public function get_default_sortable(): string { 1989 $sortlink = new moodle_url('/grade/report/grader/index.php', [ 1990 'id' => $this->courseid, 1991 'sortitemid' => 'firstname', 1992 'sort' => 'asc' 1993 ]); 1994 $this->gpr->add_url_params($sortlink); 1995 return $sortlink->out(false); 1996 } 1997 1998 /** 1999 * Return class used for text alignment. 2000 * 2001 * @param grade_item $item Can be grade item or grade 2002 * @return string class name used for text alignment 2003 */ 2004 public function get_cell_display_class(grade_item $item): string { 2005 global $USER; 2006 2007 $gradetypeclass = ''; 2008 if (!empty($USER->editing)) { 2009 switch ($item->gradetype) { 2010 case GRADE_TYPE_SCALE: 2011 $gradetypeclass = ' grade_type_scale'; 2012 break; 2013 case GRADE_TYPE_VALUE: 2014 $gradetypeclass = ' grade_type_value'; 2015 break; 2016 case GRADE_TYPE_TEXT: 2017 $gradetypeclass = ' grade_type_text'; 2018 break; 2019 } 2020 } else { 2021 $gradedisplaytype = $item->get_displaytype(); 2022 2023 // Letter grades, scales and text grades are left aligned. 2024 $textgrade = false; 2025 $textgrades = [GRADE_DISPLAY_TYPE_LETTER, 2026 GRADE_DISPLAY_TYPE_REAL_LETTER, 2027 GRADE_DISPLAY_TYPE_LETTER_REAL, 2028 GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE, 2029 GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER]; 2030 if (in_array($gradedisplaytype, $textgrades)) { 2031 $textgrade = true; 2032 } 2033 2034 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'gradereport_grader', 'scales'); 2035 $scalesarray = $cache->get(get_class($this)); 2036 2037 if ($textgrade || ($item->gradetype == GRADE_TYPE_TEXT)) { 2038 $gradetypeclass = ' grade_type_text'; 2039 } else if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 2040 if ($gradedisplaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) { 2041 $gradetypeclass = ' grade_type_value'; 2042 } else { 2043 $gradetypeclass = ' grade_type_scale'; 2044 } 2045 } else { 2046 $gradetypeclass = ' grade_type_value'; 2047 } 2048 } 2049 return $gradetypeclass; 2050 } 2051 } 2052 2053 /** 2054 * Adds report specific context variable 2055 * 2056 * @param context_course $context Course context 2057 * @param int $courseid Course ID 2058 * @param array $element An array representing an element in the grade_tree 2059 * @param grade_plugin_return $gpr A grade_plugin_return object 2060 * @param string $mode Not used 2061 * @param stdClass|null $templatecontext Template context 2062 * @return stdClass|null 2063 */ 2064 function gradereport_grader_get_report_link(context_course $context, int $courseid, 2065 array $element, grade_plugin_return $gpr, string $mode, ?stdClass $templatecontext): ?stdClass { 2066 2067 static $report = null; 2068 if (!$report) { 2069 $report = new grade_report_grader($courseid, $gpr, $context); 2070 } 2071 2072 if ($mode == 'category') { 2073 if (!isset($templatecontext)) { 2074 $templatecontext = new stdClass(); 2075 } 2076 2077 $categoryid = $element['object']->id; 2078 2079 // Load language strings. 2080 $strswitchminus = get_string('aggregatesonly', 'grades'); 2081 $strswitchplus = get_string('gradesonly', 'grades'); 2082 $strswitchwhole = get_string('fullmode', 'grades'); 2083 2084 $url = new moodle_url($gpr->get_return_url(null, ['target' => $element['eid'], 'sesskey' => sesskey()])); 2085 2086 $gradesonly = false; 2087 $aggregatesonly = false; 2088 $fullmode = false; 2089 if (in_array($categoryid, $report->collapsed['gradesonly'])) { 2090 $gradesonly = true; 2091 } else if (in_array($categoryid, $report->collapsed['aggregatesonly'])) { 2092 $aggregatesonly = true; 2093 } else { 2094 $fullmode = true; 2095 } 2096 $templatecontext->gradesonlyurl = 2097 $report->get_category_view_mode_link($url, $strswitchplus, 'switch_plus', $gradesonly); 2098 $templatecontext->aggregatesonlyurl = 2099 $report->get_category_view_mode_link($url, $strswitchminus, 'switch_minus', $aggregatesonly); 2100 $templatecontext->fullmodeurl = 2101 $report->get_category_view_mode_link($url, $strswitchwhole, 'switch_whole', $fullmode); 2102 return $templatecontext; 2103 } else if ($mode == 'gradeitem') { 2104 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) { 2105 $templatecontext->columncollapse = $report->get_hide_show_link(); 2106 $templatecontext->dataid = $element['name']; 2107 } 2108 2109 // We do not want grade category total items to be hidden away as it is controlled by something else. 2110 if (isset($element['object']->id) && !$element['object']->is_aggregate_item()) { 2111 $templatecontext->columncollapse = $report->get_hide_show_link(); 2112 } 2113 return $templatecontext; 2114 } 2115 return null; 2116 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body