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