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