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