Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403] [Versions 39 and 310]

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