MDL-66147 mod_assign: submissions overview page shows time interval
[moodle.git] / mod / assign / locallib.php
CommitLineData
bbd0e548
DW
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 class assignment
19 *
20 * This class provides all the functionality for the new assign module.
21 *
22 * @package mod_assign
23 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
e5403f8c 29// Assignment submission statuses.
9e3eee67 30define('ASSIGN_SUBMISSION_STATUS_NEW', 'new');
df211804 31define('ASSIGN_SUBMISSION_STATUS_REOPENED', 'reopened');
e5403f8c
DW
32define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
33define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
bbd0e548 34
e5403f8c 35// Search filters for grading page.
064f1503 36define('ASSIGN_FILTER_NONE', 'none');
bbd0e548 37define('ASSIGN_FILTER_SUBMITTED', 'submitted');
c80d59f2 38define('ASSIGN_FILTER_NOT_SUBMITTED', 'notsubmitted');
bbd0e548 39define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
064f1503
DW
40define('ASSIGN_FILTER_REQUIRE_GRADING', 'requiregrading');
41define('ASSIGN_FILTER_GRANTED_EXTENSION', 'grantedextension');
bbd0e548 42
c80d59f2
JF
43// Marker filter for grading page.
44define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
45
df211804
DW
46// Reopen attempt methods.
47define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
48define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
49define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
50
51// Special value means allow unlimited attempts.
52define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
53
2d1075e3
JO
54// Special value means no grade has been set.
55define('ASSIGN_GRADE_NOT_SET', -1);
56
bd3ee807
MN
57// Grading states.
58define('ASSIGN_GRADING_STATUS_GRADED', 'graded');
59define('ASSIGN_GRADING_STATUS_NOT_GRADED', 'notgraded');
60
f8d107b3
DM
61// Marking workflow states.
62define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
63define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
64define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
65define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
66define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
67define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
68
d685b959
IT
69/** ASSIGN_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
70define("ASSIGN_MAX_EVENT_LENGTH", "432000");
71
7faf78cb
HB
72// Name of file area for intro attachments.
73define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
74
294dce67
MN
75// Event types.
76define('ASSIGN_EVENT_TYPE_DUE', 'due');
77define('ASSIGN_EVENT_TYPE_GRADINGDUE', 'gradingdue');
78define('ASSIGN_EVENT_TYPE_OPEN', 'open');
79define('ASSIGN_EVENT_TYPE_CLOSE', 'close');
80
e5403f8c
DW
81require_once($CFG->libdir . '/accesslib.php');
82require_once($CFG->libdir . '/formslib.php');
bbd0e548 83require_once($CFG->dirroot . '/repository/lib.php');
e5403f8c
DW
84require_once($CFG->dirroot . '/mod/assign/mod_form.php');
85require_once($CFG->libdir . '/gradelib.php');
86require_once($CFG->dirroot . '/grade/grading/lib.php');
87require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
88require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
89require_once($CFG->dirroot . '/mod/assign/renderable.php');
90require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
37743241 91require_once($CFG->libdir . '/portfolio/caller.php');
bbd0e548 92
bb690849
DW
93use \mod_assign\output\grading_app;
94
bbd0e548
DW
95/**
96 * Standard base class for mod_assign (assignment types).
97 *
98 * @package mod_assign
99 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
101 */
102class assign {
103
bbd0e548
DW
104 /** @var stdClass the assignment record that contains the global settings for this assign instance */
105 private $instance;
106
db381d5c
JD
107 /** @var array $var array an array containing per-user assignment records, each having calculated properties (e.g. dates) */
108 private $userinstances = [];
109
db8514bc 110 /** @var grade_item the grade_item record for this assign instance's primary grade item. */
0d64c75f
PN
111 private $gradeitem;
112
e5403f8c
DW
113 /** @var context the context of the course module for this assign instance
114 * (or just the course if we are creating a new one)
115 */
bbd0e548
DW
116 private $context;
117
118 /** @var stdClass the course this assign instance belongs to */
119 private $course;
bc5a657b 120
cfc81f03
DW
121 /** @var stdClass the admin config for all assign instances */
122 private $adminconfig;
123
bbd0e548
DW
124 /** @var assign_renderer the custom renderer for this module */
125 private $output;
126
c13ac85d 127 /** @var cm_info the course module for this assign instance */
bbd0e548
DW
128 private $coursemodule;
129
e5403f8c
DW
130 /** @var array cache for things like the coursemodule name or the scale menu -
131 * only lives for a single request.
132 */
bbd0e548
DW
133 private $cache;
134
135 /** @var array list of the installed submission plugins */
136 private $submissionplugins;
137
138 /** @var array list of the installed feedback plugins */
139 private $feedbackplugins;
140
e5403f8c
DW
141 /** @var string action to be used to return to this page
142 * (without repeating any form submissions etc).
143 */
bbd0e548
DW
144 private $returnaction = 'view';
145
146 /** @var array params to be used to return to this page */
147 private $returnparams = array();
148
149 /** @var string modulename prevents excessive calls to get_string */
f5b32abe 150 private static $modulename = null;
bbd0e548
DW
151
152 /** @var string modulenameplural prevents excessive calls to get_string */
f5b32abe 153 private static $modulenameplural = null;
bbd0e548 154
f8d107b3
DM
155 /** @var array of marking workflow states for the current user */
156 private $markingworkflowstates = null;
157
4c4c7b3f 158 /** @var bool whether to exclude users with inactive enrolment */
1ecb8044 159 private $showonlyactiveenrol = null;
4c4c7b3f 160
1a51661b 161 /** @var string A key used to identify userlists created by this object. */
3fca6937
NM
162 private $useridlistid = null;
163
c46db93c
DW
164 /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
165 private $participants = array();
166
bc006a66
DM
167 /** @var array cached list of user groups when team submissions are enabled. The cache key will be the user. */
168 private $usersubmissiongroups = array();
169
ee5d4eef
AH
170 /** @var array cached list of user groups. The cache key will be the user. */
171 private $usergroups = array();
172
6d6e297b
DM
173 /** @var array cached list of IDs of users who share group membership with the user. The cache key will be the user. */
174 private $sharedgroupmembers = array();
175
75c21e7e
AG
176 /**
177 * @var stdClass The most recent team submission. Used to determine additional attempt numbers and whether
178 * to update the gradebook.
179 */
180 private $mostrecentteamsubmission = null;
181
bbd0e548 182 /**
e5403f8c 183 * Constructor for the base assign class.
bbd0e548 184 *
c13ac85d 185 * Note: For $coursemodule you can supply a stdclass if you like, but it
186 * will be more efficient to supply a cm_info object.
187 *
e5403f8c
DW
188 * @param mixed $coursemodulecontext context|null the course module context
189 * (or the course context if the coursemodule has not been
190 * created yet).
191 * @param mixed $coursemodule the current course module if it was already loaded,
192 * otherwise this class will load one from the context as required.
193 * @param mixed $course the current course if it was already loaded,
194 * otherwise this class will load one from the context as required.
bbd0e548
DW
195 */
196 public function __construct($coursemodulecontext, $coursemodule, $course) {
1a51661b
DM
197 global $SESSION;
198
bbd0e548 199 $this->context = $coursemodulecontext;
bbd0e548 200 $this->course = $course;
e5403f8c 201
c13ac85d 202 // Ensure that $this->coursemodule is a cm_info object (or null).
203 $this->coursemodule = cm_info::create($coursemodule);
204
e5403f8c
DW
205 // Temporary cache only lives for a single request - used to reduce db lookups.
206 $this->cache = array();
bbd0e548
DW
207
208 $this->submissionplugins = $this->load_plugins('assignsubmission');
209 $this->feedbackplugins = $this->load_plugins('assignfeedback');
3fca6937
NM
210
211 // Extra entropy is required for uniqid() to work on cygwin.
212 $this->useridlistid = clean_param(uniqid('', true), PARAM_ALPHANUM);
1a51661b
DM
213
214 if (!isset($SESSION->mod_assign_useridlist)) {
215 $SESSION->mod_assign_useridlist = [];
216 }
bbd0e548
DW
217 }
218
219 /**
e5403f8c 220 * Set the action and parameters that can be used to return to the current page.
bbd0e548
DW
221 *
222 * @param string $action The action for the current page
e5403f8c
DW
223 * @param array $params An array of name value pairs which form the parameters
224 * to return to the current page.
bbd0e548
DW
225 * @return void
226 */
227 public function register_return_link($action, $params) {
d04557b3
DW
228 global $PAGE;
229 $params['action'] = $action;
77a53060
DW
230 $cm = $this->get_course_module();
231 if ($cm) {
232 $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $cm->id));
233 } else {
234 $currenturl = new moodle_url('/mod/assign/index.php', array('id' => $this->get_course()->id));
235 }
d04557b3
DW
236
237 $currenturl->params($params);
238 $PAGE->set_url($currenturl);
bbd0e548
DW
239 }
240
241 /**
e5403f8c
DW
242 * Return an action that can be used to get back to the current page.
243 *
bbd0e548
DW
244 * @return string action
245 */
246 public function get_return_action() {
d04557b3
DW
247 global $PAGE;
248
3216f616
JL
249 // Web services don't set a URL, we should avoid debugging when ussing the url object.
250 if (!WS_SERVER) {
251 $params = $PAGE->url->params();
252 }
d04557b3 253
c2114099
DW
254 if (!empty($params['action'])) {
255 return $params['action'];
256 }
257 return '';
bbd0e548
DW
258 }
259
260 /**
e5403f8c
DW
261 * Based on the current assignment settings should we display the intro.
262 *
bbd0e548
DW
263 * @return bool showintro
264 */
7faf78cb 265 public function show_intro() {
bbd0e548
DW
266 if ($this->get_instance()->alwaysshowdescription ||
267 time() > $this->get_instance()->allowsubmissionsfromdate) {
268 return true;
269 }
270 return false;
271 }
272
273 /**
e5403f8c
DW
274 * Return a list of parameters that can be used to get back to the current page.
275 *
bbd0e548
DW
276 * @return array params
277 */
278 public function get_return_params() {
d04557b3
DW
279 global $PAGE;
280
96a037f7
ALH
281 $params = array();
282 if (!WS_SERVER) {
283 $params = $PAGE->url->params();
284 }
c2114099
DW
285 unset($params['id']);
286 unset($params['action']);
287 return $params;
bbd0e548
DW
288 }
289
290 /**
e5403f8c
DW
291 * Set the submitted form data.
292 *
bbd0e548
DW
293 * @param stdClass $data The form data (instance)
294 */
295 public function set_instance(stdClass $data) {
296 $this->instance = $data;
297 }
298
299 /**
e5403f8c
DW
300 * Set the context.
301 *
bbd0e548
DW
302 * @param context $context The new context
303 */
304 public function set_context(context $context) {
305 $this->context = $context;
306 }
307
308 /**
e5403f8c
DW
309 * Set the course data.
310 *
bbd0e548
DW
311 * @param stdClass $course The course data
312 */
313 public function set_course(stdClass $course) {
314 $this->course = $course;
315 }
316
317 /**
e5403f8c
DW
318 * Get list of feedback plugins installed.
319 *
bbd0e548
DW
320 * @return array
321 */
322 public function get_feedback_plugins() {
323 return $this->feedbackplugins;
324 }
325
326 /**
e5403f8c
DW
327 * Get list of submission plugins installed.
328 *
bbd0e548
DW
329 * @return array
330 */
331 public function get_submission_plugins() {
332 return $this->submissionplugins;
333 }
334
b473171a
DW
335 /**
336 * Is blind marking enabled and reveal identities not set yet?
337 *
338 * @return bool
339 */
340 public function is_blind_marking() {
341 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
342 }
343
f14afd29
AW
344 /**
345 * Is hidden grading enabled?
346 *
347 * This just checks the assignment settings. Remember to check
348 * the user has the 'showhiddengrader' capability too
349 *
350 * @return bool
351 */
352 public function is_hidden_grader() {
353 return $this->get_instance()->hidegrader;
354 }
355
b473171a
DW
356 /**
357 * Does an assignment have submission(s) or grade(s) already?
358 *
359 * @return bool
360 */
361 public function has_submissions_or_grades() {
362 $allgrades = $this->count_grades();
363 $allsubmissions = $this->count_submissions();
364 if (($allgrades == 0) && ($allsubmissions == 0)) {
365 return false;
366 }
367 return true;
368 }
bbd0e548
DW
369
370 /**
e5403f8c
DW
371 * Get a specific submission plugin by its type.
372 *
bbd0e548
DW
373 * @param string $subtype assignsubmission | assignfeedback
374 * @param string $type
375 * @return mixed assign_plugin|null
376 */
df47b77f 377 public function get_plugin_by_type($subtype, $type) {
bbd0e548
DW
378 $shortsubtype = substr($subtype, strlen('assign'));
379 $name = $shortsubtype . 'plugins';
d0d4796b
DW
380 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
381 return null;
382 }
bbd0e548
DW
383 $pluginlist = $this->$name;
384 foreach ($pluginlist as $plugin) {
385 if ($plugin->get_type() == $type) {
386 return $plugin;
387 }
388 }
389 return null;
390 }
391
392 /**
e5403f8c
DW
393 * Get a feedback plugin by type.
394 *
bbd0e548
DW
395 * @param string $type - The type of plugin e.g comments
396 * @return mixed assign_feedback_plugin|null
397 */
398 public function get_feedback_plugin_by_type($type) {
399 return $this->get_plugin_by_type('assignfeedback', $type);
400 }
401
402 /**
e5403f8c
DW
403 * Get a submission plugin by type.
404 *
bbd0e548
DW
405 * @param string $type - The type of plugin e.g comments
406 * @return mixed assign_submission_plugin|null
407 */
408 public function get_submission_plugin_by_type($type) {
409 return $this->get_plugin_by_type('assignsubmission', $type);
410 }
411
412 /**
e5403f8c
DW
413 * Load the plugins from the sub folders under subtype.
414 *
bbd0e548
DW
415 * @param string $subtype - either submission or feedback
416 * @return array - The sorted list of plugins
417 */
e5e89cac 418 public function load_plugins($subtype) {
bbd0e548
DW
419 global $CFG;
420 $result = array();
421
bd3b3bba 422 $names = core_component::get_plugin_list($subtype);
bbd0e548
DW
423
424 foreach ($names as $name => $path) {
425 if (file_exists($path . '/locallib.php')) {
426 require_once($path . '/locallib.php');
427
428 $shortsubtype = substr($subtype, strlen('assign'));
429 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
430
431 $plugin = new $pluginclass($this, $name);
432
433 if ($plugin instanceof assign_plugin) {
434 $idx = $plugin->get_sort_order();
e5403f8c
DW
435 while (array_key_exists($idx, $result)) {
436 $idx +=1;
437 }
bbd0e548
DW
438 $result[$idx] = $plugin;
439 }
440 }
441 }
442 ksort($result);
443 return $result;
444 }
445
bbd0e548
DW
446 /**
447 * Display the assignment, used by view.php
448 *
449 * The assignment is displayed differently depending on your role,
450 * the settings for the assignment and the status of the assignment.
e5403f8c 451 *
bbd0e548 452 * @param string $action The current action if any.
bb690849 453 * @param array $args Optional arguments to pass to the view (instead of getting them from GET and POST).
df211804 454 * @return string - The page output.
bbd0e548 455 */
bb690849 456 public function view($action='', $args = array()) {
e61036f4 457 global $PAGE;
bbd0e548
DW
458
459 $o = '';
460 $mform = null;
34b8f3a8 461 $notices = array();
34e338a4 462 $nextpageparams = array();
bbd0e548 463
34e338a4
MN
464 if (!empty($this->get_course_module()->id)) {
465 $nextpageparams['id'] = $this->get_course_module()->id;
466 }
d04557b3 467
34b8f3a8 468 // Handle form submissions first.
bbd0e548
DW
469 if ($action == 'savesubmission') {
470 $action = 'editsubmission';
34b8f3a8 471 if ($this->process_save_submission($mform, $notices)) {
d04557b3 472 $action = 'redirect';
37fc47f1
DW
473 if ($this->can_grade()) {
474 $nextpageparams['action'] = 'grading';
475 } else {
476 $nextpageparams['action'] = 'view';
477 }
bbd0e548 478 }
df211804
DW
479 } else if ($action == 'editprevioussubmission') {
480 $action = 'editsubmission';
481 if ($this->process_copy_previous_attempt($notices)) {
482 $action = 'redirect';
483 $nextpageparams['action'] = 'editsubmission';
484 }
9e795179 485 } else if ($action == 'lock') {
05a6445a 486 $this->process_lock_submission();
d04557b3
DW
487 $action = 'redirect';
488 $nextpageparams['action'] = 'grading';
37fc47f1
DW
489 } else if ($action == 'removesubmission') {
490 $this->process_remove_submission();
491 $action = 'redirect';
492 if ($this->can_grade()) {
493 $nextpageparams['action'] = 'grading';
494 } else {
495 $nextpageparams['action'] = 'view';
496 }
df211804
DW
497 } else if ($action == 'addattempt') {
498 $this->process_add_attempt(required_param('userid', PARAM_INT));
499 $action = 'redirect';
500 $nextpageparams['action'] = 'grading';
9e795179 501 } else if ($action == 'reverttodraft') {
bbd0e548 502 $this->process_revert_to_draft();
d04557b3
DW
503 $action = 'redirect';
504 $nextpageparams['action'] = 'grading';
9e795179 505 } else if ($action == 'unlock') {
05a6445a 506 $this->process_unlock_submission();
d04557b3
DW
507 $action = 'redirect';
508 $nextpageparams['action'] = 'grading';
f8d107b3
DM
509 } else if ($action == 'setbatchmarkingworkflowstate') {
510 $this->process_set_batch_marking_workflow_state();
511 $action = 'redirect';
512 $nextpageparams['action'] = 'grading';
513 } else if ($action == 'setbatchmarkingallocation') {
514 $this->process_set_batch_marking_allocation();
515 $action = 'redirect';
516 $nextpageparams['action'] = 'grading';
9e795179 517 } else if ($action == 'confirmsubmit') {
94f26900 518 $action = 'submit';
57fbd5f9 519 if ($this->process_submit_for_grading($mform, $notices)) {
d04557b3
DW
520 $action = 'redirect';
521 $nextpageparams['action'] = 'view';
57fbd5f9
DW
522 } else if ($notices) {
523 $action = 'viewsubmitforgradingerror';
524 }
525 } else if ($action == 'submitotherforgrading') {
526 if ($this->process_submit_other_for_grading($mform, $notices)) {
527 $action = 'redirect';
528 $nextpageparams['action'] = 'grading';
529 } else {
530 $action = 'viewsubmitforgradingerror';
94f26900 531 }
df47b77f
DW
532 } else if ($action == 'gradingbatchoperation') {
533 $action = $this->process_grading_batch_operation($mform);
d04557b3
DW
534 if ($action == 'grading') {
535 $action = 'redirect';
536 $nextpageparams['action'] = 'grading';
537 }
9e795179 538 } else if ($action == 'submitgrade') {
ba30fe35 539 if (optional_param('saveandshownext', null, PARAM_RAW)) {
e5403f8c 540 // Save and show next.
bbd0e548
DW
541 $action = 'grade';
542 if ($this->process_save_grade($mform)) {
d04557b3
DW
543 $action = 'redirect';
544 $nextpageparams['action'] = 'grade';
545 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
3fca6937 546 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
bbd0e548 547 }
ba30fe35 548 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
d04557b3
DW
549 $action = 'redirect';
550 $nextpageparams['action'] = 'grade';
551 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
3fca6937 552 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
ba30fe35 553 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
d04557b3
DW
554 $action = 'redirect';
555 $nextpageparams['action'] = 'grade';
556 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
3fca6937 557 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
ba30fe35 558 } else if (optional_param('savegrade', null, PARAM_RAW)) {
e5403f8c 559 // Save changes button.
bbd0e548
DW
560 $action = 'grade';
561 if ($this->process_save_grade($mform)) {
082ad257
JF
562 $action = 'redirect';
563 $nextpageparams['action'] = 'savegradingresult';
bbd0e548
DW
564 }
565 } else {
e5403f8c 566 // Cancel button.
d04557b3
DW
567 $action = 'redirect';
568 $nextpageparams['action'] = 'grading';
bbd0e548 569 }
9e795179 570 } else if ($action == 'quickgrade') {
bf78ebd6
DW
571 $message = $this->process_save_quick_grades();
572 $action = 'quickgradingresult';
9e795179 573 } else if ($action == 'saveoptions') {
bbd0e548 574 $this->process_save_grading_options();
d04557b3
DW
575 $action = 'redirect';
576 $nextpageparams['action'] = 'grading';
9e795179
DW
577 } else if ($action == 'saveextension') {
578 $action = 'grantextension';
579 if ($this->process_save_extension($mform)) {
d04557b3
DW
580 $action = 'redirect';
581 $nextpageparams['action'] = 'grading';
9e795179 582 }
b473171a
DW
583 } else if ($action == 'revealidentitiesconfirm') {
584 $this->process_reveal_identities();
d04557b3
DW
585 $action = 'redirect';
586 $nextpageparams['action'] = 'grading';
bbd0e548
DW
587 }
588
d04557b3 589 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
3fca6937 590 'useridlistid' => optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM));
bbd0e548
DW
591 $this->register_return_link($action, $returnparams);
592
e61036f4
DB
593 // Include any page action as part of the body tag CSS id.
594 if (!empty($action)) {
595 $PAGE->set_pagetype('mod-assign-' . $action);
596 }
34b8f3a8 597 // Now show the right view page.
d04557b3
DW
598 if ($action == 'redirect') {
599 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
600 redirect($nextpageurl);
601 return;
df211804 602 } else if ($action == 'savegradingresult') {
082ad257 603 $message = get_string('gradingchangessaved', 'assign');
df211804 604 $o .= $this->view_savegrading_result($message);
bf78ebd6
DW
605 } else if ($action == 'quickgradingresult') {
606 $mform = null;
607 $o .= $this->view_quickgrading_result($message);
bb690849
DW
608 } else if ($action == 'gradingpanel') {
609 $o .= $this->view_single_grading_panel($args);
bbd0e548
DW
610 } else if ($action == 'grade') {
611 $o .= $this->view_single_grade_page($mform);
612 } else if ($action == 'viewpluginassignfeedback') {
613 $o .= $this->view_plugin_content('assignfeedback');
614 } else if ($action == 'viewpluginassignsubmission') {
615 $o .= $this->view_plugin_content('assignsubmission');
616 } else if ($action == 'editsubmission') {
34b8f3a8 617 $o .= $this->view_edit_submission_page($mform, $notices);
bb690849
DW
618 } else if ($action == 'grader') {
619 $o .= $this->view_grader();
bbd0e548
DW
620 } else if ($action == 'grading') {
621 $o .= $this->view_grading_page();
622 } else if ($action == 'downloadall') {
623 $o .= $this->download_submissions();
624 } else if ($action == 'submit') {
94f26900 625 $o .= $this->check_submit_for_grading($mform);
9e795179
DW
626 } else if ($action == 'grantextension') {
627 $o .= $this->view_grant_extension($mform);
b473171a
DW
628 } else if ($action == 'revealidentities') {
629 $o .= $this->view_reveal_identities_confirm($mform);
37fc47f1
DW
630 } else if ($action == 'removesubmissionconfirm') {
631 $o .= $this->view_remove_submission_confirm();
df47b77f
DW
632 } else if ($action == 'plugingradingbatchoperation') {
633 $o .= $this->view_plugin_grading_batch_operation($mform);
7a2b911c 634 } else if ($action == 'viewpluginpage') {
df47b77f 635 $o .= $this->view_plugin_page();
64220210
DW
636 } else if ($action == 'viewcourseindex') {
637 $o .= $this->view_course_index();
f8d107b3
DM
638 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
639 $o .= $this->view_batch_set_workflow_state($mform);
640 } else if ($action == 'viewbatchmarkingallocation') {
641 $o .= $this->view_batch_markingallocation($mform);
57fbd5f9
DW
642 } else if ($action == 'viewsubmitforgradingerror') {
643 $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
7323c473
JO
644 } else if ($action == 'fixrescalednullgrades') {
645 $o .= $this->view_fix_rescaled_null_grades();
bbd0e548
DW
646 } else {
647 $o .= $this->view_submission_page();
648 }
649
650 return $o;
651 }
652
bbd0e548 653 /**
e5403f8c 654 * Add this instance to the database.
bbd0e548
DW
655 *
656 * @param stdClass $formdata The data submitted from the form
657 * @param bool $callplugins This is used to skip the plugin code
658 * when upgrading an old assignment to a new one (the plugins get called manually)
659 * @return mixed false if an error occurs or the int id of the new instance
660 */
661 public function add_instance(stdClass $formdata, $callplugins) {
662 global $DB;
8e1266bf 663 $adminconfig = $this->get_admin_config();
bbd0e548
DW
664
665 $err = '';
666
e5403f8c 667 // Add the database record.
bbd0e548
DW
668 $update = new stdClass();
669 $update->name = $formdata->name;
670 $update->timemodified = time();
671 $update->timecreated = time();
672 $update->course = $formdata->course;
673 $update->courseid = $formdata->course;
674 $update->intro = $formdata->intro;
675 $update->introformat = $formdata->introformat;
18de52db 676 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
bbd0e548 677 $update->submissiondrafts = $formdata->submissiondrafts;
94f26900 678 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
bbd0e548 679 $update->sendnotifications = $formdata->sendnotifications;
75f87a57 680 $update->sendlatenotifications = $formdata->sendlatenotifications;
8e1266bf
DW
681 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
682 if (isset($formdata->sendstudentnotifications)) {
683 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
684 }
b618f2d9 685 $update->duedate = $formdata->duedate;
9e795179 686 $update->cutoffdate = $formdata->cutoffdate;
3e1c0275 687 $update->gradingduedate = $formdata->gradingduedate;
bbd0e548
DW
688 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
689 $update->grade = $formdata->grade;
694b11ab 690 $update->completionsubmit = !empty($formdata->completionsubmit);
12a1a0da
DW
691 $update->teamsubmission = $formdata->teamsubmission;
692 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
1fba9cf6
DW
693 if (isset($formdata->teamsubmissiongroupingid)) {
694 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
695 }
b473171a 696 $update->blindmarking = $formdata->blindmarking;
f14afd29
AW
697 if (isset($formdata->hidegrader)) {
698 $update->hidegrader = $formdata->hidegrader;
699 }
e8490064
DW
700 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
701 if (!empty($formdata->attemptreopenmethod)) {
702 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
703 }
df211804
DW
704 if (!empty($formdata->maxattempts)) {
705 $update->maxattempts = $formdata->maxattempts;
706 }
e528997a
AH
707 if (isset($formdata->preventsubmissionnotingroup)) {
708 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
709 }
f8d107b3
DM
710 $update->markingworkflow = $formdata->markingworkflow;
711 $update->markingallocation = $formdata->markingallocation;
5a96486b
DM
712 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
713 $update->markingallocation = 0;
714 }
12a1a0da 715
bbd0e548
DW
716 $returnid = $DB->insert_record('assign', $update);
717 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
e5403f8c 718 // Cache the course record.
bbd0e548
DW
719 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
720
7faf78cb
HB
721 $this->save_intro_draft_files($formdata);
722
bbd0e548 723 if ($callplugins) {
e5403f8c 724 // Call save_settings hook for submission plugins.
bbd0e548
DW
725 foreach ($this->submissionplugins as $plugin) {
726 if (!$this->update_plugin_instance($plugin, $formdata)) {
727 print_error($plugin->get_error());
728 return false;
729 }
730 }
731 foreach ($this->feedbackplugins as $plugin) {
732 if (!$this->update_plugin_instance($plugin, $formdata)) {
733 print_error($plugin->get_error());
734 return false;
735 }
736 }
737
e5403f8c
DW
738 // In the case of upgrades the coursemodule has not been set,
739 // so we need to wait before calling these two.
bbd0e548 740 $this->update_calendar($formdata->coursemodule);
9ffbdafc
AG
741 if (!empty($formdata->completionexpected)) {
742 \core_completion\api::update_completion_date_event($formdata->coursemodule, 'assign', $this->instance,
743 $formdata->completionexpected);
744 }
bbd0e548
DW
745 $this->update_gradebook(false, $formdata->coursemodule);
746
747 }
748
749 $update = new stdClass();
750 $update->id = $this->get_instance()->id;
751 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
752 $DB->update_record('assign', $update);
753
754 return $returnid;
755 }
756
757 /**
e5403f8c 758 * Delete all grades from the gradebook for this assignment.
bbd0e548
DW
759 *
760 * @return bool
761 */
47f48152 762 protected function delete_grades() {
bbd0e548
DW
763 global $CFG;
764
e5403f8c
DW
765 $result = grade_update('mod/assign',
766 $this->get_course()->id,
767 'mod',
768 'assign',
769 $this->get_instance()->id,
770 0,
771 null,
772 array('deleted'=>1));
773 return $result == GRADE_UPDATE_OK;
bbd0e548
DW
774 }
775
776 /**
e5403f8c 777 * Delete this instance from the database.
bbd0e548
DW
778 *
779 * @return bool false if an error occurs
780 */
781 public function delete_instance() {
782 global $DB;
783 $result = true;
784
785 foreach ($this->submissionplugins as $plugin) {
786 if (!$plugin->delete_instance()) {
787 print_error($plugin->get_error());
788 $result = false;
789 }
790 }
791 foreach ($this->feedbackplugins as $plugin) {
792 if (!$plugin->delete_instance()) {
793 print_error($plugin->get_error());
794 $result = false;
795 }
796 }
797
e5403f8c 798 // Delete files associated with this assignment.
bbd0e548
DW
799 $fs = get_file_storage();
800 if (! $fs->delete_area_files($this->context->id) ) {
801 $result = false;
802 }
803
d685b959
IT
804 $this->delete_all_overrides();
805
e5403f8c 806 // Delete_records will throw an exception if it fails - so no need for error checking here.
26ac0abc
MN
807 $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id));
808 $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id));
809 $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id));
810 $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id));
811 $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id));
bbd0e548 812
e5403f8c 813 // Delete items from the gradebook.
bbd0e548
DW
814 if (! $this->delete_grades()) {
815 $result = false;
816 }
817
e5403f8c 818 // Delete the instance.
40fe1538 819 // We must delete the module record after we delete the grade item.
bbd0e548
DW
820 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
821
822 return $result;
823 }
824
d685b959
IT
825 /**
826 * Deletes a assign override from the database and clears any corresponding calendar events
827 *
828 * @param int $overrideid The id of the override being deleted
829 * @return bool true on success
830 */
831 public function delete_override($overrideid) {
832 global $CFG, $DB;
833
834 require_once($CFG->dirroot . '/calendar/lib.php');
835
f3ec5411
JP
836 $cm = $this->get_course_module();
837 if (empty($cm)) {
838 $instance = $this->get_instance();
839 $cm = get_coursemodule_from_instance('assign', $instance->id, $instance->course);
840 }
d685b959
IT
841
842 $override = $DB->get_record('assign_overrides', array('id' => $overrideid), '*', MUST_EXIST);
843
844 // Delete the events.
f3ec5411 845 $conds = array('modulename' => 'assign', 'instance' => $this->get_instance()->id);
d685b959
IT
846 if (isset($override->userid)) {
847 $conds['userid'] = $override->userid;
848 } else {
849 $conds['groupid'] = $override->groupid;
850 }
851 $events = $DB->get_records('event', $conds);
852 foreach ($events as $event) {
853 $eventold = calendar_event::load($event);
854 $eventold->delete();
855 }
856
857 $DB->delete_records('assign_overrides', array('id' => $overrideid));
858
859 // Set the common parameters for one of the events we will be triggering.
860 $params = array(
861 'objectid' => $override->id,
862 'context' => context_module::instance($cm->id),
863 'other' => array(
864 'assignid' => $override->assignid
865 )
866 );
867 // Determine which override deleted event to fire.
868 if (!empty($override->userid)) {
869 $params['relateduserid'] = $override->userid;
870 $event = \mod_assign\event\user_override_deleted::create($params);
871 } else {
872 $params['other']['groupid'] = $override->groupid;
873 $event = \mod_assign\event\group_override_deleted::create($params);
874 }
875
876 // Trigger the override deleted event.
877 $event->add_record_snapshot('assign_overrides', $override);
878 $event->trigger();
879
880 return true;
881 }
882
883 /**
884 * Deletes all assign overrides from the database and clears any corresponding calendar events
885 */
886 public function delete_all_overrides() {
887 global $DB;
888
f3ec5411 889 $overrides = $DB->get_records('assign_overrides', array('assignid' => $this->get_instance()->id), 'id');
d685b959
IT
890 foreach ($overrides as $override) {
891 $this->delete_override($override->id);
892 }
893 }
894
895 /**
896 * Updates the assign properties with override information for a user.
897 *
898 * Algorithm: For each assign setting, if there is a matching user-specific override,
899 * then use that otherwise, if there are group-specific overrides, return the most
900 * lenient combination of them. If neither applies, leave the assign setting unchanged.
901 *
902 * @param int $userid The userid.
903 */
904 public function update_effective_access($userid) {
905
906 $override = $this->override_exists($userid);
907
908 // Merge with assign defaults.
909 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
910 foreach ($keys as $key) {
911 if (isset($override->{$key})) {
912 $this->get_instance()->{$key} = $override->{$key};
913 }
914 }
915
916 }
917
a13f1f49
KH
918 /**
919 * Returns whether an assign has any overrides.
920 *
921 * @return true if any, false if not
922 */
923 public function has_overrides() {
924 global $DB;
925
926 $override = $DB->record_exists('assign_overrides', array('assignid' => $this->get_instance()->id));
927
928 if ($override) {
929 return true;
930 }
931
932 return false;
933 }
934
d685b959
IT
935 /**
936 * Returns user override
937 *
938 * Algorithm: For each assign setting, if there is a matching user-specific override,
26aedd4a
CB
939 * then use that otherwise, if there are group-specific overrides, use the one with the
940 * lowest sort order. If neither applies, leave the assign setting unchanged.
d685b959
IT
941 *
942 * @param int $userid The userid.
26aedd4a 943 * @return stdClass The override
d685b959
IT
944 */
945 public function override_exists($userid) {
946 global $DB;
947
26aedd4a
CB
948 // Gets an assoc array containing the keys for defined user overrides only.
949 $getuseroverride = function($userid) use ($DB) {
950 $useroverride = $DB->get_record('assign_overrides', ['assignid' => $this->get_instance()->id, 'userid' => $userid]);
951 return $useroverride ? get_object_vars($useroverride) : [];
952 };
d685b959 953
26aedd4a
CB
954 // Gets an assoc array containing the keys for defined group overrides only.
955 $getgroupoverride = function($userid) use ($DB) {
956 $groupings = groups_get_user_groups($this->get_instance()->course, $userid);
d685b959 957
26aedd4a
CB
958 if (empty($groupings[0])) {
959 return [];
960 }
d685b959 961
d685b959
IT
962 // Select all overrides that apply to the User's groups.
963 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
964 $sql = "SELECT * FROM {assign_overrides}
26aedd4a 965 WHERE groupid $extra AND assignid = ? ORDER BY sortorder ASC";
d685b959 966 $params[] = $this->get_instance()->id;
26aedd4a
CB
967 $groupoverride = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
968
969 return $groupoverride ? get_object_vars($groupoverride) : [];
970 };
971
972 // Later arguments clobber earlier ones with array_merge. The two helper functions
973 // return arrays containing keys for only the defined overrides. So we get the
974 // desired behaviour as per the algorithm.
975 return (object)array_merge(
976 ['duedate' => null, 'cutoffdate' => null, 'allowsubmissionsfromdate' => null],
977 $getgroupoverride($userid),
978 $getuseroverride($userid)
979 );
d685b959
IT
980 }
981
f4c21561
RW
982 /**
983 * Check if the given calendar_event is either a user or group override
984 * event.
985 *
986 * @return bool
987 */
988 public function is_override_calendar_event(\calendar_event $event) {
989 global $DB;
990
991 if (!isset($event->modulename)) {
992 return false;
993 }
994
995 if ($event->modulename != 'assign') {
996 return false;
997 }
998
999 if (!isset($event->instance)) {
1000 return false;
1001 }
1002
1003 if (!isset($event->userid) && !isset($event->groupid)) {
1004 return false;
1005 }
1006
1007 $overrideparams = [
1008 'assignid' => $event->instance
1009 ];
1010
1011 if (isset($event->groupid)) {
1012 $overrideparams['groupid'] = $event->groupid;
1013 } else if (isset($event->userid)) {
1014 $overrideparams['userid'] = $event->userid;
1015 }
1016
1017 if ($DB->get_record('assign_overrides', $overrideparams)) {
1018 return true;
1019 } else {
1020 return false;
1021 }
1022 }
1023
1024 /**
1025 * This function calculates the minimum and maximum cutoff values for the timestart of
1026 * the given event.
1027 *
1028 * It will return an array with two values, the first being the minimum cutoff value and
1029 * the second being the maximum cutoff value. Either or both values can be null, which
1030 * indicates there is no minimum or maximum, respectively.
1031 *
1032 * If a cutoff is required then the function must return an array containing the cutoff
1033 * timestamp and error string to display to the user if the cutoff value is violated.
1034 *
1035 * A minimum and maximum cutoff return value will look like:
1036 * [
1037 * [1505704373, 'The due date must be after the sbumission start date'],
1038 * [1506741172, 'The due date must be before the cutoff date']
1039 * ]
1040 *
6688ae2b
RW
1041 * If the event does not have a valid timestart range then [false, false] will
1042 * be returned.
1043 *
f4c21561 1044 * @param calendar_event $event The calendar event to get the time range for
6688ae2b 1045 * @return array
f4c21561
RW
1046 */
1047 function get_valid_calendar_event_timestart_range(\calendar_event $event) {
1048 $instance = $this->get_instance();
1049 $submissionsfromdate = $instance->allowsubmissionsfromdate;
1050 $cutoffdate = $instance->cutoffdate;
1051 $duedate = $instance->duedate;
1052 $gradingduedate = $instance->gradingduedate;
1053 $mindate = null;
1054 $maxdate = null;
1055
1056 if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
1057 // This check is in here because due date events are currently
1058 // the only events that can be overridden, so we can save a DB
1059 // query if we don't bother checking other events.
1060 if ($this->is_override_calendar_event($event)) {
6688ae2b
RW
1061 // This is an override event so there is no valid timestart
1062 // range to set it to.
1063 return [false, false];
f4c21561
RW
1064 }
1065
1066 if ($submissionsfromdate) {
1067 $mindate = [
1068 $submissionsfromdate,
1069 get_string('duedatevalidation', 'assign'),
1070 ];
1071 }
1072
1073 if ($cutoffdate) {
1074 $maxdate = [
1075 $cutoffdate,
1076 get_string('cutoffdatevalidation', 'assign'),
1077 ];
1078 }
1079
1080 if ($gradingduedate) {
1081 // If we don't have a cutoff date or we've got a grading due date
1082 // that is earlier than the cutoff then we should use that as the
1083 // upper limit for the due date.
1084 if (!$cutoffdate || $gradingduedate < $cutoffdate) {
1085 $maxdate = [
1086 $gradingduedate,
1087 get_string('gradingdueduedatevalidation', 'assign'),
1088 ];
1089 }
1090 }
1091 } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1092 if ($duedate) {
1093 $mindate = [
1094 $duedate,
1095 get_string('gradingdueduedatevalidation', 'assign'),
1096 ];
1097 } else if ($submissionsfromdate) {
1098 $mindate = [
1099 $submissionsfromdate,
1100 get_string('gradingduefromdatevalidation', 'assign'),
1101 ];
1102 }
1103 }
1104
1105 return [$mindate, $maxdate];
1106 }
1107
d38dc52f 1108 /**
e5403f8c
DW
1109 * Actual implementation of the reset course functionality, delete all the
1110 * assignment submissions for course $data->courseid.
1111 *
1561a37c 1112 * @param stdClass $data the data submitted from the reset course.
e5403f8c
DW
1113 * @return array status array
1114 */
d38dc52f 1115 public function reset_userdata($data) {
e5403f8c 1116 global $CFG, $DB;
d38dc52f
RW
1117
1118 $componentstr = get_string('modulenameplural', 'assign');
1119 $status = array();
1120
1121 $fs = get_file_storage();
1122 if (!empty($data->reset_assign_submissions)) {
1123 // Delete files associated with this assignment.
1124 foreach ($this->submissionplugins as $plugin) {
1125 $fileareas = array();
1126 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
1127 $fileareas = $plugin->get_file_areas();
43fb9ced 1128 foreach ($fileareas as $filearea => $notused) {
d38dc52f
RW
1129 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
1130 }
1131
1132 if (!$plugin->delete_instance()) {
1133 $status[] = array('component'=>$componentstr,
e5403f8c 1134 'item'=>get_string('deleteallsubmissions', 'assign'),
d38dc52f
RW
1135 'error'=>$plugin->get_error());
1136 }
1137 }
1138
1139 foreach ($this->feedbackplugins as $plugin) {
1140 $fileareas = array();
1141 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
1142 $fileareas = $plugin->get_file_areas();
43fb9ced 1143 foreach ($fileareas as $filearea => $notused) {
d38dc52f
RW
1144 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
1145 }
1146
1147 if (!$plugin->delete_instance()) {
1148 $status[] = array('component'=>$componentstr,
e5403f8c 1149 'item'=>get_string('deleteallsubmissions', 'assign'),
d38dc52f
RW
1150 'error'=>$plugin->get_error());
1151 }
1152 }
1153
26ac0abc
MN
1154 $assignids = $DB->get_records('assign', array('course' => $data->courseid), '', 'id');
1155 list($sql, $params) = $DB->get_in_or_equal(array_keys($assignids));
d38dc52f 1156
26ac0abc
MN
1157 $DB->delete_records_select('assign_submission', "assignment $sql", $params);
1158 $DB->delete_records_select('assign_user_flags', "assignment $sql", $params);
e5403f8c 1159
d38dc52f 1160 $status[] = array('component'=>$componentstr,
e5403f8c 1161 'item'=>get_string('deleteallsubmissions', 'assign'),
d38dc52f
RW
1162 'error'=>false);
1163
e5403f8c 1164 if (!empty($data->reset_gradebook_grades)) {
26ac0abc 1165 $DB->delete_records_select('assign_grades', "assignment $sql", $params);
d38dc52f
RW
1166 // Remove all grades from gradebook.
1167 require_once($CFG->dirroot.'/mod/assign/lib.php');
1168 assign_reset_gradebook($data->courseid);
1a9e8542 1169 }
48242bf3 1170
1a9e8542
ZT
1171 // Reset revealidentities for assign if blindmarking is enabled.
1172 if ($this->get_instance()->blindmarking) {
1173 $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id));
d38dc52f
RW
1174 }
1175 }
d685b959
IT
1176
1177 // Remove user overrides.
1178 if (!empty($data->reset_assign_user_overrides)) {
1179 $DB->delete_records_select('assign_overrides',
1180 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1181 $status[] = array(
1182 'component' => $componentstr,
1183 'item' => get_string('useroverridesdeleted', 'assign'),
1184 'error' => false);
1185 }
1186 // Remove group overrides.
1187 if (!empty($data->reset_assign_group_overrides)) {
1188 $DB->delete_records_select('assign_overrides',
1189 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1190 $status[] = array(
1191 'component' => $componentstr,
1192 'item' => get_string('groupoverridesdeleted', 'assign'),
1193 'error' => false);
1194 }
1195
d38dc52f
RW
1196 // Updating dates - shift may be negative too.
1197 if ($data->timeshift) {
d685b959
IT
1198 $DB->execute("UPDATE {assign_overrides}
1199 SET allowsubmissionsfromdate = allowsubmissionsfromdate + ?
1200 WHERE assignid = ? AND allowsubmissionsfromdate <> 0",
1201 array($data->timeshift, $this->get_instance()->id));
1202 $DB->execute("UPDATE {assign_overrides}
1203 SET duedate = duedate + ?
1204 WHERE assignid = ? AND duedate <> 0",
1205 array($data->timeshift, $this->get_instance()->id));
1206 $DB->execute("UPDATE {assign_overrides}
1207 SET cutoffdate = cutoffdate + ?
1208 WHERE assignid =? AND cutoffdate <> 0",
1209 array($data->timeshift, $this->get_instance()->id));
1210
0d14fcbc
AA
1211 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1212 // See MDL-9367.
d38dc52f 1213 shift_course_mod_dates('assign',
e5403f8c 1214 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
d38dc52f 1215 $data->timeshift,
e63515ba 1216 $data->courseid, $this->get_instance()->id);
d38dc52f
RW
1217 $status[] = array('component'=>$componentstr,
1218 'item'=>get_string('datechanged'),
1219 'error'=>false);
1220 }
1221
1222 return $status;
1223 }
1224
bbd0e548 1225 /**
e5403f8c 1226 * Update the settings for a single plugin.
bbd0e548
DW
1227 *
1228 * @param assign_plugin $plugin The plugin to update
1229 * @param stdClass $formdata The form data
1230 * @return bool false if an error occurs
1231 */
47f48152 1232 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
bbd0e548
DW
1233 if ($plugin->is_visible()) {
1234 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
b0da618b 1235 if (!empty($formdata->$enabledname)) {
bbd0e548
DW
1236 $plugin->enable();
1237 if (!$plugin->save_settings($formdata)) {
1238 print_error($plugin->get_error());
1239 return false;
1240 }
1241 } else {
1242 $plugin->disable();
1243 }
1244 }
1245 return true;
1246 }
1247
1248 /**
e5403f8c 1249 * Update the gradebook information for this assignment.
bbd0e548
DW
1250 *
1251 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
1252 * @param int $coursemoduleid This is required because it might not exist in the database yet
1253 * @return bool
1254 */
1255 public function update_gradebook($reset, $coursemoduleid) {
e5403f8c
DW
1256 global $CFG;
1257
bbd0e548
DW
1258 require_once($CFG->dirroot.'/mod/assign/lib.php');
1259 $assign = clone $this->get_instance();
1260 $assign->cmidnumber = $coursemoduleid;
456d7bc7
RT
1261
1262 // Set assign gradebook feedback plugin status (enabled and visible).
1263 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
1264
bbd0e548
DW
1265 $param = null;
1266 if ($reset) {
1267 $param = 'reset';
1268 }
1269
1270 return assign_grade_item_update($assign, $param);
1271 }
1272
80989850
BH
1273 /**
1274 * Get the marking table page size
1275 *
1276 * @return integer
1277 */
1278 public function get_assign_perpage() {
1279 $perpage = (int) get_user_preferences('assign_perpage', 10);
1280 $adminconfig = $this->get_admin_config();
1281 $maxperpage = -1;
1282 if (isset($adminconfig->maxperpage)) {
1283 $maxperpage = $adminconfig->maxperpage;
1284 }
1285 if (isset($maxperpage) &&
1286 $maxperpage != -1 &&
1287 ($perpage == -1 || $perpage > $maxperpage)) {
1288 $perpage = $maxperpage;
1289 }
1290 return $perpage;
1291 }
1292
e5403f8c
DW
1293 /**
1294 * Load and cache the admin config for this module.
bc5a657b 1295 *
cfc81f03
DW
1296 * @return stdClass the plugin config
1297 */
1298 public function get_admin_config() {
1299 if ($this->adminconfig) {
1300 return $this->adminconfig;
1301 }
b11808c7 1302 $this->adminconfig = get_config('assign');
cfc81f03
DW
1303 return $this->adminconfig;
1304 }
1305
bbd0e548 1306 /**
e5403f8c 1307 * Update the calendar entries for this assignment.
bbd0e548 1308 *
e5403f8c
DW
1309 * @param int $coursemoduleid - Required to pass this in because it might
1310 * not exist in the database yet.
bbd0e548
DW
1311 * @return bool
1312 */
1313 public function update_calendar($coursemoduleid) {
1314 global $DB, $CFG;
1315 require_once($CFG->dirroot.'/calendar/lib.php');
1316
e5403f8c
DW
1317 // Special case for add_instance as the coursemodule has not been set yet.
1318 $instance = $this->get_instance();
bbd0e548 1319
294dce67
MN
1320 // Start with creating the event.
1321 $event = new stdClass();
1322 $event->modulename = 'assign';
1323 $event->courseid = $instance->course;
1324 $event->groupid = 0;
1325 $event->userid = 0;
1326 $event->instance = $instance->id;
294dce67
MN
1327 $event->type = CALENDAR_EVENT_TYPE_ACTION;
1328
1329 // Convert the links to pluginfile. It is a bit hacky but at this stage the files
1330 // might not have been saved in the module area yet.
1331 $intro = $instance->intro;
1332 if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
1333 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
1334 }
1335
1336 // We need to remove the links to files as the calendar is not ready
1337 // to support module events with file areas.
1338 $intro = strip_pluginfile_content($intro);
1339 if ($this->show_intro()) {
1340 $event->description = array(
1341 'text' => $intro,
1342 'format' => $instance->introformat
1343 );
1344 } else {
1345 $event->description = array(
1346 'text' => '',
1347 'format' => $instance->introformat
1348 );
1349 }
72797e68 1350
294dce67 1351 $eventtype = ASSIGN_EVENT_TYPE_DUE;
e5403f8c 1352 if ($instance->duedate) {
f10721d6 1353 $event->name = get_string('calendardue', 'assign', $instance->name);
294dce67
MN
1354 $event->eventtype = $eventtype;
1355 $event->timestart = $instance->duedate;
1356 $event->timesort = $instance->duedate;
98239b2d
JP
1357 $select = "modulename = :modulename
1358 AND instance = :instance
1359 AND eventtype = :eventtype
1360 AND groupid = 0
1361 AND courseid <> 0";
72797e68 1362 $params = array('modulename' => 'assign', 'instance' => $instance->id, 'eventtype' => $eventtype);
98239b2d 1363 $event->id = $DB->get_field_select('event', 'id', $select, $params);
0cfc7d13 1364
294dce67
MN
1365 // Now process the event.
1366 if ($event->id) {
e1cd93ce 1367 $calendarevent = calendar_event::load($event->id);
bbf1fde4 1368 $calendarevent->update($event, false);
ae7638f7 1369 } else {
bbf1fde4 1370 calendar_event::create($event, false);
ae7638f7 1371 }
294dce67
MN
1372 } else {
1373 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1374 'eventtype' => $eventtype));
1375 }
bbd0e548 1376
294dce67
MN
1377 $eventtype = ASSIGN_EVENT_TYPE_GRADINGDUE;
1378 if ($instance->gradingduedate) {
f10721d6 1379 $event->name = get_string('calendargradingdue', 'assign', $instance->name);
294dce67
MN
1380 $event->eventtype = $eventtype;
1381 $event->timestart = $instance->gradingduedate;
1382 $event->timesort = $instance->gradingduedate;
1383 $event->id = $DB->get_field('event', 'id', array('modulename' => 'assign',
1384 'instance' => $instance->id, 'eventtype' => $event->eventtype));
1385
1386 // Now process the event.
0cfc7d13 1387 if ($event->id) {
bbd0e548 1388 $calendarevent = calendar_event::load($event->id);
bbf1fde4 1389 $calendarevent->update($event, false);
bbd0e548 1390 } else {
bbf1fde4 1391 calendar_event::create($event, false);
bbd0e548
DW
1392 }
1393 } else {
294dce67
MN
1394 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1395 'eventtype' => $eventtype));
bbd0e548 1396 }
bbd0e548 1397
294dce67
MN
1398 return true;
1399 }
bbd0e548
DW
1400
1401 /**
e5403f8c 1402 * Update this instance in the database.
bbd0e548
DW
1403 *
1404 * @param stdClass $formdata - the data submitted from the form
1405 * @return bool false if an error occurs
1406 */
1407 public function update_instance($formdata) {
1408 global $DB;
8e1266bf 1409 $adminconfig = $this->get_admin_config();
bbd0e548
DW
1410
1411 $update = new stdClass();
1412 $update->id = $formdata->instance;
1413 $update->name = $formdata->name;
1414 $update->timemodified = time();
1415 $update->course = $formdata->course;
1416 $update->intro = $formdata->intro;
1417 $update->introformat = $formdata->introformat;
18de52db 1418 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
bbd0e548 1419 $update->submissiondrafts = $formdata->submissiondrafts;
94f26900 1420 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
bbd0e548 1421 $update->sendnotifications = $formdata->sendnotifications;
75f87a57 1422 $update->sendlatenotifications = $formdata->sendlatenotifications;
8e1266bf
DW
1423 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
1424 if (isset($formdata->sendstudentnotifications)) {
1425 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
1426 }
b618f2d9 1427 $update->duedate = $formdata->duedate;
9e795179 1428 $update->cutoffdate = $formdata->cutoffdate;
3e1c0275 1429 $update->gradingduedate = $formdata->gradingduedate;
bbd0e548
DW
1430 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
1431 $update->grade = $formdata->grade;
a9f5fc15 1432 if (!empty($formdata->completionunlocked)) {
1433 $update->completionsubmit = !empty($formdata->completionsubmit);
1434 }
12a1a0da
DW
1435 $update->teamsubmission = $formdata->teamsubmission;
1436 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
1fba9cf6
DW
1437 if (isset($formdata->teamsubmissiongroupingid)) {
1438 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
1439 }
f14afd29
AW
1440 if (isset($formdata->hidegrader)) {
1441 $update->hidegrader = $formdata->hidegrader;
1442 }
b473171a 1443 $update->blindmarking = $formdata->blindmarking;
e8490064
DW
1444 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
1445 if (!empty($formdata->attemptreopenmethod)) {
1446 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
1447 }
df211804
DW
1448 if (!empty($formdata->maxattempts)) {
1449 $update->maxattempts = $formdata->maxattempts;
1450 }
e528997a
AH
1451 if (isset($formdata->preventsubmissionnotingroup)) {
1452 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
1453 }
f8d107b3
DM
1454 $update->markingworkflow = $formdata->markingworkflow;
1455 $update->markingallocation = $formdata->markingallocation;
5a96486b
DM
1456 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
1457 $update->markingallocation = 0;
1458 }
12a1a0da 1459
bbd0e548
DW
1460 $result = $DB->update_record('assign', $update);
1461 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
1462
7faf78cb
HB
1463 $this->save_intro_draft_files($formdata);
1464
e5403f8c 1465 // Load the assignment so the plugins have access to it.
bbd0e548 1466
e5403f8c 1467 // Call save_settings hook for submission plugins.
bbd0e548
DW
1468 foreach ($this->submissionplugins as $plugin) {
1469 if (!$this->update_plugin_instance($plugin, $formdata)) {
1470 print_error($plugin->get_error());
1471 return false;
1472 }
1473 }
1474 foreach ($this->feedbackplugins as $plugin) {
1475 if (!$this->update_plugin_instance($plugin, $formdata)) {
1476 print_error($plugin->get_error());
1477 return false;
1478 }
1479 }
1480
bbd0e548 1481 $this->update_calendar($this->get_course_module()->id);
9ffbdafc
AG
1482 $completionexpected = (!empty($formdata->completionexpected)) ? $formdata->completionexpected : null;
1483 \core_completion\api::update_completion_date_event($this->get_course_module()->id, 'assign', $this->instance,
1484 $completionexpected);
bbd0e548
DW
1485 $this->update_gradebook(false, $this->get_course_module()->id);
1486
1487 $update = new stdClass();
1488 $update->id = $this->get_instance()->id;
1489 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
1490 $DB->update_record('assign', $update);
1491
bbd0e548
DW
1492 return $result;
1493 }
1494
7faf78cb
HB
1495 /**
1496 * Save the attachments in the draft areas.
1497 *
1498 * @param stdClass $formdata
1499 */
1500 protected function save_intro_draft_files($formdata) {
1501 if (isset($formdata->introattachments)) {
1502 file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1503 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1504 }
1505 }
1506
bbd0e548 1507 /**
e5403f8c 1508 * Add elements in grading plugin form.
bbd0e548
DW
1509 *
1510 * @param mixed $grade stdClass|null
1511 * @param MoodleQuickForm $mform
1512 * @param stdClass $data
fc7b7d52 1513 * @param int $userid - The userid we are grading
bbd0e548
DW
1514 * @return void
1515 */
47f48152 1516 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
bbd0e548
DW
1517 foreach ($this->feedbackplugins as $plugin) {
1518 if ($plugin->is_enabled() && $plugin->is_visible()) {
3a5c3b3c 1519 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
bbd0e548
DW
1520 }
1521 }
1522 }
1523
1524
1525
1526 /**
e5403f8c 1527 * Add one plugins settings to edit plugin form.
bbd0e548
DW
1528 *
1529 * @param assign_plugin $plugin The plugin to add the settings from
e5403f8c
DW
1530 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1531 * This form is modified directly (not returned).
b0da618b
DW
1532 * @param array $pluginsenabled A list of form elements to be added to a group.
1533 * The new element is added to this array by this function.
bbd0e548
DW
1534 * @return void
1535 */
b0da618b 1536 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
bbd0e548 1537 global $CFG;
f159ad73 1538 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1539 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1540 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1541 $mform->setType($name, PARAM_BOOL);
1542 $plugin->get_settings($mform);
1543 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
b0da618b
DW
1544 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1545 $label = $plugin->get_name();
b0da618b 1546 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
9ed5b0c1
TB
1547 $helpicon = $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1548 $pluginsenabled[] = $mform->createElement('static', '', '', $helpicon);
bbd0e548 1549
cfc81f03 1550 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
bbd0e548
DW
1551 if ($plugin->get_config('enabled') !== false) {
1552 $default = $plugin->is_enabled();
1553 }
1554 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1555
1556 $plugin->get_settings($mform);
1557
1558 }
bbd0e548
DW
1559 }
1560
bbd0e548 1561 /**
e5403f8c 1562 * Add settings to edit plugin form.
bbd0e548 1563 *
e5403f8c
DW
1564 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1565 * This form is modified directly (not returned).
bbd0e548
DW
1566 * @return void
1567 */
1568 public function add_all_plugin_settings(MoodleQuickForm $mform) {
df211804 1569 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
bbd0e548 1570
b0da618b
DW
1571 $submissionpluginsenabled = array();
1572 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
bbd0e548 1573 foreach ($this->submissionplugins as $plugin) {
b0da618b 1574 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
bbd0e548 1575 }
b0da618b
DW
1576 $group->setElements($submissionpluginsenabled);
1577
df211804 1578 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
b0da618b
DW
1579 $feedbackpluginsenabled = array();
1580 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
bbd0e548 1581 foreach ($this->feedbackplugins as $plugin) {
b0da618b 1582 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
bbd0e548 1583 }
b0da618b
DW
1584 $group->setElements($feedbackpluginsenabled);
1585 $mform->setExpanded('submissiontypes');
bbd0e548
DW
1586 }
1587
1588 /**
1589 * Allow each plugin an opportunity to update the defaultvalues
1590 * passed in to the settings form (needed to set up draft areas for
1591 * editor and filemanager elements)
e5403f8c 1592 *
bbd0e548
DW
1593 * @param array $defaultvalues
1594 */
1595 public function plugin_data_preprocessing(&$defaultvalues) {
1596 foreach ($this->submissionplugins as $plugin) {
1597 if ($plugin->is_visible()) {
1598 $plugin->data_preprocessing($defaultvalues);
1599 }
1600 }
1601 foreach ($this->feedbackplugins as $plugin) {
1602 if ($plugin->is_visible()) {
1603 $plugin->data_preprocessing($defaultvalues);
1604 }
1605 }
1606 }
1607
1608 /**
1609 * Get the name of the current module.
1610 *
1611 * @return string the module name (Assignment)
1612 */
1613 protected function get_module_name() {
1614 if (isset(self::$modulename)) {
1615 return self::$modulename;
1616 }
1617 self::$modulename = get_string('modulename', 'assign');
1618 return self::$modulename;
1619 }
1620
1621 /**
1622 * Get the plural name of the current module.
1623 *
1624 * @return string the module name plural (Assignments)
1625 */
1626 protected function get_module_name_plural() {
1627 if (isset(self::$modulenameplural)) {
1628 return self::$modulenameplural;
1629 }
1630 self::$modulenameplural = get_string('modulenameplural', 'assign');
1631 return self::$modulenameplural;
1632 }
1633
1634 /**
1635 * Has this assignment been constructed from an instance?
1636 *
1637 * @return bool
1638 */
1639 public function has_instance() {
1640 return $this->instance || $this->get_course_module();
1641 }
1642
1643 /**
db381d5c 1644 * Get the settings for the current instance of this assignment.
bbd0e548
DW
1645 *
1646 * @return stdClass The settings
db381d5c 1647 * @throws dml_exception
bbd0e548 1648 */
db381d5c 1649 public function get_default_instance() {
bbd0e548 1650 global $DB;
db381d5c 1651 if (!$this->instance && $this->get_course_module()) {
e5403f8c
DW
1652 $params = array('id' => $this->get_course_module()->instance);
1653 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
db381d5c
JD
1654
1655 $this->userinstances = [];
bbd0e548
DW
1656 }
1657 return $this->instance;
1658 }
1659
db381d5c
JD
1660 /**
1661 * Get the settings for the current instance of this assignment
1662 * @param int|null $userid the id of the user to load the assign instance for.
1663 * @return stdClass The settings
1664 */
1665 public function get_instance(int $userid = null) : stdClass {
1666 global $USER;
1667 $userid = $userid ?? $USER->id;
1668
1669 $this->instance = $this->get_default_instance();
1670
1671 // If we have the user instance already, just return it.
1672 if (isset($this->userinstances[$userid])) {
1673 return $this->userinstances[$userid];
1674 }
1675
1676 // Calculate properties which vary per user.
1677 $this->userinstances[$userid] = $this->calculate_properties($this->instance, $userid);
1678 return $this->userinstances[$userid];
1679 }
1680
1681 /**
1682 * Calculates and updates various properties based on the specified user.
1683 *
1684 * @param stdClass $record the raw assign record.
1685 * @param int $userid the id of the user to calculate the properties for.
1686 * @return stdClass a new record having calculated properties.
1687 */
1688 private function calculate_properties(\stdClass $record, int $userid) : \stdClass {
1689 $record = clone ($record);
1690
1691 // Relative dates.
1692 if (!empty($record->duedate)) {
1693 $course = $this->get_course();
1694 $usercoursedates = course_get_course_dates_for_user_id($course, $userid);
1695 if ($usercoursedates['start']) {
1696 $userprops = ['duedate' => $record->duedate + $usercoursedates['startoffset']];
1697 $record = (object) array_merge((array) $record, (array) $userprops);
1698 }
1699 }
1700 return $record;
1701 }
1702
0d64c75f
PN
1703 /**
1704 * Get the primary grade item for this assign instance.
1705 *
db8514bc 1706 * @return grade_item The grade_item record
0d64c75f
PN
1707 */
1708 public function get_grade_item() {
1709 if ($this->gradeitem) {
1710 return $this->gradeitem;
1711 }
1712 $instance = $this->get_instance();
1713 $params = array('itemtype' => 'mod',
1714 'itemmodule' => 'assign',
1715 'iteminstance' => $instance->id,
1716 'courseid' => $instance->course,
1717 'itemnumber' => 0);
1718 $this->gradeitem = grade_item::fetch($params);
1719 if (!$this->gradeitem) {
1720 throw new coding_exception('Improper use of the assignment class. ' .
1721 'Cannot load the grade item.');
1722 }
1723 return $this->gradeitem;
1724 }
1725
bbd0e548 1726 /**
e5403f8c
DW
1727 * Get the context of the current course.
1728 *
bbd0e548
DW
1729 * @return mixed context|null The course context
1730 */
1731 public function get_course_context() {
1732 if (!$this->context && !$this->course) {
e5403f8c
DW
1733 throw new coding_exception('Improper use of the assignment class. ' .
1734 'Cannot load the course context.');
bbd0e548
DW
1735 }
1736 if ($this->context) {
1737 return $this->context->get_course_context();
1738 } else {
1739 return context_course::instance($this->course->id);
1740 }
1741 }
1742
1743
1744 /**
e5403f8c 1745 * Get the current course module.
bbd0e548 1746 *
c13ac85d 1747 * @return cm_info|null The course module or null if not known
bbd0e548
DW
1748 */
1749 public function get_course_module() {
1750 if ($this->coursemodule) {
1751 return $this->coursemodule;
1752 }
1753 if (!$this->context) {
1754 return null;
1755 }
1756
1757 if ($this->context->contextlevel == CONTEXT_MODULE) {
c13ac85d 1758 $modinfo = get_fast_modinfo($this->get_course());
1759 $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
bbd0e548
DW
1760 return $this->coursemodule;
1761 }
1762 return null;
1763 }
1764
1765 /**
e5403f8c 1766 * Get context module.
bbd0e548
DW
1767 *
1768 * @return context
1769 */
1770 public function get_context() {
1771 return $this->context;
1772 }
1773
1774 /**
e5403f8c
DW
1775 * Get the current course.
1776 *
bbd0e548
DW
1777 * @return mixed stdClass|null The course
1778 */
1779 public function get_course() {
1780 global $DB;
e5403f8c 1781
db381d5c 1782 if ($this->course && is_object($this->course)) {
bbd0e548
DW
1783 return $this->course;
1784 }
1785
1786 if (!$this->context) {
1787 return null;
1788 }
e5403f8c
DW
1789 $params = array('id' => $this->get_course_context()->instanceid);
1790 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1791
bbd0e548
DW
1792 return $this->course;
1793 }
1794
7faf78cb
HB
1795 /**
1796 * Count the number of intro attachments.
1797 *
1798 * @return int
1799 */
1800 protected function count_attachments() {
1801
1802 $fs = get_file_storage();
1803 $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1804 0, 'id', false);
1805
1806 return count($files);
1807 }
1808
1809 /**
1810 * Are there any intro attachments to display?
1811 *
1812 * @return boolean
1813 */
1814 protected function has_visible_attachments() {
1815 return ($this->count_attachments() > 0);
1816 }
1817
bbd0e548 1818 /**
e5403f8c 1819 * Return a grade in user-friendly form, whether it's a scale or not.
bbd0e548 1820 *
9682626e 1821 * @param mixed $grade int|null
bf78ebd6 1822 * @param boolean $editing Are we allowing changes to this grade?
2a4fbc32
SH
1823 * @param int $userid The user id the grade belongs to
1824 * @param int $modified Timestamp from when the grade was last modified
bbd0e548
DW
1825 * @return string User-friendly representation of grade
1826 */
bf78ebd6 1827 public function display_grade($grade, $editing, $userid=0, $modified=0) {
bbd0e548
DW
1828 global $DB;
1829
1830 static $scalegrades = array();
1831
be79d93f
DW
1832 $o = '';
1833
2a4fbc32 1834 if ($this->get_instance()->grade >= 0) {
e5403f8c 1835 // Normal number.
e7ade405 1836 if ($editing && $this->get_instance()->grade > 0) {
2d8a9ce9
DW
1837 if ($grade < 0) {
1838 $displaygrade = '';
1839 } else {
40e0baf0 1840 $displaygrade = format_float($grade, $this->get_grade_item()->get_decimals());
2d8a9ce9 1841 }
e5403f8c
DW
1842 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1843 get_string('usergrade', 'assign') .
1844 '</label>';
1845 $o .= '<input type="text"
1846 id="quickgrade_' . $userid . '"
1847 name="quickgrade_' . $userid . '"
1848 value="' . $displaygrade . '"
1849 size="6"
1850 maxlength="10"
1851 class="quickgrade"/>';
40e0baf0 1852 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, $this->get_grade_item()->get_decimals());
bf78ebd6 1853 return $o;
bbd0e548 1854 } else {
a1e54f4d 1855 if ($grade == -1 || $grade === null) {
be79d93f 1856 $o .= '-';
a1e54f4d 1857 } else {
0d64c75f
PN
1858 $item = $this->get_grade_item();
1859 $o .= grade_format_gradevalue($grade, $item);
1860 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1861 // If displaying the raw grade, also display the total value.
40e0baf0 1862 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, $item->get_decimals());
0d64c75f 1863 }
a1e54f4d 1864 }
0d64c75f 1865 return $o;
bbd0e548
DW
1866 }
1867
2a4fbc32 1868 } else {
e5403f8c 1869 // Scale.
bbd0e548
DW
1870 if (empty($this->cache['scale'])) {
1871 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1872 $this->cache['scale'] = make_menu_from_list($scale->scale);
1873 } else {
be79d93f
DW
1874 $o .= '-';
1875 return $o;
bbd0e548
DW
1876 }
1877 }
bf78ebd6 1878 if ($editing) {
e5403f8c
DW
1879 $o .= '<label class="accesshide"
1880 for="quickgrade_' . $userid . '">' .
1881 get_string('usergrade', 'assign') .
1882 '</label>';
7400be1b 1883 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
bf78ebd6
DW
1884 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1885 foreach ($this->cache['scale'] as $optionid => $option) {
1886 $selected = '';
1887 if ($grade == $optionid) {
1888 $selected = 'selected="selected"';
1889 }
1890 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1891 }
1892 $o .= '</select>';
bf78ebd6
DW
1893 return $o;
1894 } else {
1895 $scaleid = (int)$grade;
1896 if (isset($this->cache['scale'][$scaleid])) {
be79d93f
DW
1897 $o .= $this->cache['scale'][$scaleid];
1898 return $o;
bf78ebd6 1899 }
be79d93f
DW
1900 $o .= '-';
1901 return $o;
bbd0e548 1902 }
bbd0e548
DW
1903 }
1904 }
1905
bb690849 1906 /**
1b2f9dc6
RW
1907 * Get the submission status/grading status for all submissions in this assignment for the
1908 * given paticipants.
1909 *
eb43ef6c 1910 * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
bb690849
DW
1911 * If this is a group assignment, group info is also returned.
1912 *
1b2f9dc6
RW
1913 * @param array $participants an associative array where the key is the participant id and
1914 * the value is the participant record.
1915 * @return array an associative array where the key is the participant id and the value is
1916 * the participant record.
bb690849 1917 */
1b2f9dc6 1918 private function get_submission_info_for_participants($participants) {
bb690849
DW
1919 global $DB;
1920
bb690849
DW
1921 if (empty($participants)) {
1922 return $participants;
1923 }
1924
1925 list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1926
1927 $assignid = $this->get_instance()->id;
1928 $params['assignmentid1'] = $assignid;
1929 $params['assignmentid2'] = $assignid;
eb43ef6c 1930 $params['assignmentid3'] = $assignid;
bb690849 1931
eb43ef6c 1932 $fields = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade, uf.extensionduedate';
c06ce32d 1933 $from = ' FROM {user} u
bb690849
DW
1934 LEFT JOIN {assign_submission} s
1935 ON u.id = s.userid
1936 AND s.assignment = :assignmentid1
1937 AND s.latest = 1
1938 LEFT JOIN {assign_grades} g
1939 ON u.id = g.userid
1940 AND g.assignment = :assignmentid2
1941 AND g.attemptnumber = s.attemptnumber
eb43ef6c
TB
1942 LEFT JOIN {assign_user_flags} uf
1943 ON u.id = uf.userid
1944 AND uf.assignment = :assignmentid3
c06ce32d
AN
1945 ';
1946 $where = ' WHERE u.id ' . $insql;
1947
1948 if (!empty($this->get_instance()->blindmarking)) {
1949 $from .= 'LEFT JOIN {assign_user_mapping} um
1950 ON u.id = um.userid
eb43ef6c
TB
1951 AND um.assignment = :assignmentid4 ';
1952 $params['assignmentid4'] = $assignid;
c06ce32d
AN
1953 $fields .= ', um.id as recordid ';
1954 }
1955
1956 $sql = "$fields $from $where";
bb690849
DW
1957
1958 $records = $DB->get_records_sql($sql, $params);
1959
1960 if ($this->get_instance()->teamsubmission) {
1961 // Get all groups.
1962 $allgroups = groups_get_all_groups($this->get_course()->id,
1963 array_keys($participants),
1964 $this->get_instance()->teamsubmissiongroupingid,
1965 'DISTINCT g.id, g.name');
1966
1967 }
1968 foreach ($participants as $userid => $participant) {
1969 $participants[$userid]->fullname = $this->fullname($participant);
1970 $participants[$userid]->submitted = false;
1971 $participants[$userid]->requiregrading = false;
eb43ef6c 1972 $participants[$userid]->grantedextension = false;
bb690849
DW
1973 }
1974
1975 foreach ($records as $userid => $submissioninfo) {
1976 // These filters are 100% the same as the ones in the grading table SQL.
1977 $submitted = false;
1978 $requiregrading = false;
eb43ef6c 1979 $grantedextension = false;
bb690849
DW
1980
1981 if (!empty($submissioninfo->stime) && $submissioninfo->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1982 $submitted = true;
1983 }
1984
1985 if ($submitted && ($submissioninfo->stime >= $submissioninfo->gtime ||
1986 empty($submissioninfo->gtime) ||
1987 $submissioninfo->grade === null)) {
1988 $requiregrading = true;
1989 }
1990
eb43ef6c
TB
1991 if (!empty($submissioninfo->extensionduedate)) {
1992 $grantedextension = true;
1993 }
1994
bb690849
DW
1995 $participants[$userid]->submitted = $submitted;
1996 $participants[$userid]->requiregrading = $requiregrading;
eb43ef6c 1997 $participants[$userid]->grantedextension = $grantedextension;
bb690849
DW
1998 if ($this->get_instance()->teamsubmission) {
1999 $group = $this->get_submission_group($userid);
2000 if ($group) {
2001 $participants[$userid]->groupid = $group->id;
2002 $participants[$userid]->groupname = $group->name;
2003 }
2004 }
2005 }
2006 return $participants;
2007 }
2008
1b2f9dc6
RW
2009 /**
2010 * Get the submission status/grading status for all submissions in this assignment.
eb43ef6c 2011 * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1b2f9dc6
RW
2012 * If this is a group assignment, group info is also returned.
2013 *
2014 * @param int $currentgroup
064f1503 2015 * @param boolean $tablesort Apply current user table sorting preferences.
eb43ef6c
TB
2016 * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'grantedextension',
2017 * 'groupid', 'groupname'
1b2f9dc6 2018 */
064f1503
DW
2019 public function list_participants_with_filter_status_and_group($currentgroup, $tablesort = false) {
2020 $participants = $this->list_participants($currentgroup, false, $tablesort);
1b2f9dc6
RW
2021
2022 if (empty($participants)) {
2023 return $participants;
2024 } else {
2025 return $this->get_submission_info_for_participants($participants);
2026 }
2027 }
2028
064f1503
DW
2029 /**
2030 * Return a valid order by segment for list_participants that matches
2031 * the sorting of the current grading table. Not every field is supported,
2032 * we are only concerned with a list of users so we can't search on anything
2033 * that is not part of the user information (like grading statud or last modified stuff).
2034 *
2035 * @return string Order by clause for list_participants
2036 */
2037 private function get_grading_sort_sql() {
2038 $usersort = flexible_table::get_sort_for_table('mod_assign_grading');
2039 $extrauserfields = get_extra_user_fields($this->get_context());
2040
2041 $userfields = explode(',', user_picture::fields('', $extrauserfields));
2042 $orderfields = explode(',', $usersort);
2043 $validlist = [];
2044
2045 foreach ($orderfields as $orderfield) {
2046 $orderfield = trim($orderfield);
2047 foreach ($userfields as $field) {
2048 $parts = explode(' ', $orderfield);
2049 if ($parts[0] == $field) {
2050 // Prepend the user table prefix and count this as a valid order field.
2051 array_push($validlist, 'u.' . $orderfield);
2052 }
2053 }
2054 }
2055 // Produce a final list.
2056 $result = implode(',', $validlist);
2057 if (empty($result)) {
2058 // Fall back ordering when none has been set.
2059 $result = 'u.lastname, u.firstname, u.id';
2060 }
2061
2062 return $result;
2063 }
2064
bbd0e548 2065 /**
e5403f8c
DW
2066 * Load a list of users enrolled in the current course with the specified permission and group.
2067 * 0 for no group.
064f1503 2068 * Apply any current sort filters from the grading table.
bbd0e548
DW
2069 *
2070 * @param int $currentgroup
2071 * @param bool $idsonly
2072 * @return array List of user records
2073 */
064f1503 2074 public function list_participants($currentgroup, $idsonly, $tablesort = false) {
230ae095 2075 global $DB, $USER;
bc006a66 2076
064f1503
DW
2077 // Get the last known sort order for the grading table.
2078
bc006a66
DM
2079 if (empty($currentgroup)) {
2080 $currentgroup = 0;
2081 }
2082
c46db93c
DW
2083 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
2084 if (!isset($this->participants[$key])) {
eb4c4661 2085 list($esql, $params) = get_enrolled_sql($this->context, 'mod/assign:submit', $currentgroup,
1ecb8044 2086 $this->show_only_active_users());
c46db93c 2087
eb4c4661
AN
2088 $fields = 'u.*';
2089 $orderby = 'u.lastname, u.firstname, u.id';
064f1503 2090
eb4c4661 2091 $additionaljoins = '';
230ae095 2092 $additionalfilters = '';
eb4c4661
AN
2093 $instance = $this->get_instance();
2094 if (!empty($instance->blindmarking)) {
2095 $additionaljoins .= " LEFT JOIN {assign_user_mapping} um
2096 ON u.id = um.userid
2097 AND um.assignment = :assignmentid1
2098 LEFT JOIN {assign_submission} s
2099 ON u.id = s.userid
2100 AND s.assignment = :assignmentid2
2101 AND s.latest = 1
2102 ";
2103 $params['assignmentid1'] = (int) $instance->id;
2104 $params['assignmentid2'] = (int) $instance->id;
2105 $fields .= ', um.id as recordid ';
2106
2107 // Sort by submission time first, then by um.id to sort reliably by the blind marking id.
2108 // Note, different DBs have different ordering of NULL values.
2109 // Therefore we coalesce the current time into the timecreated field, and the max possible integer into
2110 // the ID field.
064f1503
DW
2111 if (empty($tablesort)) {
2112 $orderby = "COALESCE(s.timecreated, " . time() . ") ASC, COALESCE(s.id, " . PHP_INT_MAX . ") ASC, um.id ASC";
2113 }
eb4c4661
AN
2114 }
2115
230ae095
DW
2116 if ($instance->markingworkflow &&
2117 $instance->markingallocation &&
bfca67f0
PS
2118 !has_capability('mod/assign:manageallocations', $this->get_context()) &&
2119 has_capability('mod/assign:grade', $this->get_context())) {
230ae095
DW
2120
2121 $additionaljoins .= ' LEFT JOIN {assign_user_flags} uf
2122 ON u.id = uf.userid
2123 AND uf.assignment = :assignmentid3';
2124
2125 $params['assignmentid3'] = (int) $instance->id;
2126
2127 $additionalfilters .= ' AND uf.allocatedmarker = :markerid';
2128 $params['markerid'] = $USER->id;
2129 }
2130
eb4c4661
AN
2131 $sql = "SELECT $fields
2132 FROM {user} u
2133 JOIN ($esql) je ON je.id = u.id
2134 $additionaljoins
2135 WHERE u.deleted = 0
230ae095 2136 $additionalfilters
eb4c4661
AN
2137 ORDER BY $orderby";
2138
2139 $users = $DB->get_records_sql($sql, $params);
2140
c46db93c 2141 $cm = $this->get_course_module();
c13ac85d 2142 $info = new \core_availability\info_module($cm);
2143 $users = $info->filter_user_list($users);
c46db93c
DW
2144
2145 $this->participants[$key] = $users;
bbd0e548 2146 }
a0e59f04 2147
064f1503
DW
2148 if ($tablesort) {
2149 // Resort the user list according to the grading table sort and filter settings.
2150 $sortedfiltereduserids = $this->get_grading_userid_list(true, '');
2151 $sortedfilteredusers = [];
2152 foreach ($sortedfiltereduserids as $nextid) {
2153 $nextid = intval($nextid);
2154 if (isset($this->participants[$key][$nextid])) {
2155 $sortedfilteredusers[$nextid] = $this->participants[$key][$nextid];
2156 }
2157 }
2158 $this->participants[$key] = $sortedfilteredusers;
2159 }
2160
c46db93c
DW
2161 if ($idsonly) {
2162 $idslist = array();
2163 foreach ($this->participants[$key] as $id => $user) {
2164 $idslist[$id] = new stdClass();
2165 $idslist[$id]->id = $id;
a0e59f04 2166 }
c46db93c 2167 return $idslist;
a0e59f04 2168 }
c46db93c 2169 return $this->participants[$key];
bbd0e548
DW
2170 }
2171
1b2f9dc6
RW
2172 /**
2173 * Load a user if they are enrolled in the current course. Populated with submission
2174 * status for this assignment.
2175 *
2176 * @param int $userid
2177 * @return null|stdClass user record
2178 */
2179 public function get_participant($userid) {
7ec6d873 2180 global $DB, $USER;
1b2f9dc6 2181
7ec6d873
RW
2182 if ($userid == $USER->id) {
2183 $participant = clone ($USER);
2184 } else {
2185 $participant = $DB->get_record('user', array('id' => $userid));
2186 }
1b2f9dc6
RW
2187 if (!$participant) {
2188 return null;
2189 }
2190
2191 if (!is_enrolled($this->context, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
2192 return null;
2193 }
2194
2195 $result = $this->get_submission_info_for_participants(array($participant->id => $participant));
2196 return $result[$participant->id];
2197 }
2198
12a1a0da 2199 /**
e5403f8c 2200 * Load a count of valid teams for this assignment.
12a1a0da 2201 *
bc006a66 2202 * @param int $activitygroup Activity active group
12a1a0da
DW
2203 * @return int number of valid teams
2204 */
bc006a66
DM
2205 public function count_teams($activitygroup = 0) {
2206
2207 $count = 0;
2208
2209 $participants = $this->list_participants($activitygroup, true);
2210
2211 // If a team submission grouping id is provided all good as all returned groups
2212 // are the submission teams, but if no team submission grouping was specified
2213 // $groups will contain all participants groups.
2214 if ($this->get_instance()->teamsubmissiongroupingid) {
12a1a0da 2215
bc006a66
DM
2216 // We restrict the users to the selected group ones.
2217 $groups = groups_get_all_groups($this->get_course()->id,
2218 array_keys($participants),
2219 $this->get_instance()->teamsubmissiongroupingid,
2220 'DISTINCT g.id, g.name');
12a1a0da 2221
bc006a66
DM
2222 $count = count($groups);
2223
2224 // When a specific group is selected we don't count the default group users.
2225 if ($activitygroup == 0) {
e528997a
AH
2226 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
2227 // See if there are any users in the default group.
2228 $defaultusers = $this->get_submission_group_members(0, true);
2229 if (count($defaultusers) > 0) {
2230 $count += 1;
2231 }
bc006a66 2232 }
426bb5ae
SL
2233 } else if ($activitygroup != 0 && empty($groups)) {
2234 // Set count to 1 if $groups returns empty.
2235 // It means the group is not part of $this->get_instance()->teamsubmissiongroupingid.
2236 $count = 1;
bc006a66
DM
2237 }
2238 } else {
2239 // It is faster to loop around participants if no grouping was specified.
2240 $groups = array();
2241 foreach ($participants as $participant) {
2242 if ($group = $this->get_submission_group($participant->id)) {
2243 $groups[$group->id] = true;
e528997a 2244 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
bc006a66
DM
2245 $groups[0] = true;
2246 }
2247 }
12a1a0da 2248
bc006a66 2249 $count = count($groups);
12a1a0da 2250 }
bc006a66 2251
12a1a0da
DW
2252 return $count;
2253 }
2254
bbd0e548 2255 /**
c494e18c 2256 * Load a count of active users enrolled in the current course with the specified permission and group.
e5403f8c 2257 * 0 for no group.
bbd0e548
DW
2258 *
2259 * @param int $currentgroup
2260 * @return int number of matching users
2261 */
2262 public function count_participants($currentgroup) {
a0e59f04 2263 return count($this->list_participants($currentgroup, true));
bbd0e548
DW
2264 }
2265
f70079b9 2266 /**
c494e18c 2267 * Load a count of active users submissions in the current module that require grading
f70079b9 2268 * This means the submission modification time is more recent than the
7a9fd6da 2269 * grading modification time and the status is SUBMITTED.
f70079b9 2270 *
ddeabbc5 2271 * @param mixed $currentgroup int|null the group for counting (if null the function will determine it)
f70079b9
DW
2272 * @return int number of matching submissions
2273 */
ddeabbc5 2274 public function count_submissions_need_grading($currentgroup = null) {
f70079b9
DW
2275 global $DB;
2276
8f7e1c05
DW
2277 if ($this->get_instance()->teamsubmission) {
2278 // This does not make sense for group assignment because the submission is shared.
2279 return 0;
2280 }
2281
ddeabbc5
JL
2282 if ($currentgroup === null) {
2283 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2284 }
c494e18c 2285 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05
DW
2286
2287 $params['assignid'] = $this->get_instance()->id;
2288 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
32ad5c86 2289 $sqlscalegrade = $this->get_instance()->grade < 0 ? ' OR g.grade = -1' : '';
8f7e1c05
DW
2290
2291 $sql = 'SELECT COUNT(s.userid)
2292 FROM {assign_submission} s
2293 LEFT JOIN {assign_grades} g ON
2294 s.assignment = g.assignment AND
df211804 2295 s.userid = g.userid AND
ad030ab4 2296 g.attemptnumber = s.attemptnumber
0c7b6910 2297 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05 2298 WHERE
ad030ab4 2299 s.latest = 1 AND
8f7e1c05
DW
2300 s.assignment = :assignid AND
2301 s.timemodified IS NOT NULL AND
2302 s.status = :submitted AND
32ad5c86
PS
2303 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL '
2304 . $sqlscalegrade . ')';
f70079b9 2305
8f7e1c05 2306 return $DB->count_records_sql($sql, $params);
f70079b9
DW
2307 }
2308
bbd0e548 2309 /**
e5403f8c 2310 * Load a count of grades.
b473171a
DW
2311 *
2312 * @return int number of grades
2313 */
2314 public function count_grades() {
2315 global $DB;
2316
2317 if (!$this->has_instance()) {
2318 return 0;
2319 }
2320
8f7e1c05 2321 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
c494e18c 2322 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05
DW
2323
2324 $params['assignid'] = $this->get_instance()->id;
2325
2326 $sql = 'SELECT COUNT(g.userid)
2327 FROM {assign_grades} g
0c7b6910 2328 JOIN(' . $esql . ') e ON e.id = g.userid
8f7e1c05 2329 WHERE g.assignment = :assignid';
b473171a
DW
2330
2331 return $DB->count_records_sql($sql, $params);
2332 }
2333
2334 /**
e5403f8c 2335 * Load a count of submissions.
b473171a 2336 *
ab14ab74 2337 * @param bool $includenew When true, also counts the submissions with status 'new'.
b473171a
DW
2338 * @return int number of submissions
2339 */
ab14ab74 2340 public function count_submissions($includenew = false) {
b473171a
DW
2341 global $DB;
2342
2343 if (!$this->has_instance()) {
2344 return 0;
2345 }
2346
8f7e1c05 2347 $params = array();
ab14ab74
FM
2348 $sqlnew = '';
2349
2350 if (!$includenew) {
2351 $sqlnew = ' AND s.status <> :status ';
2352 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
2353 }
b473171a
DW
2354
2355 if ($this->get_instance()->teamsubmission) {
8f7e1c05 2356 // We cannot join on the enrolment tables for group submissions (no userid).
df211804 2357 $sql = 'SELECT COUNT(DISTINCT s.groupid)
8f7e1c05
DW
2358 FROM {assign_submission} s
2359 WHERE
2360 s.assignment = :assignid AND
2361 s.timemodified IS NOT NULL AND
ab14ab74
FM
2362 s.userid = :groupuserid' .
2363 $sqlnew;
8f7e1c05
DW
2364
2365 $params['assignid'] = $this->get_instance()->id;
2366 $params['groupuserid'] = 0;
2367 } else {
2368 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
ab14ab74 2369 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05 2370
ab14ab74 2371 $params = array_merge($params, $enrolparams);
8f7e1c05
DW
2372 $params['assignid'] = $this->get_instance()->id;
2373
df211804 2374 $sql = 'SELECT COUNT(DISTINCT s.userid)
8f7e1c05 2375 FROM {assign_submission} s
0c7b6910 2376 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05
DW
2377 WHERE
2378 s.assignment = :assignid AND
ab14ab74
FM
2379 s.timemodified IS NOT NULL ' .
2380 $sqlnew;
4c4c7b3f 2381
b473171a 2382 }
8f7e1c05 2383
b473171a
DW
2384 return $DB->count_records_sql($sql, $params);
2385 }
2386
2387 /**
e5403f8c 2388 * Load a count of submissions with a specified status.
bbd0e548
DW
2389 *
2390 * @param string $status The submission status - should match one of the constants
ddeabbc5 2391 * @param mixed $currentgroup int|null the group for counting (if null the function will determine it)
bbd0e548
DW
2392 * @return int number of matching submissions
2393 */
ddeabbc5 2394 public function count_submissions_with_status($status, $currentgroup = null) {
bbd0e548 2395 global $DB;
8f7e1c05 2396
ddeabbc5
JL
2397 if ($currentgroup === null) {
2398 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2399 }
c494e18c 2400 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05
DW
2401
2402 $params['assignid'] = $this->get_instance()->id;
df211804 2403 $params['assignid2'] = $this->get_instance()->id;
8f7e1c05 2404 $params['submissionstatus'] = $status;
12a1a0da
DW
2405
2406 if ($this->get_instance()->teamsubmission) {
bc006a66
DM
2407
2408 $groupsstr = '';
2409 if ($currentgroup != 0) {
2410 // If there is an active group we should only display the current group users groups.
2411 $participants = $this->list_participants($currentgroup, true);
2412 $groups = groups_get_all_groups($this->get_course()->id,
2413 array_keys($participants),
2414 $this->get_instance()->teamsubmissiongroupingid,
2415 'DISTINCT g.id, g.name');
426bb5ae
SL
2416 if (empty($groups)) {
2417 // If $groups is empty it means it is not part of $this->get_instance()->teamsubmissiongroupingid.
2418 // All submissions from students that do not belong to any of teamsubmissiongroupingid groups
2419 // count towards groupid = 0. Setting to true as only '0' key matters.
2420 $groups = [true];
2421 }
bc006a66
DM
2422 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
2423 $groupsstr = 's.groupid ' . $groupssql . ' AND';
2424 $params = $params + $groupsparams;
2425 }
8f7e1c05
DW
2426 $sql = 'SELECT COUNT(s.groupid)
2427 FROM {assign_submission} s
2428 WHERE
ad030ab4 2429 s.latest = 1 AND
8f7e1c05
DW
2430 s.assignment = :assignid AND
2431 s.timemodified IS NOT NULL AND
bc006a66
DM
2432 s.userid = :groupuserid AND '
2433 . $groupsstr . '
8f7e1c05
DW
2434 s.status = :submissionstatus';
2435 $params['groupuserid'] = 0;
2436 } else {
2437 $sql = 'SELECT COUNT(s.userid)
2438 FROM {assign_submission} s
0c7b6910 2439 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05 2440 WHERE
ad030ab4 2441 s.latest = 1 AND
8f7e1c05
DW
2442 s.assignment = :assignid AND
2443 s.timemodified IS NOT NULL AND
2444 s.status = :submissionstatus';
4c4c7b3f 2445
12a1a0da 2446 }
8f7e1c05 2447
12a1a0da 2448 return $DB->count_records_sql($sql, $params);
bbd0e548
DW
2449 }
2450
2451 /**
2452 * Utility function to get the userid for every row in the grading table
e5403f8c 2453 * so the order can be frozen while we iterate it.
bbd0e548 2454 *
064f1503
DW
2455 * @param boolean $cached If true, the cached list from the session could be returned.
2456 * @param string $useridlistid String value used for caching the participant list.
bbd0e548
DW
2457 * @return array An array of userids
2458 */
064f1503
DW
2459 protected function get_grading_userid_list($cached = false, $useridlistid = '') {
2460 if ($cached) {
2461 if (empty($useridlistid)) {
2462 $useridlistid = $this->get_useridlist_key_id();
2463 }
2464 $useridlistkey = $this->get_useridlist_key($useridlistid);
2465 if (empty($SESSION->mod_assign_useridlist[$useridlistkey])) {
2466 $SESSION->mod_assign_useridlist[$useridlistkey] = $this->get_grading_userid_list(false, '');
2467 }
2468 return $SESSION->mod_assign_useridlist[$useridlistkey];
2469 }
bbd0e548 2470 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 2471 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
2472
2473 $useridlist = $table->get_column_data('userid');
2474
2475 return $useridlist;
2476 }
2477
bbd0e548 2478 /**
e5403f8c 2479 * Generate zip file from array of given files.
bbd0e548 2480 *
e5403f8c
DW
2481 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
2482 * This array is indexed by the final file name and each
2483 * element in the array is an instance of a stored_file object.
2484 * @return path of temp file - note this returned file does
2485 * not have a .zip extension - it is a temp file.
bbd0e548 2486 */
47f48152 2487 protected function pack_files($filesforzipping) {
e5403f8c
DW
2488 global $CFG;
2489 // Create path for new zip file.
2490 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
2491 // Zip files.
2492 $zipper = new zip_packer();
2493 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
2494 return $tempzip;
bbd0e548 2495 }
e5403f8c 2496 return false;
bbd0e548
DW
2497 }
2498
bbd0e548 2499 /**
3f7b501e
SH
2500 * Finds all assignment notifications that have yet to be mailed out, and mails them.
2501 *
e5403f8c 2502 * Cron function to be run periodically according to the moodle cron.
bbd0e548
DW
2503 *
2504 * @return bool
2505 */
e5403f8c 2506 public static function cron() {
3f7b501e 2507 global $DB;
75f87a57 2508
e5403f8c 2509 // Only ever send a max of one days worth of updates.
75f87a57
DW
2510 $yesterday = time() - (24 * 3600);
2511 $timenow = time();
abd0f0ae 2512 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
75f87a57 2513
70cfc878
JF
2514 // Collect all submissions that require mailing.
2515 // Submissions are included if all are true:
2516 // - The assignment is visible in the gradebook.
2517 // - No previous notification has been sent.
851b5c7f 2518 // - The grader was a real user, not an automated process.
70cfc878
JF
2519 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
2520 // if marking workflow is enabled, the workflow state is at 'released'.
f14afd29 2521 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities, a.hidegrader,
cf29b1e0 2522 g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
3f7b501e
SH
2523 FROM {assign} a
2524 JOIN {assign_grades} g ON g.assignment = a.id
fdd3ebc5 2525 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
86dced43
TB
2526 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
2527 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
fdd3ebc5 2528 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
cf29b1e0 2529 LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
70cfc878
JF
2530 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
2531 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
851b5c7f 2532 g.grader > 0 AND uf.mailed = 0 AND gri.hidden = 0
f33be9eb 2533 ORDER BY a.course, cm.id";
e5403f8c 2534
70cfc878
JF
2535 $params = array(
2536 'yesterday' => $yesterday,
2537 'today' => $timenow,
2538 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
2539 );
3f7b501e 2540 $submissions = $DB->get_records_sql($sql, $params);
75f87a57 2541
ae7638f7 2542 if (!empty($submissions)) {
c8314005 2543
ae7638f7 2544 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
75f87a57 2545
ae7638f7
DW
2546 // Preload courses we are going to need those.
2547 $courseids = array();
2548 foreach ($submissions as $submission) {
2549 $courseids[] = $submission->course;
2550 }
e5403f8c 2551
ae7638f7
DW
2552 // Filter out duplicates.
2553 $courseids = array_unique($courseids);
2554 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2555 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
2556 $sql = 'SELECT c.*, ' . $ctxselect .
2557 ' FROM {course} c
2558 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
2559 WHERE c.id ' . $courseidsql;
e5403f8c 2560
ae7638f7
DW
2561 $params['contextlevel'] = CONTEXT_COURSE;
2562 $courses = $DB->get_records_sql($sql, $params);
e5403f8c 2563
ae7638f7
DW
2564 // Clean up... this could go on for a while.
2565 unset($courseids);
2566 unset($ctxselect);
2567 unset($courseidsql);
2568 unset($params);
3f7b501e 2569
ae7638f7
DW
2570 // Message students about new feedback.
2571 foreach ($submissions as $submission) {
75f87a57 2572
ae7638f7 2573 mtrace("Processing assignment submission $submission->id ...");
75f87a57 2574
ae7638f7
DW
2575 // Do not cache user lookups - could be too many.
2576 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
2577 mtrace('Could not find user ' . $submission->userid);
2578 continue;
2579 }
75f87a57 2580
ae7638f7
DW
2581 // Use a cache to prevent the same DB queries happening over and over.
2582 if (!array_key_exists($submission->course, $courses)) {
2583 mtrace('Could not find course ' . $submission->course);
2584 continue;
2585 }
2586 $course = $courses[$submission->course];
2587 if (isset($course->ctxid)) {
2588 // Context has not yet been preloaded. Do so now.
2589 context_helper::preload_from_record($course);
2590 }
75f87a57 2591
ae7638f7
DW
2592 // Override the language and timezone of the "current" user, so that
2593 // mail is customised for the receiver.
2594 cron_setup_user($user, $course);
2595
2596 // Context lookups are already cached.
2597 $coursecontext = context_course::instance($course->id);
2598 if (!is_enrolled($coursecontext, $user->id)) {
2599 $courseshortname = format_string($course->shortname,
2600 true,
2601 array('context' => $coursecontext));
2602 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
2603 continue;
2604 }
75f87a57 2605
ae7638f7
DW
2606 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
2607 mtrace('Could not find grader ' . $submission->grader);
2608 continue;
2609 }
75f87a57 2610
ccd6839a 2611 $modinfo = get_fast_modinfo($course, $user->id);
86dced43 2612 $cm = $modinfo->get_cm($submission->cmid);
ae7638f7 2613 // Context lookups are already cached.
86dced43 2614 $contextmodule = context_module::instance($cm->id);
ae7638f7 2615
ccd6839a
TB
2616 if (!$cm->uservisible) {
2617 // Hold mail notification for assignments the user cannot access until later.
75f87a57
DW
2618 continue;
2619 }
bbd0e548 2620
f14afd29 2621 // Notify the student. Default to the non-anon version.
ae7638f7 2622 $messagetype = 'feedbackavailable';
f14afd29
AW
2623 // Message type needs 'anon' if "hidden grading" is enabled and the student
2624 // doesn't have permission to see the grader.
2625 if ($submission->hidegrader && !has_capability('mod/assign:showhiddengrader', $contextmodule, $user)) {
2626 $messagetype = 'feedbackavailableanon';
2627 // There's no point in having an "anonymous grader" if the notification email
91a2215e
DM
2628 // comes from them. Send the email from the noreply user instead.
2629 $grader = core_user::get_noreply_user();
f14afd29
AW
2630 }
2631
ae7638f7
DW
2632 $eventtype = 'assign_notification';
2633 $updatetime = $submission->lastmodified;
2634 $modulename = get_string('modulename', 'assign');
75f87a57 2635
ae7638f7
DW
2636 $uniqueid = 0;
2637 if ($submission->blindmarking && !$submission->revealidentities) {
cf29b1e0 2638 if (empty($submission->recordid)) {
0163e5d2 2639 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $grader->id);
cf29b1e0
AN
2640 } else {
2641 $uniqueid = $submission->recordid;
2642 }
ae7638f7
DW
2643 }
2644 $showusers = $submission->blindmarking && !$submission->revealidentities;
2645 self::send_assignment_notification($grader,
2646 $user,
2647 $messagetype,
2648 $eventtype,
2649 $updatetime,
86dced43 2650 $cm,
ae7638f7
DW
2651 $contextmodule,
2652 $course,
2653 $modulename,
2654 $submission->name,
2655 $showusers,
2656 $uniqueid);
2657
2658 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
2659 if ($flags) {
2660 $flags->mailed = 1;
2661 $DB->update_record('assign_user_flags', $flags);
2662 } else {
2663 $flags = new stdClass();
2664 $flags->userid = $user->id;
2665 $flags->assignment = $submission->assignment;
2666 $flags->mailed = 1;
2667 $DB->insert_record('assign_user_flags', $flags);
2668 }
b473171a 2669
ae7638f7 2670 mtrace('Done');
df211804 2671 }
ae7638f7 2672 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
75f87a57 2673
ae7638f7
DW
2674 cron_setup_user();
2675
2676 // Free up memory just to be sure.
2677 unset($courses);
75f87a57 2678 }
75f87a57 2679
ae7638f7
DW
2680 // Update calendar events to provide a description.
2681 $sql = 'SELECT id
2682 FROM {assign}
2683 WHERE
2684 allowsubmissionsfromdate >= :lastcron AND
2685 allowsubmissionsfromdate <= :timenow AND
2686 alwaysshowdescription = 0';
2687 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2688 $newlyavailable = $DB->get_records_sql($sql, $params);
2689 foreach ($newlyavailable as $record) {
2690 $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
2691 $context = context_module::instance($cm->id);
3f7b501e 2692
ae7638f7
DW
2693 $assignment = new assign($context, null, null);
2694 $assignment->update_calendar($cm->id);
2695 }
bbd0e548
DW
2696
2697 return true;
2698 }
2699
d6c673ed
DW
2700 /**
2701 * Mark in the database that this grade record should have an update notification sent by cron.
2702 *
2703 * @param stdClass $grade a grade record keyed on id
a4b10a52 2704 * @param bool $mailedoverride when true, flag notification to be sent again.
d6c673ed
DW
2705 * @return bool true for success
2706 */
a4b10a52 2707 public function notify_grade_modified($grade, $mailedoverride = false) {
d6c673ed
DW
2708 global $DB;
2709
df211804 2710 $flags = $this->get_user_flags($grade->userid, true);
a4b10a52 2711 if ($flags->mailed != 1 || $mailedoverride) {
df211804 2712 $flags->mailed = 0;
d6c673ed
DW
2713 }
2714
df211804
DW
2715 return $this->update_user_flags($flags);
2716 }
2717
2718 /**
2719 * Update user flags for this user in this assignment.
2720 *
2721 * @param stdClass $flags a flags record keyed on id
2722 * @return bool true for success
2723 */
2724 public function update_user_flags($flags) {
2725 global $DB;
2726 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
2727 return false;
2728 }
2729
2730 $result = $DB->update_record('assign_user_flags', $flags);
2731 return $result;
d6c673ed
DW
2732 }
2733
bbd0e548 2734 /**
e5403f8c 2735 * Update a grade in the grade table for the assignment and in the gradebook.
bbd0e548
DW
2736 *
2737 * @param stdClass $grade a grade record keyed on id
ab38cb28 2738 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
bbd0e548
DW
2739 * @return bool true for success
2740 */
ab38cb28 2741 public function update_grade($grade, $reopenattempt = false) {
bbd0e548
DW
2742 global $DB;
2743
2744 $grade->timemodified = time();
2745
f8d107b3
DM
2746 if (!empty($grade->workflowstate)) {
2747 $validstates = $this->get_marking_workflow_states_for_current_user();
2748 if (!array_key_exists($grade->workflowstate, $validstates)) {
2749 return false;
2750 }
2751 }
2752
bbd0e548
DW
2753 if ($grade->grade && $grade->grade != -1) {
2754 if ($this->get_instance()->grade > 0) {
2755 if (!is_numeric($grade->grade)) {
2756 return false;
2757 } else if ($grade->grade > $this->get_instance()->grade) {
2758 return false;
2759 } else if ($grade->grade < 0) {
2760 return false;
2761 }
2762 } else {
e5403f8c 2763 // This is a scale.
bbd0e548
DW
2764 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
2765 $scaleoptions = make_menu_from_list($scale->scale);
2766 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
2767 return false;
2768 }
2769 }
2770 }
2771 }
2772
a8fdb36c
DW
2773 if (empty($grade->attemptnumber)) {
2774 // Set it to the default.
2775 $grade->attemptnumber = 0;
2776 }
e77bacab 2777 $DB->update_record('assign_grades', $grade);
df211804 2778
df211804
DW
2779 $submission = null;
2780 if ($this->get_instance()->teamsubmission) {
75c21e7e
AG
2781 if (isset($this->mostrecentteamsubmission)) {
2782 $submission = $this->mostrecentteamsubmission;
2783 } else {
2784 $submission = $this->get_group_submission($grade->userid, 0, false);
2785 }
df211804
DW
2786 } else {
2787 $submission = $this->get_user_submission($grade->userid, false);
2788 }
767fda9b 2789
75c21e7e 2790 // Only push to gradebook if the update is for the most recent attempt.
df211804
DW
2791 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
2792 return true;
2793 }
2794
bd3ee807
MN
2795 if ($this->gradebook_item_update(null, $grade)) {
2796 \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
2797 }
e77bacab
MP
2798
2799 // If the conditions are met, allow another attempt.
2800 if ($submission) {
2801 $this->reopen_submission_if_required($grade->userid,
2802 $submission,
2803 $reopenattempt);
bbd0e548 2804 }
bd3ee807 2805
e77bacab 2806 return true;
bbd0e548
DW
2807 }
2808
9e795179 2809 /**
e5403f8c 2810 * View the grant extension date page.
9e795179
DW
2811 *
2812 * Uses url parameters 'userid'
2813 * or from parameter 'selectedusers'
e5403f8c 2814 *
9e795179
DW
2815 * @param moodleform $mform - Used for validation of the submitted data
2816 * @return string
2817 */
47f48152 2818 protected function view_grant_extension($mform) {
ffcfffbe 2819 global $CFG;
9e795179
DW
2820 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2821
2822 $o = '';
26670f5e 2823
9e795179 2824 $data = new stdClass();
26670f5e 2825 $data->id = $this->get_course_module()->id;
9e795179 2826
26670f5e 2827 $formparams = array(
ffcfffbe
IT
2828 'instance' => $this->get_instance(),
2829 'assign' => $this
26670f5e
JF
2830 );
2831
ffcfffbe
IT
2832 $users = optional_param('userid', 0, PARAM_INT);
2833 if (!$users) {
2834 $users = required_param('selectedusers', PARAM_SEQUENCE);
2835 }
2836 $userlist = explode(',', $users);
26670f5e 2837
d685b959
IT
2838 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
2839 $maxoverride = array('allowsubmissionsfromdate' => 0, 'duedate' => 0, 'cutoffdate' => 0);
2840 foreach ($userlist as $userid) {
2841 // To validate extension date with users overrides.
2842 $override = $this->override_exists($userid);
2843 foreach ($keys as $key) {
2844 if ($override->{$key}) {
2845 if ($maxoverride[$key] < $override->{$key}) {
2846 $maxoverride[$key] = $override->{$key};
2847 }
2848 } else if ($maxoverride[$key] < $this->get_instance()->{$key}) {
2849 $maxoverride[$key] = $this->get_instance()->{$key};
2850 }
2851 }
2852 }
2853 foreach ($keys as $key) {
2854 if ($maxoverride[$key]) {
2855 $this->get_instance()->{$key} = $maxoverride[$key];
2856 }
2857 }
2858
ffcfffbe 2859 $formparams['userlist'] = $userlist;
9e795179 2860
ffcfffbe
IT
2861 $data->selectedusers = $users;
2862 $data->userid = 0;
26670f5e 2863
ffcfffbe
IT
2864 if (empty($mform)) {
2865 $mform = new mod_assign_extension_form(null, $formparams);
9e795179 2866 }
26670f5e 2867 $mform->set_data($data);
e5403f8c
DW
2868 $header = new assign_header($this->get_instance(),
2869 $this->get_context(),
2870 $this->show_intro(),
2871 $this->get_course_module()->id,
2872 get_string('grantextension', 'assign'));
2873 $o .= $this->get_renderer()->render($header);
49d83b9d 2874 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
9e795179
DW
2875 $o .= $this->view_footer();
2876 return $o;
2877 }
2878
12a1a0da 2879 /**
e5403f8c 2880 * Get a list of the users in the same group as this user.
12a1a0da
DW
2881 *
2882 * @param int $groupid The id of the group whose members we want or 0 for the default group
2883 * @param bool $onlyids Whether to retrieve only the user id's
b2885704 2884 * @param bool $excludesuspended Whether to exclude suspended users
12a1a0da
DW
2885 * @return array The users (possibly id's only)
2886 */
b2885704 2887 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
12a1a0da
DW
2888 $members = array();
2889 if ($groupid != 0) {
64ccb37d 2890 $allusers = $this->list_participants($groupid, $onlyids);
12a1a0da
DW
2891 foreach ($allusers as $user) {
2892 if ($this->get_submission_group($user->id)) {
2893 $members[] = $user;
2894 }
2895 }
2896 } else {
2897 $allusers = $this->list_participants(null, $onlyids);
2898 foreach ($allusers as $user) {
2899 if ($this->get_submission_group($user->id) == null) {
2900 $members[] = $user;
2901 }
2902 }
2903 }
4c4c7b3f 2904 // Exclude suspended users, if user can't see them.
b2885704 2905 if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
4c4c7b3f 2906 foreach ($members as $key => $member) {
1ecb8044 2907 if (!$this->is_active_user($member->id)) {
4c4c7b3f
RT
2908 unset($members[$key]);
2909 }
2910 }
2911 }
bc006a66 2912
12a1a0da
DW
2913 return $members;
2914 }
2915
2916 /**
e5403f8c 2917 * Get a list of the users in the same group as this user that have not submitted the assignment.
12a1a0da
DW
2918 *
2919 * @param int $groupid The id of the group whose members we want or 0 for the default group
2920 * @param bool $onlyids Whether to retrieve only the user id's
2921 * @return array The users (possibly id's only)
2922 */
2923 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
e5403f8c
DW
2924 $instance = $this->get_instance();
2925 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
12a1a0da
DW
2926 return array();
2927 }
2928 $members = $this->get_submission_group_members($groupid, $onlyids);
2929
2930 foreach ($members as $id => $member) {
2931 $submission = $this->get_user_submission($member->id, false);
df211804 2932 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
12a1a0da 2933 unset($members[$id]);
88cfe469
DW
2934 } else {
2935 if ($this->is_blind_marking()) {
e5403f8c
DW
2936 $members[$id]->alias = get_string('hiddenuser', 'assign') .
2937 $this->get_uniqueid_for_user($id);
88cfe469 2938 }
12a1a0da
DW
2939 }
2940 }
2941 return $members;
2942 }
2943
2944 /**
e5403f8c 2945 * Load the group submission object for a particular user, optionally creating it if required.
12a1a0da
DW
2946 *
2947 * @param int $userid The id of the user whose submission we want
e5403f8c
DW
2948 * @param int $groupid The id of the group for this user - may be 0 in which
2949 * case it is determined from the userid.
12a1a0da 2950 * @param bool $create If set to true a new submission object will be created in the database
9e3eee67 2951 * with the status set to "new".
df211804 2952 * @param int $attemptnumber - -1 means the latest attempt
12a1a0da
DW
2953 * @return stdClass The submission
2954 */
df211804 2955 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
12a1a0da
DW
2956 global $DB;
2957
2958 if ($groupid == 0) {
2959 $group = $this->get_submission_group($userid);
2960 if ($group) {
2961 $groupid = $group->id;
2962 }
2963 }
2964
12a1a0da
DW
2965 // Now get the group submission.
2966 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
df211804
DW
2967 if ($attemptnumber >= 0) {
2968 $params['attemptnumber'] = $attemptnumber;
2969 }
2970
2971 // Only return the row with the highest attemptnumber.
2972 $submission = null;
2973 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2974 if ($submissions) {
2975 $submission = reset($submissions);
2976 }
12a1a0da
DW
2977
2978 if ($submission) {
2979 return $submission;
2980 }
2981 if ($create) {
2982 $submission = new stdClass();
e5403f8c
DW
2983 $submission->assignment = $this->get_instance()->id;
2984 $submission->userid = 0;
2985 $submission->groupid = $groupid;
12a1a0da
DW
2986 $submission->timecreated = time();
2987 $submission->timemodified = $submission->timecreated;
df211804
DW
2988 if ($attemptnumber >= 0) {
2989 $submission->attemptnumber = $attemptnumber;
12a1a0da 2990 } else {
df211804 2991 $submission->attemptnumber = 0;
12a1a0da 2992 }
1523f9e0
DW
2993 // Work out if this is the latest submission.
2994 $submission->latest = 0;
2995 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2996 if ($attemptnumber == -1) {
2997 // This is a new submission so it must be the latest.
2998 $submission->latest = 1;
2999 } else {
3000 // We need to work this out.
3001 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
3002 if ($result) {
3003 $latestsubmission = reset($result);
3004 }
3005 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
3006 $submission->latest = 1;
3007 }
3008 }
3009 if ($submission->latest) {
3010 // This is the case when we need to set latest to 0 for all the other attempts.
3011 $DB->set_field('assign_submission', 'latest', 0, $params);
3012 }
9e3eee67 3013 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
12a1a0da 3014 $sid = $DB->insert_record('assign_submission', $submission);
4781ff2e 3015 return $DB->get_record('assign_submission', array('id' => $sid));
12a1a0da
DW
3016 }
3017 return false;
3018 }
3019
df47b77f 3020 /**
64220210
DW
3021 * View a summary listing of all assignments in the current course.
3022 *
3023 * @return string
3024 */
3025 private function view_course_index() {
3026 global $USER;
3027
3028 $o = '';
3029
3030 $course = $this->get_course();
3031 $strplural = get_string('modulenameplural', 'assign');
3032
3033 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
3034 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
3035 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
3036 return $o;
3037 }
3038
09af1e28 3039 $strsectionname = '';
64220210
DW
3040 $usesections = course_format_uses_sections($course->format);
3041 $modinfo = get_fast_modinfo($course);
3042
3043 if ($usesections) {
09af1e28 3044 $strsectionname = get_string('sectionname', 'format_'.$course->format);
64220210
DW
3045 $sections = $modinfo->get_section_info_all();
3046 }
3047 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
3048
3049 $timenow = time();
3050
3051 $currentsection = '';
3052 foreach ($modinfo->instances['assign'] as $cm) {
3053 if (!$cm->uservisible) {
3054 continue;
3055 }
3056
e5403f8c 3057 $timedue = $cms[$cm->id]->duedate;
64220210
DW
3058
3059 $sectionname = '';
3060 if ($usesections && $cm->sectionnum) {
3061 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
3062 }
3063
3064 $submitted = '';
3065 $context = context_module::instance($cm->id);
3066
3067 $assignment = new assign($context, $cm, $course);
3068
d685b959
IT
3069 // Apply overrides.
3070 $assignment->update_effective_access($USER->id);
3071 $timedue = $assignment->get_instance()->duedate;
3072
64220210
DW
3073 if (has_capability('mod/assign:grade', $context)) {
3074 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
3075
3076 } else if (has_capability('mod/assign:submit', $context)) {
3c4fd881
DW
3077 if ($assignment->get_instance()->teamsubmission) {
3078 $usersubmission = $assignment->get_group_submission($USER->id, 0, false);
3079 } else {
3080 $usersubmission = $assignment->get_user_submission($USER->id, false);
3081 }
64220210
DW
3082
3083 if (!empty($usersubmission->status)) {
3084 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
3085 } else {
3086 $submitted = get_string('submissionstatus_', 'assign');
3087 }
3088 }
539af602
DW
3089 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
3090 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
3091 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
3092 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
64220210
DW
3093 } else {
3094 $grade = '-';
3095 }
3096
92c9be19 3097 $courseindexsummary->add_assign_info($cm->id, $cm->get_formatted_name(), $sectionname, $timedue, $submitted, $grade);
64220210
DW
3098
3099 }
3100
3101 $o .= $this->get_renderer()->render($courseindexsummary);
3102 $o .= $this->view_footer();
3103
3104 return $o;
3105 }
3106
3107 /**
3108 * View a page rendered by a plugin.
df47b77f 3109 *
e5403f8c 3110 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
df47b77f
DW
3111 *
3112 * @return string
3113 */
47f48152 3114 protected function view_plugin_page() {
df47b77f
DW
3115 global $USER;
3116
3117 $o = '';
3118
3119 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
82a8d0d2 3120 $plugintype = required_param('plugin', PARAM_PLUGIN);
df47b77f
DW
3121 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
3122
3123 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
3124 if (!$plugin) {
3125 print_error('invalidformdata', '');
3126 return;
3127 }
3128
3129 $o .= $plugin->view_page($pluginaction);
3130
3131 return $o;
3132 }
3133
3134
12a1a0da
DW
3135 /**
3136 * This is used for team assignments to get the group for the specified user.
3137 * If the user is a member of multiple or no groups this will return false
3138 *
3139 * @param int $userid The id of the user whose submission we want
3140 * @return mixed The group or false
3141 */
3142 public function get_submission_group($userid) {
bc006a66
DM
3143
3144 if (isset($this->usersubmissiongroups[$userid])) {
3145 return $this->usersubmissiongroups[$userid];
3146 }
3147
ee5d4eef 3148 $groups = $this->get_all_groups($userid);
12a1a0da 3149 if (count($groups) != 1) {
bc006a66
DM
3150 $return = false;
3151 } else {
3152 $return = array_pop($groups);
12a1a0da 3153 }
bc006a66
DM
3154
3155 // Cache the user submission group.
3156 $this->usersubmissiongroups[$userid] = $return;
3157
3158 return $return;
12a1a0da
DW
3159 }
3160
a059ef2e
DP
3161 /**
3162 * Gets all groups the user is a member of.
3163 *
3164 * @param int $userid Teh id of the user who's groups we are checking
3165 * @return array The group objects
3166 */
ce449f63 3167 public function get_all_groups($userid) {
ee5d4eef
AH
3168 if (isset($this->usergroups[$userid])) {
3169 return $this->usergroups[$userid];
3170 }
3171
3172 $grouping = $this->get_instance()->teamsubmissiongroupingid;
3173 $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
3174
3175 $this->usergroups[$userid] = $return;
3176
3177 return $return;
3178 }
3179
9e795179 3180
bbd0e548 3181 /**
e5403f8c
DW
3182 * Display the submission that is used by a plugin.
3183 *
3184 * Uses url parameters 'sid', 'gid' and 'plugin'.
3185 *
bbd0e548
DW
3186 * @param string $pluginsubtype
3187 * @return string
3188 */
47f48152 3189 protected function view_plugin_content($pluginsubtype) {
bbd0e548
DW
3190 $o = '';
3191
3192 $submissionid = optional_param('sid', 0, PARAM_INT);
3193 $gradeid = optional_param('gid', 0, PARAM_INT);
82a8d0d2 3194 $plugintype = required_param('plugin', PARAM_PLUGIN);
bbd0e548
DW
3195 $item = null;
3196 if ($pluginsubtype == 'assignsubmission') {
3197 $plugin = $this->get_submission_plugin_by_type($plugintype);
3198 if ($submissionid <= 0) {
3199 throw new coding_exception('Submission id should not be 0');
3200 }
3201 $item = $this->get_submission($submissionid);
3202
e5403f8c 3203 // Check permissions.
2ba3ce98
AA
3204 if (empty($item->userid)) {
3205 // Group submission.
3206 $this->require_view_group_submission($item->groupid);
3207 } else {
3208 $this->require_view_submission($item->userid);
3209 }
49d83b9d 3210 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
3211 $this->get_context(),
3212 $this->show_intro(),
3213 $this->get_course_module()->id,
3214 $plugin->get_name()));
49d83b9d 3215 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
bbd0e548
DW
3216 $item,
3217 assign_submission_plugin_submission::FULL,
3218 $this->get_course_module()->id,
3219 $this->get_return_action(),
3220 $this->get_return_params()));
3221
1be7aef2 3222 // Trigger event for viewing a submission.
1b90858f
PS
3223 \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
3224
bbd0e548
DW
3225 } else {
3226 $plugin = $this->get_feedback_plugin_by_type($plugintype);