weekly release 3.2dev
[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
0d64c75f
PN
94 /** @var stdClass the grade_item record for this assign instance's primary grade item. */
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 *
1248 * @return stdClass The grade_item record
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
be79d93f
DW
1374 $o = '';
1375
2a4fbc32 1376 if ($this->get_instance()->grade >= 0) {
e5403f8c 1377 // Normal number.
e7ade405 1378 if ($editing && $this->get_instance()->grade > 0) {
2d8a9ce9
DW
1379 if ($grade < 0) {
1380 $displaygrade = '';
1381 } else {
dd8ba800 1382 $displaygrade = format_float($grade, 2);
2d8a9ce9 1383 }
e5403f8c
DW
1384 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1385 get_string('usergrade', 'assign') .
1386 '</label>';
1387 $o .= '<input type="text"
1388 id="quickgrade_' . $userid . '"
1389 name="quickgrade_' . $userid . '"
1390 value="' . $displaygrade . '"
1391 size="6"
1392 maxlength="10"
1393 class="quickgrade"/>';
1394 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
bf78ebd6 1395 return $o;
bbd0e548 1396 } else {
a1e54f4d 1397 if ($grade == -1 || $grade === null) {
be79d93f 1398 $o .= '-';
a1e54f4d 1399 } else {
0d64c75f
PN
1400 $item = $this->get_grade_item();
1401 $o .= grade_format_gradevalue($grade, $item);
1402 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1403 // If displaying the raw grade, also display the total value.
1404 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, 2);
1405 }
a1e54f4d 1406 }
0d64c75f 1407 return $o;
bbd0e548
DW
1408 }
1409
2a4fbc32 1410 } else {
e5403f8c 1411 // Scale.
bbd0e548
DW
1412 if (empty($this->cache['scale'])) {
1413 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1414 $this->cache['scale'] = make_menu_from_list($scale->scale);
1415 } else {
be79d93f
DW
1416 $o .= '-';
1417 return $o;
bbd0e548
DW
1418 }
1419 }
bf78ebd6 1420 if ($editing) {
e5403f8c
DW
1421 $o .= '<label class="accesshide"
1422 for="quickgrade_' . $userid . '">' .
1423 get_string('usergrade', 'assign') .
1424 '</label>';
7400be1b 1425 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
bf78ebd6
DW
1426 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1427 foreach ($this->cache['scale'] as $optionid => $option) {
1428 $selected = '';
1429 if ($grade == $optionid) {
1430 $selected = 'selected="selected"';
1431 }
1432 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1433 }
1434 $o .= '</select>';
bf78ebd6
DW
1435 return $o;
1436 } else {
1437 $scaleid = (int)$grade;
1438 if (isset($this->cache['scale'][$scaleid])) {
be79d93f
DW
1439 $o .= $this->cache['scale'][$scaleid];
1440 return $o;
bf78ebd6 1441 }
be79d93f
DW
1442 $o .= '-';
1443 return $o;
bbd0e548 1444 }
bbd0e548
DW
1445 }
1446 }
1447
bb690849 1448 /**
1b2f9dc6
RW
1449 * Get the submission status/grading status for all submissions in this assignment for the
1450 * given paticipants.
1451 *
bb690849
DW
1452 * These statuses match the available filters (requiregrading, submitted, notsubmitted).
1453 * If this is a group assignment, group info is also returned.
1454 *
1b2f9dc6
RW
1455 * @param array $participants an associative array where the key is the participant id and
1456 * the value is the participant record.
1457 * @return array an associative array where the key is the participant id and the value is
1458 * the participant record.
bb690849 1459 */
1b2f9dc6 1460 private function get_submission_info_for_participants($participants) {
bb690849
DW
1461 global $DB;
1462
bb690849
DW
1463 if (empty($participants)) {
1464 return $participants;
1465 }
1466
1467 list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1468
1469 $assignid = $this->get_instance()->id;
1470 $params['assignmentid1'] = $assignid;
1471 $params['assignmentid2'] = $assignid;
1472
c06ce32d
AN
1473 $fields = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade';
1474 $from = ' FROM {user} u
bb690849
DW
1475 LEFT JOIN {assign_submission} s
1476 ON u.id = s.userid
1477 AND s.assignment = :assignmentid1
1478 AND s.latest = 1
1479 LEFT JOIN {assign_grades} g
1480 ON u.id = g.userid
1481 AND g.assignment = :assignmentid2
1482 AND g.attemptnumber = s.attemptnumber
c06ce32d
AN
1483 ';
1484 $where = ' WHERE u.id ' . $insql;
1485
1486 if (!empty($this->get_instance()->blindmarking)) {
1487 $from .= 'LEFT JOIN {assign_user_mapping} um
1488 ON u.id = um.userid
1489 AND um.assignment = :assignmentid3 ';
1490 $params['assignmentid3'] = $assignid;
1491 $fields .= ', um.id as recordid ';
1492 }
1493
1494 $sql = "$fields $from $where";
bb690849
DW
1495
1496 $records = $DB->get_records_sql($sql, $params);
1497
1498 if ($this->get_instance()->teamsubmission) {
1499 // Get all groups.
1500 $allgroups = groups_get_all_groups($this->get_course()->id,
1501 array_keys($participants),
1502 $this->get_instance()->teamsubmissiongroupingid,
1503 'DISTINCT g.id, g.name');
1504
1505 }
1506 foreach ($participants as $userid => $participant) {
1507 $participants[$userid]->fullname = $this->fullname($participant);
1508 $participants[$userid]->submitted = false;
1509 $participants[$userid]->requiregrading = false;
1510 }
1511
1512 foreach ($records as $userid => $submissioninfo) {
1513 // These filters are 100% the same as the ones in the grading table SQL.
1514 $submitted = false;
1515 $requiregrading = false;
1516
1517 if (!empty($submissioninfo->stime) && $submissioninfo->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1518 $submitted = true;
1519 }
1520
1521 if ($submitted && ($submissioninfo->stime >= $submissioninfo->gtime ||
1522 empty($submissioninfo->gtime) ||
1523 $submissioninfo->grade === null)) {
1524 $requiregrading = true;
1525 }
1526
1527 $participants[$userid]->submitted = $submitted;
1528 $participants[$userid]->requiregrading = $requiregrading;
1529 if ($this->get_instance()->teamsubmission) {
1530 $group = $this->get_submission_group($userid);
1531 if ($group) {
1532 $participants[$userid]->groupid = $group->id;
1533 $participants[$userid]->groupname = $group->name;
1534 }
1535 }
1536 }
1537 return $participants;
1538 }
1539
1b2f9dc6
RW
1540 /**
1541 * Get the submission status/grading status for all submissions in this assignment.
1542 * These statuses match the available filters (requiregrading, submitted, notsubmitted).
1543 * If this is a group assignment, group info is also returned.
1544 *
1545 * @param int $currentgroup
1546 * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'groupid', 'groupname'
1547 */
1548 public function list_participants_with_filter_status_and_group($currentgroup) {
1549 $participants = $this->list_participants($currentgroup, false);
1550
1551 if (empty($participants)) {
1552 return $participants;
1553 } else {
1554 return $this->get_submission_info_for_participants($participants);
1555 }
1556 }
1557
bbd0e548 1558 /**
e5403f8c
DW
1559 * Load a list of users enrolled in the current course with the specified permission and group.
1560 * 0 for no group.
bbd0e548
DW
1561 *
1562 * @param int $currentgroup
1563 * @param bool $idsonly
1564 * @return array List of user records
1565 */
1566 public function list_participants($currentgroup, $idsonly) {
bc006a66
DM
1567
1568 if (empty($currentgroup)) {
1569 $currentgroup = 0;
1570 }
1571
c46db93c
DW
1572 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1573 if (!isset($this->participants[$key])) {
bb690849
DW
1574 $order = 'u.lastname, u.firstname, u.id';
1575 if ($this->is_blind_marking()) {
1576 $order = 'u.id';
1577 }
1578 $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', $order, null, null,
1ecb8044 1579 $this->show_only_active_users());
c46db93c
DW
1580
1581 $cm = $this->get_course_module();
c13ac85d 1582 $info = new \core_availability\info_module($cm);
1583 $users = $info->filter_user_list($users);
c46db93c
DW
1584
1585 $this->participants[$key] = $users;
bbd0e548 1586 }
a0e59f04 1587
c46db93c
DW
1588 if ($idsonly) {
1589 $idslist = array();
1590 foreach ($this->participants[$key] as $id => $user) {
1591 $idslist[$id] = new stdClass();
1592 $idslist[$id]->id = $id;
a0e59f04 1593 }
c46db93c 1594 return $idslist;
a0e59f04 1595 }
c46db93c 1596 return $this->participants[$key];
bbd0e548
DW
1597 }
1598
1b2f9dc6
RW
1599 /**
1600 * Load a user if they are enrolled in the current course. Populated with submission
1601 * status for this assignment.
1602 *
1603 * @param int $userid
1604 * @return null|stdClass user record
1605 */
1606 public function get_participant($userid) {
1607 global $DB;
1608
1609 $participant = $DB->get_record('user', array('id' => $userid));
1610 if (!$participant) {
1611 return null;
1612 }
1613
1614 if (!is_enrolled($this->context, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
1615 return null;
1616 }
1617
1618 $result = $this->get_submission_info_for_participants(array($participant->id => $participant));
1619 return $result[$participant->id];
1620 }
1621
12a1a0da 1622 /**
e5403f8c 1623 * Load a count of valid teams for this assignment.
12a1a0da 1624 *
bc006a66 1625 * @param int $activitygroup Activity active group
12a1a0da
DW
1626 * @return int number of valid teams
1627 */
bc006a66
DM
1628 public function count_teams($activitygroup = 0) {
1629
1630 $count = 0;
1631
1632 $participants = $this->list_participants($activitygroup, true);
1633
1634 // If a team submission grouping id is provided all good as all returned groups
1635 // are the submission teams, but if no team submission grouping was specified
1636 // $groups will contain all participants groups.
1637 if ($this->get_instance()->teamsubmissiongroupingid) {
12a1a0da 1638
bc006a66
DM
1639 // We restrict the users to the selected group ones.
1640 $groups = groups_get_all_groups($this->get_course()->id,
1641 array_keys($participants),
1642 $this->get_instance()->teamsubmissiongroupingid,
1643 'DISTINCT g.id, g.name');
12a1a0da 1644
bc006a66
DM
1645 $count = count($groups);
1646
1647 // When a specific group is selected we don't count the default group users.
1648 if ($activitygroup == 0) {
e528997a
AH
1649 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1650 // See if there are any users in the default group.
1651 $defaultusers = $this->get_submission_group_members(0, true);
1652 if (count($defaultusers) > 0) {
1653 $count += 1;
1654 }
bc006a66
DM
1655 }
1656 }
1657 } else {
1658 // It is faster to loop around participants if no grouping was specified.
1659 $groups = array();
1660 foreach ($participants as $participant) {
1661 if ($group = $this->get_submission_group($participant->id)) {
1662 $groups[$group->id] = true;
e528997a 1663 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
bc006a66
DM
1664 $groups[0] = true;
1665 }
1666 }
12a1a0da 1667
bc006a66 1668 $count = count($groups);
12a1a0da 1669 }
bc006a66 1670
12a1a0da
DW
1671 return $count;
1672 }
1673
bbd0e548 1674 /**
c494e18c 1675 * Load a count of active users enrolled in the current course with the specified permission and group.
e5403f8c 1676 * 0 for no group.
bbd0e548
DW
1677 *
1678 * @param int $currentgroup
1679 * @return int number of matching users
1680 */
1681 public function count_participants($currentgroup) {
a0e59f04 1682 return count($this->list_participants($currentgroup, true));
bbd0e548
DW
1683 }
1684
f70079b9 1685 /**
c494e18c 1686 * Load a count of active users submissions in the current module that require grading
f70079b9 1687 * This means the submission modification time is more recent than the
7a9fd6da 1688 * grading modification time and the status is SUBMITTED.
f70079b9
DW
1689 *
1690 * @return int number of matching submissions
1691 */
1692 public function count_submissions_need_grading() {
1693 global $DB;
1694
8f7e1c05
DW
1695 if ($this->get_instance()->teamsubmission) {
1696 // This does not make sense for group assignment because the submission is shared.
1697 return 0;
1698 }
1699
1700 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
c494e18c 1701 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05
DW
1702
1703 $params['assignid'] = $this->get_instance()->id;
1704 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1705
1706 $sql = 'SELECT COUNT(s.userid)
1707 FROM {assign_submission} s
1708 LEFT JOIN {assign_grades} g ON
1709 s.assignment = g.assignment AND
df211804 1710 s.userid = g.userid AND
ad030ab4 1711 g.attemptnumber = s.attemptnumber
0c7b6910 1712 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05 1713 WHERE
ad030ab4 1714 s.latest = 1 AND
8f7e1c05
DW
1715 s.assignment = :assignid AND
1716 s.timemodified IS NOT NULL AND
1717 s.status = :submitted AND
ab848fea 1718 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL)';
f70079b9 1719
8f7e1c05 1720 return $DB->count_records_sql($sql, $params);
f70079b9
DW
1721 }
1722
bbd0e548 1723 /**
e5403f8c 1724 * Load a count of grades.
b473171a
DW
1725 *
1726 * @return int number of grades
1727 */
1728 public function count_grades() {
1729 global $DB;
1730
1731 if (!$this->has_instance()) {
1732 return 0;
1733 }
1734
8f7e1c05 1735 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
c494e18c 1736 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05
DW
1737
1738 $params['assignid'] = $this->get_instance()->id;
1739
1740 $sql = 'SELECT COUNT(g.userid)
1741 FROM {assign_grades} g
0c7b6910 1742 JOIN(' . $esql . ') e ON e.id = g.userid
8f7e1c05 1743 WHERE g.assignment = :assignid';
b473171a
DW
1744
1745 return $DB->count_records_sql($sql, $params);
1746 }
1747
1748 /**
e5403f8c 1749 * Load a count of submissions.
b473171a 1750 *
ab14ab74 1751 * @param bool $includenew When true, also counts the submissions with status 'new'.
b473171a
DW
1752 * @return int number of submissions
1753 */
ab14ab74 1754 public function count_submissions($includenew = false) {
b473171a
DW
1755 global $DB;
1756
1757 if (!$this->has_instance()) {
1758 return 0;
1759 }
1760
8f7e1c05 1761 $params = array();
ab14ab74
FM
1762 $sqlnew = '';
1763
1764 if (!$includenew) {
1765 $sqlnew = ' AND s.status <> :status ';
1766 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
1767 }
b473171a
DW
1768
1769 if ($this->get_instance()->teamsubmission) {
8f7e1c05 1770 // We cannot join on the enrolment tables for group submissions (no userid).
df211804 1771 $sql = 'SELECT COUNT(DISTINCT s.groupid)
8f7e1c05
DW
1772 FROM {assign_submission} s
1773 WHERE
1774 s.assignment = :assignid AND
1775 s.timemodified IS NOT NULL AND
ab14ab74
FM
1776 s.userid = :groupuserid' .
1777 $sqlnew;
8f7e1c05
DW
1778
1779 $params['assignid'] = $this->get_instance()->id;
1780 $params['groupuserid'] = 0;
1781 } else {
1782 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
ab14ab74 1783 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05 1784
ab14ab74 1785 $params = array_merge($params, $enrolparams);
8f7e1c05
DW
1786 $params['assignid'] = $this->get_instance()->id;
1787
df211804 1788 $sql = 'SELECT COUNT(DISTINCT s.userid)
8f7e1c05 1789 FROM {assign_submission} s
0c7b6910 1790 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05
DW
1791 WHERE
1792 s.assignment = :assignid AND
ab14ab74
FM
1793 s.timemodified IS NOT NULL ' .
1794 $sqlnew;
4c4c7b3f 1795
b473171a 1796 }
8f7e1c05 1797
b473171a
DW
1798 return $DB->count_records_sql($sql, $params);
1799 }
1800
1801 /**
e5403f8c 1802 * Load a count of submissions with a specified status.
bbd0e548
DW
1803 *
1804 * @param string $status The submission status - should match one of the constants
1805 * @return int number of matching submissions
1806 */
1807 public function count_submissions_with_status($status) {
1808 global $DB;
8f7e1c05
DW
1809
1810 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
c494e18c 1811 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
8f7e1c05
DW
1812
1813 $params['assignid'] = $this->get_instance()->id;
df211804 1814 $params['assignid2'] = $this->get_instance()->id;
8f7e1c05 1815 $params['submissionstatus'] = $status;
12a1a0da
DW
1816
1817 if ($this->get_instance()->teamsubmission) {
bc006a66
DM
1818
1819 $groupsstr = '';
1820 if ($currentgroup != 0) {
1821 // If there is an active group we should only display the current group users groups.
1822 $participants = $this->list_participants($currentgroup, true);
1823 $groups = groups_get_all_groups($this->get_course()->id,
1824 array_keys($participants),
1825 $this->get_instance()->teamsubmissiongroupingid,
1826 'DISTINCT g.id, g.name');
1827 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
1828 $groupsstr = 's.groupid ' . $groupssql . ' AND';
1829 $params = $params + $groupsparams;
1830 }
8f7e1c05
DW
1831 $sql = 'SELECT COUNT(s.groupid)
1832 FROM {assign_submission} s
1833 WHERE
ad030ab4 1834 s.latest = 1 AND
8f7e1c05
DW
1835 s.assignment = :assignid AND
1836 s.timemodified IS NOT NULL AND
bc006a66
DM
1837 s.userid = :groupuserid AND '
1838 . $groupsstr . '
8f7e1c05
DW
1839 s.status = :submissionstatus';
1840 $params['groupuserid'] = 0;
1841 } else {
1842 $sql = 'SELECT COUNT(s.userid)
1843 FROM {assign_submission} s
0c7b6910 1844 JOIN(' . $esql . ') e ON e.id = s.userid
8f7e1c05 1845 WHERE
ad030ab4 1846 s.latest = 1 AND
8f7e1c05
DW
1847 s.assignment = :assignid AND
1848 s.timemodified IS NOT NULL AND
1849 s.status = :submissionstatus';
4c4c7b3f 1850
12a1a0da 1851 }
8f7e1c05 1852
12a1a0da 1853 return $DB->count_records_sql($sql, $params);
bbd0e548
DW
1854 }
1855
1856 /**
1857 * Utility function to get the userid for every row in the grading table
e5403f8c 1858 * so the order can be frozen while we iterate it.
bbd0e548
DW
1859 *
1860 * @return array An array of userids
1861 */
47f48152 1862 protected function get_grading_userid_list() {
bbd0e548 1863 $filter = get_user_preferences('assign_filter', '');
bf78ebd6 1864 $table = new assign_grading_table($this, 0, $filter, 0, false);
bbd0e548
DW
1865
1866 $useridlist = $table->get_column_data('userid');
1867
1868 return $useridlist;
1869 }
1870
bbd0e548 1871 /**
e5403f8c 1872 * Generate zip file from array of given files.
bbd0e548 1873 *
e5403f8c
DW
1874 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1875 * This array is indexed by the final file name and each
1876 * element in the array is an instance of a stored_file object.
1877 * @return path of temp file - note this returned file does
1878 * not have a .zip extension - it is a temp file.
bbd0e548 1879 */
47f48152 1880 protected function pack_files($filesforzipping) {
e5403f8c
DW
1881 global $CFG;
1882 // Create path for new zip file.
1883 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1884 // Zip files.
1885 $zipper = new zip_packer();
1886 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1887 return $tempzip;
bbd0e548 1888 }
e5403f8c 1889 return false;
bbd0e548
DW
1890 }
1891
bbd0e548 1892 /**
3f7b501e
SH
1893 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1894 *
e5403f8c 1895 * Cron function to be run periodically according to the moodle cron.
bbd0e548
DW
1896 *
1897 * @return bool
1898 */
e5403f8c 1899 public static function cron() {
3f7b501e 1900 global $DB;
75f87a57 1901
e5403f8c 1902 // Only ever send a max of one days worth of updates.
75f87a57
DW
1903 $yesterday = time() - (24 * 3600);
1904 $timenow = time();
abd0f0ae 1905 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
75f87a57 1906
70cfc878
JF
1907 // Collect all submissions that require mailing.
1908 // Submissions are included if all are true:
1909 // - The assignment is visible in the gradebook.
1910 // - No previous notification has been sent.
1911 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
1912 // if marking workflow is enabled, the workflow state is at 'released'.
86dced43 1913 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
cf29b1e0 1914 g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
3f7b501e
SH
1915 FROM {assign} a
1916 JOIN {assign_grades} g ON g.assignment = a.id
fdd3ebc5 1917 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
86dced43
TB
1918 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
1919 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
fdd3ebc5 1920 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
cf29b1e0 1921 LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
70cfc878
JF
1922 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
1923 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
f33be9eb
TB
1924 uf.mailed = 0 AND gri.hidden = 0
1925 ORDER BY a.course, cm.id";
e5403f8c 1926
70cfc878
JF
1927 $params = array(
1928 'yesterday' => $yesterday,
1929 'today' => $timenow,
1930 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
1931 );
3f7b501e 1932 $submissions = $DB->get_records_sql($sql, $params);
75f87a57 1933
ae7638f7 1934 if (!empty($submissions)) {
c8314005 1935
ae7638f7 1936 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
75f87a57 1937
ae7638f7
DW
1938 // Preload courses we are going to need those.
1939 $courseids = array();
1940 foreach ($submissions as $submission) {
1941 $courseids[] = $submission->course;
1942 }
e5403f8c 1943
ae7638f7
DW
1944 // Filter out duplicates.
1945 $courseids = array_unique($courseids);
1946 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1947 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1948 $sql = 'SELECT c.*, ' . $ctxselect .
1949 ' FROM {course} c
1950 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1951 WHERE c.id ' . $courseidsql;
e5403f8c 1952
ae7638f7
DW
1953 $params['contextlevel'] = CONTEXT_COURSE;
1954 $courses = $DB->get_records_sql($sql, $params);
e5403f8c 1955
ae7638f7
DW
1956 // Clean up... this could go on for a while.
1957 unset($courseids);
1958 unset($ctxselect);
1959 unset($courseidsql);
1960 unset($params);
3f7b501e 1961
ae7638f7
DW
1962 // Message students about new feedback.
1963 foreach ($submissions as $submission) {
75f87a57 1964
ae7638f7 1965 mtrace("Processing assignment submission $submission->id ...");
75f87a57 1966
ae7638f7
DW
1967 // Do not cache user lookups - could be too many.
1968 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1969 mtrace('Could not find user ' . $submission->userid);
1970 continue;
1971 }
75f87a57 1972
ae7638f7
DW
1973 // Use a cache to prevent the same DB queries happening over and over.
1974 if (!array_key_exists($submission->course, $courses)) {
1975 mtrace('Could not find course ' . $submission->course);
1976 continue;
1977 }
1978 $course = $courses[$submission->course];
1979 if (isset($course->ctxid)) {
1980 // Context has not yet been preloaded. Do so now.
1981 context_helper::preload_from_record($course);
1982 }
75f87a57 1983
ae7638f7
DW
1984 // Override the language and timezone of the "current" user, so that
1985 // mail is customised for the receiver.
1986 cron_setup_user($user, $course);
1987
1988 // Context lookups are already cached.
1989 $coursecontext = context_course::instance($course->id);
1990 if (!is_enrolled($coursecontext, $user->id)) {
1991 $courseshortname = format_string($course->shortname,
1992 true,
1993 array('context' => $coursecontext));
1994 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1995 continue;
1996 }
75f87a57 1997
ae7638f7
DW
1998 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1999 mtrace('Could not find grader ' . $submission->grader);
2000 continue;
2001 }
75f87a57 2002
ccd6839a 2003 $modinfo = get_fast_modinfo($course, $user->id);
86dced43 2004 $cm = $modinfo->get_cm($submission->cmid);
ae7638f7 2005 // Context lookups are already cached.
86dced43 2006 $contextmodule = context_module::instance($cm->id);
ae7638f7 2007
ccd6839a
TB
2008 if (!$cm->uservisible) {
2009 // Hold mail notification for assignments the user cannot access until later.
75f87a57
DW
2010 continue;
2011 }
bbd0e548 2012
ae7638f7
DW
2013 // Need to send this to the student.
2014 $messagetype = 'feedbackavailable';
2015 $eventtype = 'assign_notification';
2016 $updatetime = $submission->lastmodified;
2017 $modulename = get_string('modulename', 'assign');
75f87a57 2018
ae7638f7
DW
2019 $uniqueid = 0;
2020 if ($submission->blindmarking && !$submission->revealidentities) {
cf29b1e0
AN
2021 if (empty($submission->recordid)) {
2022 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
2023 } else {
2024 $uniqueid = $submission->recordid;
2025 }
ae7638f7
DW
2026 }
2027 $showusers = $submission->blindmarking && !$submission->revealidentities;
2028 self::send_assignment_notification($grader,
2029 $user,
2030 $messagetype,
2031 $eventtype,
2032 $updatetime,
86dced43 2033 $cm,
ae7638f7
DW
2034 $contextmodule,
2035 $course,
2036 $modulename,
2037 $submission->name,
2038 $showusers,
2039 $uniqueid);
2040
2041 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
2042 if ($flags) {
2043 $flags->mailed = 1;
2044 $DB->update_record('assign_user_flags', $flags);
2045 } else {
2046 $flags = new stdClass();
2047 $flags->userid = $user->id;
2048 $flags->assignment = $submission->assignment;
2049 $flags->mailed = 1;
2050 $DB->insert_record('assign_user_flags', $flags);
2051 }
b473171a 2052
ae7638f7 2053 mtrace('Done');
df211804 2054 }
ae7638f7 2055 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
75f87a57 2056
ae7638f7
DW
2057 cron_setup_user();
2058
2059 // Free up memory just to be sure.
2060 unset($courses);
75f87a57 2061 }
75f87a57 2062
ae7638f7
DW
2063 // Update calendar events to provide a description.
2064 $sql = 'SELECT id
2065 FROM {assign}
2066 WHERE
2067 allowsubmissionsfromdate >= :lastcron AND
2068 allowsubmissionsfromdate <= :timenow AND
2069 alwaysshowdescription = 0';
2070 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2071 $newlyavailable = $DB->get_records_sql($sql, $params);
2072 foreach ($newlyavailable as $record) {
2073 $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
2074 $context = context_module::instance($cm->id);
3f7b501e 2075
ae7638f7
DW
2076 $assignment = new assign($context, null, null);
2077 $assignment->update_calendar($cm->id);
2078 }
bbd0e548
DW
2079
2080 return true;
2081 }
2082
d6c673ed
DW
2083 /**
2084 * Mark in the database that this grade record should have an update notification sent by cron.
2085 *
2086 * @param stdClass $grade a grade record keyed on id
a4b10a52 2087 * @param bool $mailedoverride when true, flag notification to be sent again.
d6c673ed
DW
2088 * @return bool true for success
2089 */
a4b10a52 2090 public function notify_grade_modified($grade, $mailedoverride = false) {
d6c673ed
DW
2091 global $DB;
2092
df211804 2093 $flags = $this->get_user_flags($grade->userid, true);
a4b10a52 2094 if ($flags->mailed != 1 || $mailedoverride) {
df211804 2095 $flags->mailed = 0;
d6c673ed
DW
2096 }
2097
df211804
DW
2098 return $this->update_user_flags($flags);
2099 }
2100
2101 /**
2102 * Update user flags for this user in this assignment.
2103 *
2104 * @param stdClass $flags a flags record keyed on id
2105 * @return bool true for success
2106 */
2107 public function update_user_flags($flags) {
2108 global $DB;
2109 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
2110 return false;
2111 }
2112
2113 $result = $DB->update_record('assign_user_flags', $flags);
2114 return $result;
d6c673ed
DW
2115 }
2116
bbd0e548 2117 /**
e5403f8c 2118 * Update a grade in the grade table for the assignment and in the gradebook.
bbd0e548
DW
2119 *
2120 * @param stdClass $grade a grade record keyed on id
ab38cb28 2121 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
bbd0e548
DW
2122 * @return bool true for success
2123 */
ab38cb28 2124 public function update_grade($grade, $reopenattempt = false) {
bbd0e548
DW
2125 global $DB;
2126
2127 $grade->timemodified = time();
2128
f8d107b3
DM
2129 if (!empty($grade->workflowstate)) {
2130 $validstates = $this->get_marking_workflow_states_for_current_user();
2131 if (!array_key_exists($grade->workflowstate, $validstates)) {
2132 return false;
2133 }
2134 }
2135
bbd0e548
DW
2136 if ($grade->grade && $grade->grade != -1) {
2137 if ($this->get_instance()->grade > 0) {
2138 if (!is_numeric($grade->grade)) {
2139 return false;
2140 } else if ($grade->grade > $this->get_instance()->grade) {
2141 return false;
2142 } else if ($grade->grade < 0) {
2143 return false;
2144 }
2145 } else {
e5403f8c 2146 // This is a scale.
bbd0e548
DW
2147 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
2148 $scaleoptions = make_menu_from_list($scale->scale);
2149 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
2150 return false;
2151 }
2152 }
2153 }
2154 }
2155
a8fdb36c
DW
2156 if (empty($grade->attemptnumber)) {
2157 // Set it to the default.
2158 $grade->attemptnumber = 0;
2159 }
e77bacab 2160 $DB->update_record('assign_grades', $grade);
df211804 2161
df211804
DW
2162 $submission = null;
2163 if ($this->get_instance()->teamsubmission) {
2164 $submission = $this->get_group_submission($grade->userid, 0, false);
2165 } else {
2166 $submission = $this->get_user_submission($grade->userid, false);
2167 }
767fda9b
GF
2168
2169 // Only push to gradebook if the update is for the latest attempt.
df211804
DW
2170 // Not the latest attempt.
2171 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
2172 return true;
2173 }
2174
bd3ee807
MN
2175 if ($this->gradebook_item_update(null, $grade)) {
2176 \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
2177 }
e77bacab
MP
2178
2179 // If the conditions are met, allow another attempt.
2180 if ($submission) {
2181 $this->reopen_submission_if_required($grade->userid,
2182 $submission,
2183 $reopenattempt);
bbd0e548 2184 }
bd3ee807 2185
e77bacab 2186 return true;
bbd0e548
DW
2187 }
2188
9e795179 2189 /**
e5403f8c 2190 * View the grant extension date page.
9e795179
DW
2191 *
2192 * Uses url parameters 'userid'
2193 * or from parameter 'selectedusers'
e5403f8c 2194 *
9e795179
DW
2195 * @param moodleform $mform - Used for validation of the submitted data
2196 * @return string
2197 */
47f48152 2198 protected function view_grant_extension($mform) {
9e795179
DW
2199 global $DB, $CFG;
2200 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2201
2202 $o = '';
26670f5e 2203
9e795179 2204 $data = new stdClass();
26670f5e 2205 $data->id = $this->get_course_module()->id;
9e795179 2206
26670f5e
JF
2207 $formparams = array(
2208 'instance' => $this->get_instance()
2209 );
2210
2211 $extrauserfields = get_extra_user_fields($this->get_context());
2212
2213 if ($mform) {
2214 $submitteddata = $mform->get_data();
2215 $users = $submitteddata->selectedusers;
2216 $userlist = explode(',', $users);
2217
2218 $data->selectedusers = $users;
2219 $data->userid = 0;
9e795179 2220
26670f5e
JF
2221 $usershtml = '';
2222 $usercount = 0;
2223 foreach ($userlist as $userid) {
2224 if ($usercount >= 5) {
2225 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
2226 break;
2227 }
2228 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
2229
2230 $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
2231 $this->get_course()->id,
2232 has_capability('moodle/site:viewfullnames',
2233 $this->get_course_context()),
2234 $this->is_blind_marking(),
2235 $this->get_uniqueid_for_user($user->id),
2236 $extrauserfields,
2237 !$this->is_active_user($userid)));
2238 $usercount += 1;
2239 }
2240
2241 $formparams['userscount'] = count($userlist);
2242 $formparams['usershtml'] = $usershtml;
2243
2244 } else {
2245 $userid = required_param('userid', PARAM_INT);
9e795179 2246 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
26670f5e 2247 $flags = $this->get_user_flags($userid, false);
9e795179 2248
26670f5e 2249 $data->userid = $user->id;
9f65f9c3
DW
2250 if ($flags) {
2251 $data->extensionduedate = $flags->extensionduedate;
9e795179 2252 }
26670f5e
JF
2253
2254 $usershtml = $this->get_renderer()->render(new assign_user_summary($user,
2255 $this->get_course()->id,
2256 has_capability('moodle/site:viewfullnames',
2257 $this->get_course_context()),
2258 $this->is_blind_marking(),
2259 $this->get_uniqueid_for_user($user->id),
2260 $extrauserfields,
2261 !$this->is_active_user($userid)));
2262 $formparams['usershtml'] = $usershtml;
9e795179 2263 }
26670f5e
JF
2264
2265 $mform = new mod_assign_extension_form(null, $formparams);
2266 $mform->set_data($data);
e5403f8c
DW
2267 $header = new assign_header($this->get_instance(),
2268 $this->get_context(),
2269 $this->show_intro(),
2270 $this->get_course_module()->id,
2271 get_string('grantextension', 'assign'));
2272 $o .= $this->get_renderer()->render($header);
49d83b9d 2273 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
9e795179
DW
2274 $o .= $this->view_footer();
2275 return $o;
2276 }
2277
12a1a0da 2278 /**
e5403f8c 2279 * Get a list of the users in the same group as this user.
12a1a0da
DW
2280 *
2281 * @param int $groupid The id of the group whose members we want or 0 for the default group
2282 * @param bool $onlyids Whether to retrieve only the user id's
b2885704 2283 * @param bool $excludesuspended Whether to exclude suspended users
12a1a0da
DW
2284 * @return array The users (possibly id's only)
2285 */
b2885704 2286 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
12a1a0da
DW
2287 $members = array();
2288 if ($groupid != 0) {
64ccb37d 2289 $allusers = $this->list_participants($groupid, $onlyids);
12a1a0da
DW
2290 foreach ($allusers as $user) {
2291 if ($this->get_submission_group($user->id)) {
2292 $members[] = $user;
2293 }
2294 }
2295 } else {
2296 $allusers = $this->list_participants(null, $onlyids);
2297 foreach ($allusers as $user) {
2298 if ($this->get_submission_group($user->id) == null) {
2299 $members[] = $user;
2300 }
2301 }
2302 }
4c4c7b3f 2303 // Exclude suspended users, if user can't see them.
b2885704 2304 if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
4c4c7b3f 2305 foreach ($members as $key => $member) {
1ecb8044 2306 if (!$this->is_active_user($member->id)) {
4c4c7b3f
RT
2307 unset($members[$key]);
2308 }
2309 }
2310 }
bc006a66 2311
12a1a0da
DW
2312 return $members;
2313 }
2314
2315 /**
e5403f8c 2316 * Get a list of the users in the same group as this user that have not submitted the assignment.
12a1a0da
DW
2317 *
2318 * @param int $groupid The id of the group whose members we want or 0 for the default group
2319 * @param bool $onlyids Whether to retrieve only the user id's
2320 * @return array The users (possibly id's only)
2321 */
2322 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
e5403f8c
DW
2323 $instance = $this->get_instance();
2324 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
12a1a0da
DW
2325 return array();
2326 }
2327 $members = $this->get_submission_group_members($groupid, $onlyids);
2328
2329 foreach ($members as $id => $member) {
2330 $submission = $this->get_user_submission($member->id, false);
df211804 2331 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
12a1a0da 2332 unset($members[$id]);
88cfe469
DW
2333 } else {
2334 if ($this->is_blind_marking()) {
e5403f8c
DW
2335 $members[$id]->alias = get_string('hiddenuser', 'assign') .
2336 $this->get_uniqueid_for_user($id);
88cfe469 2337 }
12a1a0da
DW
2338 }
2339 }
2340 return $members;
2341 }
2342
2343 /**
e5403f8c 2344 * Load the group submission object for a particular user, optionally creating it if required.
12a1a0da
DW
2345 *
2346 * @param int $userid The id of the user whose submission we want
e5403f8c
DW
2347 * @param int $groupid The id of the group for this user - may be 0 in which
2348 * case it is determined from the userid.
12a1a0da 2349 * @param bool $create If set to true a new submission object will be created in the database
9e3eee67 2350 * with the status set to "new".
df211804 2351 * @param int $attemptnumber - -1 means the latest attempt
12a1a0da
DW
2352 * @return stdClass The submission
2353 */
df211804 2354 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
12a1a0da
DW
2355 global $DB;
2356
2357 if ($groupid == 0) {
2358 $group = $this->get_submission_group($userid);
2359 if ($group) {
2360 $groupid = $group->id;
2361 }
2362 }
2363
12a1a0da
DW
2364 // Now get the group submission.
2365 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
df211804
DW
2366 if ($attemptnumber >= 0) {
2367 $params['attemptnumber'] = $attemptnumber;
2368 }
2369
2370 // Only return the row with the highest attemptnumber.
2371 $submission = null;
2372 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2373 if ($submissions) {
2374 $submission = reset($submissions);
2375 }
12a1a0da
DW
2376
2377 if ($submission) {
2378 return $submission;
2379 }
2380 if ($create) {
2381 $submission = new stdClass();
e5403f8c
DW
2382 $submission->assignment = $this->get_instance()->id;
2383 $submission->userid = 0;
2384 $submission->groupid = $groupid;
12a1a0da
DW
2385 $submission->timecreated = time();
2386 $submission->timemodified = $submission->timecreated;
df211804
DW
2387 if ($attemptnumber >= 0) {
2388 $submission->attemptnumber = $attemptnumber;
12a1a0da 2389 } else {
df211804 2390 $submission->attemptnumber = 0;
12a1a0da 2391 }
1523f9e0
DW
2392 // Work out if this is the latest submission.
2393 $submission->latest = 0;
2394 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2395 if ($attemptnumber == -1) {
2396 // This is a new submission so it must be the latest.
2397 $submission->latest = 1;
2398 } else {
2399 // We need to work this out.
2400 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2401 if ($result) {
2402 $latestsubmission = reset($result);
2403 }
2404 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2405 $submission->latest = 1;
2406 }
2407 }
2408 if ($submission->latest) {
2409 // This is the case when we need to set latest to 0 for all the other attempts.
2410 $DB->set_field('assign_submission', 'latest', 0, $params);
2411 }
9e3eee67 2412 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
12a1a0da 2413 $sid = $DB->insert_record('assign_submission', $submission);
4781ff2e 2414 return $DB->get_record('assign_submission', array('id' => $sid));
12a1a0da
DW
2415 }
2416 return false;
2417 }
2418
df47b77f 2419 /**
64220210
DW
2420 * View a summary listing of all assignments in the current course.
2421 *
2422 * @return string
2423 */
2424 private function view_course_index() {
2425 global $USER;
2426
2427 $o = '';
2428
2429 $course = $this->get_course();
2430 $strplural = get_string('modulenameplural', 'assign');
2431
2432 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2433 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2434 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2435 return $o;
2436 }
2437
09af1e28 2438 $strsectionname = '';
64220210
DW
2439 $usesections = course_format_uses_sections($course->format);
2440 $modinfo = get_fast_modinfo($course);
2441
2442 if ($usesections) {
09af1e28 2443 $strsectionname = get_string('sectionname', 'format_'.$course->format);
64220210
DW
2444 $sections = $modinfo->get_section_info_all();
2445 }
2446 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2447
2448 $timenow = time();
2449
2450 $currentsection = '';
2451 foreach ($modinfo->instances['assign'] as $cm) {
2452 if (!$cm->uservisible) {
2453 continue;
2454 }
2455
e5403f8c 2456 $timedue = $cms[$cm->id]->duedate;
64220210
DW
2457
2458 $sectionname = '';
2459 if ($usesections && $cm->sectionnum) {
2460 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2461 }
2462
2463 $submitted = '';
2464 $context = context_module::instance($cm->id);
2465
2466 $assignment = new assign($context, $cm, $course);
2467
2468 if (has_capability('mod/assign:grade', $context)) {
2469 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2470
2471 } else if (has_capability('mod/assign:submit', $context)) {
2472 $usersubmission = $assignment->get_user_submission($USER->id, false);
2473
2474 if (!empty($usersubmission->status)) {
2475 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2476 } else {
2477 $submitted = get_string('submissionstatus_', 'assign');
2478 }
2479 }
539af602
DW
2480 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2481 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2482 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2483 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
64220210
DW
2484 } else {
2485 $grade = '-';
2486 }
2487
92c9be19 2488 $courseindexsummary->add_assign_info($cm->id, $cm->get_formatted_name(), $sectionname, $timedue, $submitted, $grade);
64220210
DW
2489
2490 }
2491
2492 $o .= $this->get_renderer()->render($courseindexsummary);
2493 $o .= $this->view_footer();
2494
2495 return $o;
2496 }
2497
2498 /**
2499 * View a page rendered by a plugin.
df47b77f 2500 *
e5403f8c 2501 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
df47b77f
DW
2502 *
2503 * @return string
2504 */
47f48152 2505 protected function view_plugin_page() {
df47b77f
DW
2506 global $USER;
2507
2508 $o = '';
2509
2510 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2511 $plugintype = required_param('plugin', PARAM_TEXT);
2512 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2513
2514 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2515 if (!$plugin) {
2516 print_error('invalidformdata', '');
2517 return;
2518 }
2519
2520 $o .= $plugin->view_page($pluginaction);
2521
2522 return $o;
2523 }
2524
2525
12a1a0da
DW
2526 /**
2527 * This is used for team assignments to get the group for the specified user.
2528 * If the user is a member of multiple or no groups this will return false
2529 *
2530 * @param int $userid The id of the user whose submission we want
2531 * @return mixed The group or false
2532 */
2533 public function get_submission_group($userid) {
bc006a66
DM
2534
2535 if (isset($this->usersubmissiongroups[$userid])) {
2536 return $this->usersubmissiongroups[$userid];
2537 }
2538
ee5d4eef 2539 $groups = $this->get_all_groups($userid);
12a1a0da 2540 if (count($groups) != 1) {
bc006a66
DM
2541 $return = false;
2542 } else {
2543 $return = array_pop($groups);
12a1a0da 2544 }
bc006a66
DM
2545
2546 // Cache the user submission group.
2547 $this->usersubmissiongroups[$userid] = $return;
2548
2549 return $return;
12a1a0da
DW
2550 }
2551
a059ef2e
DP
2552 /**
2553 * Gets all groups the user is a member of.
2554 *
2555 * @param int $userid Teh id of the user who's groups we are checking
2556 * @return array The group objects
2557 */
ce449f63 2558 public function get_all_groups($userid) {
ee5d4eef
AH
2559 if (isset($this->usergroups[$userid])) {
2560 return $this->usergroups[$userid];
2561 }
2562
2563 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2564 $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2565
2566 $this->usergroups[$userid] = $return;
2567
2568 return $return;
2569 }
2570
9e795179 2571
bbd0e548 2572 /**
e5403f8c
DW
2573 * Display the submission that is used by a plugin.
2574 *
2575 * Uses url parameters 'sid', 'gid' and 'plugin'.
2576 *
bbd0e548
DW
2577 * @param string $pluginsubtype
2578 * @return string
2579 */
47f48152 2580 protected function view_plugin_content($pluginsubtype) {
bbd0e548
DW
2581 $o = '';
2582
2583 $submissionid = optional_param('sid', 0, PARAM_INT);
2584 $gradeid = optional_param('gid', 0, PARAM_INT);
2585 $plugintype = required_param('plugin', PARAM_TEXT);
2586 $item = null;
2587 if ($pluginsubtype == 'assignsubmission') {
2588 $plugin = $this->get_submission_plugin_by_type($plugintype);
2589 if ($submissionid <= 0) {
2590 throw new coding_exception('Submission id should not be 0');
2591 }
2592 $item = $this->get_submission($submissionid);
2593
e5403f8c 2594 // Check permissions.
4a47008c 2595 $this->require_view_submission($item->userid);
49d83b9d 2596 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2597 $this->get_context(),
2598 $this->show_intro(),
2599 $this->get_course_module()->id,
2600 $plugin->get_name()));
49d83b9d 2601 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
bbd0e548
DW
2602 $item,
2603 assign_submission_plugin_submission::FULL,
2604 $this->get_course_module()->id,
2605 $this->get_return_action(),
2606 $this->get_return_params()));
2607
1be7aef2 2608 // Trigger event for viewing a submission.
1b90858f
PS
2609 \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2610
bbd0e548
DW
2611 } else {
2612 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2613 if ($gradeid <= 0) {
2614 throw new coding_exception('Grade id should not be 0');
2615 }
2616 $item = $this->get_grade($gradeid);
e5403f8c 2617 // Check permissions.
4a47008c 2618 $this->require_view_submission($item->userid);
49d83b9d 2619 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2620 $this->get_context(),
2621 $this->show_intro(),
2622 $this->get_course_module()->id,
2623 $plugin->get_name()));
49d83b9d 2624 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
bbd0e548
DW
2625 $item,
2626 assign_feedback_plugin_feedback::FULL,
2627 $this->get_course_module()->id,
2628 $this->get_return_action(),
2629 $this->get_return_params()));
3290c01d
MN
2630
2631 // Trigger event for viewing feedback.
1b90858f 2632 \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
bbd0e548
DW
2633 }
2634
bbd0e548
DW
2635 $o .= $this->view_return_links();
2636
2637 $o .= $this->view_footer();
1be7aef2 2638
bbd0e548
DW
2639 return $o;
2640 }
2641
2406815b
DW
2642 /**
2643 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2644 *
1561a37c 2645 * @param string $text - The replacement text
2406815b
DW
2646 * @param stdClass $user - The user record
2647 * @param assign_plugin $plugin - The assignment plugin
2648 */
2649 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2650 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2651 $groupname = '';
2652 if ($groupmode) {
2653 $groupid = groups_get_activity_group($this->get_course_module(), true);
2654 $groupname = groups_get_group_name($groupid).'-';
2655 }
2656
2657 if ($this->is_blind_marking()) {
2658 $prefix = $groupname . get_string('participant', 'assign');
2659 $prefix = str_replace('_', ' ', $prefix);
2660 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2661 } else {
2662 $prefix = $groupname . fullname($user);
2663 $prefix = str_replace('_', ' ', $prefix);
2664 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2665 }
2666
2667 $subtype = $plugin->get_subtype();
2668 $type = $plugin->get_type();
2669 $prefix = $prefix . $subtype . '_' . $type . '_';
2670
2671 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2672
2673 return $result;
2674 }
2675
bbd0e548 2676 /**
e5403f8c 2677 * Render the content in editor that is often used by plugin.
bbd0e548
DW
2678 *
2679 * @param string $filearea
2680 * @param int $submissionid
2681 * @param string $plugintype
2682 * @param string $editor
2683 * @param string $component
2684 * @return string
2685 */
2686 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2687 global $CFG;
2688
2689 $result = '';
2690
2691 $plugin = $this->get_submission_plugin_by_type($plugintype);
2692
2693 $text = $plugin->get_editor_text($editor, $submissionid);
2694 $format = $plugin->get_editor_format($editor, $submissionid);
2695
e5403f8c
DW
2696 $finaltext = file_rewrite_pluginfile_urls($text,
2697 'pluginfile.php',
2698 $this->get_context()->id,
2699 $component,
2700 $filearea,
2701 $submissionid);
2702 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2703 $result .= format_text($finaltext, $format, $params);
bbd0e548 2704
418bd23f 2705 if ($CFG->enableportfolios && has_capability('mod/assign:exportownsubmission', $this->context)) {
bbd0e548
DW
2706 require_once($CFG->libdir . '/portfoliolib.php');
2707
2708 $button = new portfolio_add_button();
e5403f8c
DW
2709 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2710 'sid' => $submissionid,
2711 'plugin' => $plugintype,
2712 'editor' => $editor,
2713 'area'=>$filearea);
2714 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
bbd0e548
DW
2715 $fs = get_file_storage();
2716
e5403f8c
DW
2717 if ($files = $fs->get_area_files($this->context->id,
2718 $component,
2719 $filearea,
2720 $submissionid,
2721 'timemodified',
2722 false)) {
bbd0e548
DW
2723 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2724 } else {
2725 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2726 }
2727 $result .= $button->to_html();
2728 }
2729 return $result;
2730 }
2731
df211804 2732 /**
d9bfe3c5 2733 * Display a continue page after grading.
df211804 2734 *
d9bfe3c5 2735 * @param string $message - The message to display.
df211804
DW
2736 * @return string
2737 */
2738 protected function view_savegrading_result($message) {
2739 $o = '';
2740 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2741 $this->get_context(),
2742 $this->show_intro(),
2743 $this->get_course_module()->id,
2744 get_string('savegradingresult', 'assign')));
2745 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2746 $message,
2747 $this->get_course_module()->id);
2748 $o .= $this->get_renderer()->render($gradingresult);
2749 $o .= $this->view_footer();
2750 return $o;
2751 }
bf78ebd6 2752 /**
d9bfe3c5 2753 * Display a continue page after quickgrading.
bf78ebd6 2754 *
d9bfe3c5 2755 * @param string $message - The message to display.
bf78ebd6
DW
2756 * @return string
2757 */
47f48152 2758 protected function view_quickgrading_result($message) {
bf78ebd6 2759 $o = '';
49d83b9d 2760 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bf78ebd6
DW
2761 $this->get_context(),
2762 $this->show_intro(),
2763 $this->get_course_module()->id,
2764 get_string('quickgradingresult', 'assign')));
cfdd3e5c 2765 $lastpage = optional_param('lastpage', null, PARAM_INT);
df211804
DW
2766 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2767 $message,
cfdd3e5c
GF
2768 $this->get_course_module()->id,
2769 false,
2770 $lastpage);
e5403f8c 2771 $o .= $this->get_renderer()->render($gradingresult);
bf78ebd6
DW
2772 $o .= $this->view_footer();
2773 return $o;
2774 }
bbd0e548
DW
2775
2776 /**
e5403f8c 2777 * Display the page footer.
bbd0e548 2778 *
bf78ebd6 2779 * @return string
bbd0e548 2780 */
47f48152 2781 protected function view_footer() {
1be7aef2
MN
2782 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2783 if (!PHPUNIT_TEST) {
2784 return $this->get_renderer()->render_footer();
2785 }
2786
2787 return '';
bbd0e548
DW
2788 }
2789
4a47008c
DW
2790 /**
2791 * Throw an error if the permissions to view this users submission are missing.
2792 *
2793 * @throws required_capability_exception
2794 * @return none
2795 */
2796 public function require_view_submission($userid) {
2797 if (!$this->can_view_submission($userid)) {
2798 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2799 }
2800 }
2801
2802 /**
2803 * Throw an error if the permissions to view grades in this assignment are missing.
2804 *
2805 * @throws required_capability_exception
2806 * @return none
2807 */
2808 public function require_view_grades() {
2809 if (!$this->can_view_grades()) {
2810 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2811 }
2812 }
2813
2814 /**
2815 * Does this user have view grade or grade permission for this assignment?
2816 *
2817 * @return bool
2818 */
2819 public function can_view_grades() {
2820 // Permissions check.
2821 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2822 return false;
2823 }
2824
2825 return true;
2826 }
2827
bbd0e548 2828 /**
e5403f8c 2829 * Does this user have grade permission for this assignment?
bbd0e548
DW
2830 *
2831 * @return bool
2832 */
5c386472 2833 public function can_grade() {
e5403f8c 2834 // Permissions check.
bbd0e548
DW
2835 if (!has_capability('mod/assign:grade', $this->context)) {
2836 return false;
2837 }
2838
2839 return true;
2840 }
2841
2842 /**
e5403f8c 2843 * Download a zip file of all assignment submissions.
bbd0e548 2844 *
064814ea 2845 * @param array $userids Array of user ids to download assignment submissions in a zip file
df211804 2846 * @return string - If an error occurs, this will contain the error page.
bbd0e548 2847 */
064814ea 2848 protected function download_submissions($userids = false) {
e5403f8c 2849 global $CFG, $DB;
bbd0e548 2850
d0d4796b 2851 // More efficient to load this here.
bbd0e548
DW
2852 require_once($CFG->libdir.'/filelib.php');
2853
08334e06
MS
2854 // Increase the server timeout to handle the creation and sending of large zip files.
2855 core_php_time_limit::raise();
2856
4a47008c 2857 $this->require_view_grades();
76640b27 2858
d0d4796b 2859 // Load all users with submit.
4c4c7b3f 2860 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
1ecb8044 2861 $this->show_only_active_users());
bbd0e548 2862
d0d4796b 2863 // Build a list of files to zip.
bbd0e548
DW
2864 $filesforzipping = array();
2865 $fs = get_file_storage();
2866
2867 $groupmode = groups_get_activity_groupmode($this->get_course_module());
d0d4796b
DW
2868 // All users.
2869 $groupid = 0;
bbd0e548
DW
2870 $groupname = '';
2871 if ($groupmode) {
2872 $groupid = groups_get_activity_group($this->get_course_module(), true);
2873 $groupname = groups_get_group_name($groupid).'-';
2874 }
2875
d0d4796b 2876 // Construct the zip file name.
e5403f8c
DW
2877 $filename = clean_filename($this->get_course()->shortname . '-' .
2878 $this->get_instance()->name . '-' .
2879 $groupname.$this->get_course_module()->id . '.zip');
bbd0e548 2880
d0d4796b
DW
2881 // Get all the files for each student.
2882 foreach ($students as $student) {
2883 $userid = $student->id;
d0d8a2da 2884 // Download all assigments submission or only selected users.
064814ea 2885 if ($userids and !in_array($userid, $userids)) {
d0d8a2da 2886 continue;
2887 }
bbd0e548 2888
7a2b911c 2889 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
d0d4796b 2890 // Get the plugins to add their own files to the zip.
bbd0e548 2891
d0d4796b
DW
2892 $submissiongroup = false;
2893 $groupname = '';
2894 if ($this->get_instance()->teamsubmission) {
2895 $submission = $this->get_group_submission($userid, 0, false);
2896 $submissiongroup = $this->get_submission_group($userid);
21f77397
DW
2897 if ($submissiongroup) {
2898 $groupname = $submissiongroup->name . '-';
2899 } else {
2900 $groupname = get_string('defaultteam', 'assign') . '-';
2901 }
b473171a 2902 } else {
d0d4796b 2903 $submission = $this->get_user_submission($userid, false);
b473171a 2904 }
bbd0e548 2905
b473171a 2906 if ($this->is_blind_marking()) {
e5403f8c 2907 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
18a5b4d8 2908 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
b473171a 2909 } else {
e5403f8c 2910 $prefix = str_replace('_', ' ', $groupname . fullname($student));
18a5b4d8 2911 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
b473171a 2912 }
bbd0e548 2913
d0d4796b
DW
2914 if ($submission) {
2915 foreach ($this->submissionplugins as $plugin) {
2916 if ($plugin->is_enabled() && $plugin->is_visible()) {
2406815b 2917 $pluginfiles = $plugin->get_files($submission, $student);
18a5b4d8 2918 foreach ($pluginfiles as $zipfilepath => $file) {
7a2b911c
DW
2919 $subtype = $plugin->get_subtype();
2920 $type = $plugin->get_type();
18a5b4d8 2921 $zipfilename = basename($zipfilepath);
e5403f8c 2922 $prefixedfilename = clean_filename($prefix .
18a5b4d8 2923 '_' .
e5403f8c
DW
2924 $subtype .
2925 '_' .
2926 $type .
18a5b4d8 2927 '_');
2928 if ($type == 'file') {
2929 $pathfilename = $prefixedfilename . $file->get_filepath() . $zipfilename;
2930 } else if ($type == 'onlinetext') {
2931 $pathfilename = $prefixedfilename . '/' . $zipfilename;
2932 } else {
2933 $pathfilename = $prefixedfilename . '/' . $zipfilename;
2934 }
2935 $pathfilename = clean_param($pathfilename, PARAM_PATH);
2936 $filesforzipping[$pathfilename] = $file;
d0d4796b 2937 }
bbd0e548
DW
2938 }
2939 }
2940 }
bbd0e548 2941 }
d0d4796b 2942 }
afa3e637 2943 $result = '';
5c778358 2944 if (count($filesforzipping) == 0) {
afa3e637
DW
2945 $header = new assign_header($this->get_instance(),
2946 $this->get_context(),
2947 '',
2948 $this->get_course_module()->id,
2949 get_string('downloadall', 'assign'));
2950 $result .= $this->get_renderer()->render($header);
5c778358 2951 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
afa3e637
DW
2952 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2953 'action'=>'grading'));
2954 $result .= $this->get_renderer()->continue_button($url);
5c778358 2955 $result .= $this->view_footer();
5c778358 2956 } else if ($zipfile = $this->pack_files($filesforzipping)) {
1b90858f 2957 \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
d0d4796b
DW
2958 // Send file and delete after sending.
2959 send_temp_file($zipfile, $filename);
afa3e637 2960 // We will not get here - send_temp_file calls exit.
bbd0e548 2961 }
afa3e637 2962 return $result;
bbd0e548
DW
2963 }
2964
2965 /**
e5403f8c 2966 * Util function to add a message to the log.
bbd0e548 2967 *
c17e70e5
MN
2968 * @deprecated since 2.7 - Use new events system instead.
2969 * (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2970 *
bbd0e548
DW
2971 * @param string $action The current action
2972 * @param string $info A detailed description of the change. But no more than 255 characters.
2973 * @param string $url The url to the assign module instance.
caa06f4b
FM
2974 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2975 * retrieve the arguments to use them with the new event system (Event 2).
2976 * @return void|array
bbd0e548 2977 */
caa06f4b 2978 public function add_to_log($action = '', $info = '', $url='', $return = false) {
bbd0e548
DW
2979 global $USER;
2980
2981 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2982 if ($url != '') {
2983 $fullurl .= '&' . $url;
2984 }
2985
caa06f4b
FM
2986 $args = array(
2987 $this->get_course()->id,
2988 'assign',
2989 $action,
2990 $fullurl,
2991 $info,
666abe6e 2992 $this->get_course_module()->id
caa06f4b
FM
2993 );
2994
2995 if ($return) {
c17e70e5
MN
2996 // We only need to call debugging when returning a value. This is because the call to
2997 // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2998 debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
caa06f4b
FM
2999 return $args;
3000 }
3001 call_user_func_array('add_to_log', $args);
bbd0e548
DW
3002 }
3003
2cffef9f 3004 /**
e5403f8c 3005 * Lazy load the page renderer and expose the renderer to plugins.
49d83b9d 3006 *
2cffef9f
PC
3007 * @return assign_renderer
3008 */
23fffa2b 3009 public function get_renderer() {
2cffef9f
PC
3010 global $PAGE;
3011 if ($this->output) {
3012 return $this->output;
3013 }
bb690849 3014 $this->output = $PAGE->get_renderer('mod_assign', null, RENDERER_TARGET_GENERAL);
2cffef9f
PC
3015 return $this->output;
3016 }
bbd0e548
DW
3017
3018 /**
e5403f8c 3019 * Load the submission object for a particular user, optionally creating it if required.
bbd0e548 3020 *
12a1a0da
DW
3021 * For team assignments there are 2 submissions - the student submission and the team submission
3022 * All files are associated with the team submission but the status of the students contribution is
3023 * recorded separately.
3024 *
bbd0e548 3025 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
f6b4fe38 3026 * @param bool $create If set to true a new submission object will be created in the database with the status set to "new".
df211804 3027 * @param int $attemptnumber - -1 means the latest attempt
bbd0e548
DW
3028 * @return stdClass The submission
3029 */
df211804 3030 public function get_user_submission($userid, $create, $attemptnumber=-1) {
bbd0e548
DW
3031 global $DB, $USER;
3032
3033 if (!$userid) {
3034 $userid = $USER->id;
3035 }
12a1a0da
DW
3036 // If the userid is not null then use userid.
3037 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
df211804
DW
3038 if ($attemptnumber >= 0) {
3039 $params['attemptnumber'] = $attemptnumber;
3040 }
3041
3042 // Only return the row with the highest attemptnumber.
3043 $submission = null;
3044 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
3045 if ($submissions) {
3046 $submission = reset($submissions);
3047 }
bbd0e548
DW
3048
3049 if ($submission) {
3050 return $submission;
3051 }
3052 if ($create) {
3053 $submission = new stdClass();
3054 $submission->assignment = $this->get_instance()->id;
3055 $submission->userid = $userid;
3056 $submission->timecreated = time();
3057 $submission->timemodified = $submission->timecreated;
9e3eee67 3058 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
df211804
DW
3059 if ($attemptnumber >= 0) {
3060 $submission->attemptnumber = $attemptnumber;
3061 } else {
3062 $submission->attemptnumber = 0;
3063 }
1523f9e0
DW
3064 // Work out if this is the latest submission.
3065 $submission->latest = 0;
3066 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
3067 if ($attemptnumber == -1) {
3068 // This is a new submission so it must be the latest.
3069 $submission->latest = 1;
3070 } else {
3071 // We need to work this out.
3072 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
9e3eee67 3073 $latestsubmission = null;
1523f9e0
DW
3074 if ($result) {
3075 $latestsubmission = reset($result);
3076 }
9e3eee67 3077 if (empty($latestsubmission) || ($attemptnumber > $latestsubmission->attemptnumber)) {
1523f9e0
DW
3078 $submission->latest = 1;
3079 }
3080 }
3081 if ($submission->latest) {
3082 // This is the case when we need to set latest to 0 for all the other attempts.
3083 $DB->set_field('assign_submission', 'latest', 0, $params);
3084 }
bbd0e548 3085 $sid = $DB->insert_record('assign_submission', $submission);
4781ff2e 3086 return $DB->get_record('assign_submission', array('id' => $sid));
bbd0e548
DW
3087 }
3088 return false;
3089 }
3090
3091 /**
e5403f8c 3092 * Load the submission object from it's id.
bbd0e548
DW
3093 *
3094 * @param int $submissionid The id of the submission we want
3095 * @return stdClass The submission
3096 */
47f48152 3097 protected function get_submission($submissionid) {
bbd0e548
DW
3098 global $DB;
3099
e5403f8c
DW
3100 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
3101 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
bbd0e548
DW
3102 }
3103
df211804
DW
3104 /**
3105 * This will retrieve a user flags object from the db optionally creating it if required.
3106 * The user flags was split from the user_grades table in 2.5.
3107 *
3108 * @param int $userid The user we are getting the flags for.
3109 * @param bool $create If true the flags record will be created if it does not exist
3110 * @return stdClass The flags record
3111 */
3112 public function get_user_flags($userid, $create) {
3113 global $DB, $USER;
3114
3115 // If the userid is not null then use userid.
3116 if (!$userid) {
3117 $userid = $USER->id;
3118 }
3119
3120 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
3121
3122 $flags = $DB->get_record('assign_user_flags', $params);
3123
3124 if ($flags) {
3125 return $flags;
3126 }
3127 if ($create) {
3128 $flags = new stdClass();
3129 $flags->assignment = $this->get_instance()->id;
3130 $flags->userid = $userid;
3131 $flags->locked = 0;
3132 $flags->extensionduedate = 0;
f8d107b3
DM
3133 $flags->workflowstate = '';
3134 $flags->allocatedmarker = 0;
df211804
DW
3135
3136 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
3137 // This is because students only want to be notified about certain types of update (grades and feedback).
3138 $flags->mailed = 2;
3139
3140 $fid = $DB->insert_record('assign_user_flags', $flags);
3141 $flags->id = $fid;
3142 return $flags;
3143 }
3144 return false;
3145 }
3146
bbd0e548 3147 /**
e5403f8c 3148 * This will retrieve a grade object from the db, optionally creating it if required.
bbd0e548
DW
3149 *
3150 * @param int $userid The user we are grading
3151 * @param bool $create If true the grade will be created if it does not exist
df211804 3152 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
bbd0e548
DW
3153 * @return stdClass The grade record
3154 */
df211804 3155 public function get_user_grade($userid, $create, $attemptnumber=-1) {
bbd0e548
DW
3156 global $DB, $USER;
3157
df211804 3158 // If the userid is not null then use userid.
bbd0e548
DW
3159 if (!$userid) {
3160 $userid = $USER->id;
3161 }
9d3c6b95 3162 $submission = null;
bbd0e548 3163
df211804 3164 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
9d3c6b95 3165 if ($attemptnumber < 0 || $create) {
e7af1926
DW
3166 // Make sure this grade matches the latest submission attempt.
3167 if ($this->get_instance()->teamsubmission) {
9e3eee67 3168 $submission = $this->get_group_submission($userid, 0, true);
e7af1926 3169 } else {
9e3eee67 3170 $submission = $this->get_user_submission($userid, true);
e7af1926
DW
3171 }
3172 if ($submission) {
3173 $attemptnumber = $submission->attemptnumber;
3174 }
3175 }
3176
df211804
DW
3177 if ($attemptnumber >= 0) {
3178 $params['attemptnumber'] = $attemptnumber;
3179 }
bbd0e548 3180
df211804
DW
3181 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
3182
3183 if ($grades) {
3184 return reset($grades);
bbd0e548
DW
3185 }
3186 if ($create) {
3187 $grade = new stdClass();
3188 $grade->assignment = $this->get_instance()->id;
3189 $grade->userid = $userid;
3190 $grade->timecreated = time();