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