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