Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * 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, true, $this->gradinginfo);
 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 format_string($group->name, true, ['context' => $this->assignment->get_context()]);
 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, true, $this->gradinginfo);
 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, true, $this->gradinginfo);
 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          $timelimitenabled = get_config('assign', 'enabletimelimit');
1082  
1083          $due = $instance->duedate;
1084          if ($row->extensionduedate) {
1085              $due = $row->extensionduedate;
1086          } else if (!empty($row->duedate)) {
1087              // The override due date.
1088              $due = $row->duedate;
1089          }
1090  
1091          $group = false;
1092          $submission = false;
1093  
1094          if ($instance->teamsubmission) {
1095              $this->get_group_and_submission($row->id, $group, $submission, -1);
1096          }
1097  
1098          if ($instance->teamsubmission && !$group && !$instance->preventsubmissionnotingroup) {
1099              $group = true;
1100          }
1101  
1102          if ($group && $submission) {
1103              $timesubmitted = $submission->timemodified;
1104              $status = $submission->status;
1105          } else {
1106              $timesubmitted = $row->timesubmitted;
1107              $status = $row->status;
1108          }
1109  
1110          $displaystatus = $status;
1111          if ($displaystatus == 'new') {
1112              $displaystatus = '';
1113          }
1114  
1115          if ($this->assignment->is_any_submission_plugin_enabled()) {
1116  
1117              $o .= $this->output->container(get_string('submissionstatus_' . $displaystatus, 'assign'),
1118                                             array('class' => 'submissionstatus' .$displaystatus));
1119              if ($due && $timesubmitted > $due && $status != ASSIGN_SUBMISSION_STATUS_NEW) {
1120                  $usertime = format_time($timesubmitted - $due);
1121                  $latemessage = get_string('submittedlateshort',
1122                                            'assign',
1123                                            $usertime);
1124                  $o .= $this->output->container($latemessage, 'latesubmission');
1125              } else if ($timelimitenabled && $instance->timelimit && !empty($submission->timestarted)
1126                  && ($timesubmitted - $submission->timestarted > $instance->timelimit)
1127                  && $status != ASSIGN_SUBMISSION_STATUS_NEW) {
1128                  $usertime = format_time($timesubmitted - $submission->timestarted - $instance->timelimit);
1129                  $latemessage = get_string('submittedlateshort',
1130                      'assign',
1131                      $usertime);
1132                  $o .= $this->output->container($latemessage, 'latesubmission');
1133              }
1134              if ($row->locked) {
1135                  $lockedstr = get_string('submissionslockedshort', 'assign');
1136                  $o .= $this->output->container($lockedstr, 'lockedsubmission');
1137              }
1138  
1139              // Add status of "grading" if markflow is not enabled.
1140              if (!$instance->markingworkflow) {
1141                  if ($row->grade !== null && $row->grade >= 0) {
1142                      if ($row->timemarked < $row->timesubmitted) {
1143                          $o .= $this->output->container(get_string('gradedfollowupsubmit', 'assign'), 'gradingreminder');
1144                      } else {
1145                          $o .= $this->output->container(get_string('graded', 'assign'), 'submissiongraded');
1146                      }
1147                  } else if (!$timesubmitted || $status == ASSIGN_SUBMISSION_STATUS_NEW) {
1148                      $now = time();
1149                      if ($due && ($now > $due)) {
1150                          $overduestr = get_string('overdue', 'assign', format_time($now - $due));
1151                          $o .= $this->output->container($overduestr, 'overduesubmission');
1152                      }
1153                  }
1154              }
1155          }
1156  
1157          if ($instance->markingworkflow) {
1158              $o .= $this->col_workflowstatus($row);
1159          }
1160          if ($row->extensionduedate) {
1161              $userdate = userdate($row->extensionduedate);
1162              $extensionstr = get_string('userextensiondate', 'assign', $userdate);
1163              $o .= $this->output->container($extensionstr, 'extensiondate');
1164          }
1165  
1166          if ($this->is_downloading()) {
1167              $o = strip_tags(rtrim(str_replace('</div>', ' - ', $o), '- '));
1168          }
1169  
1170          return $o;
1171      }
1172  
1173      /**
1174       * Format a column of data for display.
1175       *
1176       * @param stdClass $row
1177       * @return string
1178       */
1179      public function col_allowsubmissionsfromdate(stdClass $row) {
1180          $o = '';
1181  
1182          if ($row->allowsubmissionsfromdate) {
1183              $userdate = userdate($row->allowsubmissionsfromdate);
1184              $o = ($this->is_downloading()) ? $userdate : $this->output->container($userdate, 'allowsubmissionsfromdate');
1185          }
1186  
1187          return $o;
1188      }
1189  
1190      /**
1191       * Format a column of data for display.
1192       *
1193       * @param stdClass $row
1194       * @return string
1195       */
1196      public function col_duedate(stdClass $row) {
1197          $o = '';
1198  
1199          if ($row->duedate) {
1200              $userdate = userdate($row->duedate);
1201              $o = ($this->is_downloading()) ? $userdate : $this->output->container($userdate, 'duedate');
1202          }
1203  
1204          return $o;
1205      }
1206  
1207      /**
1208       * Format a column of data for display.
1209       *
1210       * @param stdClass $row
1211       * @return string
1212       */
1213      public function col_cutoffdate(stdClass $row) {
1214          $o = '';
1215  
1216          if ($row->cutoffdate) {
1217              $userdate = userdate($row->cutoffdate);
1218              $o = ($this->is_downloading()) ? $userdate : $this->output->container($userdate, 'cutoffdate');
1219          }
1220  
1221          return $o;
1222      }
1223  
1224      /**
1225       * Format a column of data for display.
1226       *
1227       * @param stdClass $row
1228       * @return string
1229       */
1230      public function col_userid(stdClass $row) {
1231          global $USER;
1232  
1233          $edit = '';
1234  
1235          $actions = array();
1236  
1237          $urlparams = array('id' => $this->assignment->get_course_module()->id,
1238                                 'rownum' => 0,
1239                                 'action' => 'grader');
1240  
1241          if ($this->assignment->is_blind_marking()) {
1242              if (empty($row->recordid)) {
1243                  $row->recordid = $this->assignment->get_uniqueid_for_user($row->userid);
1244              }
1245              $urlparams['blindid'] = $row->recordid;
1246          } else {
1247              $urlparams['userid'] = $row->userid;
1248          }
1249          $url = new moodle_url('/mod/assign/view.php', $urlparams);
1250          $noimage = null;
1251  
1252          if (!$row->grade) {
1253              $description = get_string('gradeverb');
1254          } else {
1255              $description = get_string('updategrade', 'assign');
1256          }
1257          $actions['grade'] = new action_menu_link_secondary(
1258              $url,
1259              $noimage,
1260              $description
1261          );
1262  
1263          // Everything we need is in the row.
1264          $submission = $row;
1265          $flags = $row;
1266          if ($this->assignment->get_instance()->teamsubmission) {
1267              // Use the cache for this.
1268              $submission = false;
1269              $group = false;
1270              $this->get_group_and_submission($row->id, $group, $submission, -1);
1271          }
1272  
1273          $submissionsopen = $this->assignment->submissions_open($row->id,
1274                                                                 true,
1275                                                                 $submission,
1276                                                                 $flags,
1277                                                                 $this->gradinginfo);
1278          $caneditsubmission = $this->assignment->can_edit_submission($row->id, $USER->id);
1279  
1280          // Hide for offline assignments.
1281          if ($this->assignment->is_any_submission_plugin_enabled()) {
1282              if (!$row->status ||
1283                      $row->status == ASSIGN_SUBMISSION_STATUS_DRAFT ||
1284                      !$this->assignment->get_instance()->submissiondrafts) {
1285  
1286                  if (!$row->locked) {
1287                      $urlparams = array('id' => $this->assignment->get_course_module()->id,
1288                                         'userid' => $row->id,
1289                                         'action' => 'lock',
1290                                         'sesskey' => sesskey(),
1291                                         'page' => $this->currpage);
1292                      $url = new moodle_url('/mod/assign/view.php', $urlparams);
1293  
1294                      $description = get_string('preventsubmissionsshort', 'assign');
1295                      $actions['lock'] = new action_menu_link_secondary(
1296                          $url,
1297                          $noimage,
1298                          $description
1299                      );
1300                  } else {
1301                      $urlparams = array('id' => $this->assignment->get_course_module()->id,
1302                                         'userid' => $row->id,
1303                                         'action' => 'unlock',
1304                                         'sesskey' => sesskey(),
1305                                         'page' => $this->currpage);
1306                      $url = new moodle_url('/mod/assign/view.php', $urlparams);
1307                      $description = get_string('allowsubmissionsshort', 'assign');
1308                      $actions['unlock'] = new action_menu_link_secondary(
1309                          $url,
1310                          $noimage,
1311                          $description
1312                      );
1313                  }
1314              }
1315  
1316              if ($submissionsopen &&
1317                      $USER->id != $row->id &&
1318                      $caneditsubmission) {
1319                  $urlparams = array('id' => $this->assignment->get_course_module()->id,
1320                                     'userid' => $row->id,
1321                                     'action' => 'editsubmission',
1322                                     'sesskey' => sesskey(),
1323                                     'page' => $this->currpage);
1324                  $url = new moodle_url('/mod/assign/view.php', $urlparams);
1325                  $description = get_string('editsubmission', 'assign');
1326                  $actions['editsubmission'] = new action_menu_link_secondary(
1327                      $url,
1328                      $noimage,
1329                      $description
1330                  );
1331              }
1332              if ($USER->id != $row->id &&
1333                      $caneditsubmission &&
1334                      !empty($row->status)) {
1335                  $urlparams = array('id' => $this->assignment->get_course_module()->id,
1336                                     'userid' => $row->id,
1337                                     'action' => 'removesubmissionconfirm',
1338                                     'sesskey' => sesskey(),
1339                                     'page' => $this->currpage);
1340                  $url = new moodle_url('/mod/assign/view.php', $urlparams);
1341                  $description = get_string('removesubmission', 'assign');
1342                  $actions['removesubmission'] = new action_menu_link_secondary(
1343                      $url,
1344                      $noimage,
1345                      $description
1346                  );
1347              }
1348          }
1349          if (($this->assignment->get_instance()->duedate ||
1350                  $this->assignment->get_instance()->cutoffdate) &&
1351                  $this->hasgrantextension) {
1352               $urlparams = array('id' => $this->assignment->get_course_module()->id,
1353                                  'userid' => $row->id,
1354                                  'action' => 'grantextension',
1355                                  'sesskey' => sesskey(),
1356                                  'page' => $this->currpage);
1357               $url = new moodle_url('/mod/assign/view.php', $urlparams);
1358               $description = get_string('grantextension', 'assign');
1359               $actions['grantextension'] = new action_menu_link_secondary(
1360                   $url,
1361                   $noimage,
1362                   $description
1363               );
1364          }
1365          if ($row->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED &&
1366                  $this->assignment->get_instance()->submissiondrafts) {
1367              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1368                                 'userid' => $row->id,
1369                                 'action' => 'reverttodraft',
1370                                 'sesskey' => sesskey(),
1371                                 'page' => $this->currpage);
1372              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1373              $description = get_string('reverttodraftshort', 'assign');
1374              $actions['reverttodraft'] = new action_menu_link_secondary(
1375                  $url,
1376                  $noimage,
1377                  $description
1378              );
1379          }
1380          if ($row->status == ASSIGN_SUBMISSION_STATUS_DRAFT &&
1381                  $this->assignment->get_instance()->submissiondrafts &&
1382                  $caneditsubmission &&
1383                  $submissionsopen &&
1384                  $row->id != $USER->id) {
1385              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1386                                 'userid' => $row->id,
1387                                 'action' => 'submitotherforgrading',
1388                                 'sesskey' => sesskey(),
1389                                 'page' => $this->currpage);
1390              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1391              $description = get_string('submitforgrading', 'assign');
1392              $actions['submitforgrading'] = new action_menu_link_secondary(
1393                  $url,
1394                  $noimage,
1395                  $description
1396              );
1397          }
1398  
1399          $ismanual = $this->assignment->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL;
1400          $hassubmission = !empty($row->status);
1401          $notreopened = $hassubmission && $row->status != ASSIGN_SUBMISSION_STATUS_REOPENED;
1402          $isunlimited = $this->assignment->get_instance()->maxattempts == ASSIGN_UNLIMITED_ATTEMPTS;
1403          $hasattempts = $isunlimited || $row->attemptnumber < $this->assignment->get_instance()->maxattempts - 1;
1404  
1405          if ($ismanual && $hassubmission && $notreopened && $hasattempts) {
1406              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1407                                 'userid' => $row->id,
1408                                 'action' => 'addattempt',
1409                                 'sesskey' => sesskey(),
1410                                 'page' => $this->currpage);
1411              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1412              $description = get_string('addattempt', 'assign');
1413              $actions['addattempt'] = new action_menu_link_secondary(
1414                  $url,
1415                  $noimage,
1416                  $description
1417              );
1418          }
1419  
1420          $menu = new action_menu();
1421          $menu->set_owner_selector('.gradingtable-actionmenu');
1422          $menu->set_boundary('window');
1423          $menu->set_menu_trigger(get_string('edit'));
1424          foreach ($actions as $action) {
1425              $menu->add($action);
1426          }
1427  
1428          // Prioritise the menu ahead of all other actions.
1429          $menu->prioritise = true;
1430  
1431          $edit .= $this->output->render($menu);
1432  
1433          return $edit;
1434      }
1435  
1436      /**
1437       * Write the plugin summary with an optional link to view the full feedback/submission.
1438       *
1439       * @param assign_plugin $plugin Submission plugin or feedback plugin
1440       * @param stdClass $item Submission or grade
1441       * @param string $returnaction The return action to pass to the
1442       *                             view_submission page (the current page)
1443       * @param string $returnparams The return params to pass to the view_submission
1444       *                             page (the current page)
1445       * @return string The summary with an optional link
1446       */
1447      private function format_plugin_summary_with_link(assign_plugin $plugin,
1448                                                       stdClass $item,
1449                                                       $returnaction,
1450                                                       $returnparams) {
1451          $link = '';
1452          $showviewlink = false;
1453  
1454          $summary = $plugin->view_summary($item, $showviewlink);
1455          $separator = '';
1456          if ($showviewlink) {
1457              $viewstr = get_string('view' . substr($plugin->get_subtype(), strlen('assign')), 'assign');
1458              $icon = $this->output->pix_icon('t/preview', $viewstr);
1459              $urlparams = array('id' => $this->assignment->get_course_module()->id,
1460                                                       'sid' => $item->id,
1461                                                       'gid' => $item->id,
1462                                                       'plugin' => $plugin->get_type(),
1463                                                       'action' => 'viewplugin' . $plugin->get_subtype(),
1464                                                       'returnaction' => $returnaction,
1465                                                       'returnparams' => http_build_query($returnparams));
1466              $url = new moodle_url('/mod/assign/view.php', $urlparams);
1467              $link = $this->output->action_link($url, $icon);
1468              $separator = $this->output->spacer(array(), true);
1469          }
1470  
1471          return $link . $separator . $summary;
1472      }
1473  
1474  
1475      /**
1476       * Format the submission and feedback columns.
1477       *
1478       * @param string $colname The column name
1479       * @param stdClass $row The submission row
1480       * @return mixed string or NULL
1481       */
1482      public function other_cols($colname, $row) {
1483          // For extra user fields the result is already in $row.
1484          if (empty($this->plugincache[$colname])) {
1485              return parent::other_cols($colname, $row);
1486          }
1487  
1488          // This must be a plugin field.
1489          $plugincache = $this->plugincache[$colname];
1490  
1491          $plugin = $plugincache[0];
1492  
1493          $field = null;
1494          if (isset($plugincache[1])) {
1495              $field = $plugincache[1];
1496          }
1497  
1498          if ($plugin->is_visible() && $plugin->is_enabled()) {
1499              if ($plugin->get_subtype() == 'assignsubmission') {
1500                  if ($this->assignment->get_instance()->teamsubmission) {
1501                      $group = false;
1502                      $submission = false;
1503  
1504                      $this->get_group_and_submission($row->id, $group, $submission, -1);
1505                      if ($submission) {
1506                          if ($submission->status == ASSIGN_SUBMISSION_STATUS_REOPENED) {
1507                              // For a newly reopened submission - we want to show the previous submission in the table.
1508                              $this->get_group_and_submission($row->id, $group, $submission, $submission->attemptnumber-1);
1509                          }
1510                          if (isset($field)) {
1511                              return $plugin->get_editor_text($field, $submission->id);
1512                          }
1513                          return $this->format_plugin_summary_with_link($plugin,
1514                                                                        $submission,
1515                                                                        'grading',
1516                                                                        array());
1517                      }
1518                  } else if ($row->submissionid) {
1519                      if ($row->status == ASSIGN_SUBMISSION_STATUS_REOPENED) {
1520                          // For a newly reopened submission - we want to show the previous submission in the table.
1521                          $submission = $this->assignment->get_user_submission($row->userid, false, $row->attemptnumber - 1);
1522                      } else {
1523                          $submission = new stdClass();
1524                          $submission->id = $row->submissionid;
1525                          $submission->timecreated = $row->firstsubmission;
1526                          $submission->timemodified = $row->timesubmitted;
1527                          $submission->assignment = $this->assignment->get_instance()->id;
1528                          $submission->userid = $row->userid;
1529                          $submission->attemptnumber = $row->attemptnumber;
1530                      }
1531                      // Field is used for only for import/export and refers the the fieldname for the text editor.
1532                      if (isset($field)) {
1533                          return $plugin->get_editor_text($field, $submission->id);
1534                      }
1535                      return $this->format_plugin_summary_with_link($plugin,
1536                                                                    $submission,
1537                                                                    'grading',
1538                                                                    array());
1539                  }
1540              } else {
1541                  $grade = null;
1542                  if (isset($field)) {
1543                      return $plugin->get_editor_text($field, $row->gradeid);
1544                  }
1545  
1546                  if ($row->gradeid) {
1547                      $grade = new stdClass();
1548                      $grade->id = $row->gradeid;
1549                      $grade->timecreated = $row->firstmarked;
1550                      $grade->timemodified = $row->timemarked;
1551                      $grade->assignment = $this->assignment->get_instance()->id;
1552                      $grade->userid = $row->userid;
1553                      $grade->grade = $row->grade;
1554                      $grade->mailed = $row->mailed;
1555                      $grade->attemptnumber = $row->attemptnumber;
1556                  }
1557                  if ($this->quickgrading && $plugin->supports_quickgrading()) {
1558                      return $plugin->get_quickgrading_html($row->userid, $grade);
1559                  } else if ($grade) {
1560                      return $this->format_plugin_summary_with_link($plugin,
1561                                                                    $grade,
1562                                                                    'grading',
1563                                                                    array());
1564                  }
1565              }
1566          }
1567          return '';
1568      }
1569  
1570      /**
1571       * Using the current filtering and sorting - load all rows and return a single column from them.
1572       *
1573       * @param string $columnname The name of the raw column data
1574       * @return array of data
1575       */
1576      public function get_column_data($columnname) {
1577          $this->setup();
1578          $this->currpage = 0;
1579          $this->query_db($this->tablemaxrows);
1580          $result = array();
1581          foreach ($this->rawdata as $row) {
1582              $result[] = $row->$columnname;
1583          }
1584          return $result;
1585      }
1586  
1587      /**
1588       * Return things to the renderer.
1589       *
1590       * @return string the assignment name
1591       */
1592      public function get_assignment_name() {
1593          return $this->assignment->get_instance()->name;
1594      }
1595  
1596      /**
1597       * Return things to the renderer.
1598       *
1599       * @return int the course module id
1600       */
1601      public function get_course_module_id() {
1602          return $this->assignment->get_course_module()->id;
1603      }
1604  
1605      /**
1606       * Return things to the renderer.
1607       *
1608       * @return int the course id
1609       */
1610      public function get_course_id() {
1611          return $this->assignment->get_course()->id;
1612      }
1613  
1614      /**
1615       * Return things to the renderer.
1616       *
1617       * @return stdClass The course context
1618       */
1619      public function get_course_context() {
1620          return $this->assignment->get_course_context();
1621      }
1622  
1623      /**
1624       * Return things to the renderer.
1625       *
1626       * @return bool Does this assignment accept submissions
1627       */
1628      public function submissions_enabled() {
1629          return $this->assignment->is_any_submission_plugin_enabled();
1630      }
1631  
1632      /**
1633       * Return things to the renderer.
1634       *
1635       * @return bool Can this user view all grades (the gradebook)
1636       */
1637      public function can_view_all_grades() {
1638          $context = $this->assignment->get_course_context();
1639          return has_capability('gradereport/grader:view', $context) &&
1640                 has_capability('moodle/grade:viewall', $context);
1641      }
1642  
1643      /**
1644       * Always return a valid sort - even if the userid column is missing.
1645       * @return array column name => SORT_... constant.
1646       */
1647      public function get_sort_columns() {
1648          $result = parent::get_sort_columns();
1649  
1650          $assignment = $this->assignment->get_instance();
1651          if (empty($assignment->blindmarking)) {
1652              $result = array_merge($result, array('userid' => SORT_ASC));
1653          } else {
1654              $result = array_merge($result, [
1655                      'COALESCE(s.timecreated, '  . time()        . ')'   => SORT_ASC,
1656                      'COALESCE(s.id, '           . PHP_INT_MAX   . ')'   => SORT_ASC,
1657                      'um.id'                                             => SORT_ASC,
1658                  ]);
1659          }
1660          return $result;
1661      }
1662  
1663      /**
1664       * Override the table show_hide_link to not show for select column.
1665       *
1666       * @param string $column the column name, index into various names.
1667       * @param int $index numerical index of the column.
1668       * @return string HTML fragment.
1669       */
1670      protected function show_hide_link($column, $index) {
1671          if ($index > 0 || !$this->hasgrade) {
1672              return parent::show_hide_link($column, $index);
1673          }
1674          return '';
1675      }
1676  
1677      /**
1678       * Overides setup to ensure it will only run a single time.
1679       */
1680      public function setup() {
1681          // Check if the setup function has been called before, we should not run it twice.
1682          // If we do the sortorder of the table will be broken.
1683          if (!empty($this->setup)) {
1684              return;
1685          }
1686          parent::setup();
1687      }
1688  }