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