Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 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                          throw new \moodle_exception('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          $columnstounset = array();
 806          $strgrade = $this->get_lang_string('gradenoun');
 807          $strfeedback  = $this->get_lang_string("feedback");
 808          $arrows = $this->get_sort_arrows();
 809  
 810          $jsarguments = array(
 811              'cfg'       => array('ajaxenabled'=>false),
 812              'items'     => array(),
 813              'users'     => array(),
 814              'feedback'  => array(),
 815              'grades'    => array()
 816          );
 817          $jsscales = array();
 818  
 819          // Get preferences once.
 820          $showactivityicons = $this->get_pref('showactivityicons');
 821          $quickgrading = $this->get_pref('quickgrading');
 822          $showquickfeedback = $this->get_pref('showquickfeedback');
 823          $enableajax = $this->get_pref('enableajax');
 824          $showanalysisicon = $this->get_pref('showanalysisicon');
 825  
 826          // Get strings which are re-used inside the loop.
 827          $strftimedatetimeshort = get_string('strftimedatetimeshort');
 828          $strexcludedgrades = get_string('excluded', 'grades');
 829          $strerror = get_string('error');
 830  
 831          $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
 832  
 833          foreach ($this->gtree->get_levels() as $key => $row) {
 834              $headingrow = new html_table_row();
 835              $headingrow->attributes['class'] = 'heading_name_row';
 836  
 837              foreach ($row as $columnkey => $element) {
 838                  $sortlink = clone($this->baseurl);
 839                  if (isset($element['object']->id)) {
 840                      $sortlink->param('sortitemid', $element['object']->id);
 841                  }
 842  
 843                  $eid    = $element['eid'];
 844                  $object = $element['object'];
 845                  $type   = $element['type'];
 846                  $categorystate = @$element['categorystate'];
 847  
 848                  if (!empty($element['colspan'])) {
 849                      $colspan = $element['colspan'];
 850                  } else {
 851                      $colspan = 1;
 852                  }
 853  
 854                  if (!empty($element['depth'])) {
 855                      $catlevel = 'catlevel'.$element['depth'];
 856                  } else {
 857                      $catlevel = '';
 858                  }
 859  
 860                  // Element is a filler
 861                  if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
 862                      $fillercell = new html_table_cell();
 863                      $fillercell->attributes['class'] = $type . ' ' . $catlevel;
 864                      $fillercell->colspan = $colspan;
 865                      $fillercell->text = '&nbsp;';
 866  
 867                      // This is a filler cell; don't use a <th>, it'll confuse screen readers.
 868                      $fillercell->header = false;
 869                      $headingrow->cells[] = $fillercell;
 870                  } else if ($type == 'category') {
 871                      // Make sure the grade category has a grade total or at least has child grade items.
 872                      if (grade_tree::can_output_item($element)) {
 873                          // Element is a category.
 874                          $categorycell = new html_table_cell();
 875                          $categorycell->attributes['class'] = 'category ' . $catlevel;
 876                          $categorycell->colspan = $colspan;
 877                          $categorycell->text = $this->get_course_header($element);
 878                          $categorycell->header = true;
 879                          $categorycell->scope = 'col';
 880  
 881                          // Print icons.
 882                          if (!empty($USER->editing)) {
 883                              $categorycell->text .= $this->get_icons($element);
 884                          }
 885  
 886                          $headingrow->cells[] = $categorycell;
 887                      }
 888                  } else {
 889                      // Element is a grade_item
 890                      if ($element['object']->id == $this->sortitemid) {
 891                          if ($this->sortorder == 'ASC') {
 892                              $arrow = $this->get_sort_arrow('up', $sortlink);
 893                          } else {
 894                              $arrow = $this->get_sort_arrow('down', $sortlink);
 895                          }
 896                      } else {
 897                          $arrow = $this->get_sort_arrow('move', $sortlink);
 898                      }
 899  
 900                      $headerlink = $this->gtree->get_element_header($element, true, $showactivityicons, false, false, true);
 901  
 902                      $itemcell = new html_table_cell();
 903                      $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable'. ' i'. $element['object']->id;
 904                      $itemcell->attributes['data-itemid'] = $element['object']->id;
 905  
 906                      if ($element['object']->is_hidden()) {
 907                          $itemcell->attributes['class'] .= ' dimmed_text';
 908                      }
 909  
 910                      $singleview = '';
 911  
 912                      // FIXME: MDL-52678 This is extremely hacky we should have an API for inserting grade column links.
 913                      if (get_capability_info('gradereport/singleview:view')) {
 914                          if (has_all_capabilities(array('gradereport/singleview:view', 'moodle/grade:viewall',
 915                              'moodle/grade:edit'), $this->context)) {
 916  
 917                              $strsingleview = get_string('singleview', 'grades', $element['object']->get_name());
 918                              $url = new moodle_url('/grade/report/singleview/index.php', array(
 919                                  'id' => $this->course->id,
 920                                  'item' => 'grade',
 921                                  'itemid' => $element['object']->id));
 922                              $singleview = $OUTPUT->action_icon(
 923                                      $url,
 924                                      new pix_icon('t/editstring', ''),
 925                                      null,
 926                                      ['title' => $strsingleview, 'aria-label' => $strsingleview]
 927                              );
 928                          }
 929                      }
 930  
 931                      $itemcell->colspan = $colspan;
 932                      $itemcell->text = $headerlink . $arrow . $singleview;
 933                      $itemcell->header = true;
 934                      $itemcell->scope = 'col';
 935  
 936                      $headingrow->cells[] = $itemcell;
 937                  }
 938              }
 939              $rows[] = $headingrow;
 940          }
 941  
 942          $rows = $this->get_right_icons_row($rows);
 943  
 944          // Preload scale objects for items with a scaleid and initialize tab indices
 945          $scaleslist = array();
 946  
 947          foreach ($this->gtree->get_items() as $itemid => $item) {
 948              $scale = null;
 949              if (!empty($item->scaleid)) {
 950                  $scaleslist[] = $item->scaleid;
 951                  $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
 952              } else {
 953                  $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
 954              }
 955          }
 956          $scalesarray = array();
 957  
 958          if (!empty($scaleslist)) {
 959              $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
 960          }
 961          $jsscales = $scalesarray;
 962  
 963          // Get all the grade items if the user can not view hidden grade items.
 964          // It is possible that the user is simply viewing the 'Course total' by switching to the 'Aggregates only' view
 965          // and that this user does not have the ability to view hidden items. In this case we still need to pass all the
 966          // grade items (in case one has been hidden) as the course total shown needs to be adjusted for this particular
 967          // user.
 968          if (!$this->canviewhidden) {
 969              $allgradeitems = $this->get_allgradeitems();
 970          }
 971  
 972          foreach ($this->users as $userid => $user) {
 973  
 974              if ($this->canviewhidden) {
 975                  $altered = array();
 976                  $unknown = array();
 977              } else {
 978                  $usergrades = $this->allgrades[$userid];
 979                  $hidingaffected = grade_grade::get_hiding_affected($usergrades, $allgradeitems);
 980                  $altered = $hidingaffected['altered'];
 981                  $unknown = $hidingaffected['unknowngrades'];
 982                  unset($hidingaffected);
 983              }
 984  
 985              $itemrow = new html_table_row();
 986              $itemrow->id = 'user_'.$userid;
 987  
 988              $fullname = fullname($user, $viewfullnames);
 989              $jsarguments['users'][$userid] = $fullname;
 990  
 991              foreach ($this->gtree->items as $itemid => $unused) {
 992                  $item =& $this->gtree->items[$itemid];
 993                  $grade = $this->grades[$userid][$item->id];
 994  
 995                  $itemcell = new html_table_cell();
 996  
 997                  $itemcell->id = 'u'.$userid.'i'.$itemid;
 998                  $itemcell->attributes['data-itemid'] = $itemid;
 999  
1000                  // Get the decimal points preference for this item
1001                  $decimalpoints = $item->get_decimals();
1002  
1003                  if (array_key_exists($itemid, $unknown)) {
1004                      $gradeval = null;
1005                  } else if (array_key_exists($itemid, $altered)) {
1006                      $gradeval = $altered[$itemid];
1007                  } else {
1008                      $gradeval = $grade->finalgrade;
1009                  }
1010                  if (!empty($grade->finalgrade)) {
1011                      $gradevalforjs = null;
1012                      if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1013                          $gradevalforjs = (int)$gradeval;
1014                      } else {
1015                          $gradevalforjs = format_float($gradeval, $decimalpoints);
1016                      }
1017                      $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforjs);
1018                  }
1019  
1020                  // MDL-11274
1021                  // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
1022                  if (!$this->canviewhidden and $grade->is_hidden()) {
1023                      if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
1024                          // 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
1025                          $itemcell->text = "<span class='datesubmitted'>" .
1026                                  userdate($grade->get_datesubmitted(), $strftimedatetimeshort) . "</span>";
1027                      } else {
1028                          $itemcell->text = '-';
1029                      }
1030                      $itemrow->cells[] = $itemcell;
1031                      continue;
1032                  }
1033  
1034                  // emulate grade element
1035                  $eid = $this->gtree->get_grade_eid($grade);
1036                  $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
1037  
1038                  $itemcell->attributes['class'] .= ' grade i'.$itemid;
1039                  if ($item->is_category_item()) {
1040                      $itemcell->attributes['class'] .= ' cat';
1041                  }
1042                  if ($item->is_course_item()) {
1043                      $itemcell->attributes['class'] .= ' course';
1044                  }
1045                  if ($grade->is_overridden()) {
1046                      $itemcell->attributes['class'] .= ' overridden';
1047                      $itemcell->attributes['aria-label'] = get_string('overriddengrade', 'gradereport_grader');
1048                  }
1049  
1050                  if (!empty($grade->feedback)) {
1051                      $feedback = wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br>');
1052                      $itemcell->attributes['data-feedback'] = $feedback;
1053                      $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content' => $feedback);
1054                  }
1055  
1056                  if ($grade->is_excluded()) {
1057                      // Adding white spaces before and after to prevent a screenreader from
1058                      // thinking that the words are attached to the next/previous <span> or text.
1059                      $itemcell->text .= " <span class='excludedfloater'>" . $strexcludedgrades . "</span> ";
1060                  }
1061  
1062                  // Do not show any icons if no grade (no record in DB to match)
1063                  if (!$item->needsupdate and !empty($USER->editing)) {
1064                      $itemcell->text .= $this->get_icons($element);
1065                  }
1066  
1067                  $hidden = '';
1068                  if ($grade->is_hidden()) {
1069                      $hidden = ' dimmed_text ';
1070                  }
1071  
1072                  $gradepass = ' gradefail ';
1073                  $gradepassicon = $OUTPUT->pix_icon('i/invalid', get_string('fail', 'grades'));
1074                  if ($grade->is_passed($item)) {
1075                      $gradepass = ' gradepass ';
1076                      $gradepassicon = $OUTPUT->pix_icon('i/valid', get_string('pass', 'grades'));
1077                  } else if (is_null($grade->is_passed($item))) {
1078                      $gradepass = '';
1079                      $gradepassicon = '';
1080                  }
1081  
1082                  // if in editing mode, we need to print either a text box
1083                  // or a drop down (for scales)
1084                  // grades in item of type grade category or course are not directly editable
1085                  if ($item->needsupdate) {
1086                      $itemcell->text .= "<span class='gradingerror{$hidden}'>" . $strerror . "</span>";
1087  
1088                  } else if (!empty($USER->editing)) {
1089  
1090                      if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1091                          $itemcell->attributes['class'] .= ' grade_type_scale';
1092                      } else if ($item->gradetype == GRADE_TYPE_VALUE) {
1093                          $itemcell->attributes['class'] .= ' grade_type_value';
1094                      } else if ($item->gradetype == GRADE_TYPE_TEXT) {
1095                          $itemcell->attributes['class'] .= ' grade_type_text';
1096                      }
1097  
1098                      if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1099                          $scale = $scalesarray[$item->scaleid];
1100                          $gradeval = (int)$gradeval; // scales use only integers
1101                          $scales = explode(",", $scale->scale);
1102                          // reindex because scale is off 1
1103  
1104                          // MDL-12104 some previous scales might have taken up part of the array
1105                          // so this needs to be reset
1106                          $scaleopt = array();
1107                          $i = 0;
1108                          foreach ($scales as $scaleoption) {
1109                              $i++;
1110                              $scaleopt[$i] = $scaleoption;
1111                          }
1112  
1113                          if ($quickgrading and $grade->is_editable()) {
1114                              $oldval = empty($gradeval) ? -1 : $gradeval;
1115                              if (empty($item->outcomeid)) {
1116                                  $nogradestr = $this->get_lang_string('nograde');
1117                              } else {
1118                                  $nogradestr = $this->get_lang_string('nooutcome', 'grades');
1119                              }
1120                              $attributes = ['id' => 'grade_' . $userid . '_' . $item->id];
1121                              $gradelabel = $fullname . ' ' . $item->get_name(true);
1122                              $itemcell->text .= html_writer::label(
1123                                  get_string('useractivitygrade', 'gradereport_grader', $gradelabel), $attributes['id'], false,
1124                                      array('class' => 'accesshide'));
1125                              $itemcell->text .= html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']', $gradeval, array(-1=>$nogradestr), $attributes);
1126                          } else if (!empty($scale)) {
1127                              $scales = explode(",", $scale->scale);
1128  
1129                              // invalid grade if gradeval < 1
1130                              if ($gradeval < 1) {
1131                                  $itemcell->text .= $gradepassicon .
1132                                      "<span class='gradevalue{$hidden}{$gradepass}'>-</span>";
1133                              } else {
1134                                  $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
1135                                  $itemcell->text .= $gradepassicon .
1136                                      "<span class='gradevalue{$hidden}{$gradepass}'>{$scales[$gradeval - 1]}</span>";
1137                              }
1138                          }
1139  
1140                      } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
1141                          if ($quickgrading and $grade->is_editable()) {
1142                              $value = format_float($gradeval, $decimalpoints);
1143                              $gradelabel = $fullname . ' ' . $item->get_name(true);
1144                              $itemcell->text .= '<label class="accesshide" for="grade_'.$userid.'_'.$item->id.'">'
1145                                            .get_string('useractivitygrade', 'gradereport_grader', $gradelabel).'</label>';
1146  
1147                              // Set this input field with type="number" if the decimal separator for current language is set to
1148                              // a period. Other decimal separators may not be recognised by browsers yet which may cause issues
1149                              // when entering grades.
1150                              $decsep = get_string('decsep', 'core_langconfig');
1151                              $isnumeric = $decsep === '.';
1152                              $inputtype = $isnumeric ? 'number' : 'text';
1153                              $inputparams = [
1154                                  'type' => $inputtype,
1155                                  'class' => 'text',
1156                                  'title' => $strgrade,
1157                                  'name' => "grade[{$userid}][{$item->id}]",
1158                                  'id' => "grade_{$userid}_{$item->id}",
1159                                  'value' => $value,
1160                              ];
1161                              // If we're rendering this as a number field, set step and min/max attributes (if applicable).
1162                              if ($isnumeric) {
1163                                  $inputparams['step'] = 'any';
1164                                  if (isset($item->grademin)) {
1165                                      $inputparams['min'] = $item->grademin;
1166                                  }
1167                                  if (isset($item->grademax)) {
1168                                      $inputparams['max'] = $item->grademax;
1169                                  }
1170                              }
1171  
1172                              $itemcell->text .= html_writer::empty_tag('input', $inputparams);
1173                          } else {
1174                              $itemcell->text .= $gradepassicon . "<span class='gradevalue{$hidden}{$gradepass}'>" .
1175                                      format_float($gradeval, $decimalpoints) . "</span>";
1176                          }
1177                      }
1178  
1179                      // If quickfeedback is on, print an input element
1180                      if ($showquickfeedback and $grade->is_editable()) {
1181                          $feedbacklabel = $fullname . ' ' . $item->get_name(true);
1182                          $itemcell->text .= '<label class="accesshide" for="feedback_'.$userid.'_'.$item->id.'">'
1183                                        .get_string('useractivityfeedback', 'gradereport_grader', $feedbacklabel).'</label>';
1184                          $itemcell->text .= '<input class="quickfeedback" id="feedback_'.$userid.'_'.$item->id
1185                                        . '" size="6" title="' . $strfeedback . '" type="text" name="feedback['.$userid.']['.$item->id.']" value="' . s($grade->feedback) . '" />';
1186                      }
1187  
1188                  } else { // Not editing
1189                      $gradedisplaytype = $item->get_displaytype();
1190  
1191                      if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1192                          $itemcell->attributes['class'] .= ' grade_type_scale';
1193                      } else if ($item->gradetype == GRADE_TYPE_VALUE) {
1194                          $itemcell->attributes['class'] .= ' grade_type_value';
1195                      } else if ($item->gradetype == GRADE_TYPE_TEXT) {
1196                          $itemcell->attributes['class'] .= ' grade_type_text';
1197                      }
1198  
1199                      // Only allow edting if the grade is editable (not locked, not in a unoverridable category, etc).
1200                      if ($enableajax && $grade->is_editable()) {
1201                          // If a grade item is type text, and we don't have show quick feedback on, it can't be edited.
1202                          if ($item->gradetype != GRADE_TYPE_TEXT || $showquickfeedback) {
1203                              $itemcell->attributes['class'] .= ' clickable';
1204                          }
1205                      }
1206  
1207                      if ($item->needsupdate) {
1208                          $itemcell->text .= $gradepassicon . "<span class='gradingerror{$hidden}{$gradepass}'>" . $error . "</span>";
1209                      } else {
1210                          // The max and min for an aggregation may be different to the grade_item.
1211                          if (!is_null($gradeval)) {
1212                              $item->grademax = $grade->get_grade_max();
1213                              $item->grademin = $grade->get_grade_min();
1214                          }
1215  
1216                          $itemcell->text .= $gradepassicon . "<span class='gradevalue{$hidden}{$gradepass}'>" .
1217                                  grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null) . "</span>";
1218                          if ($showanalysisicon) {
1219                              $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
1220                          }
1221                      }
1222                  }
1223  
1224                  // Enable keyboard navigation if the grade is editable (not locked, not in a unoverridable category, etc).
1225                  if ($enableajax && $grade->is_editable()) {
1226                      // If a grade item is type text, and we don't have show quick feedback on, it can't be edited.
1227                      if ($item->gradetype != GRADE_TYPE_TEXT || $showquickfeedback) {
1228                          $itemcell->attributes['class'] .= ' gbnavigable';
1229                      }
1230                  }
1231  
1232                  if (!empty($this->gradeserror[$item->id][$userid])) {
1233                      $itemcell->text .= $this->gradeserror[$item->id][$userid];
1234                  }
1235  
1236                  $itemrow->cells[] = $itemcell;
1237              }
1238              $rows[] = $itemrow;
1239          }
1240  
1241          if ($enableajax) {
1242              $jsarguments['cfg']['ajaxenabled'] = true;
1243              $jsarguments['cfg']['scales'] = array();
1244              foreach ($jsscales as $scale) {
1245                  // Trim the scale values, as they may have a space that is ommitted from values later.
1246                  $jsarguments['cfg']['scales'][$scale->id] = array_map('trim', explode(',', $scale->scale));
1247              }
1248              $jsarguments['cfg']['feedbacktrunclength'] =  $this->feedback_trunc_length;
1249  
1250              // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades']
1251          }
1252          $jsarguments['cfg']['isediting'] = !empty($USER->editing);
1253          $jsarguments['cfg']['courseid'] = $this->courseid;
1254          $jsarguments['cfg']['studentsperpage'] = $this->get_students_per_page();
1255          $jsarguments['cfg']['showquickfeedback'] = (bool) $showquickfeedback;
1256  
1257          $module = array(
1258              'name'      => 'gradereport_grader',
1259              'fullpath'  => '/grade/report/grader/module.js',
1260              'requires'  => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
1261          );
1262          $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
1263          $PAGE->requires->strings_for_js(array('addfeedback', 'feedback', 'grade'), 'grades');
1264          $PAGE->requires->strings_for_js(array('ajaxchoosescale', 'ajaxclicktoclose', 'ajaxerror', 'ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
1265          if (!$enableajax && !empty($USER->editing)) {
1266              $PAGE->requires->js_call_amd('core_form/changechecker', 'watchFormById', ['gradereport_grader']);
1267          }
1268  
1269          $rows = $this->get_right_range_row($rows);
1270          if ($displayaverages) {
1271              $rows = $this->get_right_avg_row($rows, true);
1272              $rows = $this->get_right_avg_row($rows);
1273          }
1274  
1275          return $rows;
1276      }
1277  
1278      /**
1279       * Depending on the style of report (fixedstudents vs traditional one-table),
1280       * arranges the rows of data in one or two tables, and returns the output of
1281       * these tables in HTML
1282       * @param boolean $displayaverages whether to display average rows in the table
1283       * @return string HTML
1284       */
1285      public function get_grade_table($displayaverages = false) {
1286          global $OUTPUT;
1287          $leftrows = $this->get_left_rows($displayaverages);
1288          $rightrows = $this->get_right_rows($displayaverages);
1289  
1290          $html = '';
1291  
1292          $fulltable = new html_table();
1293          $fulltable->attributes['class'] = 'gradereport-grader-table';
1294          $fulltable->id = 'user-grades';
1295          $fulltable->caption = get_string('summarygrader', 'gradereport_grader');
1296          $fulltable->captionhide = true;
1297          // We don't want the table to be enclosed within in a .table-responsive div as it is heavily customised.
1298          $fulltable->responsive = false;
1299  
1300          // Extract rows from each side (left and right) and collate them into one row each
1301          foreach ($leftrows as $key => $row) {
1302              $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1303              $fulltable->data[] = $row;
1304          }
1305          $html .= html_writer::table($fulltable);
1306          return $OUTPUT->container($html, 'gradeparent');
1307      }
1308  
1309      /**
1310       * Builds and return the row of icons for the left side of the report.
1311       * It only has one cell that says "Controls"
1312       * @param array $rows The Array of rows for the left part of the report
1313       * @param int $colspan The number of columns this cell has to span
1314       * @return array Array of rows for the left part of the report
1315       */
1316      public function get_left_icons_row($rows=array(), $colspan=1) {
1317          global $USER;
1318  
1319          if (!empty($USER->editing)) {
1320              $controlsrow = new html_table_row();
1321              $controlsrow->attributes['class'] = 'controls';
1322              $controlscell = new html_table_cell();
1323              $controlscell->attributes['class'] = 'header controls';
1324              $controlscell->header = true;
1325              $controlscell->colspan = $colspan;
1326              $controlscell->text = $this->get_lang_string('controls', 'grades');
1327              $controlsrow->cells[] = $controlscell;
1328  
1329              $rows[] = $controlsrow;
1330          }
1331          return $rows;
1332      }
1333  
1334      /**
1335       * Builds and return the header for the row of ranges, for the left part of the grader report.
1336       * @param array $rows The Array of rows for the left part of the report
1337       * @param int $colspan The number of columns this cell has to span
1338       * @return array Array of rows for the left part of the report
1339       */
1340      public function get_left_range_row($rows=array(), $colspan=1) {
1341          global $CFG, $USER;
1342  
1343          if ($this->get_pref('showranges')) {
1344              $rangerow = new html_table_row();
1345              $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1346              $rangecell = new html_table_cell();
1347              $rangecell->attributes['class'] = 'header range';
1348              $rangecell->colspan = $colspan;
1349              $rangecell->header = true;
1350              $rangecell->scope = 'row';
1351              $rangecell->text = $this->get_lang_string('range', 'grades');
1352              $rangerow->cells[] = $rangecell;
1353              $rows[] = $rangerow;
1354          }
1355  
1356          return $rows;
1357      }
1358  
1359      /**
1360       * Builds and return the headers for the rows of averages, for the left part of the grader report.
1361       * @param array $rows The Array of rows for the left part of the report
1362       * @param int $colspan The number of columns this cell has to span
1363       * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1364       * @return array Array of rows for the left part of the report
1365       */
1366      public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1367          if (!$this->canviewhidden) {
1368              // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1369              // better not show them at all if user can not see all hideen grades
1370              return $rows;
1371          }
1372  
1373          $showaverages = $this->get_pref('showaverages');
1374          $showaveragesgroup = $this->currentgroup && $showaverages;
1375          $straveragegroup = get_string('groupavg', 'grades');
1376  
1377          if ($groupavg) {
1378              if ($showaveragesgroup) {
1379                  $groupavgrow = new html_table_row();
1380                  $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1381                  $groupavgcell = new html_table_cell();
1382                  $groupavgcell->attributes['class'] = 'header range';
1383                  $groupavgcell->colspan = $colspan;
1384                  $groupavgcell->header = true;
1385                  $groupavgcell->scope = 'row';
1386                  $groupavgcell->text = $straveragegroup;
1387                  $groupavgrow->cells[] = $groupavgcell;
1388                  $rows[] = $groupavgrow;
1389              }
1390          } else {
1391              $straverage = get_string('overallaverage', 'grades');
1392  
1393              if ($showaverages) {
1394                  $avgrow = new html_table_row();
1395                  $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1396                  $avgcell = new html_table_cell();
1397                  $avgcell->attributes['class'] = 'header range';
1398                  $avgcell->colspan = $colspan;
1399                  $avgcell->header = true;
1400                  $avgcell->scope = 'row';
1401                  $avgcell->text = $straverage;
1402                  $avgrow->cells[] = $avgcell;
1403                  $rows[] = $avgrow;
1404              }
1405          }
1406  
1407          return $rows;
1408      }
1409  
1410      /**
1411       * Builds and return the row of icons when editing is on, for the right part of the grader report.
1412       * @param array $rows The Array of rows for the right part of the report
1413       * @return array Array of rows for the right part of the report
1414       */
1415      public function get_right_icons_row($rows=array()) {
1416          global $USER;
1417          if (!empty($USER->editing)) {
1418              $iconsrow = new html_table_row();
1419              $iconsrow->attributes['class'] = 'controls';
1420  
1421              foreach ($this->gtree->items as $itemid => $unused) {
1422                  // emulate grade element
1423                  $item = $this->gtree->get_item($itemid);
1424  
1425                  $eid = $this->gtree->get_item_eid($item);
1426                  $element = $this->gtree->locate_element($eid);
1427                  $itemcell = new html_table_cell();
1428                  $itemcell->attributes['class'] = 'controls icons i'.$itemid;
1429                  $itemcell->text = $this->get_icons($element);
1430                  $iconsrow->cells[] = $itemcell;
1431              }
1432              $rows[] = $iconsrow;
1433          }
1434          return $rows;
1435      }
1436  
1437      /**
1438       * Builds and return the row of ranges for the right part of the grader report.
1439       * @param array $rows The Array of rows for the right part of the report
1440       * @return array Array of rows for the right part of the report
1441       */
1442      public function get_right_range_row($rows=array()) {
1443          global $OUTPUT;
1444  
1445          if ($this->get_pref('showranges')) {
1446              $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1447              $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1448              $rangerow = new html_table_row();
1449              $rangerow->attributes['class'] = 'heading range';
1450  
1451              foreach ($this->gtree->items as $itemid => $unused) {
1452                  $item =& $this->gtree->items[$itemid];
1453                  $itemcell = new html_table_cell();
1454                  $itemcell->attributes['class'] .= ' range i'. $itemid;
1455  
1456                  $hidden = '';
1457                  if ($item->is_hidden()) {
1458                      $hidden = ' dimmed_text ';
1459                  }
1460  
1461                  $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1462  
1463                  $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1464                  $rangerow->cells[] = $itemcell;
1465              }
1466              $rows[] = $rangerow;
1467          }
1468          return $rows;
1469      }
1470  
1471      /**
1472       * Builds and return the row of averages for the right part of the grader report.
1473       * @param array $rows Whether to return only group averages or all averages.
1474       * @param bool $grouponly Whether to return only group averages or all averages.
1475       * @return array Array of rows for the right part of the report
1476       */
1477      public function get_right_avg_row($rows=array(), $grouponly=false) {
1478          global $USER, $DB, $OUTPUT, $CFG;
1479  
1480          if (!$this->canviewhidden) {
1481              // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1482              // better not show them at all if user can not see all hidden grades.
1483              return $rows;
1484          }
1485  
1486          $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1487          $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1488          $meanselection         = $this->get_pref('meanselection');
1489          $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1490  
1491          if ($grouponly) {
1492              $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1493              $groupsql = $this->groupsql;
1494              $groupwheresql = $this->groupwheresql;
1495              $groupwheresqlparams = $this->groupwheresql_params;
1496          } else {
1497              $showaverages = $this->get_pref('showaverages');
1498              $groupsql = "";
1499              $groupwheresql = "";
1500              $groupwheresqlparams = array();
1501          }
1502  
1503          if ($showaverages) {
1504              $totalcount = $this->get_numusers($grouponly);
1505  
1506              // Limit to users with a gradeable role.
1507              list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1508  
1509              // Limit to users with an active enrollment.
1510              $coursecontext = $this->context->get_course_context(true);
1511              $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
1512              $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
1513              $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
1514              list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
1515  
1516              // We want to query both the current context and parent contexts.
1517              list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
1518  
1519              $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams);
1520  
1521              // Find sums of all grade items in course.
1522              $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1523                        FROM {grade_items} gi
1524                        JOIN {grade_grades} g ON g.itemid = gi.id
1525                        JOIN {user} u ON u.id = g.userid
1526                        JOIN ($enrolledsql) je ON je.id = u.id
1527                        JOIN (
1528                                 SELECT DISTINCT ra.userid
1529                                   FROM {role_assignments} ra
1530                                  WHERE ra.roleid $gradebookrolessql
1531                                    AND ra.contextid $relatedctxsql
1532                             ) rainner ON rainner.userid = u.id
1533                        $groupsql
1534                       WHERE gi.courseid = :courseid
1535                         AND u.deleted = 0
1536                         AND g.finalgrade IS NOT NULL
1537                         $groupwheresql
1538                       GROUP BY g.itemid";
1539              $sumarray = array();
1540              if ($sums = $DB->get_records_sql($sql, $params)) {
1541                  foreach ($sums as $itemid => $csum) {
1542                      $sumarray[$itemid] = $csum->sum;
1543                  }
1544              }
1545  
1546              // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1547              // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1548              $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1549                        FROM {grade_items} gi
1550                        CROSS JOIN ($enrolledsql) u
1551                        JOIN {role_assignments} ra
1552                             ON ra.userid = u.id
1553                        LEFT OUTER JOIN {grade_grades} g
1554                             ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1555                        $groupsql
1556                       WHERE gi.courseid = :courseid
1557                             AND ra.roleid $gradebookrolessql
1558                             AND ra.contextid $relatedctxsql
1559                             AND g.id IS NULL
1560                             $groupwheresql
1561                    GROUP BY gi.id";
1562  
1563              $ungradedcounts = $DB->get_records_sql($sql, $params);
1564  
1565              $avgrow = new html_table_row();
1566              $avgrow->attributes['class'] = 'avg';
1567  
1568              foreach ($this->gtree->items as $itemid => $unused) {
1569                  $item =& $this->gtree->items[$itemid];
1570  
1571                  if ($item->needsupdate) {
1572                      $avgcell = new html_table_cell();
1573                      $avgcell->attributes['class'] = 'i'. $itemid;
1574                      $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1575                      $avgrow->cells[] = $avgcell;
1576                      continue;
1577                  }
1578  
1579                  if (!isset($sumarray[$item->id])) {
1580                      $sumarray[$item->id] = 0;
1581                  }
1582  
1583                  if (empty($ungradedcounts[$itemid])) {
1584                      $ungradedcount = 0;
1585                  } else {
1586                      $ungradedcount = $ungradedcounts[$itemid]->count;
1587                  }
1588  
1589                  if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1590                      $meancount = $totalcount - $ungradedcount;
1591                  } else { // Bump up the sum by the number of ungraded items * grademin
1592                      $sumarray[$item->id] += $ungradedcount * $item->grademin;
1593                      $meancount = $totalcount;
1594                  }
1595  
1596                  // Determine which display type to use for this average
1597                  if (!empty($USER->editing)) {
1598                      $displaytype = GRADE_DISPLAY_TYPE_REAL;
1599  
1600                  } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1601                      $displaytype = $item->get_displaytype();
1602  
1603                  } else {
1604                      $displaytype = $averagesdisplaytype;
1605                  }
1606  
1607                  // Override grade_item setting if a display preference (not inherit) was set for the averages
1608                  if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1609                      $decimalpoints = $item->get_decimals();
1610  
1611                  } else {
1612                      $decimalpoints = $averagesdecimalpoints;
1613                  }
1614  
1615                  if (!isset($sumarray[$item->id]) || $meancount == 0) {
1616                      $avgcell = new html_table_cell();
1617                      $avgcell->attributes['class'] = 'i'. $itemid;
1618                      $avgcell->text = '-';
1619                      $avgrow->cells[] = $avgcell;
1620  
1621                  } else {
1622                      $sum = $sumarray[$item->id];
1623                      $avgradeval = $sum/$meancount;
1624                      $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1625  
1626                      $numberofgrades = '';
1627                      if ($shownumberofgrades) {
1628                          $numberofgrades = " ($meancount)";
1629                      }
1630  
1631                      $avgcell = new html_table_cell();
1632                      $avgcell->attributes['class'] = 'i'. $itemid;
1633                      $avgcell->text = $gradehtml.$numberofgrades;
1634                      $avgrow->cells[] = $avgcell;
1635                  }
1636              }
1637              $rows[] = $avgrow;
1638          }
1639          return $rows;
1640      }
1641  
1642      /**
1643       * Given element category, create a collapsible icon and
1644       * course header.
1645       *
1646       * @param array $element
1647       * @return string HTML
1648       */
1649      protected function get_course_header($element) {
1650          global $OUTPUT;
1651  
1652          $icon = '';
1653          // If object is a category, display expand/contract icon.
1654          if ($element['type'] == 'category') {
1655              // Load language strings.
1656              $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1657              $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1658              $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1659  
1660              $url = new moodle_url($this->gpr->get_return_url(null, array('target' => $element['eid'], 'sesskey' => sesskey())));
1661  
1662              if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1663                  $url->param('action', 'switch_plus');
1664                  $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', ''), null,
1665                          ['title' => $strswitchplus, 'aria-label' => $strswitchplus]);
1666                  $showing = get_string('showingaggregatesonly', 'grades');
1667              } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1668                  $url->param('action', 'switch_whole');
1669                  $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', ''), null,
1670                          ['title' => $strswitchwhole, 'aria-label' => $strswitchwhole]);
1671                  $showing = get_string('showinggradesonly', 'grades');
1672              } else {
1673                  $url->param('action', 'switch_minus');
1674                  $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', ''), null,
1675                          ['title' => $strswitchminus, 'aria-label' => $strswitchminus]);
1676                  $showing = get_string('showingfullmode', 'grades');
1677              }
1678          }
1679  
1680          $name = $element['object']->get_name();
1681          $nameunescaped = $element['object']->get_name(false);
1682          $describedbyid = uniqid();
1683          $courseheader = html_writer::tag('span', $name, [
1684              'title' => $nameunescaped,
1685              'class' => 'gradeitemheader',
1686              'aria-describedby' => $describedbyid
1687          ]);
1688          $courseheader .= html_writer::div($showing, 'sr-only', [
1689              'id' => $describedbyid
1690          ]);
1691          $courseheader .= $icon;
1692  
1693          return $courseheader;
1694      }
1695  
1696      /**
1697       * Given a grade_category, grade_item or grade_grade, this function
1698       * figures out the state of the object and builds then returns a div
1699       * with the icons needed for the grader report.
1700       *
1701       * @param array $element
1702       * @return string HTML
1703       */
1704      protected function get_icons($element) {
1705          global $CFG, $USER, $OUTPUT;
1706  
1707          if (empty($USER->editing)) {
1708              return '<div class="grade_icons" />';
1709          }
1710  
1711          // Init all icons
1712          $editicon = '';
1713  
1714          $editable = true;
1715  
1716          if ($element['type'] == 'grade') {
1717              $item = $element['object']->grade_item;
1718              if ($item->is_course_item() or $item->is_category_item()) {
1719                  $editable = $this->overridecat;
1720              }
1721          }
1722  
1723          if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem' && $editable) {
1724              $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1725          }
1726  
1727          $editcalculationicon = '';
1728          $showhideicon        = '';
1729          $lockunlockicon      = '';
1730  
1731          if (has_capability('moodle/grade:manage', $this->context)) {
1732              if ($this->get_pref('showcalculations')) {
1733                  $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1734              }
1735  
1736              if ($this->get_pref('showeyecons')) {
1737                  $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1738              }
1739  
1740              if ($this->get_pref('showlocks')) {
1741                  $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1742              }
1743  
1744          }
1745  
1746          $gradeanalysisicon   = '';
1747          if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1748              $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
1749          }
1750  
1751          return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
1752      }
1753  
1754      /**
1755       * Given a category element returns collapsing +/- icon if available
1756       *
1757       * @deprecated since Moodle 2.9 MDL-46662 - please do not use this function any more.
1758       */
1759      protected function get_collapsing_icon($element) {
1760          throw new coding_exception('get_collapsing_icon() can not be used any more, please use get_course_header() instead.');
1761      }
1762  
1763      /**
1764       * Processes a single action against a category, grade_item or grade.
1765       * @param string $target eid ({type}{id}, e.g. c4 for category4)
1766       * @param string $action Which action to take (edit, delete etc...)
1767       * @return
1768       */
1769      public function process_action($target, $action) {
1770          return self::do_process_action($target, $action, $this->course->id);
1771      }
1772  
1773      /**
1774       * From the list of categories that this user prefers to collapse choose ones that belong to the current course.
1775       *
1776       * This function serves two purposes.
1777       * Mainly it helps migrating from user preference style when all courses were stored in one preference.
1778       * Also it helps to remove the settings for categories that were removed if the array for one course grows too big.
1779       *
1780       * @param int $courseid
1781       * @param array $collapsed
1782       * @return array
1783       */
1784      protected static function filter_collapsed_categories($courseid, $collapsed) {
1785          global $DB;
1786          // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1787          $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? [];
1788          $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? [];
1789  
1790          if (empty($collapsed['aggregatesonly']) && empty($collapsed['gradesonly'])) {
1791              return $collapsed;
1792          }
1793          $cats = $DB->get_fieldset_select('grade_categories', 'id', 'courseid = ?', array($courseid));
1794          $collapsed['aggregatesonly'] = array_values(array_intersect($collapsed['aggregatesonly'], $cats));
1795          $collapsed['gradesonly'] = array_values(array_intersect($collapsed['gradesonly'], $cats));
1796          return $collapsed;
1797      }
1798  
1799      /**
1800       * Returns the list of categories that this user wants to collapse or display aggregatesonly
1801       *
1802       * This method also migrates on request from the old format of storing user preferences when they were stored
1803       * in one preference for all courses causing DB error when trying to insert very big value.
1804       *
1805       * @param int $courseid
1806       * @return array
1807       */
1808      protected static function get_collapsed_preferences($courseid) {
1809          if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories'.$courseid)) {
1810              $collapsed = json_decode($collapsed, true);
1811              // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1812              $collapsed['aggregatesonly'] = $collapsed['aggregatesonly'] ?? [];
1813              $collapsed['gradesonly'] = $collapsed['gradesonly'] ?? [];
1814              return $collapsed;
1815          }
1816  
1817          // Try looking for old location of user setting that used to store all courses in one serialized user preference.
1818          $collapsed = ['aggregatesonly' => [], 'gradesonly' => []]; // Use this if old settings are not found.
1819          $collapsedall = [];
1820          $oldprefexists = false;
1821          if (($oldcollapsedpref = get_user_preferences('grade_report_grader_collapsed_categories')) !== null) {
1822              $oldprefexists = true;
1823              if ($collapsedall = unserialize_array($oldcollapsedpref)) {
1824                  // Ensure we always have an element for aggregatesonly and another for gradesonly, no matter it's empty.
1825                  $collapsedall['aggregatesonly'] = $collapsedall['aggregatesonly'] ?? [];
1826                  $collapsedall['gradesonly'] = $collapsedall['gradesonly'] ?? [];
1827                  // We found the old-style preference, filter out only categories that belong to this course and update the prefs.
1828                  $collapsed = static::filter_collapsed_categories($courseid, $collapsedall);
1829                  if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1830                      static::set_collapsed_preferences($courseid, $collapsed);
1831                      $collapsedall['aggregatesonly'] = array_diff($collapsedall['aggregatesonly'], $collapsed['aggregatesonly']);
1832                      $collapsedall['gradesonly'] = array_diff($collapsedall['gradesonly'], $collapsed['gradesonly']);
1833                      if (!empty($collapsedall['aggregatesonly']) || !empty($collapsedall['gradesonly'])) {
1834                          set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsedall));
1835                      }
1836                  }
1837              }
1838          }
1839  
1840          // Arrived here, if the old pref exists and it doesn't contain
1841          // more information, it means that the migration of all the
1842          // data to new, by course, preferences is completed, so
1843          // the old one can be safely deleted.
1844          if ($oldprefexists &&
1845                  empty($collapsedall['aggregatesonly']) &&
1846                  empty($collapsedall['gradesonly'])) {
1847              unset_user_preference('grade_report_grader_collapsed_categories');
1848          }
1849  
1850          return $collapsed;
1851      }
1852  
1853      /**
1854       * Sets the list of categories that user wants to see collapsed in user preferences
1855       *
1856       * This method may filter or even trim the list if it does not fit in DB field.
1857       *
1858       * @param int $courseid
1859       * @param array $collapsed
1860       */
1861      protected static function set_collapsed_preferences($courseid, $collapsed) {
1862          global $DB;
1863          // In an unlikely case that the list of collapsed categories for one course is too big for the user preference size,
1864          // try to filter the list of categories since array may contain categories that were deleted.
1865          if (strlen(json_encode($collapsed)) >= 1333) {
1866              $collapsed = static::filter_collapsed_categories($courseid, $collapsed);
1867          }
1868  
1869          // If this did not help, "forget" about some of the collapsed categories. Still better than to loose all information.
1870          while (strlen(json_encode($collapsed)) >= 1333) {
1871              if (count($collapsed['aggregatesonly'])) {
1872                  array_pop($collapsed['aggregatesonly']);
1873              }
1874              if (count($collapsed['gradesonly'])) {
1875                  array_pop($collapsed['gradesonly']);
1876              }
1877          }
1878  
1879          if (!empty($collapsed['aggregatesonly']) || !empty($collapsed['gradesonly'])) {
1880              set_user_preference('grade_report_grader_collapsed_categories'.$courseid, json_encode($collapsed));
1881          } else {
1882              unset_user_preference('grade_report_grader_collapsed_categories'.$courseid);
1883          }
1884      }
1885  
1886      /**
1887       * Processes a single action against a category, grade_item or grade.
1888       * @param string $target eid ({type}{id}, e.g. c4 for category4)
1889       * @param string $action Which action to take (edit, delete etc...)
1890       * @param int $courseid affected course.
1891       * @return
1892       */
1893      public static function do_process_action($target, $action, $courseid = null) {
1894          global $DB;
1895          // TODO: this code should be in some grade_tree static method
1896          $targettype = substr($target, 0, 2);
1897          $targetid = substr($target, 2);
1898          // TODO: end
1899  
1900          if ($targettype !== 'cg') {
1901              // The following code only works with categories.
1902              return true;
1903          }
1904  
1905          if (!$courseid) {
1906              debugging('Function grade_report_grader::do_process_action() now requires additional argument courseid',
1907                  DEBUG_DEVELOPER);
1908              if (!$courseid = $DB->get_field('grade_categories', 'courseid', array('id' => $targetid), IGNORE_MISSING)) {
1909                  return true;
1910              }
1911          }
1912  
1913          $collapsed = static::get_collapsed_preferences($courseid);
1914  
1915          switch ($action) {
1916              case 'switch_minus': // Add category to array of aggregatesonly
1917                  if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1918                      $collapsed['aggregatesonly'][] = $targetid;
1919                      static::set_collapsed_preferences($courseid, $collapsed);
1920                  }
1921                  break;
1922  
1923              case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1924                  $key = array_search($targetid, $collapsed['aggregatesonly']);
1925                  if ($key !== false) {
1926                      unset($collapsed['aggregatesonly'][$key]);
1927                  }
1928                  if (!in_array($targetid, $collapsed['gradesonly'])) {
1929                      $collapsed['gradesonly'][] = $targetid;
1930                  }
1931                  static::set_collapsed_preferences($courseid, $collapsed);
1932                  break;
1933              case 'switch_whole': // Remove the category from the array of collapsed cats
1934                  $key = array_search($targetid, $collapsed['gradesonly']);
1935                  if ($key !== false) {
1936                      unset($collapsed['gradesonly'][$key]);
1937                      static::set_collapsed_preferences($courseid, $collapsed);
1938                  }
1939  
1940                  break;
1941              default:
1942                  break;
1943          }
1944  
1945          return true;
1946      }
1947  
1948      /**
1949       * Refactored function for generating HTML of sorting links with matching arrows.
1950       * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1951       * to inject into a table header cell.
1952       * @param array $extrafields Array of extra fields being displayed, such as
1953       *   user idnumber
1954       * @return array An associative array of HTML sorting links+arrows
1955       */
1956      public function get_sort_arrows(array $extrafields = array()) {
1957          global $OUTPUT, $CFG;
1958          $arrows = array();
1959  
1960          $strsortasc   = $this->get_lang_string('sortasc', 'grades');
1961          $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
1962          $iconasc = $OUTPUT->pix_icon('t/sort_asc', $strsortasc, '', array('class' => 'iconsmall sorticon'));
1963          $icondesc = $OUTPUT->pix_icon('t/sort_desc', $strsortdesc, '', array('class' => 'iconsmall sorticon'));
1964  
1965          // Sourced from tablelib.php
1966          // Check the full name display for sortable fields.
1967          if (has_capability('moodle/site:viewfullnames', $this->context)) {
1968              $nameformat = $CFG->alternativefullnameformat;
1969          } else {
1970              $nameformat = $CFG->fullnamedisplay;
1971          }
1972  
1973          if ($nameformat == 'language') {
1974              $nameformat = get_string('fullnamedisplay');
1975          }
1976  
1977          $arrows['studentname'] = '';
1978          $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat);
1979          if (!empty($requirednames)) {
1980              foreach ($requirednames as $name) {
1981                  $arrows['studentname'] .= html_writer::link(
1982                      new moodle_url($this->baseurl, array('sortitemid' => $name)), $this->get_lang_string($name)
1983                  );
1984                  if ($this->sortitemid == $name) {
1985                      $arrows['studentname'] .= $this->sortorder == 'ASC' ? $iconasc : $icondesc;
1986                  }
1987                  $arrows['studentname'] .= ' / ';
1988              }
1989  
1990              $arrows['studentname'] = substr($arrows['studentname'], 0, -3);
1991          }
1992  
1993          foreach ($extrafields as $field) {
1994              $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1995                      array('sortitemid' => $field)), \core_user\fields::get_display_name($field));
1996              $arrows[$field] = $fieldlink;
1997  
1998              if ($field == $this->sortitemid) {
1999                  if ($this->sortorder == 'ASC') {
2000                      $arrows[$field] .= $iconasc;
2001                  } else {
2002                      $arrows[$field] .= $icondesc;
2003                  }
2004              }
2005          }
2006  
2007          return $arrows;
2008      }
2009  
2010      /**
2011       * Returns the maximum number of students to be displayed on each page
2012       *
2013       * @return int The maximum number of students to display per page
2014       */
2015      public function get_students_per_page(): int {
2016          return (int) $this->get_pref('studentsperpage');
2017      }
2018  }