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