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