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