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