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