Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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 /** 106 * Length at which feedback will be truncated (to the nearest word) and an ellipsis be added. 107 * TODO replace this by a report preference 108 * @var int $feedback_trunc_length 109 */ 110 protected $feedback_trunc_length = 50; 111 112 /** 113 * Allow category grade overriding 114 * @var bool $overridecat 115 */ 116 protected $overridecat; 117 118 /** 119 * Constructor. Sets local copies of user preferences and initialises grade_tree. 120 * @param int $courseid 121 * @param object $gpr grade plugin return tracking object 122 * @param string $context 123 * @param int $page The current page being viewed (when report is paged) 124 * @param int $sortitemid The id of the grade_item by which to sort the table 125 */ 126 public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null) { 127 global $CFG; 128 parent::__construct($courseid, $gpr, $context, $page); 129 130 $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->course->id)); 131 132 // load collapsed settings for this report 133 $this->collapsed = static::get_collapsed_preferences($this->course->id); 134 135 if (empty($CFG->enableoutcomes)) { 136 $nooutcomes = false; 137 } else { 138 $nooutcomes = get_user_preferences('grade_report_shownooutcomes'); 139 } 140 141 // if user report preference set or site report setting set use it, otherwise use course or site setting 142 $switch = $this->get_pref('aggregationposition'); 143 if ($switch == '') { 144 $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition); 145 } 146 147 // Grab the grade_tree for this course 148 $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes); 149 150 $this->sortitemid = $sortitemid; 151 152 // base url for sorting by first/last name 153 154 $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid)); 155 156 $studentsperpage = $this->get_students_per_page(); 157 if (!empty($this->page) && !empty($studentsperpage)) { 158 $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page)); 159 } 160 161 $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid)); 162 163 $this->setup_groups(); 164 $this->setup_users(); 165 $this->setup_sortitemid(); 166 167 $this->overridecat = (bool)get_config('moodle', 'grade_overridecat'); 168 } 169 170 /** 171 * Processes the data sent by the form (grades and feedbacks). 172 * Caller is responsible for all access control checks 173 * @param array $data form submission (with magic quotes) 174 * @return array empty array if success, array of warnings if something fails. 175 */ 176 public function process_data($data) { 177 global $DB; 178 $warnings = array(); 179 180 $separategroups = false; 181 $mygroups = array(); 182 if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) { 183 $separategroups = true; 184 $mygroups = groups_get_user_groups($this->course->id); 185 $mygroups = $mygroups[0]; // ignore groupings 186 // reorder the groups fro better perf below 187 $current = array_search($this->currentgroup, $mygroups); 188 if ($current !== false) { 189 unset($mygroups[$current]); 190 array_unshift($mygroups, $this->currentgroup); 191 } 192 } 193 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context); 194 195 // always initialize all arrays 196 $queue = array(); 197 198 $this->load_users(); 199 $this->load_final_grades(); 200 201 // Were any changes made? 202 $changedgrades = false; 203 $timepageload = clean_param($data->timepageload, PARAM_INT); 204 205 foreach ($data as $varname => $students) { 206 207 $needsupdate = false; 208 209 // skip, not a grade nor feedback 210 if (strpos($varname, 'grade') === 0) { 211 $datatype = 'grade'; 212 } else if (strpos($varname, 'feedback') === 0) { 213 $datatype = 'feedback'; 214 } else { 215 continue; 216 } 217 218 foreach ($students as $userid => $items) { 219 $userid = clean_param($userid, PARAM_INT); 220 foreach ($items as $itemid => $postedvalue) { 221 $itemid = clean_param($itemid, PARAM_INT); 222 223 // Was change requested? 224 $oldvalue = $this->grades[$userid][$itemid]; 225 if ($datatype === 'grade') { 226 // If there was no grade and there still isn't 227 if (is_null($oldvalue->finalgrade) && $postedvalue == -1) { 228 // -1 means no grade 229 continue; 230 } 231 232 // If the grade item uses a custom scale 233 if (!empty($oldvalue->grade_item->scaleid)) { 234 235 if ((int)$oldvalue->finalgrade === (int)$postedvalue) { 236 continue; 237 } 238 } else { 239 // The grade item uses a numeric scale 240 241 // Format the finalgrade from the DB so that it matches the grade from the client 242 if ($postedvalue === format_float($oldvalue->finalgrade, $oldvalue->grade_item->get_decimals())) { 243 continue; 244 } 245 } 246 247 $changedgrades = true; 248 249 } else if ($datatype === 'feedback') { 250 // If quick grading is on, feedback needs to be compared without line breaks. 251 if ($this->get_pref('quickgrading')) { 252 $oldvalue->feedback = preg_replace("/\r\n|\r|\n/", "", $oldvalue->feedback); 253 } 254 if (($oldvalue->feedback === $postedvalue) or ($oldvalue->feedback === null and empty($postedvalue))) { 255 continue; 256 } 257 } 258 259 if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { 260 print_error('invalidgradeitemid'); 261 } 262 263 // Pre-process grade 264 if ($datatype == 'grade') { 265 $feedback = false; 266 $feedbackformat = false; 267 if ($gradeitem->gradetype == GRADE_TYPE_SCALE) { 268 if ($postedvalue == -1) { // -1 means no grade 269 $finalgrade = null; 270 } else { 271 $finalgrade = $postedvalue; 272 } 273 } else { 274 $finalgrade = unformat_float($postedvalue); 275 } 276 277 $errorstr = ''; 278 $skip = false; 279 280 $dategraded = $oldvalue->get_dategraded(); 281 if (!empty($dategraded) && $timepageload < $dategraded) { 282 // Warn if the grade was updated while we were editing this form. 283 $errorstr = 'gradewasmodifiedduringediting'; 284 $skip = true; 285 } else if (!is_null($finalgrade)) { 286 // Warn if the grade is out of bounds. 287 $bounded = $gradeitem->bounded_grade($finalgrade); 288 if ($bounded > $finalgrade) { 289 $errorstr = 'lessthanmin'; 290 } else if ($bounded < $finalgrade) { 291 $errorstr = 'morethanmax'; 292 } 293 } 294 295 if ($errorstr) { 296 $userfieldsapi = \core_user\fields::for_name(); 297 $userfields = 'id, ' . $userfieldsapi->get_sql('', false, '', '', false)->selects; 298 $user = $DB->get_record('user', array('id' => $userid), $userfields); 299 $gradestr = new stdClass(); 300 $gradestr->username = fullname($user, $viewfullnames); 301 $gradestr->itemname = $gradeitem->get_name(); 302 $warnings[] = get_string($errorstr, 'grades', $gradestr); 303 if ($skip) { 304 // Skipping the update of this grade it failed the tests above. 305 continue; 306 } 307 } 308 309 } else if ($datatype == 'feedback') { 310 $finalgrade = false; 311 $trimmed = trim($postedvalue); 312 if (empty($trimmed)) { 313 $feedback = null; 314 } else { 315 $feedback = $postedvalue; 316 } 317 } 318 319 // group access control 320 if ($separategroups) { 321 // note: we can not use $this->currentgroup because it would fail badly 322 // when having two browser windows each with different group 323 $sharinggroup = false; 324 foreach ($mygroups as $groupid) { 325 if (groups_is_member($groupid, $userid)) { 326 $sharinggroup = true; 327 break; 328 } 329 } 330 if (!$sharinggroup) { 331 // either group membership changed or somebody is hacking grades of other group 332 $warnings[] = get_string('errorsavegrade', 'grades'); 333 continue; 334 } 335 } 336 337 $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, 338 FORMAT_MOODLE, null, null, true); 339 340 // We can update feedback without reloading the grade item as it doesn't affect grade calculations 341 if ($datatype === 'feedback') { 342 $this->grades[$userid][$itemid]->feedback = $feedback; 343 } 344 } 345 } 346 } 347 348 if ($changedgrades) { 349 // If a final grade was overriden reload grades so dependent grades like course total will be correct 350 $this->grades = null; 351 } 352 353 return $warnings; 354 } 355 356 357 /** 358 * Setting the sort order, this depends on last state 359 * all this should be in the new table class that we might need to use 360 * for displaying grades. 361 */ 362 private function setup_sortitemid() { 363 364 global $SESSION; 365 366 if (!isset($SESSION->gradeuserreport)) { 367 $SESSION->gradeuserreport = new stdClass(); 368 } 369 370 if ($this->sortitemid) { 371 if (!isset($SESSION->gradeuserreport->sort)) { 372 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC'; 373 } else { 374 // this is the first sort, i.e. by last name 375 if (!isset($SESSION->gradeuserreport->sortitemid)) { 376 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC'; 377 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) { 378 // same as last sort 379 if ($SESSION->gradeuserreport->sort == 'ASC') { 380 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC'; 381 } else { 382 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC'; 383 } 384 } else { 385 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC'; 386 } 387 } 388 $SESSION->gradeuserreport->sortitemid = $this->sortitemid; 389 } else { 390 // not requesting sort, use last setting (for paging) 391 392 if (isset($SESSION->gradeuserreport->sortitemid)) { 393 $this->sortitemid = $SESSION->gradeuserreport->sortitemid; 394 } else { 395 $this->sortitemid = 'lastname'; 396 } 397 398 if (isset($SESSION->gradeuserreport->sort)) { 399 $this->sortorder = $SESSION->gradeuserreport->sort; 400 } else { 401 $this->sortorder = 'ASC'; 402 } 403 } 404 } 405 406 /** 407 * pulls out the userids of the users to be display, and sorts them 408 */ 409 public function load_users() { 410 global $CFG, $DB; 411 412 if (!empty($this->users)) { 413 return; 414 } 415 $this->setup_users(); 416 417 // Limit to users with a gradeable role. 418 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0'); 419 420 // Check the status of showing only active enrolments. 421 $coursecontext = $this->context->get_course_context(true); 422 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); 423 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); 424 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext); 425 426 // Limit to users with an active enrollment. 427 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol); 428 429 // Fields we need from the user table. 430 $userfieldsapi = \core_user\fields::for_identity($this->context)->with_userpic(); 431 $userfieldssql = $userfieldsapi->get_sql('u', true, '', '', false); 432 433 // We want to query both the current context and parent contexts. 434 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx'); 435 436 // If the user has clicked one of the sort asc/desc arrows. 437 if (is_numeric($this->sortitemid)) { 438 $params = array_merge(array('gitemid' => $this->sortitemid), $gradebookrolesparams, $this->userwheresql_params, 439 $this->groupwheresql_params, $enrolledparams, $relatedctxparams); 440 441 $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid"; 442 $sort = "g.finalgrade $this->sortorder, u.idnumber, u.lastname, u.firstname, u.email"; 443 } else { 444 $sortjoin = ''; 445 446 // The default sort will be that provided by the site for users, unless a valid user field is requested, 447 // the value of which takes precedence. 448 [$sort] = users_order_by_sql('u', null, $this->context, $userfieldssql->mappings); 449 if (array_key_exists($this->sortitemid, $userfieldssql->mappings)) { 450 451 // Ensure user sort field doesn't duplicate one of the default sort fields. 452 $usersortfield = $userfieldssql->mappings[$this->sortitemid]; 453 $defaultsortfields = array_diff(explode(', ', $sort), [$usersortfield]); 454 455 $sort = "{$usersortfield} {$this->sortorder}, " . implode(', ', $defaultsortfields); 456 } 457 458 $params = array_merge($gradebookrolesparams, $this->userwheresql_params, $this->groupwheresql_params, $enrolledparams, $relatedctxparams); 459 } 460 $params = array_merge($userfieldssql->params, $params); 461 $sql = "SELECT {$userfieldssql->selects} 462 FROM {user} u 463 {$userfieldssql->joins} 464 JOIN ($enrolledsql) je ON je.id = u.id 465 $this->groupsql 466 $sortjoin 467 JOIN ( 468 SELECT DISTINCT ra.userid 469 FROM {role_assignments} ra 470 WHERE ra.roleid IN ($this->gradebookroles) 471 AND ra.contextid $relatedctxsql 472 ) rainner ON rainner.userid = u.id 473 AND u.deleted = 0 474 $this->userwheresql 475 $this->groupwheresql 476 ORDER BY $sort"; 477 $studentsperpage = $this->get_students_per_page(); 478 $this->users = $DB->get_records_sql($sql, $params, $studentsperpage * $this->page, $studentsperpage); 479 480 if (empty($this->users)) { 481 $this->userselect = ''; 482 $this->users = array(); 483 $this->userselect_params = array(); 484 } else { 485 list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0'); 486 $this->userselect = "AND g.userid $usql"; 487 $this->userselect_params = $uparams; 488 489 // First flag everyone as not suspended. 490 foreach ($this->users as $user) { 491 $this->users[$user->id]->suspendedenrolment = false; 492 } 493 494 // If we want to mix both suspended and not suspended users, let's find out who is suspended. 495 if (!$showonlyactiveenrol) { 496 $sql = "SELECT ue.userid 497 FROM {user_enrolments} ue 498 JOIN {enrol} e ON e.id = ue.enrolid 499 WHERE ue.userid $usql 500 AND ue.status = :uestatus 501 AND e.status = :estatus 502 AND e.courseid = :courseid 503 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2) 504 GROUP BY ue.userid"; 505 506 $time = time(); 507 $params = array_merge($uparams, array('estatus' => ENROL_INSTANCE_ENABLED, 'uestatus' => ENROL_USER_ACTIVE, 508 'courseid' => $coursecontext->instanceid, 'now1' => $time, 'now2' => $time)); 509 $useractiveenrolments = $DB->get_records_sql($sql, $params); 510 511 foreach ($this->users as $user) { 512 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments); 513 } 514 } 515 } 516 return $this->users; 517 } 518 519 /** 520 * Load all grade items. 521 */ 522 protected function get_allgradeitems() { 523 if (!empty($this->allgradeitems)) { 524 return $this->allgradeitems; 525 } 526 $allgradeitems = grade_item::fetch_all(array('courseid' => $this->courseid)); 527 // But hang on - don't include ones which are set to not show the grade at all. 528 $this->allgradeitems = array_filter($allgradeitems, function($item) { 529 return $item->gradetype != GRADE_TYPE_NONE; 530 }); 531 532 return $this->allgradeitems; 533 } 534 535 /** 536 * we supply the userids in this query, and get all the grades 537 * pulls out all the grades, this does not need to worry about paging 538 */ 539 public function load_final_grades() { 540 global $CFG, $DB; 541 542 if (!empty($this->grades)) { 543 return; 544 } 545 546 if (empty($this->users)) { 547 return; 548 } 549 550 // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it! 551 $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params); 552 $sql = "SELECT g.* 553 FROM {grade_items} gi, 554 {grade_grades} g 555 WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}"; 556 557 $userids = array_keys($this->users); 558 $allgradeitems = $this->get_allgradeitems(); 559 560 if ($grades = $DB->get_records_sql($sql, $params)) { 561 foreach ($grades as $graderec) { 562 $grade = new grade_grade($graderec, false); 563 if (!empty($allgradeitems[$graderec->itemid])) { 564 // Note: Filter out grades which have a grade type of GRADE_TYPE_NONE. 565 // Only grades without this type are present in $allgradeitems. 566 $this->allgrades[$graderec->userid][$graderec->itemid] = $grade; 567 } 568 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!! 569 $this->grades[$graderec->userid][$graderec->itemid] = $grade; 570 $this->grades[$graderec->userid][$graderec->itemid]->grade_item = $this->gtree->get_item($graderec->itemid); // db caching 571 } 572 } 573 } 574 575 // prefil grades that do not exist yet 576 foreach ($userids as $userid) { 577 foreach ($this->gtree->get_items() as $itemid => $unused) { 578 if (!isset($this->grades[$userid][$itemid])) { 579 $this->grades[$userid][$itemid] = new grade_grade(); 580 $this->grades[$userid][$itemid]->itemid = $itemid; 581 $this->grades[$userid][$itemid]->userid = $userid; 582 $this->grades[$userid][$itemid]->grade_item = $this->gtree->get_item($itemid); // db caching 583 584 $this->allgrades[$userid][$itemid] = $this->grades[$userid][$itemid]; 585 } 586 } 587 } 588 589 // Pre fill grades for any remaining items which might be collapsed. 590 foreach ($userids as $userid) { 591 foreach ($allgradeitems as $itemid => $gradeitem) { 592 if (!isset($this->allgrades[$userid][$itemid])) { 593 $this->allgrades[$userid][$itemid] = new grade_grade(); 594 $this->allgrades[$userid][$itemid]->itemid = $itemid; 595 $this->allgrades[$userid][$itemid]->userid = $userid; 596 $this->allgrades[$userid][$itemid]->grade_item = $gradeitem; 597 } 598 } 599 } 600 } 601 602 /** 603 * Gets html toggle 604 * @deprecated since Moodle 2.4 as it appears not to be used any more. 605 */ 606 public function get_toggles_html() { 607 throw new coding_exception('get_toggles_html() can not be used any more'); 608 } 609 610 /** 611 * Prints html toggle 612 * @deprecated since 2.4 as it appears not to be used any more. 613 * @param unknown $type 614 */ 615 public function print_toggle($type) { 616 throw new coding_exception('print_toggle() can not be used any more'); 617 } 618 619 /** 620 * Builds and returns the rows that will make up the left part of the grader report 621 * This consists of student names and icons, links to user reports and id numbers, as well 622 * as header cells for these columns. It also includes the fillers required for the 623 * categories displayed on the right side of the report. 624 * @param boolean $displayaverages whether to display average rows in the table 625 * @return array Array of html_table_row objects 626 */ 627 public function get_left_rows($displayaverages) { 628 global $CFG, $USER, $OUTPUT; 629 630 $rows = array(); 631 632 $showuserimage = $this->get_pref('showuserimage'); 633 // FIXME: MDL-52678 This get_capability_info is hacky and we should have an API for inserting grade row links instead. 634 $canseeuserreport = false; 635 $canseesingleview = false; 636 if (get_capability_info('gradereport/'.$CFG->grade_profilereport.':view')) { 637 $canseeuserreport = has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context); 638 } 639 if (get_capability_info('gradereport/singleview:view')) { 640 $canseesingleview = has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall', 641 'moodle/grade:edit'), $this->context); 642 } 643 $hasuserreportcell = $canseeuserreport || $canseesingleview; 644 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context); 645 646 $strfeedback = $this->get_lang_string("feedback"); 647 648 $extrafields = \core_user\fields::get_identity_fields($this->context); 649 650 $arrows = $this->get_sort_arrows($extrafields); 651 652 $colspan = 1 + $hasuserreportcell + count($extrafields); 653 654 $levels = count($this->gtree->levels) - 1; 655 656 $fillercell = new html_table_cell(); 657 $fillercell->header = true; 658 $fillercell->attributes['scope'] = 'col'; 659 $fillercell->attributes['class'] = 'cell topleft'; 660 $fillercell->text = html_writer::span(get_string('participants'), 'accesshide'); 661 $fillercell->colspan = $colspan; 662 $fillercell->rowspan = $levels; 663 $row = new html_table_row(array($fillercell)); 664 $rows[] = $row; 665 666 for ($i = 1; $i < $levels; $i++) { 667 $row = new html_table_row(); 668 $rows[] = $row; 669 } 670 671 $headerrow = new html_table_row(); 672 $headerrow->attributes['class'] = 'heading'; 673 674 $studentheader = new html_table_cell(); 675 // The browser's scrollbar may partly cover (in certain operative systems) the content in the student header 676 // when horizontally scrolling through the table contents (most noticeable when in RTL mode). 677 // Therefore, add slight padding on the left or right when using RTL mode. 678 $studentheader->attributes['class'] = "header pl-3"; 679 $studentheader->scope = 'col'; 680 $studentheader->header = true; 681 $studentheader->id = 'studentheader'; 682 $studentheader->text = $arrows['studentname']; 683 $headerrow->cells[] = $studentheader; 684 685 if ($hasuserreportcell) { 686 $emptyheader = new html_table_cell(); 687 $headerrow->cells[] = $emptyheader; 688 } 689 690 foreach ($extrafields as $field) { 691 $fieldheader = new html_table_cell(); 692 $fieldheader->attributes['class'] = 'userfield user' . $field; 693 $fieldheader->scope = 'col'; 694 $fieldheader->header = true; 695 $fieldheader->text = $arrows[$field]; 696 697 $headerrow->cells[] = $fieldheader; 698 } 699 700 $rows[] = $headerrow; 701 702 $rows = $this->get_left_icons_row($rows, $colspan); 703 704 $suspendedstring = null; 705 706 $usercount = 0; 707 foreach ($this->users as $userid => $user) { 708 $userrow = new html_table_row(); 709 $userrow->id = 'fixed_user_'.$userid; 710 $userrow->attributes['class'] = ($usercount % 2) ? 'userrow even' : 'userrow odd'; 711 712 $usercell = new html_table_cell(); 713 $usercell->attributes['class'] = ($usercount % 2) ? 'header user even' : 'header user odd'; 714 $usercount++; 715 716 $usercell->header = true; 717 $usercell->scope = 'row'; 718 719 if ($showuserimage) { 720 $usercell->text = $OUTPUT->user_picture($user, ['link' => false, 'visibletoscreenreaders' => false]); 721 } 722 723 $fullname = fullname($user, $viewfullnames); 724 $usercell->text = html_writer::link( 725 new moodle_url('/user/view.php', ['id' => $user->id, 'course' => $this->course->id]), 726 $usercell->text . $fullname, 727 ['class' => 'username'] 728 ); 729 730 if (!empty($user->suspendedenrolment)) { 731 $usercell->attributes['class'] .= ' usersuspended'; 732 733 //may be lots of suspended users so only get the string once 734 if (empty($suspendedstring)) { 735 $suspendedstring = get_string('userenrolmentsuspended', 'grades'); 736 } 737 $icon = $OUTPUT->pix_icon('i/enrolmentsuspended', $suspendedstring); 738 $usercell->text .= html_writer::tag('span', $icon, array('class'=>'usersuspendedicon')); 739 } 740 // The browser's scrollbar may partly cover (in certain operative systems) the content in the user cells 741 // when horizontally scrolling through the table contents (most noticeable when in RTL mode). 742 // Therefore, add slight padding on the left or right when using RTL mode. 743 $usercell->attributes['class'] .= ' pl-3'; 744 745 $userrow->cells[] = $usercell; 746 747 $userreportcell = new html_table_cell(); 748 $userreportcell->attributes['class'] = 'userreport'; 749 $userreportcell->header = false; 750 if ($canseeuserreport) { 751 $a = new stdClass(); 752 $a->user = $fullname; 753 $strgradesforuser = get_string('gradesforuser', 'grades', $a); 754 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', 755 ['userid' => $user->id, 'id' => $this->course->id]); 756 $userreportcell->text .= $OUTPUT->action_icon($url, new pix_icon('t/grades', ''), null, 757 ['title' => $strgradesforuser, 'aria-label' => $strgradesforuser]); 758 } 759 760 if ($canseesingleview) { 761 $strsingleview = get_string('singleview', 'grades', $fullname); 762 $url = new moodle_url('/grade/report/singleview/index.php', 763 ['id' => $this->course->id, 'itemid' => $user->id, 'item' => 'user']); 764 $singleview = $OUTPUT->action_icon($url, new pix_icon('t/editstring', ''), null, 765 ['title' => $strsingleview, 'aria-label' => $strsingleview]); 766 $userreportcell->text .= $singleview; 767 } 768 769 if ($userreportcell->text) { 770 $userrow->cells[] = $userreportcell; 771 } 772 773 foreach ($extrafields as $field) { 774 $fieldcell = new html_table_cell(); 775 $fieldcell->attributes['class'] = 'userfield user' . $field; 776 $fieldcell->header = false; 777 $fieldcell->text = s($user->{$field}); 778 $userrow->cells[] = $fieldcell; 779 } 780 781 $userrow->attributes['data-uid'] = $userid; 782 $rows[] = $userrow; 783 } 784 785 $rows = $this->get_left_range_row($rows, $colspan); 786 if ($displayaverages) { 787 $rows = $this->get_left_avg_row($rows, $colspan, true); 788 $rows = $this->get_left_avg_row($rows, $colspan); 789 } 790 791 return $rows; 792 } 793 794 /** 795 * Builds and returns the rows that will make up the right part of the grader report 796 * @param boolean $displayaverages whether to display average rows in the table 797 * @return array Array of html_table_row objects 798 */ 799 public function get_right_rows($displayaverages) { 800 global $CFG, $USER, $OUTPUT, $DB, $PAGE; 801 802 $rows = array(); 803 $this->rowcount = 0; 804 $numrows = count($this->gtree->get_levels()); 805 $numusers = count($this->users); 806 $gradetabindex = 1; 807 $columnstounset = array(); 808 $strgrade = $this->get_lang_string('gradenoun'); 809 $strfeedback = $this->get_lang_string("feedback"); 810 $arrows = $this->get_sort_arrows(); 811 812 $jsarguments = array( 813 'cfg' => array('ajaxenabled'=>false), 814 'items' => array(), 815 'users' => array(), 816 'feedback' => array(), 817 'grades' => array() 818 ); 819 $jsscales = array(); 820 821 // Get preferences once. 822 $showactivityicons = $this->get_pref('showactivityicons'); 823 $quickgrading = $this->get_pref('quickgrading'); 824 $showquickfeedback = $this->get_pref('showquickfeedback'); 825 $enableajax = $this->get_pref('enableajax'); 826 $showanalysisicon = $this->get_pref('showanalysisicon'); 827 828 // Get strings which are re-used inside the loop. 829 $strftimedatetimeshort = get_string('strftimedatetimeshort'); 830 $strexcludedgrades = get_string('excluded', 'grades'); 831 $strerror = get_string('error'); 832 833 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context); 834 835 foreach ($this->gtree->get_levels() as $key => $row) { 836 $headingrow = new html_table_row(); 837 $headingrow->attributes['class'] = 'heading_name_row'; 838 839 foreach ($row as $columnkey => $element) { 840 $sortlink = clone($this->baseurl); 841 if (isset($element['object']->id)) { 842 $sortlink->param('sortitemid', $element['object']->id); 843 } 844 845 $eid = $element['eid']; 846 $object = $element['object']; 847 $type = $element['type']; 848 $categorystate = @$element['categorystate']; 849 850 if (!empty($element['colspan'])) { 851 $colspan = $element['colspan']; 852 } else { 853 $colspan = 1; 854 } 855 856 if (!empty($element['depth'])) { 857 $catlevel = 'catlevel'.$element['depth']; 858 } else { 859 $catlevel = ''; 860 } 861 862 // Element is a filler 863 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') { 864 $fillercell = new html_table_cell(); 865 $fillercell->attributes['class'] = $type . ' ' . $catlevel; 866 $fillercell->colspan = $colspan; 867 $fillercell->text = ' '; 868 869 // This is a filler cell; don't use a <th>, it'll confuse screen readers. 870 $fillercell->header = false; 871 $headingrow->cells[] = $fillercell; 872 } else if ($type == 'category') { 873 // Make sure the grade category has a grade total or at least has child grade items. 874 if (grade_tree::can_output_item($element)) { 875 // Element is a category. 876 $categorycell = new html_table_cell(); 877 $categorycell->attributes['class'] = 'category ' . $catlevel; 878 $categorycell->colspan = $colspan; 879 $categorycell->text = $this->get_course_header($element); 880 $categorycell->header = true; 881 $categorycell->scope = 'col'; 882 883 // Print icons. 884 if (!empty($USER->editing)) { 885 $categorycell->text .= $this->get_icons($element); 886 } 887 888 $headingrow->cells[] = $categorycell; 889 } 890 } else { 891 // Element is a grade_item 892 if ($element['object']->id == $this->sortitemid) { 893 if ($this->sortorder == 'ASC') { 894 $arrow = $this->get_sort_arrow('up', $sortlink); 895 } else { 896 $arrow = $this->get_sort_arrow('down', $sortlink); 897 } 898 } else { 899 $arrow = $this->get_sort_arrow('move', $sortlink); 900 } 901 902 $headerlink = $this->gtree->get_element_header($element, true, $showactivityicons, false, false, true); 903 904 $itemcell = new html_table_cell(); 905 $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable'. ' i'. $element['object']->id; 906 $itemcell->attributes['data-itemid'] = $element['object']->id; 907 908 if ($element['object']->is_hidden()) { 909 $itemcell->attributes['class'] .= ' dimmed_text'; 910 } 911 912 $singleview = ''; 913 914 // FIXME: MDL-52678 This is extremely hacky we should have an API for inserting grade column links. 915 if (get_capability_info('gradereport/singleview:view')) { 916 if (has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall', 917 'moodle/grade:edit'), $this->context)) { 918 919 $strsingleview = get_string('singleview', 'grades', $element['object']->get_name()); 920 $url = new moodle_url('/grade/report/singleview/index.php', array( 921 'id' => $this->course->id, 922 'item' => 'grade', 923 'itemid' => $element['object']->id)); 924 $singleview = $OUTPUT->action_icon( 925 $url, 926 new pix_icon('t/editstring', ''), 927 null, 928 ['title' => $strsingleview, 'aria-label' => $strsingleview] 929 ); 930 } 931 } 932 933 $itemcell->colspan = $colspan; 934 $itemcell->text = $headerlink . $arrow . $singleview; 935 $itemcell->header = true; 936 $itemcell->scope = 'col'; 937 938 $headingrow->cells[] = $itemcell; 939 } 940 } 941 $rows[] = $headingrow; 942 } 943 944 $rows = $this->get_right_icons_row($rows); 945 946 // Preload scale objects for items with a scaleid and initialize tab indices 947 $scaleslist = array(); 948 $tabindices = array(); 949 950 foreach ($this->gtree->get_items() as $itemid => $item) { 951 $scale = null; 952 if (!empty($item->scaleid)) { 953 $scaleslist[] = $item->scaleid; 954 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals()); 955 } else { 956 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals()); 957 } 958 $tabindices[$item->id]['grade'] = $gradetabindex; 959 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers; 960 $gradetabindex += $numusers * 2; 961 } 962 $scalesarray = array(); 963 964 if (!empty($scaleslist)) { 965 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist); 966 } 967 $jsscales = $scalesarray; 968 969 // Get all the grade items if the user can not view hidden grade items. 970 // It is possible that the user is simply viewing the 'Course total' by switching to the 'Aggregates only' view 971 // and that this user does not have the ability to view hidden items. In this case we still need to pass all the 972 // grade items (in case one has been hidden) as the course total shown needs to be adjusted for this particular 973 // user. 974 if (!$this->canviewhidden) { 975 $allgradeitems = $this->get_allgradeitems(); 976 } 977 978 foreach ($this->users as $userid => $user) { 979 980 if ($this->canviewhidden) { 981 $altered = array(); 982 $unknown = array(); 983 } else { 984 $usergrades = $this->allgrades[$userid]; 985 $hidingaffected = grade_grade::get_hiding_affected($usergrades, $allgradeitems); 986 $altered = $hidingaffected['altered']; 987 $unknown = $hidingaffected['unknowngrades']; 988 unset($hidingaffected); 989 } 990 991 $itemrow = new html_table_row(); 992 $itemrow->id = 'user_'.$userid; 993 994 $fullname = fullname($user, $viewfullnames); 995 $jsarguments['users'][$userid] = $fullname; 996 997 foreach ($this->gtree->items as $itemid => $unused) { 998 $item =& $this->gtree->items[$itemid]; 999 $grade = $this->grades[$userid][$item->id]; 1000 1001 $itemcell = new html_table_cell(); 1002 1003 $itemcell->id = 'u'.$userid.'i'.$itemid; 1004 $itemcell->attributes['data-itemid'] = $itemid; 1005 1006 // Get the decimal points preference for this item 1007 $decimalpoints = $item->get_decimals(); 1008 1009 if (array_key_exists($itemid, $unknown)) { 1010 $gradeval = null; 1011 } else if (array_key_exists($itemid, $altered)) { 1012 $gradeval = $altered[$itemid]; 1013 } else { 1014 $gradeval = $grade->finalgrade; 1015 } 1016 if (!empty($grade->finalgrade)) { 1017 $gradevalforjs = null; 1018 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 1019 $gradevalforjs = (int)$gradeval; 1020 } else { 1021 $gradevalforjs = format_float($gradeval, $decimalpoints); 1022 } 1023 $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforjs); 1024 } 1025 1026 // MDL-11274 1027 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden' 1028 if (!$this->canviewhidden and $grade->is_hidden()) { 1029 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) { 1030 // the problem here is that we do not have the time when grade value was modified, 'timemodified' is general modification date for grade_grades records 1031 $itemcell->text = "<span class='datesubmitted'>" . 1032 userdate($grade->get_datesubmitted(), $strftimedatetimeshort) . "</span>"; 1033 } else { 1034 $itemcell->text = '-'; 1035 } 1036 $itemrow->cells[] = $itemcell; 1037 continue; 1038 } 1039 1040 // emulate grade element 1041 $eid = $this->gtree->get_grade_eid($grade); 1042 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade'); 1043 1044 $itemcell->attributes['class'] .= ' grade i'.$itemid; 1045 if ($item->is_category_item()) { 1046 $itemcell->attributes['class'] .= ' cat'; 1047 } 1048 if ($item->is_course_item()) { 1049 $itemcell->attributes['class'] .= ' course'; 1050 } 1051 if ($grade->is_overridden()) { 1052 $itemcell->attributes['class'] .= ' overridden'; 1053 $itemcell->attributes['aria-label'] = get_string('overriddengrade', 'gradereport_grader'); 1054 } 1055 1056 if (!empty($grade->feedback)) { 1057 $feedback = wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br>'); 1058 $itemcell->attributes['data-feedback'] = $feedback; 1059 $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content' => $feedback); 1060 } 1061 1062 if ($grade->is_excluded()) { 1063 // Adding white spaces before and after to prevent a screenreader from 1064 // thinking that the words are attached to the next/previous <span> or text. 1065 $itemcell->text .= " <span class='excludedfloater'>" . $strexcludedgrades . "</span> "; 1066 } 1067 1068 // Do not show any icons if no grade (no record in DB to match) 1069 if (!$item->needsupdate and !empty($USER->editing)) { 1070 $itemcell->text .= $this->get_icons($element); 1071 } 1072 1073 $hidden = ''; 1074 if ($grade->is_hidden()) { 1075 $hidden = ' dimmed_text '; 1076 } 1077 1078 $gradepass = ' gradefail '; 1079 $gradepassicon = $OUTPUT->pix_icon('i/invalid', get_string('fail', 'grades')); 1080 if ($grade->is_passed($item)) { 1081 $gradepass = ' gradepass '; 1082 $gradepassicon = $OUTPUT->pix_icon('i/valid', get_string('pass', 'grades')); 1083 } else if (is_null($grade->is_passed($item))) { 1084 $gradepass = ''; 1085 $gradepassicon = ''; 1086 } 1087 1088 // if in editing mode, we need to print either a text box 1089 // or a drop down (for scales) 1090 // grades in item of type grade category or course are not directly editable 1091 if ($item->needsupdate) { 1092 $itemcell->text .= "<span class='gradingerror{$hidden}'>" . $strerror . "</span>"; 1093 1094 } else if (!empty($USER->editing)) { 1095 1096 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 1097 $itemcell->attributes['class'] .= ' grade_type_scale'; 1098 } else if ($item->gradetype == GRADE_TYPE_VALUE) { 1099 $itemcell->attributes['class'] .= ' grade_type_value'; 1100 } else if ($item->gradetype == GRADE_TYPE_TEXT) { 1101 $itemcell->attributes['class'] .= ' grade_type_text'; 1102 } 1103 1104 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 1105 $scale = $scalesarray[$item->scaleid]; 1106 $gradeval = (int)$gradeval; // scales use only integers 1107 $scales = explode(",", $scale->scale); 1108 // reindex because scale is off 1 1109 1110 // MDL-12104 some previous scales might have taken up part of the array 1111 // so this needs to be reset 1112 $scaleopt = array(); 1113 $i = 0; 1114 foreach ($scales as $scaleoption) { 1115 $i++; 1116 $scaleopt[$i] = $scaleoption; 1117 } 1118 1119 if ($quickgrading and $grade->is_editable()) { 1120 $oldval = empty($gradeval) ? -1 : $gradeval; 1121 if (empty($item->outcomeid)) { 1122 $nogradestr = $this->get_lang_string('nograde'); 1123 } else { 1124 $nogradestr = $this->get_lang_string('nooutcome', 'grades'); 1125 } 1126 $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id); 1127 $gradelabel = $fullname . ' ' . $item->get_name(true); 1128 $itemcell->text .= html_writer::label( 1129 get_string('useractivitygrade', 'gradereport_grader', $gradelabel), $attributes['id'], false, 1130 array('class' => 'accesshide')); 1131 $itemcell->text .= html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']', $gradeval, array(-1=>$nogradestr), $attributes); 1132 } else if (!empty($scale)) { 1133 $scales = explode(",", $scale->scale); 1134 1135 // invalid grade if gradeval < 1 1136 if ($gradeval < 1) { 1137 $itemcell->text .= $gradepassicon . 1138 "<span class='gradevalue{$hidden}{$gradepass}'>-</span>"; 1139 } else { 1140 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale 1141 $itemcell->text .= $gradepassicon . 1142 "<span class='gradevalue{$hidden}{$gradepass}'>{$scales[$gradeval - 1]}</span>"; 1143 } 1144 } 1145 1146 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type 1147 if ($quickgrading and $grade->is_editable()) { 1148 $value = format_float($gradeval, $decimalpoints); 1149 $gradelabel = $fullname . ' ' . $item->get_name(true); 1150 $itemcell->text .= '<label class="accesshide" for="grade_'.$userid.'_'.$item->id.'">' 1151 .get_string('useractivitygrade', 'gradereport_grader', $gradelabel).'</label>'; 1152 $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade'] 1153 . '" type="text" class="text" title="'. $strgrade .'" name="grade[' 1154 .$userid.'][' .$item->id.']" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />'; 1155 } else { 1156 $itemcell->text .= $gradepassicon . "<span class='gradevalue{$hidden}{$gradepass}'>" . 1157 format_float($gradeval, $decimalpoints) . "</span>"; 1158 } 1159 } 1160 1161 // If quickfeedback is on, print an input element 1162 if ($showquickfeedback and $grade->is_editable()) { 1163 $feedbacklabel = $fullname . ' ' . $item->get_name(true); 1164 $itemcell->text .= '<label class="accesshide" for="feedback_'.$userid.'_'.$item->id.'">' 1165 .get_string('useractivityfeedback', 'gradereport_grader', $feedbacklabel).'</label>'; 1166 $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id 1167 . '" size="6" title="' . $strfeedback . '" type="text" name="feedback['.$userid.']['.$item->id.']" value="' . s($grade->feedback) . '" />'; 1168 } 1169 1170 } else { // Not editing 1171 $gradedisplaytype = $item->get_displaytype(); 1172 1173 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) { 1174 $itemcell->attributes['class'] .= ' grade_type_scale'; 1175 } else if ($item->gradetype == GRADE_TYPE_VALUE) { 1176 $itemcell->attributes['class'] .= ' grade_type_value'; 1177 } else if ($item->gradetype == GRADE_TYPE_TEXT) { 1178 $itemcell->attributes['class'] .= ' grade_type_text'; 1179 } 1180 1181 // Only allow edting if the grade is editable (not locked, not in a unoverridable category, etc). 1182 if ($enableajax && $grade->is_editable()) { 1183 // If a grade item is type text, and we don't have show quick feedback on, it can't be edited. 1184 if ($item->gradetype != GRADE_TYPE_TEXT || $showquickfeedback) { 1185 $itemcell->attributes['class'] .= ' clickable'; 1186 } 1187 } 1188 1189 if ($item->needsupdate) { 1190 $itemcell->text .= $gradepassicon . "<span class='gradingerror{$hidden}{$gradepass}'>" . $error . "</span>"; 1191 } else { 1192 // The max and min for an aggregation may be different to the grade_item. 1193 if (!is_null($gradeval)) { 1194 $item->grademax = $grade->get_grade_max(); 1195 $item->grademin = $grade->get_grade_min(); 1196 } 1197 1198 $itemcell->text .= $gradepassicon . "<span class='gradevalue{$hidden}{$gradepass}'>" . 1199 grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null) . "</span>"; 1200 if ($showanalysisicon) { 1201 $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade); 1202 } 1203 } 1204 } 1205 1206 // Enable keyboard navigation if the grade is editable (not locked, not in a unoverridable category, etc). 1207 if ($enableajax && $grade->is_editable()) { 1208 // If a grade item is type text, and we don't have show quick feedback on, it can't be edited. 1209 if ($item->gradetype != GRADE_TYPE_TEXT || $showquickfeedback) { 1210 $itemcell->attributes['class'] .= ' gbnavigable'; 1211 } 1212 } 1213 1214 if (!empty($this->gradeserror[$item->id][$userid])) { 1215 $itemcell->text .= $this->gradeserror[$item->id][$userid]; 1216 } 1217 1218 $itemrow->cells[] = $itemcell; 1219 } 1220 $rows[] = $itemrow; 1221 } 1222 1223 if ($enableajax) { 1224 $jsarguments['cfg']['ajaxenabled'] = true; 1225 $jsarguments['cfg']['scales'] = array(); 1226 foreach ($jsscales as $scale) { 1227 // Trim the scale values, as they may have a space that is ommitted from values later. 1228 $jsarguments['cfg']['scales'][$scale->id] = array_map('trim', explode(',', $scale->scale)); 1229 } 1230 $jsarguments['cfg']['feedbacktrunclength'] = $this->feedback_trunc_length; 1231 1232 // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades'] 1233 } 1234 $jsarguments['cfg']['isediting'] = !empty($USER->editing); 1235 $jsarguments['cfg']['courseid'] = $this->courseid; 1236 $jsarguments['cfg']['studentsperpage'] = $this->get_students_per_page(); 1237 $jsarguments['cfg']['showquickfeedback'] = (bool) $showquickfeedback; 1238 1239 $module = array( 1240 'name' => 'gradereport_grader', 1241 'fullpath' => '/grade/report/grader/module.js', 1242 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay') 1243 ); 1244 $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module); 1245 $PAGE->requires->strings_for_js(array('addfeedback', 'feedback', 'grade'), 'grades'); 1246 $PAGE->requires->strings_for_js(array('ajaxchoosescale', 'ajaxclicktoclose', 'ajaxerror', 'ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader'); 1247 if (!$enableajax && !empty($USER->editing)) { 1248 $PAGE->requires->js_call_amd('core_form/changechecker', 'watchFormById', ['gradereport_grader']); 1249 } 1250 1251 $rows = $this->get_right_range_row($rows); 1252 if ($displayaverages) { 1253 $rows = $this->get_right_avg_row($rows, true); 1254 $rows = $this->get_right_avg_row($rows); 1255 } 1256 1257 return $rows; 1258 } 1259 1260 /** 1261 * Depending on the style of report (fixedstudents vs traditional one-table), 1262 * arranges the rows of data in one or two tables, and returns the output of 1263 * these tables in HTML 1264 * @param boolean $displayaverages whether to display average rows in the table 1265 * @return string HTML 1266 */ 1267 public function get_grade_table($displayaverages = false) { 1268 global $OUTPUT; 1269 $leftrows = $this->get_left_rows($displayaverages); 1270 $rightrows = $this->get_right_rows($displayaverages); 1271 1272 $html = ''; 1273 1274 $fulltable = new html_table(); 1275 $fulltable->attributes['class'] = 'gradereport-grader-table'; 1276 $fulltable->id = 'user-grades'; 1277 $fulltable->caption = get_string('summarygrader', 'gradereport_grader'); 1278 $fulltable->captionhide = true; 1279 // We don't want the table to be enclosed within in a .table-responsive div as it is heavily customised. 1280 $fulltable->responsive = false; 1281 1282 // Extract rows from each side (left and right) and collate them into one row each 1283 foreach ($leftrows as $key => $row) { 1284 $row->cells = array_merge($row->cells, $rightrows[$key]->cells); 1285 $fulltable->data[] = $row; 1286 } 1287 $html .= html_writer::table($fulltable); 1288 return $OUTPUT->container($html, 'gradeparent'); 1289 } 1290 1291 /** 1292 * Builds and return the row of icons for the left side of the report. 1293 * It only has one cell that says "Controls" 1294 * @param array $rows The Array of rows for the left part of the report 1295 * @param int $colspan The number of columns this cell has to span 1296 * @return array Array of rows for the left part of the report 1297 */ 1298 public function get_left_icons_row($rows=array(), $colspan=1) { 1299 global $USER; 1300 1301 if (!empty($USER->editing)) { 1302 $controlsrow = new html_table_row(); 1303 $controlsrow->attributes['class'] = 'controls'; 1304 $controlscell = new html_table_cell(); 1305 $controlscell->attributes['class'] = 'header controls'; 1306 $controlscell->header = true; 1307 $controlscell->colspan = $colspan; 1308 $controlscell->text = $this->get_lang_string('controls', 'grades'); 1309 $controlsrow->cells[] = $controlscell; 1310 1311 $rows[] = $controlsrow; 1312 } 1313 return $rows; 1314 } 1315 1316 /** 1317 * Builds and return the header for the row of ranges, for the left part of the grader report. 1318 * @param array $rows The Array of rows for the left part of the report 1319 * @param int $colspan The number of columns this cell has to span 1320 * @return array Array of rows for the left part of the report 1321 */ 1322 public function get_left_range_row($rows=array(), $colspan=1) { 1323 global $CFG, $USER; 1324 1325 if ($this->get_pref('showranges')) { 1326 $rangerow = new html_table_row(); 1327 $rangerow->attributes['class'] = 'range r'.$this->rowcount++; 1328 $rangecell = new html_table_cell(); 1329 $rangecell->attributes['class'] = 'header range'; 1330 $rangecell->colspan = $colspan; 1331 $rangecell->header = true; 1332 $rangecell->scope = 'row'; 1333 $rangecell->text = $this->get_lang_string('range', 'grades'); 1334 $rangerow->cells[] = $rangecell; 1335 $rows[] = $rangerow; 1336 } 1337 1338 return $rows; 1339 } 1340 1341 /** 1342 * Builds and return the headers for the rows of averages, for the left part of the grader report. 1343 * @param array $rows The Array of rows for the left part of the report 1344 * @param int $colspan The number of columns this cell has to span 1345 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages 1346 * @return array Array of rows for the left part of the report 1347 */ 1348 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) { 1349 if (!$this->canviewhidden) { 1350 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered 1351 // better not show them at all if user can not see all hideen grades 1352 return $rows; 1353 } 1354 1355 $showaverages = $this->get_pref('showaverages'); 1356 $showaveragesgroup = $this->currentgroup && $showaverages; 1357 $straveragegroup = get_string('groupavg', 'grades'); 1358 1359 if ($groupavg) { 1360 if ($showaveragesgroup) { 1361 $groupavgrow = new html_table_row(); 1362 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++; 1363 $groupavgcell = new html_table_cell(); 1364 $groupavgcell->attributes['class'] = 'header range'; 1365 $groupavgcell->colspan = $colspan; 1366 $groupavgcell->header = true; 1367 $groupavgcell->scope = 'row'; 1368 $groupavgcell->text = $straveragegroup; 1369 $groupavgrow->cells[] = $groupavgcell; 1370 $rows[] = $groupavgrow; 1371 } 1372 } else { 1373 $straverage = get_string('overallaverage', 'grades'); 1374 1375 if ($showaverages) { 1376 $avgrow = new html_table_row(); 1377 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++; 1378 $avgcell = new html_table_cell(); 1379 $avgcell->attributes['class'] = 'header range'; 1380 $avgcell->colspan = $colspan; 1381 $avgcell->header = true; 1382 $avgcell->scope = 'row'; 1383 $avgcell->text = $straverage; 1384 $avgrow->cells[] = $avgcell; 1385 $rows[] = $avgrow; 1386 } 1387 } 1388 1389 return $rows; 1390 } 1391 1392 /** 1393 * Builds and return the row of icons when editing is on, for the right part of the grader report. 1394 * @param array $rows The Array of rows for the right part of the report 1395 * @return array Array of rows for the right part of the report 1396 */ 1397 public function get_right_icons_row($rows=array()) { 1398 global $USER; 1399 if (!empty($USER->editing)) { 1400 $iconsrow = new html_table_row(); 1401 $iconsrow->attributes['class'] = 'controls'; 1402 1403 foreach ($this->gtree->items as $itemid => $unused) { 1404 // emulate grade element 1405 $item = $this->gtree->get_item($itemid); 1406 1407 $eid = $this->gtree->get_item_eid($item); 1408 $element = $this->gtree->locate_element($eid); 1409 $itemcell = new html_table_cell(); 1410 $itemcell->attributes['class'] = 'controls icons i'.$itemid; 1411 $itemcell->text = $this->get_icons($element); 1412 $iconsrow->cells[] = $itemcell; 1413 } 1414 $rows[] = $iconsrow; 1415 } 1416 return $rows; 1417 } 1418 1419 /** 1420 * Builds and return the row of ranges for the right part of the grader report. 1421 * @param array $rows The Array of rows for the right part of the report 1422 * @return array Array of rows for the right part of the report 1423 */ 1424 public function get_right_range_row($rows=array()) { 1425 global $OUTPUT; 1426 1427 if ($this->get_pref('showranges')) { 1428 $rangesdisplaytype = $this->get_pref('rangesdisplaytype'); 1429 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints'); 1430 $rangerow = new html_table_row(); 1431 $rangerow->attributes['class'] = 'heading range'; 1432 1433 foreach ($this->gtree->items as $itemid => $unused) { 1434 $item =& $this->gtree->items[$itemid]; 1435 $itemcell = new html_table_cell(); 1436 $itemcell->attributes['class'] .= ' range i'. $itemid; 1437 1438 $hidden = ''; 1439 if ($item->is_hidden()) { 1440 $hidden = ' dimmed_text '; 1441 } 1442 1443 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints); 1444 1445 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden); 1446 $rangerow->cells[] = $itemcell; 1447 } 1448 $rows[] = $rangerow; 1449 } 1450 return $rows; 1451 } 1452 1453 /** 1454 * Builds and return the row of averages for the right part of the grader report. 1455 * @param array $rows Whether to return only group averages or all averages. 1456 * @param bool $grouponly Whether to return only group averages or all averages. 1457 * @return array Array of rows for the right part of the report 1458 */ 1459 public function get_right_avg_row($rows=array(), $grouponly=false) { 1460 global $USER, $DB, $OUTPUT, $CFG; 1461 1462 if (!$this->canviewhidden) { 1463 // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered 1464 // better not show them at all if user can not see all hidden grades. 1465 return $rows; 1466 } 1467 1468 $averagesdisplaytype = $this->get_pref('averagesdisplaytype'); 1469 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints'); 1470 $meanselection = $this->get_pref('meanselection'); 1471 $shownumberofgrades = $this->get_pref('shownumberofgrades'); 1472 1473 if ($grouponly) { 1474 $showaverages = $this->currentgroup && $this->get_pref('showaverages'); 1475 $groupsql = $this->groupsql; 1476 $groupwheresql = $this->groupwheresql; 1477 $groupwheresqlparams = $this->groupwheresql_params; 1478 } else { 1479 $showaverages = $this->get_pref('showaverages'); 1480 $groupsql = ""; 1481 $groupwheresql = ""; 1482 $groupwheresqlparams = array(); 1483 } 1484 1485 if ($showaverages) { 1486 $totalcount = $this->get_numusers($grouponly); 1487 1488 // Limit to users with a gradeable role. 1489 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0'); 1490 1491 // Limit to users with an active enrollment. 1492 $coursecontext = $this->context->get_course_context(true); 1493 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); 1494 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); 1495 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext); 1496 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol); 1497 1498 // We want to query both the current context and parent contexts. 1499 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx'); 1500 1501 $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams); 1502 1503 // Find sums of all grade items in course. 1504 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum 1505 FROM {grade_items} gi 1506 JOIN {grade_grades} g ON g.itemid = gi.id 1507 JOIN {user} u ON u.id = g.userid 1508 JOIN ($enrolledsql) je ON je.id = u.id 1509 JOIN ( 1510 SELECT DISTINCT ra.userid 1511 FROM {role_assignments} ra 1512 WHERE ra.roleid $gradebookrolessql 1513 AND ra.contextid $relatedctxsql 1514 ) rainner ON rainner.userid = u.id 1515 $groupsql 1516 WHERE gi.courseid = :courseid 1517 AND u.deleted = 0 1518 AND g.finalgrade IS NOT NULL 1519 $groupwheresql 1520 GROUP BY g.itemid"; 1521 $sumarray = array(); 1522 if ($sums = $DB->get_records_sql($sql, $params)) { 1523 foreach ($sums as $itemid => $csum) { 1524 $sumarray[$itemid] = $csum->sum; 1525 } 1526 } 1527 1528 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0 1529 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table) 1530 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count 1531 FROM {grade_items} gi 1532 CROSS JOIN ($enrolledsql) u 1533 JOIN {role_assignments} ra 1534 ON ra.userid = u.id 1535 LEFT OUTER JOIN {grade_grades} g 1536 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL) 1537 $groupsql 1538 WHERE gi.courseid = :courseid 1539 AND ra.roleid $gradebookrolessql 1540 AND ra.contextid $relatedctxsql 1541 AND g.id IS NULL 1542 $groupwheresql 1543 GROUP BY gi.id"; 1544 1545 $ungradedcounts = $DB->get_records_sql($sql, $params); 1546 1547 $avgrow = new html_table_row(); 1548 $avgrow->attributes['class'] = 'avg'; 1549 1550 foreach ($this->gtree->items as $itemid => $unused) { 1551 $item =& $this->gtree->items[$itemid]; 1552 1553 if ($item->needsupdate) { 1554 $avgcell = new html_table_cell(); 1555 $avgcell->attributes['class'] = 'i'. $itemid; 1556 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror'); 1557 $avgrow->cells[] = $avgcell; 1558 continue; 1559 } 1560 1561 if (!isset($sumarray[$item->id])) { 1562 $sumarray[$item->id] = 0; 1563 } 1564 1565 if (empty($ungradedcounts[$itemid])) { 1566 $ungradedcount = 0; 1567 } else { 1568 $ungradedcount = $ungradedcounts[$itemid]->count; 1569 } 1570 1571 if ($meanselection == GRADE_REPORT_MEAN_GRADED) { 1572 $meancount = $totalcount - $ungradedcount; 1573 } else { // Bump up the sum by the number of ungraded items * grademin 1574 $sumarray[$item->id] += $ungradedcount * $item->grademin; 1575 $meancount = $totalcount; 1576 } 1577 1578 // Determine which display type to use for this average 1579 if (!empty($USER->editing)) { 1580 $displaytype = GRADE_DISPLAY_TYPE_REAL; 1581 1582 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences 1583 $displaytype = $item->get_displaytype(); 1584 1585 } else { 1586 $displaytype = $averagesdisplaytype; 1587 } 1588 1589 // Override grade_item setting if a display preference (not inherit) was set for the averages 1590 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) { 1591 $decimalpoints = $item->get_decimals(); 1592 1593 } else { 1594 $decimalpoints = $averagesdecimalpoints; 1595 } 1596 1597 if (!isset($sumarray[$item->id]) || $meancount == 0) { 1598 $avgcell = new html_table_cell(); 1599 $avgcell->attributes['class'] = 'i'. $itemid; 1600 $avgcell->text = '-'; 1601 $avgrow->cells[] = $avgcell; 1602 1603 } else { 1604 $sum = $sumarray[$item->id]; 1605 $avgradeval = $sum/$meancount; 1606 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints); 1607 1608 $numberofgrades = ''; 1609 if ($shownumberofgrades) { 1610 $numberofgrades = " ($meancount)"; 1611 } 1612 1613 $avgcell = new html_table_cell(); 1614 $avgcell->attributes['class'] = 'i'. $itemid; 1615 $avgcell->text = $gradehtml.$numberofgrades; 1616 $avgrow->cells[] = $avgcell; 1617 } 1618 } 1619 $rows[] = $avgrow; 1620 } 1621 return $rows; 1622 } 1623 1624 /** 1625 * Given element category, create a collapsible icon and 1626 * course header. 1627 * 1628 * @param array $element 1629 * @return string HTML 1630 */ 1631 protected function get_course_header($element) { 1632 global $OUTPUT; 1633 1634 $icon = ''; 1635 // If object is a category, display expand/contract icon. 1636 if ($element['type'] == 'category') { 1637 // Load language strings. 1638 $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades'); 1639 $strswitchplus = $this->get_lang_string('gradesonly', 'grades'); 1640 $strswitchwhole = $this->get_lang_string('fullmode', 'grades'); 1641 1642 $url = new moodle_url($this->gpr->get_return_url(null, array('target' => $element['eid'], 'sesskey' => sesskey()))); 1643 1644 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) { 1645 $url->param('action', 'switch_plus'); 1646 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', ''), null, 1647 ['title' => $strswitchplus, 'aria-label' => $strswitchplus]); 1648 $showing = get_string('showingaggregatesonly', 'grades'); 1649 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) { 1650 $url->param('action', 'switch_whole'); 1651 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', ''), null, 1652 ['title' => $strswitchwhole, 'aria-label' => $strswitchwhole]); 1653 $showing = get_string('showinggradesonly', 'grades'); 1654 } else { 1655 $url->param('action', 'switch_minus'); 1656 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', ''), null, 1657 ['title' => $strswitchminus, 'aria-label' => $strswitchminus]); 1658 $showing = get_string('showingfullmode', 'grades'); 1659 } 1660 } 1661 1662 $name = $element['object']->get_name(); 1663 $nameunescaped = $element['object']->get_name(false); 1664 $describedbyid = uniqid(); 1665 $courseheader = html_writer::tag('span', $name, [ 1666 'title' => $nameunescaped, 1667 'class' => 'gradeitemheader', 1668 'aria-describedby' => $describedbyid 1669 ]); 1670 $courseheader .= html_writer::div($showing, 'sr-only', [ 1671 'id' => $describedbyid 1672 ]); 1673 $courseheader .= $icon; 1674 1675 return $courseheader; 1676 } 1677 1678 /** 1679 * Given a grade_category, grade_item or grade_grade, this function 1680 * figures out the state of the object and builds then returns a div 1681 * with the icons needed for the grader report. 1682 * 1683 * @param array $element 1684 * @return string HTML 1685 */ 1686 protected function get_icons($element) { 1687 global $CFG, $USER, $OUTPUT; 1688 1689 if (empty($USER->editing)) { 1690 return '<div class="grade_icons" />'; 1691 } 1692 1693 // Init all icons 1694 $editicon = ''; 1695 1696 $editable = true; 1697 1698 if ($element['type'] == 'grade') { 1699 $item = $element['object']->grade_item; 1700 if ($item->is_course_item() or $item->is_category_item()) { 1701 $editable = $this->overridecat; 1702 } 1703 } 1704 1705 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) { 1706 $editicon = $this->gtree->get_edit_icon($element, $this->gpr); 1707 } 1708 1709 $editcalculationicon = ''; 1710 $showhideicon = ''; 1711 $lockunlockicon = ''; 1712 1713 if (has_capability('moodle/grade:manage', $this->context)) { 1714 if ($this->get_pref('showcalculations')) { 1715 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr); 1716 } 1717 1718 if ($this->get_pref('showeyecons')) { 1719 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr); 1720 } 1721 1722 if ($this->get_pref('showlocks')) { 1723 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr); 1724 } 1725 1726 } 1727 1728 $gradeanalysisicon = ''; 1729 if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') { 1730 $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']); 1731 } 1732 1733 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons'); 1734 } 1735 1736 /** 1737 * Given a category element returns collapsing +/- icon if available 1738 * 1739 * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more. 1740 */ 1741 protected function get_collapsing_icon($element) { 1742 throw new coding_exception('get_collapsing_icon() can not be used any more, please use get_course_header() instead.'); 1743 } 1744 1745 /** 1746 * Processes a single action against a category, grade_item or grade. 1747 * @param string $target eid ({type}{id}, e.g. c4 for category4) 1748 * @param string $action Which action to take (edit, delete etc...) 1749 * @return 1750 */ 1751 public function process_action($target, $action) { 1752 return self::do_process_action($target, $action, $this->course->id); 1753 } 1754 1755 /** 1756 * From the list of categories that this user prefers to collapse choose ones that belong to the current course. 1757 * 1758 * This function serves two purposes. 1759 * Mainly it helps migrating from user preference style when all courses were stored in one preference. 1760 * Also it helps to remove the settings for categories that were removed if the array for one course grows too big. 1761 * 1762 * @param int $courseid 1763 * @param array $collapsed 1764 * @return array 1765 */ 1766 protected static function filter_collapsed_categories($courseid, $collapsed) { 1767 global $DB; 1768 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty. 1769 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? []; 1770 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? []; 1771 1772 if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) { 1773 return $collapsed; 1774 } 1775 $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid)); 1776 $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats)); 1777 $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats)); 1778 return $collapsed; 1779 } 1780 1781 /** 1782 * Returns the list of categories that this user wants to collapse or display aggregatesonly 1783 * 1784 * This method also migrates on request from the old format of storing user preferences when they were stored 1785 * in one preference for all courses causing DB error when trying to insert very big value. 1786 * 1787 * @param int $courseid 1788 * @return array 1789 */ 1790 protected static function get_collapsed_preferences($courseid) { 1791 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) { 1792 $collapsed = json_decode($collapsed, true); 1793 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty. 1794 $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? []; 1795 $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? []; 1796 return $collapsed; 1797 } 1798 1799 // Try looking for old location of user setting that used to store all courses in one serialized user preference. 1800 $collapsed = ['aggregatesonly' => [], 'gradesonly' => []]; // Use this if old settings are not found. 1801 $collapsedall = []; 1802 $oldprefexists = false; 1803 if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) { 1804 $oldprefexists = true; 1805 if ($collapsedall = unserialize_array($oldcollapsedpref)) { 1806 // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty. 1807 $collapsedall['aggregatesonly'] = $collapsedall['aggregatesonly'] ?? []; 1808 $collapsedall['gradesonly'] = $collapsedall['gradesonly'] ?? []; 1809 // We found the old-style preference, filter out only categories that belong to this course and update the prefs. 1810 $collapsed = static::filter_collapsed_categories($courseid, $collapsedall); 1811 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) { 1812 static::set_collapsed_preferences($courseid, $collapsed); 1813 $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']); 1814 $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']); 1815 if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) { 1816 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall)); 1817 } 1818 } 1819 } 1820 } 1821 1822 // Arrived here, if the old pref exists and it doesn't contain 1823 // more information, it means that the migration of all the 1824 // data to new, by course, preferences is completed, so 1825 // the old one can be safely deleted. 1826 if ($oldprefexists && 1827 empty($collapsedall['aggregatesonly']) && 1828 empty($collapsedall['gradesonly'])) { 1829 unset_user_preference('grade_report_grader_collapsed_categories'); 1830 } 1831 1832 return $collapsed; 1833 } 1834 1835 /** 1836 * Sets the list of categories that user wants to see collapsed in user preferences 1837 * 1838 * This method may filter or even trim the list if it does not fit in DB field. 1839 * 1840 * @param int $courseid 1841 * @param array $collapsed 1842 */ 1843 protected static function set_collapsed_preferences($courseid, $collapsed) { 1844 global $DB; 1845 // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size, 1846 // try to filter the list of categories since array may contain categories that were deleted. 1847 if (strlen(json_encode($collapsed)) >= 1333) { 1848 $collapsed = static::filter_collapsed_categories($courseid, $collapsed); 1849 } 1850 1851 // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information. 1852 while (strlen(json_encode($collapsed)) >= 1333) { 1853 if (count($collapsed['aggregatesonly'])) { 1854 array_pop($collapsed['aggregatesonly']); 1855 } 1856 if (count($collapsed['gradesonly'])) { 1857 array_pop($collapsed['gradesonly']); 1858 } 1859 } 1860 1861 if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) { 1862 set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed)); 1863 } else { 1864 unset_user_preference('grade_report_grader_collapsed_categories'.$courseid); 1865 } 1866 } 1867 1868 /** 1869 * Processes a single action against a category, grade_item or grade. 1870 * @param string $target eid ({type}{id}, e.g. c4 for category4) 1871 * @param string $action Which action to take (edit, delete etc...) 1872 * @param int $courseid affected course. 1873 * @return 1874 */ 1875 public static function do_process_action($target, $action, $courseid = null) { 1876 global $DB; 1877 // TODO: this code should be in some grade_tree static method 1878 $targettype = substr($target, 0, 2); 1879 $targetid = substr($target, 2); 1880 // TODO: end 1881 1882 if ($targettype !== 'cg') { 1883 // The following code only works with categories. 1884 return true; 1885 } 1886 1887 if (!$courseid) { 1888 debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid', 1889 DEBUG_DEVELOPER); 1890 if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) { 1891 return true; 1892 } 1893 } 1894 1895 $collapsed = static::get_collapsed_preferences($courseid); 1896 1897 switch ($action) { 1898 case 'switch_minus': // Add category to array of aggregatesonly 1899 if (!in_array($targetid, $collapsed['aggregatesonly'])) { 1900 $collapsed['aggregatesonly'][] = $targetid; 1901 static::set_collapsed_preferences($courseid, $collapsed); 1902 } 1903 break; 1904 1905 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly 1906 $key = array_search($targetid, $collapsed['aggregatesonly']); 1907 if ($key !== false) { 1908 unset($collapsed['aggregatesonly'][$key]); 1909 } 1910 if (!in_array($targetid, $collapsed['gradesonly'])) { 1911 $collapsed['gradesonly'][] = $targetid; 1912 } 1913 static::set_collapsed_preferences($courseid, $collapsed); 1914 break; 1915 case 'switch_whole': // Remove the category from the array of collapsed cats 1916 $key = array_search($targetid, $collapsed['gradesonly']); 1917 if ($key !== false) { 1918 unset($collapsed['gradesonly'][$key]); 1919 static::set_collapsed_preferences($courseid, $collapsed); 1920 } 1921 1922 break; 1923 default: 1924 break; 1925 } 1926 1927 return true; 1928 } 1929 1930 /** 1931 * Refactored function for generating HTML of sorting links with matching arrows. 1932 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready 1933 * to inject into a table header cell. 1934 * @param array $extrafields Array of extra fields being displayed, such as 1935 * user idnumber 1936 * @return array An associative array of HTML sorting links+arrows 1937 */ 1938 public function get_sort_arrows(array $extrafields = array()) { 1939 global $OUTPUT, $CFG; 1940 $arrows = array(); 1941 1942 $strsortasc = $this->get_lang_string('sortasc', 'grades'); 1943 $strsortdesc = $this->get_lang_string('sortdesc', 'grades'); 1944 $iconasc = $OUTPUT->pix_icon('t/sort_asc', $strsortasc, '', array('class' => 'iconsmall sorticon')); 1945 $icondesc = $OUTPUT->pix_icon('t/sort_desc', $strsortdesc, '', array('class' => 'iconsmall sorticon')); 1946 1947 // Sourced from tablelib.php 1948 // Check the full name display for sortable fields. 1949 if (has_capability('moodle/site:viewfullnames', $this->context)) { 1950 $nameformat = $CFG->alternativefullnameformat; 1951 } else { 1952 $nameformat = $CFG->fullnamedisplay; 1953 } 1954 1955 if ($nameformat == 'language') { 1956 $nameformat = get_string('fullnamedisplay'); 1957 } 1958 1959 $arrows['studentname'] = ''; 1960 $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat); 1961 if (!empty($requirednames)) { 1962 foreach ($requirednames as $name) { 1963 $arrows['studentname'] .= html_writer::link( 1964 new moodle_url($this->baseurl, array('sortitemid' => $name)), $this->get_lang_string($name) 1965 ); 1966 if ($this->sortitemid == $name) { 1967 $arrows['studentname'] .= $this->sortorder == 'ASC' ? $iconasc : $icondesc; 1968 } 1969 $arrows['studentname'] .= ' / '; 1970 } 1971 1972 $arrows['studentname'] = substr($arrows['studentname'], 0, -3); 1973 } 1974 1975 foreach ($extrafields as $field) { 1976 $fieldlink = html_writer::link(new moodle_url($this->baseurl, 1977 array('sortitemid' => $field)), \core_user\fields::get_display_name($field)); 1978 $arrows[$field] = $fieldlink; 1979 1980 if ($field == $this->sortitemid) { 1981 if ($this->sortorder == 'ASC') { 1982 $arrows[$field] .= $iconasc; 1983 } else { 1984 $arrows[$field] .= $icondesc; 1985 } 1986 } 1987 } 1988 1989 return $arrows; 1990 } 1991 1992 /** 1993 * Returns the maximum number of students to be displayed on each page 1994 * 1995 * @return int The maximum number of students to display per page 1996 */ 1997 public function get_students_per_page(): int { 1998 return (int) $this->get_pref('studentsperpage'); 1999 } 2000 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body