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