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