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