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