Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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

   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   * This file contains the definition for the grading table which subclassses easy_table
  19   *
  20   * @package   mod_assign
  21   * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  require_once($CFG->libdir.'/tablelib.php');
  28  require_once($CFG->libdir.'/gradelib.php');
  29  require_once($CFG->dirroot.'/mod/assign/locallib.php');
  30  
  31  /**
  32   * Extends table_sql to provide a table of assignment submissions
  33   *
  34   * @package   mod_assign
  35   * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
  36   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class assign_grading_table extends table_sql implements renderable {
  39      /** @var assign $assignment */
  40      private $assignment = null;
  41      /** @var int $perpage */
  42      private $perpage = 10;
  43      /** @var int $rownum (global index of current row in table) */
  44      private $rownum = -1;
  45      /** @var renderer_base for getting output */
  46      private $output = null;
  47      /** @var stdClass gradinginfo */
  48      private $gradinginfo = null;
  49      /** @var int $tablemaxrows */
  50      private $tablemaxrows = 10000;
  51      /** @var boolean $quickgrading */
  52      private $quickgrading = false;
  53      /** @var boolean $hasgrantextension - Only do the capability check once for the entire table */
  54      private $hasgrantextension = false;
  55      /** @var boolean $hasgrade - Only do the capability check once for the entire table */
  56      private $hasgrade = false;
  57      /** @var array $groupsubmissions - A static cache of group submissions */
  58      private $groupsubmissions = array();
  59      /** @var array $submissiongroups - A static cache of submission groups */
  60      private $submissiongroups = array();
  61      /** @var string $plugingradingbatchoperations - List of plugin supported batch operations */
  62      public $plugingradingbatchoperations = array();
  63      /** @var array $plugincache - A cache of plugin lookups to match a column name to a plugin efficiently */
  64      private $plugincache = array();
  65      /** @var array $scale - A list of the keys and descriptions for the custom scale */
  66      private $scale = null;
  67  
  68      /**
  69       * overridden constructor keeps a reference to the assignment class that is displaying this table
  70       *
  71       * @param assign $assignment The assignment class
  72       * @param int $perpage how many per page
  73       * @param string $filter The current filter
  74       * @param int $rowoffset For showing a subsequent page of results
  75       * @param bool $quickgrading Is this table wrapped in a quickgrading form?
  76       * @param string $downloadfilename
  77       */
  78      public function __construct(assign $assignment,
  79                                  $perpage,
  80                                  $filter,
  81                                  $rowoffset,
  82                                  $quickgrading,
  83                                  $downloadfilename = null) {
  84          global $CFG, $PAGE, $DB, $USER;
  85  
  86          parent::__construct('mod_assign_grading-' . $assignment->get_context()->id);
  87  
  88          $this->is_persistent(true);
  89          $this->assignment = $assignment;
  90  
  91          // Check permissions up front.
  92          $this->hasgrantextension = has_capability('mod/assign:grantextension',
  93                                                    $this->assignment->get_context());
  94          $this->hasgrade = $this->assignment->can_grade();
  95  
  96          // Check if we have the elevated view capablities to see the blind details.
  97          $this->hasviewblind = has_capability('mod/assign:viewblinddetails',
  98                  $this->assignment->get_context());
  99  
 100          foreach ($assignment->get_feedback_plugins() as $plugin) {
 101              if ($plugin->is_visible() && $plugin->is_enabled()) {
 102                  foreach ($plugin->get_grading_batch_operations() as $action => $description) {
 103                      if (empty($this->plugingradingbatchoperations)) {
 104                          $this->plugingradingbatchoperations[$plugin->get_type()] = array();
 105                      }
 106                      $this->plugingradingbatchoperations[$plugin->get_type()][$action] = $description;
 107                  }
 108              }
 109          }
 110          $this->perpage = $perpage;
 111          $this->quickgrading = $quickgrading && $this->hasgrade;
 112          $this->output = $PAGE->get_renderer('mod_assign');
 113  
 114          $urlparams = array('action' => 'grading', 'id' => $assignment->get_course_module()->id);
 115          $url = new moodle_url($CFG->wwwroot . '/mod/assign/view.php', $urlparams);
 116          $this->define_baseurl($url);
 117  
 118          // Do some business - then set the sql.
 119          $currentgroup = groups_get_activity_group($assignment->get_course_module(), true);
 120  
 121          if ($rowoffset) {
 122              $this->rownum = $rowoffset - 1;
 123          }
 124  
 125          $users = array_keys( $assignment->list_participants($currentgroup, true));
 126          if (count($users) == 0) {
 127              // Insert a record that will never match to the sql is still valid.
 128              $users[] = -1;
 129          }
 130  
 131          $params = array();
 132          $params['assignmentid1'] = (int)$this->assignment->get_instance()->id;
 133          $params['assignmentid2'] = (int)$this->assignment->get_instance()->id;
 134          $params['assignmentid3'] = (int)$this->assignment->get_instance()->id;
 135          $params['newstatus'] = ASSIGN_SUBMISSION_STATUS_NEW;
 136  
 137          // TODO Does not support custom user profile fields (MDL-70456).
 138          $userfieldsapi = \core_user\fields::for_identity($this->assignment->get_context(), false)->with_userpic();
 139          $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 140          $extrauserfields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);
 141          $fields = $userfields . ', ';
 142          $fields .= 'u.id as userid, ';
 143          $fields .= 's.status as status, ';
 144          $fields .= 's.id as submissionid, ';
 145          $fields .= 's.timecreated as firstsubmission, ';
 146          $fields .= "CASE WHEN status <> :newstatus THEN s.timemodified ELSE NULL END as timesubmitted, ";
 147          $fields .= 's.attemptnumber as attemptnumber, ';
 148          $fields .= 'g.id as gradeid, ';
 149          $fields .= 'g.grade as grade, ';
 150          $fields .= 'g.timemodified as timemarked, ';
 151          $fields .= 'g.timecreated as firstmarked, ';
 152          $fields .= 'uf.mailed as mailed, ';
 153          $fields .= 'uf.locked as locked, ';
 154          $fields .= 'uf.extensionduedate as extensionduedate, ';
 155          $fields .= 'uf.workflowstate as workflowstate, ';
 156          $fields .= 'uf.allocatedmarker as allocatedmarker';
 157  
 158          $from = '{user} u
 159                           LEFT JOIN {assign_submission} s
 160                                  ON u.id = s.userid
 161                                 AND s.assignment = :assignmentid1
 162                                 AND s.latest = 1 ';
 163  
 164          // For group assignments, there can be a grade with no submission.
 165          $from .= ' LEFT JOIN {assign_grades} g
 166                              ON g.assignment = :assignmentid2
 167                             AND u.id = g.userid
 168                             AND (g.attemptnumber = s.attemptnumber OR s.attemptnumber IS NULL) ';
 169  
 170          $from .= 'LEFT JOIN {assign_user_flags} uf
 171                           ON u.id = uf.userid
 172                          AND uf.assignment = :assignmentid3 ';
 173  
 174          if ($this->assignment->get_course()->relativedatesmode) {
 175              $params['courseid1'] = $this->assignment->get_course()->id;
 176              $from .= ' LEFT JOIN (
 177              SELECT ue1.userid as enroluserid,
 178                CASE WHEN MIN(ue1.timestart - c2.startdate) < 0 THEN 0 ELSE MIN(ue1.timestart - c2.startdate) END as enrolstartoffset
 179                FROM {enrol} e1
 180                JOIN {user_enrolments} ue1
 181                  ON (ue1.enrolid = e1.id AND ue1.status = 0)
 182                JOIN {course} c2
 183                  ON c2.id = e1.courseid
 184               WHERE e1.courseid = :courseid1 AND e1.status = 0
 185               GROUP BY ue1.userid
 186              ) enroloffset
 187              ON (enroloffset.enroluserid = u.id) ';
 188          }
 189  
 190          $hasoverrides = $this->assignment->has_overrides();
 191          $inrelativedatesmode = $this->assignment->get_course()->relativedatesmode;
 192  
 193          if ($hasoverrides) {
 194              $params['assignmentid5'] = (int)$this->assignment->get_instance()->id;
 195              $params['assignmentid6'] = (int)$this->assignment->get_instance()->id;
 196              $params['assignmentid7'] = (int)$this->assignment->get_instance()->id;
 197              $params['assignmentid8'] = (int)$this->assignment->get_instance()->id;
 198              $params['assignmentid9'] = (int)$this->assignment->get_instance()->id;
 199  
 200              list($userwhere1, $userparams1) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'priorityuser');
 201              list($userwhere2, $userparams2) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'effectiveuser');
 202  
 203              $userwhere1 = "WHERE u.id {$userwhere1}";
 204              $userwhere2 = "WHERE u.id {$userwhere2}";
 205              $params = array_merge($params, $userparams1);
 206              $params = array_merge($params, $userparams2);
 207  
 208              $fields .= ', priority.priority, ';
 209              $fields .= 'effective.allowsubmissionsfromdate, ';
 210  
 211              if ($inrelativedatesmode) {
 212                  // If the priority is less than the 9999999 constant value it means it's an override
 213                  // and we should use that value directly. Otherwise we need to apply the uesr's course
 214                  // start date offset.
 215                  $fields .= 'CASE WHEN priority.priority < 9999999 THEN effective.duedate ELSE' .
 216                             ' effective.duedate + enroloffset.enrolstartoffset END as duedate, ';
 217              } else {
 218                  $fields .= 'effective.duedate, ';
 219              }
 220  
 221              $fields .= 'effective.cutoffdate ';
 222  
 223              $from .= ' LEFT JOIN (
 224                 SELECT merged.userid, min(merged.priority) priority FROM (
 225                    ( SELECT u.id as userid, 9999999 AS priority
 226                        FROM {user} u '.$userwhere1.'
 227                    )
 228                    UNION
 229                    ( SELECT uo.userid, 0 AS priority
 230                        FROM {assign_overrides} uo
 231                       WHERE uo.assignid = :assignmentid5
 232                    )
 233                    UNION
 234                    ( SELECT gm.userid, go.sortorder AS priority
 235                        FROM {assign_overrides} go
 236                        JOIN {groups} g ON g.id = go.groupid
 237                        JOIN {groups_members} gm ON gm.groupid = g.id
 238                       WHERE go.assignid = :assignmentid6
 239                    )
 240                  ) merged
 241                  GROUP BY merged.userid
 242                ) priority ON priority.userid = u.id
 243  
 244              JOIN (
 245                (SELECT 9999999 AS priority,
 246                        u.id AS userid,
 247                        a.allowsubmissionsfromdate,
 248                        a.duedate,
 249                        a.cutoffdate
 250                   FROM {user} u
 251                   JOIN {assign} a ON a.id = :assignmentid7
 252                   '.$userwhere2.'
 253                )
 254                UNION
 255                (SELECT 0 AS priority,
 256                        uo.userid,
 257                        uo.allowsubmissionsfromdate,
 258                        uo.duedate,
 259                        uo.cutoffdate
 260                   FROM {assign_overrides} uo
 261                  WHERE uo.assignid = :assignmentid8
 262                )
 263                UNION
 264                (SELECT go.sortorder AS priority,
 265                        gm.userid,
 266                        go.allowsubmissionsfromdate,
 267                        go.duedate,
 268                        go.cutoffdate
 269                   FROM {assign_overrides} go
 270                   JOIN {groups} g ON g.id = go.groupid
 271                   JOIN {groups_members} gm ON gm.groupid = g.id
 272                  WHERE go.assignid = :assignmentid9
 273                )
 274  
 275              ) effective ON effective.priority = priority.priority AND effective.userid = priority.userid ';
 276          } else if ($inrelativedatesmode) {
 277              // In relative dates mode and when we don't have overrides, include the
 278              // duedate, cutoffdate and allowsubmissionsfrom date anyway as this information is useful and can vary.
 279              $params['assignmentid5'] = (int)$this->assignment->get_instance()->id;
 280              $fields .= ', a.duedate + enroloffset.enrolstartoffset as duedate, ';
 281              $fields .= 'a.allowsubmissionsfromdate, ';
 282              $fields .= 'a.cutoffdate ';
 283              $from .= 'JOIN {assign} a ON a.id = :assignmentid5 ';
 284          }
 285  
 286          if (!empty($this->assignment->get_instance()->blindmarking)) {
 287              $from .= 'LEFT JOIN {assign_user_mapping} um
 288                               ON u.id = um.userid
 289                              AND um.assignment = :assignmentidblind ';
 290              $params['assignmentidblind'] = (int)$this->assignment->get_instance()->id;
 291              $fields .= ', um.id as recordid ';
 292          }
 293  
 294          $userparams3 = array();
 295          $userindex = 0;
 296  
 297          list($userwhere3, $userparams3) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'user');
 298          $where = 'u.id ' . $userwhere3;
 299          $params = array_merge($params, $userparams3);
 300  
 301          // The filters do not make sense when there are no submissions, so do not apply them.
 302          if ($this->assignment->is_any_submission_plugin_enabled()) {
 303              if ($filter == ASSIGN_FILTER_SUBMITTED) {
 304                  $where .= ' AND (s.timemodified IS NOT NULL AND
 305                                   s.status = :submitted) ';
 306                  $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
 307  
 308              } else if ($filter == ASSIGN_FILTER_NOT_SUBMITTED) {
 309                  $where .= ' AND (s.timemodified IS NULL OR s.status <> :submitted) ';
 310                  $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
 311              } else if ($filter == ASSIGN_FILTER_REQUIRE_GRADING) {
 312                  $where .= ' AND (s.timemodified IS NOT NULL AND
 313                                   s.status = :submitted AND
 314                                   (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL';
 315  
 316                  // Assignment grade is set to the negative grade scale id when scales are used.
 317                  if ($this->assignment->get_instance()->grade < 0) {
 318                      // Scale grades are set to -1 when not graded.
 319                      $where .= ' OR g.grade = -1';
 320                  }
 321  
 322                  $where .= '))';
 323                  $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
 324  
 325              } else if ($filter == ASSIGN_FILTER_GRANTED_EXTENSION) {
 326                  $where .= ' AND uf.extensionduedate > 0 ';
 327  
 328              } else if (strpos($filter, ASSIGN_FILTER_SINGLE_USER) === 0) {
 329                  $userfilter = (int) array_pop(explode('=', $filter));
 330                  $where .= ' AND (u.id = :userid)';
 331                  $params['userid'] = $userfilter;
 332              } else if ($filter == ASSIGN_FILTER_DRAFT) {
 333                  $where .= ' AND (s.timemodified IS NOT NULL AND
 334                                   s.status = :draft) ';
 335                  $params['draft'] = ASSIGN_SUBMISSION_STATUS_DRAFT;
 336              }
 337          }
 338  
 339          if ($this->assignment->get_instance()->markingworkflow &&
 340              $this->assignment->get_instance()->markingallocation) {
 341              if (has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
 342                  // Check to see if marker filter is set.
 343                  $markerfilter = (int)get_user_preferences('assign_markerfilter', '');
 344                  if (!empty($markerfilter)) {
 345                      if ($markerfilter == ASSIGN_MARKER_FILTER_NO_MARKER) {
 346                          $where .= ' AND (uf.allocatedmarker IS NULL OR uf.allocatedmarker = 0)';
 347                      } else {
 348                          $where .= ' AND uf.allocatedmarker = :markerid';
 349                          $params['markerid'] = $markerfilter;
 350                      }
 351                  }
 352              }
 353          }
 354  
 355          if ($this->assignment->get_instance()->markingworkflow) {
 356              $workflowstates = $this->assignment->get_marking_workflow_states_for_current_user();
 357              if (!empty($workflowstates)) {
 358                  $workflowfilter = get_user_preferences('assign_workflowfilter', '');
 359                  if ($workflowfilter == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED) {
 360                      $where .= ' AND (uf.workflowstate = :workflowstate OR uf.workflowstate IS NULL OR '.
 361                          $DB->sql_isempty('assign_user_flags', 'workflowstate', true, true).')';
 362                      $params['workflowstate'] = $workflowfilter;
 363                  } else if (array_key_exists($workflowfilter, $workflowstates)) {
 364                      $where .= ' AND uf.workflowstate = :workflowstate';
 365                      $params['workflowstate'] = $workflowfilter;
 366                  }
 367              }
 368          }
 369  
 370          $this->set_sql($fields, $from, $where, $params);
 371  
 372          if ($downloadfilename) {
 373              $this->is_downloading('csv', $downloadfilename);
 374          }
 375  
 376          $columns = array();
 377          $headers = array();
 378  
 379          // Select.
 380          if (!$this->is_downloading() && $this->hasgrade) {
 381              $columns[] = 'select';
 382              $headers[] = get_string('select') .
 383                      '<div class="selectall"><label class="accesshide" for="selectall">' . get_string('selectall') . '</label>
 384                      <input type="checkbox" id="selectall" name="selectall" title="' . get_string('selectall') . '"/></div>';
 385          }
 386  
 387          // User picture.
 388          if ($this->hasviewblind || !$this->assignment->is_blind_marking()) {
 389              if (!$this->is_downloading()) {
 390                  $columns[] = 'picture';
 391                  $headers[] = get_string('pictureofuser');
 392              } else {
 393                  $columns[] = 'recordid';
 394                  $headers[] = get_string('recordid', 'assign');
 395              }
 396  
 397              // Fullname.
 398              $columns[] = 'fullname';
 399              $headers[] = get_string('fullname');
 400  
 401              // Participant # details if can view real identities.
 402              if ($this->assignment->is_blind_marking()) {
 403                  if (!$this->is_downloading()) {
 404                      $columns[] = 'recordid';
 405                      $headers[] = get_string('recordid', 'assign');
 406                  }
 407              }
 408  
 409              foreach ($extrauserfields as $extrafield) {
 410                  $columns[] = $extrafield;
 411                  $headers[] = \core_user\fields::get_display_name($extrafield);
 412              }
 413          } else {
 414              // Record ID.
 415              $columns[] = 'recordid';
 416              $headers[] = get_string('recordid', 'assign');
 417          }
 418  
 419          // Submission status.
 420          $columns[] = 'status';
 421          $headers[] = get_string('status', 'assign');
 422  
 423          if ($hasoverrides || $inrelativedatesmode) {
 424              // Allowsubmissionsfromdate.
 425              $columns[] = 'allowsubmissionsfromdate';
 426              $headers[] = get_string('allowsubmissionsfromdate', 'assign');
 427  
 428              // Duedate.
 429              $columns[] = 'duedate';
 430              $headers[] = get_string('duedate', 'assign');
 431  
 432              // Cutoffdate.
 433              $columns[] = 'cutoffdate';
 434              $headers[] = get_string('cutoffdate', 'assign');
 435          }
 436  
 437          // Team submission columns.
 438          if ($assignment->get_instance()->teamsubmission) {
 439              $columns[] = 'team';
 440              $headers[] = get_string('submissionteam', 'assign');
 441          }
 442          // Allocated marker.
 443          if ($this->assignment->get_instance()->markingworkflow &&
 444              $this->assignment->get_instance()->markingallocation &&
 445              has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
 446              // Add a column for the allocated marker.
 447              $columns[] = 'allocatedmarker';
 448              $headers[] = get_string('marker', 'assign');
 449          }
 450          // Grade.
 451          $columns[] = 'grade';
 452          $headers[] = get_string('gradenoun');
 453          if ($this->is_downloading()) {
 454              $gradetype = $this->assignment->get_instance()->grade;
 455              if ($gradetype > 0) {
 456                  $columns[] = 'grademax';
 457                  $headers[] = get_string('maxgrade', 'assign');
 458              } else if ($gradetype < 0) {
 459                  // This is a custom scale.
 460                  $columns[] = 'scale';
 461                  $headers[] = get_string('scale', 'assign');
 462              }
 463  
 464              if ($this->assignment->get_instance()->markingworkflow) {
 465                  // Add a column for the marking workflow state.
 466                  $columns[] = 'workflowstate';
 467                  $headers[] = get_string('markingworkflowstate', 'assign');
 468              }
 469              // Add a column to show if this grade can be changed.
 470              $columns[] = 'gradecanbechanged';
 471              $headers[] = get_string('gradecanbechanged', 'assign');
 472          }
 473          if (!$this->is_downloading() && $this->hasgrade) {
 474              // We have to call this column userid so we can use userid as a default sortable column.
 475              $columns[] = 'userid';
 476              $headers[] = get_string('edit');
 477          }
 478  
 479          // Submission plugins.
 480          if ($assignment->is_any_submission_plugin_enabled()) {
 481              $columns[] = 'timesubmitted';
 482              $headers[] = get_string('lastmodifiedsubmission', 'assign');
 483  
 484              foreach ($this->assignment->get_submission_plugins() as $plugin) {
 485                  if ($this->is_downloading()) {
 486                      if ($plugin->is_visible() && $plugin->is_enabled()) {
 487                          foreach ($plugin->get_editor_fields() as $field => $description) {
 488                              $index = 'plugin' . count($this->plugincache);
 489                              $this->plugincache[$index] = array($plugin, $field);
 490                              $columns[] = $index;
 491                              $headers[] = $plugin->get_name();
 492                          }
 493                      }
 494                  } else {
 495                      if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
 496                          $index = 'plugin' . count($this->plugincache);
 497                          $this->plugincache[$index] = array($plugin);
 498                          $columns[] = $index;
 499                          $headers[] = $plugin->get_name();
 500                      }
 501                  }
 502              }
 503          }
 504  
 505          // Time marked.
 506          $columns[] = 'timemarked';
 507          $headers[] = get_string('lastmodifiedgrade', 'assign');
 508  
 509          // Feedback plugins.
 510          foreach ($this->assignment->get_feedback_plugins() as $plugin) {
 511              if ($this->is_downloading()) {
 512                  if ($plugin->is_visible() && $plugin->is_enabled()) {
 513                      foreach ($plugin->get_editor_fields() as $field => $description) {
 514                          $index = 'plugin' . count($this->plugincache);
 515                          $this->plugincache[$index] = array($plugin, $field);
 516                          $columns[] = $index;
 517                          $headers[] = $description;
 518                      }
 519                  }
 520              } else if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
 521                  $index = 'plugin' . count($this->plugincache);
 522                  $this->plugincache[$index] = array($plugin);
 523                  $columns[] = $index;
 524                  $headers[] = $plugin->get_name();
 525              }
 526          }
 527  
 528          // Exclude 'Final grade' column in downloaded grading worksheets.
 529          if (!$this->is_downloading()) {
 530              // Final grade.
 531              $columns[] = 'finalgrade';
 532              $headers[] = get_string('finalgrade', 'grades');
 533          }
 534  
 535          // Load the grading info for all users.
 536          $this->gradinginfo = grade_get_grades($this->assignment->get_course()->id,
 537                                                'mod',
 538                                                'assign',
 539                                                $this->assignment->get_instance()->id,
 540                                                $users);
 541  
 542          if (!empty($CFG->enableoutcomes) && !empty($this->gradinginfo->outcomes)) {
 543              $columns[] = 'outcomes';
 544              $headers[] = get_string('outcomes', 'grades');
 545          }
 546  
 547          // Set the columns.
 548          $this->define_columns($columns);
 549          $this->define_headers($headers);
 550          foreach ($extrauserfields as $extrafield) {
 551               $this->column_class($extrafield, $extrafield);
 552          }
 553          $this->no_sorting('recordid');
 554          $this->no_sorting('finalgrade');
 555          $this->no_sorting('userid');
 556          $this->no_sorting('select');
 557          $this->no_sorting('outcomes');
 558  
 559          if ($assignment->get_instance()->teamsubmission) {
 560              $this->no_sorting('team');
 561          }
 562  
 563          $plugincolumnindex = 0;
 564          foreach ($this->assignment->get_submission_plugins() as $plugin) {
 565              if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
 566                  $submissionpluginindex = 'plugin' . $plugincolumnindex++;
 567                  $this->no_sorting($submissionpluginindex);
 568              }
 569          }
 570          foreach ($this->assignment->get_feedback_plugins() as $plugin) {
 571              if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
 572                  $feedbackpluginindex = 'plugin' . $plugincolumnindex++;
 573                  $this->no_sorting($feedbackpluginindex);
 574              }
 575          }
 576  
 577          // When there is no data we still want the column headers printed in the csv file.
 578          if ($this->is_downloading()) {
 579              $this->start_output();
 580          }
 581      }
 582  
 583      /**
 584       * Before adding each row to the table make sure rownum is incremented.
 585       *
 586       * @param array $row row of data from db used to make one row of the table.
 587       * @return array one row for the table
 588       */
 589      public function format_row($row) {
 590          if ($this->rownum < 0) {
 591              $this->rownum = $this->currpage * $this->pagesize;
 592          } else {
 593              $this->rownum += 1;
 594          }
 595  
 596          return parent::format_row($row);
 597      }
 598  
 599      /**
 600       * Add a column with an ID that uniquely identifies this user in this assignment.
 601       *
 602       * @param stdClass $row
 603       * @return string
 604       */
 605      public function col_recordid(stdClass $row) {
 606          if (empty($row->recordid)) {
 607              $row->recordid = $this->assignment->get_uniqueid_for_user($row->userid);
 608          }
 609          return get_string('hiddenuser', 'assign') . $row->recordid;
 610      }
 611  
 612  
 613      /**
 614       * Add the userid to the row class so it can be updated via ajax.
 615       *
 616       * @param stdClass $row The row of data
 617       * @return string The row class
 618       */
 619      public function get_row_class($row) {
 620          return 'user' . $row->userid;
 621      }
 622  
 623      /**
 624       * Return the number of rows to display on a single page.
 625       *
 626       * @return int The number of rows per page
 627       */
 628      public function get_rows_per_page() {
 629          return $this->perpage;
 630      }
 631  
 632      /**
 633       * list current marking workflow state
 634       *
 635       * @param stdClass $row
 636       * @return string
 637       */
 638      public function col_workflowstatus(stdClass $row) {
 639          $o = '';
 640  
 641          $gradingdisabled = $this->assignment->grading_disabled($row->id);
 642          // The function in the assignment keeps a static cache of this list of states.
 643          $workflowstates = $this->assignment->get_marking_workflow_states_for_current_user();
 644          $workflowstate = $row->workflowstate;
 645          if (empty($workflowstate)) {
 646              $workflowstate = ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
 647          }
 648          if ($this->quickgrading && !$gradingdisabled) {
 649              $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
 650              $name = 'quickgrade_' . $row->id . '_workflowstate';
 651              $o .= html_writer::select($workflowstates, $name, $workflowstate, array('' => $notmarked));
 652              // Check if this user is a marker that can't manage allocations and doesn't have the marker column added.
 653              if ($this->assignment->get_instance()->markingworkflow &&
 654                  $this->assignment->get_instance()->markingallocation &&
 655                  !has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
 656  
 657                  $name = 'quickgrade_' . $row->id . '_allocatedmarker';
 658                  $o .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $name,
 659                          'value' => $row->allocatedmarker));
 660              }
 661          } else {
 662              $o .= $this->output->container(get_string('markingworkflowstate' . $workflowstate, 'assign'), $workflowstate);
 663          }
 664          return $o;
 665      }
 666  
 667      /**
 668       * For download only - list current marking workflow state
 669       *
 670       * @param stdClass $row - The row of data
 671       * @return string The current marking workflow state
 672       */
 673      public function col_workflowstate($row) {
 674          $state = $row->workflowstate;
 675          if (empty($state)) {
 676              $state = ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
 677          }
 678  
 679          return get_string('markingworkflowstate' . $state, 'assign');
 680      }
 681  
 682      /**
 683       * list current marker
 684       *
 685       * @param stdClass $row - The row of data
 686       * @return id the user->id of the marker.
 687       */
 688      public function col_allocatedmarker(stdClass $row) {
 689          static $markers = null;
 690          static $markerlist = array();
 691          if ($markers === null) {
 692              list($sort, $params) = users_order_by_sql('u');
 693              // Only enrolled users could be assigned as potential markers.
 694              $markers = get_enrolled_users($this->assignment->get_context(), 'mod/assign:grade', 0, 'u.*', $sort);
 695              $markerlist[0] = get_string('choosemarker', 'assign');
 696              $viewfullnames = has_capability('moodle/site:viewfullnames', $this->assignment->get_context());
 697              foreach ($markers as $marker) {
 698                  $markerlist[$marker->id] = fullname($marker, $viewfullnames);
 699              }
 700          }
 701          if (empty($markerlist)) {
 702              // TODO: add some form of notification here that no markers are available.
 703              return '';
 704          }
 705          if ($this->is_downloading()) {
 706              if (isset($markers[$row->allocatedmarker])) {
 707                  return fullname($markers[$row->allocatedmarker],
 708                          has_capability('moodle/site:viewfullnames', $this->assignment->get_context()));
 709              } else {
 710                  return '';
 711              }
 712          }
 713  
 714          if ($this->quickgrading && has_capability('mod/assign:manageallocations', $this->assignment->get_context()) &&
 715              (empty($row->workflowstate) ||
 716               $row->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_INMARKING ||
 717               $row->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED)) {
 718  
 719              $name = 'quickgrade_' . $row->id . '_allocatedmarker';
 720              return  html_writer::select($markerlist, $name, $row->allocatedmarker, false);
 721          } else if (!empty($row->allocatedmarker)) {
 722              $output = '';
 723              if ($this->quickgrading) { // Add hidden field for quickgrading page.
 724                  $name = 'quickgrade_' . $row->id . '_allocatedmarker';
 725                  $attributes = ['type' => 'hidden', 'name' => $name, 'value' => $row->allocatedmarker];
 726                  $output .= html_writer::empty_tag('input', $attributes);
 727              }
 728              $output .= $markerlist[$row->allocatedmarker];
 729              return $output;
 730          }
 731      }
 732      /**
 733       * For download only - list all the valid options for this custom scale.
 734       *
 735       * @param stdClass $row - The row of data
 736       * @return string A list of valid options for the current scale
 737       */
 738      public function col_scale($row) {
 739          global $DB;
 740  
 741          if (empty($this->scale)) {
 742              $dbparams = array('id' => -($this->assignment->get_instance()->grade));
 743              $this->scale = $DB->get_record('scale', $dbparams);
 744          }
 745  
 746          if (!empty($this->scale->scale)) {
 747              return implode("\n", explode(',', $this->scale->scale));
 748          }
 749          return '';
 750      }
 751  
 752      /**
 753       * Display a grade with scales etc.
 754       *
 755       * @param string $grade
 756       * @param boolean $editable
 757       * @param int $userid The user id of the user this grade belongs to
 758       * @param int $modified Timestamp showing when the grade was last modified
 759       * @return string The formatted grade
 760       */
 761      public function display_grade($grade, $editable, $userid, $modified) {
 762          if ($this->is_downloading()) {
 763              if ($this->assignment->get_instance()->grade >= 0) {
 764                  if ($grade == -1 || $grade === null) {
 765                      return '';
 766                  }
 767                  $gradeitem = $this->assignment->get_grade_item();
 768                  return format_float($grade, $gradeitem->get_decimals());
 769              } else {
 770                  // This is a custom scale.
 771                  $scale = $this->assignment->display_grade($grade, false);
 772                  if ($scale == '-') {
 773                      $scale = '';
 774                  }
 775                  return $scale;
 776              }
 777          }
 778          return $this->assignment->display_grade($grade, $editable, $userid, $modified);
 779      }
 780  
 781      /**
 782       * Get the team info for this user.
 783       *
 784       * @param stdClass $row
 785       * @return string The team name
 786       */
 787      public function col_team(stdClass $row) {
 788          $submission = false;
 789          $group = false;
 790          $this->get_group_and_submission($row->id, $group, $submission, -1);
 791          if ($group) {
 792              return $group->name;
 793          } else if ($this->assignment->get_instance()->preventsubmissionnotingroup) {
 794              $usergroups = $this->assignment->get_all_groups($row->id);
 795              if (count($usergroups) > 1) {
 796                  return get_string('multipleteamsgrader', 'assign');
 797              } else {
 798                  return get_string('noteamgrader', 'assign');
 799              }
 800          }
 801          return get_string('defaultteam', 'assign');
 802      }
 803  
 804      /**
 805       * Use a static cache to try and reduce DB calls.
 806       *
 807       * @param int $userid The user id for this submission
 808       * @param int $group The groupid (returned)
 809       * @param stdClass|false $submission The stdClass submission or false (returned)
 810       * @param int $attemptnumber Return a specific attempt number (-1 for latest)
 811       */
 812      protected function get_group_and_submission($userid, &$group, &$submission, $attemptnumber) {
 813          $group = false;
 814          if (isset($this->submissiongroups[$userid])) {
 815              $group = $this->submissiongroups[$userid];
 816          } else {
 817              $group = $this->assignment->get_submission_group($userid, false);
 818              $this->submissiongroups[$userid] = $group;
 819          }
 820  
 821          $groupid = 0;
 822          if ($group) {
 823              $groupid = $group->id;
 824          }
 825  
 826          // Static cache is keyed by groupid and attemptnumber.
 827          // We may need both the latest and previous attempt in the same page.
 828          if (isset($this->groupsubmissions[$groupid . ':' . $attemptnumber])) {
 829              $submission = $this->groupsubmissions[$groupid . ':' . $attemptnumber];
 830          } else {
 831              $submission = $this->assignment->get_group_submission($userid, $groupid, false, $attemptnumber);
 832              $this->groupsubmissions[$groupid . ':' . $attemptnumber] = $submission;
 833          }
 834      }
 835  
 836      /**
 837       * Format a list of outcomes.
 838       *
 839       * @param stdClass $row
 840       * @return string
 841       */
 842      public function col_outcomes(stdClass $row) {
 843          $outcomes = '';
 844          foreach ($this->gradinginfo->outcomes as $index => $outcome) {
 845              $options = make_grades_menu(-$outcome->scaleid);
 846  
 847              $options[0] = get_string('nooutcome', 'grades');
 848              if ($this->quickgrading && !($outcome->grades[$row->userid]->locked)) {
 849                  $select = '<select name="outcome_' . $index . '_' . $row->userid . '" class="quickgrade">';
 850                  foreach ($options as $optionindex => $optionvalue) {
 851                      $selected = '';
 852                      if ($outcome->grades[$row->userid]->grade == $optionindex) {
 853                          $selected = 'selected="selected"';
 854                      }
 855                      $select .= '<option value="' . $optionindex . '"' . $selected . '>' . $optionvalue . '</option>';
 856                  }
 857                  $select .= '</select>';
 858                  $outcomes .= $this->output->container($outcome->name . ': ' . $select, 'outcome');
 859              } else {
 860                  $name = $outcome->name . ': ' . $options[$outcome->grades[$row->userid]->grade];
 861                  if ($this->is_downloading()) {
 862                      $outcomes .= $name;
 863                  } else {
 864                      $outcomes .= $this->output->container($name, 'outcome');
 865                  }
 866              }
 867          }
 868  
 869          return $outcomes;
 870      }
 871  
 872  
 873      /**
 874       * Format a user picture for display.
 875       *
 876       * @param stdClass $row
 877       * @return string
 878       */
 879      public function col_picture(stdClass $row) {
 880          return $this->output->user_picture($row);
 881      }
 882  
 883      /**
 884       * Format a user record for display (link to profile).
 885       *
 886       * @param stdClass $row
 887       * @return string
 888       */
 889      public function col_fullname($row) {
 890          if (!$this->is_downloading()) {
 891              $courseid = $this->assignment->get_course()->id;
 892              $link = new moodle_url('/user/view.php', array('id' => $row->id, 'course' => $courseid));
 893              $fullname = $this->output->action_link($link, $this->assignment->fullname($row));
 894          } else {
 895              $fullname = $this->assignment->fullname($row);
 896          }
 897  
 898          if (!$this->assignment->is_active_user($row->id)) {
 899              $suspendedstring = get_string('userenrolmentsuspended', 'grades');
 900              $fullname .= ' ' . $this->output->pix_icon('i/enrolmentsuspended', $suspendedstring);
 901              $fullname = html_writer::tag('span', $fullname, array('class' => 'usersuspended'));
 902          }
 903          return $fullname;
 904      }
 905  
 906      /**
 907       * Insert a checkbox for selecting the current row for batch operations.
 908       *
 909       * @param stdClass $row
 910       * @return string
 911       */
 912      public function col_select(stdClass $row) {
 913          $selectcol = '<label class="accesshide" for="selectuser_' . $row->userid . '">';
 914          $selectcol .= get_string('selectuser', 'assign', $this->assignment->fullname($row));
 915          $selectcol .= '</label>';
 916          $selectcol .= '<input type="checkbox"
 917                                id="selectuser_' . $row->userid . '"
 918                                name="selectedusers"
 919                                value="' . $row->userid . '"/>';
 920          $selectcol .= '<input type="hidden"
 921                                name="grademodified_' . $row->userid . '"
 922                                value="' . $row->timemarked . '"/>';
 923          $selectcol .= '<input type="hidden"
 924                                name="gradeattempt_' . $row->userid . '"
 925                                value="' . $row->attemptnumber . '"/>';
 926          return $selectcol;
 927      }
 928  
 929      /**
 930       * Return a users grades from the listing of all grade data for this assignment.
 931       *
 932       * @param int $userid
 933       * @return mixed stdClass or false
 934       */
 935      private function get_gradebook_data_for_user($userid) {
 936          if (isset($this->gradinginfo->items[0]) && $this->gradinginfo->items[0]->grades[$userid]) {
 937              return $this->gradinginfo->items[0]->grades[$userid];
 938          }
 939          return false;
 940      }
 941  
 942      /**
 943       * Format a column of data for display.
 944       *
 945       * @param stdClass $row
 946       * @return string
 947       */
 948      public function col_gradecanbechanged(stdClass $row) {
 949          $gradingdisabled = $this->assignment->grading_disabled($row->id);
 950          if ($gradingdisabled) {
 951              return get_string('no');
 952          } else {
 953              return get_string('yes');
 954          }
 955      }
 956  
 957      /**
 958       * Format a column of data for display
 959       *
 960       * @param stdClass $row
 961       * @return string
 962       */
 963      public function col_grademax(stdClass $row) {
 964          if ($this->assignment->get_instance()->grade > 0) {
 965              $gradeitem = $this->assignment->get_grade_item();
 966              return format_float($this->assignment->get_instance()->grade, $gradeitem->get_decimals());
 967          } else {
 968              return '';
 969          }
 970      }
 971  
 972      /**
 973       * Format a column of data for display.
 974       *
 975       * @param stdClass $row
 976       * @return string
 977       */
 978      public function col_grade(stdClass $row) {
 979          $o = '';
 980  
 981          $link = '';
 982          $separator = $this->output->spacer(array(), true);
 983          $grade = '';
 984          $gradingdisabled = $this->assignment->grading_disabled($row->id);
 985  
 986          if (!$this->is_downloading() && $this->hasgrade) {
 987              $urlparams = array('id' => $this->assignment->get_course_module()->id,
 988                                 'rownum' => 0,
 989                                 'action' => 'grader');
 990  
 991              if ($this->assignment->is_blind_marking()) {
 992                  if (empty($row->recordid)) {
 993                      $row->recordid = $this->assignment->get_uniqueid_for_user($row->userid);
 994                  }
 995                  $urlparams['blindid'] = $row->recordid;
 996              } else {
 997                  $urlparams['userid'] = $row->userid;
 998              }
 999  
1000              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1001              $link = '<a href="' . $url . '" class="btn btn-primary">' . get_string('gradeverb') . '</a>';
1002              $grade .= $link . $separator;
1003          }
1004  
1005          $grade .= $this->display_grade($row->grade,
1006                                         $this->quickgrading && !$gradingdisabled,
1007                                         $row->userid,
1008                                         $row->timemarked);
1009  
1010          return $grade;
1011      }
1012  
1013      /**
1014       * Format a column of data for display.
1015       *
1016       * @param stdClass $row
1017       * @return string
1018       */
1019      public function col_finalgrade(stdClass $row) {
1020          $o = '';
1021  
1022          $grade = $this->get_gradebook_data_for_user($row->userid);
1023          if ($grade) {
1024              $o = $this->display_grade($grade->grade, false, $row->userid, $row->timemarked);
1025          }
1026  
1027          return $o;
1028      }
1029  
1030      /**
1031       * Format a column of data for display.
1032       *
1033       * @param stdClass $row
1034       * @return string
1035       */
1036      public function col_timemarked(stdClass $row) {
1037          $o = '-';
1038  
1039          if ($row->timemarked && $row->grade !== null && $row->grade >= 0) {
1040              $o = userdate($row->timemarked);
1041          }
1042          if ($row->timemarked && $this->is_downloading()) {
1043              // Force it for downloads as it affects import.
1044              $o = userdate($row->timemarked);
1045          }
1046  
1047          return $o;
1048      }
1049  
1050      /**
1051       * Format a column of data for display.
1052       *
1053       * @param stdClass $row
1054       * @return string
1055       */
1056      public function col_timesubmitted(stdClass $row) {
1057          $o = '-';
1058  
1059          $group = false;
1060          $submission = false;
1061          $this->get_group_and_submission($row->id, $group, $submission, -1);
1062          if ($submission && $submission->timemodified && $submission->status != ASSIGN_SUBMISSION_STATUS_NEW) {
1063              $o = userdate($submission->timemodified);
1064          } else if ($row->timesubmitted && $row->status != ASSIGN_SUBMISSION_STATUS_NEW) {
1065              $o = userdate($row->timesubmitted);
1066          }
1067  
1068          return $o;
1069      }
1070  
1071      /**
1072       * Format a column of data for display
1073       *
1074       * @param stdClass $row
1075       * @return string
1076       */
1077      public function col_status(stdClass $row) {
1078          $o = '';
1079  
1080          $instance = $this->assignment->get_instance($row->userid);
1081  
1082          $due = $instance->duedate;
1083          if ($row->extensionduedate) {
1084              $due = $row->extensionduedate;
1085          } else if (!empty($row->duedate)) {
1086              // The override due date.
1087              $due = $row->duedate;
1088          }
1089  
1090          $group = false;
1091          $submission = false;
1092  
1093          if ($instance->teamsubmission) {
1094              $this->get_group_and_submission($row->id, $group, $submission, -1);
1095          }
1096  
1097          if ($instance->teamsubmission && !$group && !$instance->preventsubmissionnotingroup) {
1098              $group = true;
1099          }
1100  
1101          if ($group && $submission) {
1102              $timesubmitted = $submission->timemodified;
1103              $status = $submission->status;
1104          } else {
1105              $timesubmitted = $row->timesubmitted;
1106              $status = $row->status;
1107          }
1108  
1109          $displaystatus = $status;
1110          if ($displaystatus == 'new') {
1111              $displaystatus = '';
1112          }
1113  
1114          if ($this->assignment->is_any_submission_plugin_enabled()) {
1115  
1116              $o .= $this->output->container(get_string('submissionstatus_' . $displaystatus, 'assign'),
1117                                             array('class' => 'submissionstatus' .$displaystatus));
1118              if ($due && $timesubmitted > $due && $status != ASSIGN_SUBMISSION_STATUS_NEW) {
1119                  $usertime = format_time($timesubmitted - $due);
1120                  $latemessage = get_string('submittedlateshort',
1121                                            'assign',
1122                                            $usertime);
1123                  $o .= $this->output->container($latemessage, 'latesubmission');
1124              }
1125              if ($row->locked) {
1126                  $lockedstr = get_string('submissionslockedshort', 'assign');
1127                  $o .= $this->output->container($lockedstr, 'lockedsubmission');
1128              }
1129  
1130              // Add status of "grading" if markflow is not enabled.
1131              if (!$instance->markingworkflow) {
1132                  if ($row->grade !== null && $row->grade >= 0) {
1133                      if ($row->timemarked < $row->timesubmitted) {
1134                          $o .= $this->output->container(get_string('gradedfollowupsubmit', 'assign'), 'gradingreminder');
1135                      } else {
1136                          $o .= $this->output->container(get_string('graded', 'assign'), 'submissiongraded');
1137                      }
1138                  } else if (!$timesubmitted || $status == ASSIGN_SUBMISSION_STATUS_NEW) {
1139                      $now = time();
1140                      if ($due && ($now > $due)) {
1141                          $overduestr = get_string('overdue', 'assign', format_time($now - $due));
1142                          $o .= $this->output->container($overduestr, 'overduesubmission');
1143                      }
1144                  }
1145              }
1146          }
1147  
1148          if ($instance->markingworkflow) {
1149              $o .= $this->col_workflowstatus($row);
1150          }
1151          if ($row->extensionduedate) {
1152              $userdate = userdate($row->extensionduedate);
1153              $extensionstr = get_string('userextensiondate', 'assign', $userdate);
1154              $o .= $this->output->container($extensionstr, 'extensiondate');
1155          }
1156  
1157          if ($this->is_downloading()) {
1158              $o = strip_tags(rtrim(str_replace('</div>', ' - ', $o), '- '));
1159          }
1160  
1161          return $o;
1162      }
1163  
1164      /**
1165       * Format a column of data for display.
1166       *
1167       * @param stdClass $row
1168       * @return string
1169       */
1170      public function col_allowsubmissionsfromdate(stdClass $row) {
1171          $o = '';
1172  
1173          if ($row->allowsubmissionsfromdate) {
1174              $userdate = userdate($row->allowsubmissionsfromdate);
1175              $o = ($this->is_downloading()) ? $userdate : $this->output->container($userdate, 'allowsubmissionsfromdate');
1176          }
1177  
1178          return $o;
1179      }
1180  
1181      /**
1182       * Format a column of data for display.
1183       *
1184       * @param stdClass $row
1185       * @return string
1186       */
1187      public function col_duedate(stdClass $row) {
1188          $o = '';
1189  
1190          if ($row->duedate) {
1191              $userdate = userdate($row->duedate);
1192              $o = ($this->is_downloading()) ? $userdate : $this->output->container($userdate, 'duedate');
1193          }
1194  
1195          return $o;
1196      }
1197  
1198      /**
1199       * Format a column of data for display.
1200       *
1201       * @param stdClass $row
1202       * @return string
1203       */
1204      public function col_cutoffdate(stdClass $row) {
1205          $o = '';
1206  
1207          if ($row->cutoffdate) {
1208              $userdate = userdate($row->cutoffdate);
1209              $o = ($this->is_downloading()) ? $userdate : $this->output->container($userdate, 'cutoffdate');
1210          }
1211  
1212          return $o;
1213      }
1214  
1215      /**
1216       * Format a column of data for display.
1217       *
1218       * @param stdClass $row
1219       * @return string
1220       */
1221      public function col_userid(stdClass $row) {
1222          global $USER;
1223  
1224          $edit = '';
1225  
1226          $actions = array();
1227  
1228          $urlparams = array('id' => $this->assignment->get_course_module()->id,
1229                                 'rownum' => 0,
1230                                 'action' => 'grader');
1231  
1232          if ($this->assignment->is_blind_marking()) {
1233              if (empty($row->recordid)) {
1234                  $row->recordid = $this->assignment->get_uniqueid_for_user($row->userid);
1235              }
1236              $urlparams['blindid'] = $row->recordid;
1237          } else {
1238              $urlparams['userid'] = $row->userid;
1239          }
1240          $url = new moodle_url('/mod/assign/view.php', $urlparams);
1241          $noimage = null;
1242  
1243          if (!$row->grade) {
1244              $description = get_string('gradeverb');
1245          } else {
1246              $description = get_string('updategrade', 'assign');
1247          }
1248          $actions['grade'] = new action_menu_link_secondary(
1249              $url,
1250              $noimage,
1251              $description
1252          );
1253  
1254          // Everything we need is in the row.
1255          $submission = $row;
1256          $flags = $row;
1257          if ($this->assignment->get_instance()->teamsubmission) {
1258              // Use the cache for this.
1259              $submission = false;
1260              $group = false;
1261              $this->get_group_and_submission($row->id, $group, $submission, -1);
1262          }
1263  
1264          $submissionsopen = $this->assignment->submissions_open($row->id,
1265                                                                 true,
1266                                                                 $submission,
1267                                                                 $flags,
1268                                                                 $this->gradinginfo);
1269          $caneditsubmission = $this->assignment->can_edit_submission($row->id, $USER->id);
1270  
1271          // Hide for offline assignments.
1272          if ($this->assignment->is_any_submission_plugin_enabled()) {
1273              if (!$row->status ||
1274                      $row->status == ASSIGN_SUBMISSION_STATUS_DRAFT ||
1275                      !$this->assignment->get_instance()->submissiondrafts) {
1276  
1277                  if (!$row->locked) {
1278                      $urlparams = array('id' => $this->assignment->get_course_module()->id,
1279                                         'userid' => $row->id,
1280                                         'action' => 'lock',
1281                                         'sesskey' => sesskey(),
1282                                         'page' => $this->currpage);
1283                      $url = new moodle_url('/mod/assign/view.php', $urlparams);
1284  
1285                      $description = get_string('preventsubmissionsshort', 'assign');
1286                      $actions['lock'] = new action_menu_link_secondary(
1287                          $url,
1288                          $noimage,
1289                          $description
1290                      );
1291                  } else {
1292                      $urlparams = array('id' => $this->assignment->get_course_module()->id,
1293                                         'userid' => $row->id,
1294                                         'action' => 'unlock',
1295                                         'sesskey' => sesskey(),
1296                                         'page' => $this->currpage);
1297                      $url = new moodle_url('/mod/assign/view.php', $urlparams);
1298                      $description = get_string('allowsubmissionsshort', 'assign');
1299                      $actions['unlock'] = new action_menu_link_secondary(
1300                          $url,
1301                          $noimage,
1302                          $description
1303                      );
1304                  }
1305              }
1306  
1307              if ($submissionsopen &&
1308                      $USER->id != $row->id &&
1309                      $caneditsubmission) {
1310                  $urlparams = array('id' => $this->assignment->get_course_module()->id,
1311                                     'userid' => $row->id,
1312                                     'action' => 'editsubmission',
1313                                     'sesskey' => sesskey(),
1314                                     'page' => $this->currpage);
1315                  $url = new moodle_url('/mod/assign/view.php', $urlparams);
1316                  $description = get_string('editsubmission', 'assign');
1317                  $actions['editsubmission'] = new action_menu_link_secondary(
1318                      $url,
1319                      $noimage,
1320                      $description
1321                  );
1322              }
1323              if ($USER->id != $row->id &&
1324                      $caneditsubmission &&
1325                      !empty($row->status)) {
1326                  $urlparams = array('id' => $this->assignment->get_course_module()->id,
1327                                     'userid' => $row->id,
1328                                     'action' => 'removesubmissionconfirm',
1329                                     'sesskey' => sesskey(),
1330                                     'page' => $this->currpage);
1331                  $url = new moodle_url('/mod/assign/view.php', $urlparams);
1332                  $description = get_string('removesubmission', 'assign');
1333                  $actions['removesubmission'] = new action_menu_link_secondary(
1334                      $url,
1335                      $noimage,
1336                      $description
1337                  );
1338              }
1339          }
1340          if (($this->assignment->get_instance()->duedate ||
1341                  $this->assignment->get_instance()->cutoffdate) &&
1342                  $this->hasgrantextension) {
1343               $urlparams = array('id' => $this->assignment->get_course_module()->id,
1344                                  'userid' => $row->id,
1345                                  'action' => 'grantextension',
1346                                  'sesskey' => sesskey(),
1347                                  'page' => $this->currpage);
1348               $url = new moodle_url('/mod/assign/view.php', $urlparams);
1349               $description = get_string('grantextension', 'assign');
1350               $actions['grantextension'] = new action_menu_link_secondary(
1351                   $url,
1352                   $noimage,
1353                   $description
1354               );
1355          }
1356          if ($row->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED &&
1357                  $this->assignment->get_instance()->submissiondrafts) {
1358              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1359                                 'userid' => $row->id,
1360                                 'action' => 'reverttodraft',
1361                                 'sesskey' => sesskey(),
1362                                 'page' => $this->currpage);
1363              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1364              $description = get_string('reverttodraftshort', 'assign');
1365              $actions['reverttodraft'] = new action_menu_link_secondary(
1366                  $url,
1367                  $noimage,
1368                  $description
1369              );
1370          }
1371          if ($row->status == ASSIGN_SUBMISSION_STATUS_DRAFT &&
1372                  $this->assignment->get_instance()->submissiondrafts &&
1373                  $caneditsubmission &&
1374                  $submissionsopen &&
1375                  $row->id != $USER->id) {
1376              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1377                                 'userid' => $row->id,
1378                                 'action' => 'submitotherforgrading',
1379                                 'sesskey' => sesskey(),
1380                                 'page' => $this->currpage);
1381              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1382              $description = get_string('submitforgrading', 'assign');
1383              $actions['submitforgrading'] = new action_menu_link_secondary(
1384                  $url,
1385                  $noimage,
1386                  $description
1387              );
1388          }
1389  
1390          $ismanual = $this->assignment->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL;
1391          $hassubmission = !empty($row->status);
1392          $notreopened = $hassubmission && $row->status != ASSIGN_SUBMISSION_STATUS_REOPENED;
1393          $isunlimited = $this->assignment->get_instance()->maxattempts == ASSIGN_UNLIMITED_ATTEMPTS;
1394          $hasattempts = $isunlimited || $row->attemptnumber < $this->assignment->get_instance()->maxattempts - 1;
1395  
1396          if ($ismanual && $hassubmission && $notreopened && $hasattempts) {
1397              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1398                                 'userid' => $row->id,
1399                                 'action' => 'addattempt',
1400                                 'sesskey' => sesskey(),
1401                                 'page' => $this->currpage);
1402              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1403              $description = get_string('addattempt', 'assign');
1404              $actions['addattempt'] = new action_menu_link_secondary(
1405                  $url,
1406                  $noimage,
1407                  $description
1408              );
1409          }
1410  
1411          $menu = new action_menu();
1412          $menu->set_owner_selector('.gradingtable-actionmenu');
1413          $menu->set_alignment(action_menu::TL, action_menu::BL);
1414          $menu->set_constraint('.gradingtable > .no-overflow');
1415          $menu->set_menu_trigger(get_string('edit'));
1416          foreach ($actions as $action) {
1417              $menu->add($action);
1418          }
1419  
1420          // Prioritise the menu ahead of all other actions.
1421          $menu->prioritise = true;
1422  
1423          $edit .= $this->output->render($menu);
1424  
1425          return $edit;
1426      }
1427  
1428      /**
1429       * Write the plugin summary with an optional link to view the full feedback/submission.
1430       *
1431       * @param assign_plugin $plugin Submission plugin or feedback plugin
1432       * @param stdClass $item Submission or grade
1433       * @param string $returnaction The return action to pass to the
1434       *                             view_submission page (the current page)
1435       * @param string $returnparams The return params to pass to the view_submission
1436       *                             page (the current page)
1437       * @return string The summary with an optional link
1438       */
1439      private function format_plugin_summary_with_link(assign_plugin $plugin,
1440                                                       stdClass $item,
1441                                                       $returnaction,
1442                                                       $returnparams) {
1443          $link = '';
1444          $showviewlink = false;
1445  
1446          $summary = $plugin->view_summary($item, $showviewlink);
1447          $separator = '';
1448          if ($showviewlink) {
1449              $viewstr = get_string('view' . substr($plugin->get_subtype(), strlen('assign')), 'assign');
1450              $icon = $this->output->pix_icon('t/preview', $viewstr);
1451              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1452                                                       'sid' => $item->id,
1453                                                       'gid' => $item->id,
1454                                                       'plugin' => $plugin->get_type(),
1455                                                       'action' => 'viewplugin' . $plugin->get_subtype(),
1456                                                       'returnaction' => $returnaction,
1457                                                       'returnparams' => http_build_query($returnparams));
1458              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1459              $link = $this->output->action_link($url, $icon);
1460              $separator = $this->output->spacer(array(), true);
1461          }
1462  
1463          return $link . $separator . $summary;
1464      }
1465  
1466  
1467      /**
1468       * Format the submission and feedback columns.
1469       *
1470       * @param string $colname The column name
1471       * @param stdClass $row The submission row
1472       * @return mixed string or NULL
1473       */
1474      public function other_cols($colname, $row) {
1475          // For extra user fields the result is already in $row.
1476          if (empty($this->plugincache[$colname])) {
1477              return parent::other_cols($colname, $row);
1478          }
1479  
1480          // This must be a plugin field.
1481          $plugincache = $this->plugincache[$colname];
1482  
1483          $plugin = $plugincache[0];
1484  
1485          $field = null;
1486          if (isset($plugincache[1])) {
1487              $field = $plugincache[1];
1488          }
1489  
1490          if ($plugin->is_visible() && $plugin->is_enabled()) {
1491              if ($plugin->get_subtype() == 'assignsubmission') {
1492                  if ($this->assignment->get_instance()->teamsubmission) {
1493                      $group = false;
1494                      $submission = false;
1495  
1496                      $this->get_group_and_submission($row->id, $group, $submission, -1);
1497                      if ($submission) {
1498                          if ($submission->status == ASSIGN_SUBMISSION_STATUS_REOPENED) {
1499                              // For a newly reopened submission - we want to show the previous submission in the table.
1500                              $this->get_group_and_submission($row->id, $group, $submission, $submission->attemptnumber-1);
1501                          }
1502                          if (isset($field)) {
1503                              return $plugin->get_editor_text($field, $submission->id);
1504                          }
1505                          return $this->format_plugin_summary_with_link($plugin,
1506                                                                        $submission,
1507                                                                        'grading',
1508                                                                        array());
1509                      }
1510                  } else if ($row->submissionid) {
1511                      if ($row->status == ASSIGN_SUBMISSION_STATUS_REOPENED) {
1512                          // For a newly reopened submission - we want to show the previous submission in the table.
1513                          $submission = $this->assignment->get_user_submission($row->userid, false, $row->attemptnumber - 1);
1514                      } else {
1515                          $submission = new stdClass();
1516                          $submission->id = $row->submissionid;
1517                          $submission->timecreated = $row->firstsubmission;
1518                          $submission->timemodified = $row->timesubmitted;
1519                          $submission->assignment = $this->assignment->get_instance()->id;
1520                          $submission->userid = $row->userid;
1521                          $submission->attemptnumber = $row->attemptnumber;
1522                      }
1523                      // Field is used for only for import/export and refers the the fieldname for the text editor.
1524                      if (isset($field)) {
1525                          return $plugin->get_editor_text($field, $submission->id);
1526                      }
1527                      return $this->format_plugin_summary_with_link($plugin,
1528                                                                    $submission,
1529                                                                    'grading',
1530                                                                    array());
1531                  }
1532              } else {
1533                  $grade = null;
1534                  if (isset($field)) {
1535                      return $plugin->get_editor_text($field, $row->gradeid);
1536                  }
1537  
1538                  if ($row->gradeid) {
1539                      $grade = new stdClass();
1540                      $grade->id = $row->gradeid;
1541                      $grade->timecreated = $row->firstmarked;
1542                      $grade->timemodified = $row->timemarked;
1543                      $grade->assignment = $this->assignment->get_instance()->id;
1544                      $grade->userid = $row->userid;
1545                      $grade->grade = $row->grade;
1546                      $grade->mailed = $row->mailed;
1547                      $grade->attemptnumber = $row->attemptnumber;
1548                  }
1549                  if ($this->quickgrading && $plugin->supports_quickgrading()) {
1550                      return $plugin->get_quickgrading_html($row->userid, $grade);
1551                  } else if ($grade) {
1552                      return $this->format_plugin_summary_with_link($plugin,
1553                                                                    $grade,
1554                                                                    'grading',
1555                                                                    array());
1556                  }
1557              }
1558          }
1559          return '';
1560      }
1561  
1562      /**
1563       * Using the current filtering and sorting - load all rows and return a single column from them.
1564       *
1565       * @param string $columnname The name of the raw column data
1566       * @return array of data
1567       */
1568      public function get_column_data($columnname) {
1569          $this->setup();
1570          $this->currpage = 0;
1571          $this->query_db($this->tablemaxrows);
1572          $result = array();
1573          foreach ($this->rawdata as $row) {
1574              $result[] = $row->$columnname;
1575          }
1576          return $result;
1577      }
1578  
1579      /**
1580       * Return things to the renderer.
1581       *
1582       * @return string the assignment name
1583       */
1584      public function get_assignment_name() {
1585          return $this->assignment->get_instance()->name;
1586      }
1587  
1588      /**
1589       * Return things to the renderer.
1590       *
1591       * @return int the course module id
1592       */
1593      public function get_course_module_id() {
1594          return $this->assignment->get_course_module()->id;
1595      }
1596  
1597      /**
1598       * Return things to the renderer.
1599       *
1600       * @return int the course id
1601       */
1602      public function get_course_id() {
1603          return $this->assignment->get_course()->id;
1604      }
1605  
1606      /**
1607       * Return things to the renderer.
1608       *
1609       * @return stdClass The course context
1610       */
1611      public function get_course_context() {
1612          return $this->assignment->get_course_context();
1613      }
1614  
1615      /**
1616       * Return things to the renderer.
1617       *
1618       * @return bool Does this assignment accept submissions
1619       */
1620      public function submissions_enabled() {
1621          return $this->assignment->is_any_submission_plugin_enabled();
1622      }
1623  
1624      /**
1625       * Return things to the renderer.
1626       *
1627       * @return bool Can this user view all grades (the gradebook)
1628       */
1629      public function can_view_all_grades() {
1630          $context = $this->assignment->get_course_context();
1631          return has_capability('gradereport/grader:view', $context) &&
1632                 has_capability('moodle/grade:viewall', $context);
1633      }
1634  
1635      /**
1636       * Always return a valid sort - even if the userid column is missing.
1637       * @return array column name => SORT_... constant.
1638       */
1639      public function get_sort_columns() {
1640          $result = parent::get_sort_columns();
1641  
1642          $assignment = $this->assignment->get_instance();
1643          if (empty($assignment->blindmarking)) {
1644              $result = array_merge($result, array('userid' => SORT_ASC));
1645          } else {
1646              $result = array_merge($result, [
1647                      'COALESCE(s.timecreated, '  . time()        . ')'   => SORT_ASC,
1648                      'COALESCE(s.id, '           . PHP_INT_MAX   . ')'   => SORT_ASC,
1649                      'um.id'                                             => SORT_ASC,
1650                  ]);
1651          }
1652          return $result;
1653      }
1654  
1655      /**
1656       * Override the table show_hide_link to not show for select column.
1657       *
1658       * @param string $column the column name, index into various names.
1659       * @param int $index numerical index of the column.
1660       * @return string HTML fragment.
1661       */
1662      protected function show_hide_link($column, $index) {
1663          if ($index > 0 || !$this->hasgrade) {
1664              return parent::show_hide_link($column, $index);
1665          }
1666          return '';
1667      }
1668  
1669      /**
1670       * Overides setup to ensure it will only run a single time.
1671       */
1672      public function setup() {
1673          // Check if the setup function has been called before, we should not run it twice.
1674          // If we do the sortorder of the table will be broken.
1675          if (!empty($this->setup)) {
1676              return;
1677          }
1678          parent::setup();
1679      }
1680  }