Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

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

    Search This Site: