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