Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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