Merge branch 'MDL-42625_master-failures-fix' of git://github.com/dmonllao/moodle
[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 744 $data->timeshift,
e63515ba 745 $data->courseid, $this->get_instance()->id);
d38dc52f
RW
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()) {
3a5c3b3c 947 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
bbd0e548
DW
948 }
949 }
950 }
951
952
953
954 /**
e5403f8c 955 * Add one plugins settings to edit plugin form.
bbd0e548
DW
956 *
957 * @param assign_plugin $plugin The plugin to add the settings from
e5403f8c
DW
958 * @param MoodleQuickForm $mform The form to add the configuration settings to.
959 * This form is modified directly (not returned).
b0da618b
DW
960 * @param array $pluginsenabled A list of form elements to be added to a group.
961 * The new element is added to this array by this function.
bbd0e548
DW
962 * @return void
963 */
b0da618b 964 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
bbd0e548 965 global $CFG;
f159ad73 966 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
967 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
968 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
969 $mform->setType($name, PARAM_BOOL);
970 $plugin->get_settings($mform);
971 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
b0da618b
DW
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.
9f3da407
MR
1559 $sql = 'SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1560 g.*, 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
09af1e28 2002 $strsectionname = '';
64220210
DW
2003 $usesections = course_format_uses_sections($course->format);
2004 $modinfo = get_fast_modinfo($course);
2005
2006 if ($usesections) {
09af1e28 2007 $strsectionname = get_string('sectionname', 'format_'.$course->format);
64220210
DW
2008 $sections = $modinfo->get_section_info_all();
2009 }
2010 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2011
2012 $timenow = time();
2013
2014 $currentsection = '';
2015 foreach ($modinfo->instances['assign'] as $cm) {
2016 if (!$cm->uservisible) {
2017 continue;
2018 }
2019
e5403f8c 2020 $timedue = $cms[$cm->id]->duedate;
64220210
DW
2021
2022 $sectionname = '';
2023 if ($usesections && $cm->sectionnum) {
2024 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2025 }
2026
2027 $submitted = '';
2028 $context = context_module::instance($cm->id);
2029
2030 $assignment = new assign($context, $cm, $course);
2031
2032 if (has_capability('mod/assign:grade', $context)) {
2033 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2034
2035 } else if (has_capability('mod/assign:submit', $context)) {
2036 $usersubmission = $assignment->get_user_submission($USER->id, false);
2037
2038 if (!empty($usersubmission->status)) {
2039 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2040 } else {
2041 $submitted = get_string('submissionstatus_', 'assign');
2042 }
2043 }
539af602
DW
2044 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2045 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2046 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2047 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
64220210
DW
2048 } else {
2049 $grade = '-';
2050 }
2051
2052 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2053
2054 }
2055
2056 $o .= $this->get_renderer()->render($courseindexsummary);
2057 $o .= $this->view_footer();
2058
2059 return $o;
2060 }
2061
2062 /**
2063 * View a page rendered by a plugin.
df47b77f 2064 *
e5403f8c 2065 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
df47b77f
DW
2066 *
2067 * @return string
2068 */
47f48152 2069 protected function view_plugin_page() {
df47b77f
DW
2070 global $USER;
2071
2072 $o = '';
2073
2074 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2075 $plugintype = required_param('plugin', PARAM_TEXT);
2076 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2077
2078 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2079 if (!$plugin) {
2080 print_error('invalidformdata', '');
2081 return;
2082 }
2083
2084 $o .= $plugin->view_page($pluginaction);
2085
2086 return $o;
2087 }
2088
2089
12a1a0da
DW
2090 /**
2091 * This is used for team assignments to get the group for the specified user.
2092 * If the user is a member of multiple or no groups this will return false
2093 *
2094 * @param int $userid The id of the user whose submission we want
2095 * @return mixed The group or false
2096 */
2097 public function get_submission_group($userid) {
e5403f8c
DW
2098 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2099 $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
12a1a0da
DW
2100 if (count($groups) != 1) {
2101 return false;
2102 }
2103 return array_pop($groups);
2104 }
2105
9e795179 2106
bbd0e548 2107 /**
e5403f8c
DW
2108 * Display the submission that is used by a plugin.
2109 *
2110 * Uses url parameters 'sid', 'gid' and 'plugin'.
2111 *
bbd0e548
DW
2112 * @param string $pluginsubtype
2113 * @return string
2114 */
47f48152 2115 protected function view_plugin_content($pluginsubtype) {
bbd0e548
DW
2116 global $USER;
2117
2118 $o = '';
2119
2120 $submissionid = optional_param('sid', 0, PARAM_INT);
2121 $gradeid = optional_param('gid', 0, PARAM_INT);
2122 $plugintype = required_param('plugin', PARAM_TEXT);
2123 $item = null;
2124 if ($pluginsubtype == 'assignsubmission') {
2125 $plugin = $this->get_submission_plugin_by_type($plugintype);
2126 if ($submissionid <= 0) {
2127 throw new coding_exception('Submission id should not be 0');
2128 }
2129 $item = $this->get_submission($submissionid);
2130
e5403f8c 2131 // Check permissions.
bbd0e548
DW
2132 if ($item->userid != $USER->id) {
2133 require_capability('mod/assign:grade', $this->context);
2134 }
49d83b9d 2135 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2136 $this->get_context(),
2137 $this->show_intro(),
2138 $this->get_course_module()->id,
2139 $plugin->get_name()));
49d83b9d 2140 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
bbd0e548
DW
2141 $item,
2142 assign_submission_plugin_submission::FULL,
2143 $this->get_course_module()->id,
2144 $this->get_return_action(),
2145 $this->get_return_params()));
2146
e5403f8c
DW
2147 $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2148 $this->add_to_log('view submission', $logmessage);
bbd0e548
DW
2149 } else {
2150 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2151 if ($gradeid <= 0) {
2152 throw new coding_exception('Grade id should not be 0');
2153 }
2154 $item = $this->get_grade($gradeid);
e5403f8c 2155 // Check permissions.
bbd0e548
DW
2156 if ($item->userid != $USER->id) {
2157 require_capability('mod/assign:grade', $this->context);
2158 }
49d83b9d 2159 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
2160 $this->get_context(),
2161 $this->show_intro(),
2162 $this->get_course_module()->id,
2163 $plugin->get_name()));
49d83b9d 2164 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
bbd0e548
DW
2165 $item,
2166 assign_feedback_plugin_feedback::FULL,
2167 $this->get_course_module()->id,
2168 $this->get_return_action(),
2169 $this->get_return_params()));
e5403f8c
DW
2170 $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2171 $this->add_to_log('view feedback', $logmessage);
bbd0e548
DW
2172 }
2173
bbd0e548
DW
2174 $o .= $this->view_return_links();
2175
2176 $o .= $this->view_footer();
2177 return $o;
2178 }
2179
2406815b
DW
2180 /**
2181 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2182 *
1561a37c 2183 * @param string $text - The replacement text
2406815b
DW
2184 * @param stdClass $user - The user record
2185 * @param assign_plugin $plugin - The assignment plugin
2186 */
2187 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2188 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2189 $groupname = '';
2190 if ($groupmode) {
2191 $groupid = groups_get_activity_group($this->get_course_module(), true);
2192 $groupname = groups_get_group_name($groupid).'-';
2193 }
2194
2195 if ($this->is_blind_marking()) {
2196 $prefix = $groupname . get_string('participant', 'assign');
2197 $prefix = str_replace('_', ' ', $prefix);
2198 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2199 } else {
2200 $prefix = $groupname . fullname($user);
2201 $prefix = str_replace('_', ' ', $prefix);
2202 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2203 }
2204
2205 $subtype = $plugin->get_subtype();
2206 $type = $plugin->get_type();
2207 $prefix = $prefix . $subtype . '_' . $type . '_';
2208
2209 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2210
2211 return $result;
2212 }
2213
bbd0e548 2214 /**
e5403f8c 2215 * Render the content in editor that is often used by plugin.
bbd0e548
DW
2216 *
2217 * @param string $filearea
2218 * @param int $submissionid
2219 * @param string $plugintype
2220 * @param string $editor
2221 * @param string $component
2222 * @return string
2223 */
2224 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2225 global $CFG;
2226
2227 $result = '';
2228
2229 $plugin = $this->get_submission_plugin_by_type($plugintype);
2230
2231 $text = $plugin->get_editor_text($editor, $submissionid);
2232 $format = $plugin->get_editor_format($editor, $submissionid);
2233
e5403f8c
DW
2234 $finaltext = file_rewrite_pluginfile_urls($text,
2235 'pluginfile.php',
2236 $this->get_context()->id,
2237 $component,
2238 $filearea,
2239 $submissionid);
2240 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2241 $result .= format_text($finaltext, $format, $params);
bbd0e548
DW
2242
2243 if ($CFG->enableportfolios) {
2244 require_once($CFG->libdir . '/portfoliolib.php');
2245
2246 $button = new portfolio_add_button();
e5403f8c
DW
2247 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2248 'sid' => $submissionid,
2249 'plugin' => $plugintype,
2250 'editor' => $editor,
2251 'area'=>$filearea);
2252 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
bbd0e548
DW
2253 $fs = get_file_storage();
2254
e5403f8c
DW
2255 if ($files = $fs->get_area_files($this->context->id,
2256 $component,
2257 $filearea,
2258 $submissionid,
2259 'timemodified',
2260 false)) {
bbd0e548
DW
2261 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2262 } else {
2263 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2264 }
2265 $result .= $button->to_html();
2266 }
2267 return $result;
2268 }
2269
df211804
DW
2270 /**
2271 * Display a continue page.
2272 *
1561a37c 2273 * @param string $message - The message to display
df211804
DW
2274 * @return string
2275 */
2276 protected function view_savegrading_result($message) {
2277 $o = '';
2278 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2279 $this->get_context(),
2280 $this->show_intro(),
2281 $this->get_course_module()->id,
2282 get_string('savegradingresult', 'assign')));
2283 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2284 $message,
2285 $this->get_course_module()->id);
2286 $o .= $this->get_renderer()->render($gradingresult);
2287 $o .= $this->view_footer();
2288 return $o;
2289 }
bf78ebd6 2290 /**
e5403f8c 2291 * Display a grading error.
bf78ebd6
DW
2292 *
2293 * @param string $message - The description of the result
2294 * @return string
2295 */
47f48152 2296 protected function view_quickgrading_result($message) {
bf78ebd6 2297 $o = '';
49d83b9d 2298 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bf78ebd6
DW
2299 $this->get_context(),
2300 $this->show_intro(),
2301 $this->get_course_module()->id,
2302 get_string('quickgradingresult', 'assign')));
df211804
DW
2303 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2304 $message,
2305 $this->get_course_module()->id);
e5403f8c 2306 $o .= $this->get_renderer()->render($gradingresult);
bf78ebd6
DW
2307 $o .= $this->view_footer();
2308 return $o;
2309 }
bbd0e548
DW
2310
2311 /**
e5403f8c 2312 * Display the page footer.
bbd0e548 2313 *
bf78ebd6 2314 * @return string
bbd0e548 2315 */
47f48152 2316 protected function view_footer() {
49d83b9d 2317 return $this->get_renderer()->render_footer();
bbd0e548
DW
2318 }
2319
2320 /**
e5403f8c 2321 * Does this user have grade permission for this assignment?
bbd0e548
DW
2322 *
2323 * @return bool
2324 */
5c386472 2325 public function can_grade() {
e5403f8c 2326 // Permissions check.
bbd0e548
DW
2327 if (!has_capability('mod/assign:grade', $this->context)) {
2328 return false;
2329 }
2330
2331 return true;
2332 }
2333
2334 /**
e5403f8c 2335 * Download a zip file of all assignment submissions.
bbd0e548 2336 *
df211804 2337 * @return string - If an error occurs, this will contain the error page.
bbd0e548 2338 */
47f48152 2339 protected function download_submissions() {
e5403f8c 2340 global $CFG, $DB;
bbd0e548 2341
d0d4796b 2342 // More efficient to load this here.
bbd0e548
DW
2343 require_once($CFG->libdir.'/filelib.php');
2344
76640b27
DW
2345 require_capability('mod/assign:grade', $this->context);
2346
d0d4796b 2347 // Load all users with submit.
4c4c7b3f 2348 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
1ecb8044 2349 $this->show_only_active_users());
bbd0e548 2350
d0d4796b 2351 // Build a list of files to zip.
bbd0e548
DW
2352 $filesforzipping = array();
2353 $fs = get_file_storage();
2354
2355 $groupmode = groups_get_activity_groupmode($this->get_course_module());
d0d4796b
DW
2356 // All users.
2357 $groupid = 0;
bbd0e548
DW
2358 $groupname = '';
2359 if ($groupmode) {
2360 $groupid = groups_get_activity_group($this->get_course_module(), true);
2361 $groupname = groups_get_group_name($groupid).'-';
2362 }
2363
d0d4796b 2364 // Construct the zip file name.
e5403f8c
DW
2365 $filename = clean_filename($this->get_course()->shortname . '-' .
2366 $this->get_instance()->name . '-' .
2367 $groupname.$this->get_course_module()->id . '.zip');
bbd0e548 2368
d0d4796b
DW
2369 // Get all the files for each student.
2370 foreach ($students as $student) {
2371 $userid = $student->id;
bbd0e548 2372
7a2b911c 2373 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
d0d4796b 2374 // Get the plugins to add their own files to the zip.
bbd0e548 2375
d0d4796b
DW
2376 $submissiongroup = false;
2377 $groupname = '';
2378 if ($this->get_instance()->teamsubmission) {
2379 $submission = $this->get_group_submission($userid, 0, false);
2380 $submissiongroup = $this->get_submission_group($userid);
21f77397
DW
2381 if ($submissiongroup) {
2382 $groupname = $submissiongroup->name . '-';
2383 } else {
2384 $groupname = get_string('defaultteam', 'assign') . '-';
2385 }
b473171a 2386 } else {
d0d4796b 2387 $submission = $this->get_user_submission($userid, false);
b473171a 2388 }
bbd0e548 2389
b473171a 2390 if ($this->is_blind_marking()) {
e5403f8c
DW
2391 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2392 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
b473171a 2393 } else {
e5403f8c
DW
2394 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2395 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
b473171a 2396 }
bbd0e548 2397
d0d4796b
DW
2398 if ($submission) {
2399 foreach ($this->submissionplugins as $plugin) {
2400 if ($plugin->is_enabled() && $plugin->is_visible()) {
2406815b 2401 $pluginfiles = $plugin->get_files($submission, $student);
d0d4796b 2402 foreach ($pluginfiles as $zipfilename => $file) {
7a2b911c
DW
2403 $subtype = $plugin->get_subtype();
2404 $type = $plugin->get_type();
e5403f8c
DW
2405 $prefixedfilename = clean_filename($prefix .
2406 $subtype .
2407 '_' .
2408 $type .
2409 '_' .
2410 $zipfilename);
d0d4796b
DW
2411 $filesforzipping[$prefixedfilename] = $file;
2412 }
bbd0e548
DW
2413 }
2414 }
2415 }
bbd0e548 2416 }
d0d4796b 2417 }
afa3e637 2418 $result = '';
5c778358 2419 if (count($filesforzipping) == 0) {
afa3e637
DW
2420 $header = new assign_header($this->get_instance(),
2421 $this->get_context(),
2422 '',
2423 $this->get_course_module()->id,
2424 get_string('downloadall', 'assign'));
2425 $result .= $this->get_renderer()->render($header);
5c778358 2426 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
afa3e637
DW
2427 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2428 'action'=>'grading'));
2429 $result .= $this->get_renderer()->continue_button($url);
5c778358 2430 $result .= $this->view_footer();
5c778358 2431 } else if ($zipfile = $this->pack_files($filesforzipping)) {
a65b5303
FM
2432 $addtolog = $this->add_to_log('download all submissions', get_string('downloadall', 'assign'), '', true);
2433 $params = array(
2434 'context' => $this->context,
2435 'objectid' => $this->get_instance()->id
2436 );
2437 $event = \mod_assign\event\all_submissions_downloaded::create($params);
2438 $event->set_legacy_logdata($addtolog);
2439 $event->trigger();
d0d4796b
DW
2440 // Send file and delete after sending.
2441 send_temp_file($zipfile, $filename);
afa3e637 2442 // We will not get here - send_temp_file calls exit.
bbd0e548 2443 }
afa3e637 2444 return $result;
bbd0e548
DW
2445 }
2446
2447 /**
e5403f8c 2448 * Util function to add a message to the log.
bbd0e548
DW
2449 *
2450 * @param string $action The current action
2451 * @param string $info A detailed description of the change. But no more than 255 characters.
2452 * @param string $url The url to the assign module instance.
caa06f4b
FM
2453 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2454 * retrieve the arguments to use them with the new event system (Event 2).
2455 * @return void|array
bbd0e548 2456 */
caa06f4b 2457 public function add_to_log($action = '', $info = '', $url='', $return = false) {
bbd0e548
DW
2458 global $USER;
2459
2460 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2461 if ($url != '') {
2462 $fullurl .= '&' . $url;
2463 }
2464
caa06f4b
FM
2465 $args = array(
2466 $this->get_course()->id,
2467 'assign',
2468 $action,
2469 $fullurl,
2470 $info,
2471 $this->get_course_module()->id,
2472 $USER->id
2473 );
2474
2475 if ($return) {
2476 return $args;
2477 }
2478 call_user_func_array('add_to_log', $args);
bbd0e548
DW
2479 }
2480
2cffef9f 2481 /**
e5403f8c 2482 * Lazy load the page renderer and expose the renderer to plugins.
49d83b9d 2483 *
2cffef9f
PC
2484 * @return assign_renderer
2485 */
23fffa2b 2486 public function get_renderer() {
2cffef9f
PC
2487 global $PAGE;
2488 if ($this->output) {
2489 return $this->output;
2490 }
2491 $this->output = $PAGE->get_renderer('mod_assign');
2492 return $this->output;
2493 }
bbd0e548
DW
2494
2495 /**
e5403f8c 2496 * Load the submission object for a particular user, optionally creating it if required.
bbd0e548 2497 *
12a1a0da
DW
2498 * For team assignments there are 2 submissions - the student submission and the team submission
2499 * All files are associated with the team submission but the status of the students contribution is
2500 * recorded separately.
2501 *
bbd0e548 2502 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
e5403f8c
DW
2503 * @param bool $create optional - defaults to false. If set to true a new submission object
2504 * will be created in the database.
df211804 2505 * @param int $attemptnumber - -1 means the latest attempt
bbd0e548
DW
2506 * @return stdClass The submission
2507 */
df211804 2508 public function get_user_submission($userid, $create, $attemptnumber=-1) {
bbd0e548
DW
2509 global $DB, $USER;
2510
2511 if (!$userid) {
2512 $userid = $USER->id;
2513 }
12a1a0da
DW
2514 // If the userid is not null then use userid.
2515 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
df211804
DW
2516 if ($attemptnumber >= 0) {
2517 $params['attemptnumber'] = $attemptnumber;
2518 }
2519
2520 // Only return the row with the highest attemptnumber.
2521 $submission = null;
2522 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2523 if ($submissions) {
2524 $submission = reset($submissions);
2525 }
bbd0e548
DW
2526
2527 if ($submission) {
2528 return $submission;
2529 }
2530 if ($create) {
2531 $submission = new stdClass();
2532 $submission->assignment = $this->get_instance()->id;
2533 $submission->userid = $userid;
2534 $submission->timecreated = time();
2535 $submission->timemodified = $submission->timecreated;
7a9fd6da 2536 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
df211804
DW
2537 if ($attemptnumber >= 0) {
2538 $submission->attemptnumber = $attemptnumber;
2539 } else {
2540 $submission->attemptnumber = 0;
2541 }
bbd0e548
DW
2542 $sid = $DB->insert_record('assign_submission', $submission);
2543 $submission->id = $sid;
2544 return $submission;
2545 }
2546 return false;
2547 }
2548
2549 /**
e5403f8c 2550 * Load the submission object from it's id.
bbd0e548
DW
2551 *
2552 * @param int $submissionid The id of the submission we want
2553 * @return stdClass The submission
2554 */
47f48152 2555 protected function get_submission($submissionid) {
bbd0e548
DW
2556 global $DB;
2557
e5403f8c
DW
2558 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2559 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
bbd0e548
DW
2560 }
2561
df211804
DW
2562 /**
2563 * This will retrieve a user flags object from the db optionally creating it if required.
2564 * The user flags was split from the user_grades table in 2.5.
2565 *
2566 * @param int $userid The user we are getting the flags for.
2567 * @param bool $create If true the flags record will be created if it does not exist
2568 * @return stdClass The flags record
2569 */
2570 public function get_user_flags($userid, $create) {
2571 global $DB, $USER;
2572
2573 // If the userid is not null then use userid.
2574 if (!$userid) {
2575 $userid = $USER->id;
2576 }
2577
2578 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2579
2580 $flags = $DB->get_record('assign_user_flags', $params);
2581
2582 if ($flags) {
2583 return $flags;
2584 }
2585 if ($create) {
2586 $flags = new stdClass();
2587 $flags->assignment = $this->get_instance()->id;
2588 $flags->userid = $userid;
2589 $flags->locked = 0;
2590 $flags->extensionduedate = 0;
f8d107b3
DM
2591 $flags->workflowstate = '';
2592 $flags->allocatedmarker = 0;
df211804
DW
2593
2594 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2595 // This is because students only want to be notified about certain types of update (grades and feedback).
2596 $flags->mailed = 2;
2597
2598 $fid = $DB->insert_record('assign_user_flags', $flags);
2599 $flags->id = $fid;
2600 return $flags;
2601 }
2602 return false;
2603 }
2604
bbd0e548 2605 /**
e5403f8c 2606 * This will retrieve a grade object from the db, optionally creating it if required.
bbd0e548
DW
2607 *
2608 * @param int $userid The user we are grading
2609 * @param bool $create If true the grade will be created if it does not exist
df211804 2610 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
bbd0e548
DW
2611 * @return stdClass The grade record
2612 */
df211804 2613 public function get_user_grade($userid, $create, $attemptnumber=-1) {
bbd0e548
DW
2614 global $DB, $USER;
2615
df211804 2616 // If the userid is not null then use userid.
bbd0e548
DW
2617 if (!$userid) {
2618 $userid = $USER->id;
2619 }
2620
df211804 2621 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
e7af1926
DW
2622 if ($attemptnumber < 0) {
2623 // Make sure this grade matches the latest submission attempt.
2624 if ($this->get_instance()->teamsubmission) {
2625 $submission = $this->get_group_submission($userid, 0, false);
2626 } else {
2627 $submission = $this->get_user_submission($userid, false);
2628 }
2629 if ($submission) {
2630 $attemptnumber = $submission->attemptnumber;
2631 }
2632 }
2633
df211804
DW
2634 if ($attemptnumber >= 0) {
2635 $params['attemptnumber'] = $attemptnumber;
2636 }
bbd0e548 2637
df211804
DW
2638 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2639
2640 if ($grades) {
2641 return reset($grades);
bbd0e548
DW
2642 }
2643 if ($create) {
2644 $grade = new stdClass();
2645 $grade->assignment = $this->get_instance()->id;
2646 $grade->userid = $userid;
2647 $grade->timecreated = time();
2648 $grade->timemodified = $grade->timecreated;
bbd0e548
DW
2649 $grade->grade = -1;
2650 $grade->grader = $USER->id;
df211804
DW
2651 if ($attemptnumber >= 0) {
2652 $grade->attemptnumber = $attemptnumber;
2653 }
d6c673ed 2654
bbd0e548
DW
2655 $gid = $DB->insert_record('assign_grades', $grade);
2656 $grade->id = $gid;
2657 return $grade;
2658 }
2659 return false;
2660 }
2661
2662 /**
e5403f8c 2663 * This will retrieve a grade object from the db.
bbd0e548
DW
2664 *
2665 * @param int $gradeid The id of the grade
2666 * @return stdClass The grade record
2667 */
47f48152 2668 protected function get_grade($gradeid) {
bbd0e548
DW
2669 global $DB;
2670
e5403f8c
DW
2671 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2672 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
bbd0e548
DW
2673 }
2674
2675 /**
e5403f8c 2676 * Print the grading page for a single user submission.
bbd0e548
DW
2677 *
2678 * @param moodleform $mform
bbd0e548
DW
2679 * @return string
2680 */
d04557b3 2681 protected function view_single_grade_page($mform) {
bbd0e548
DW
2682 global $DB, $CFG;
2683
2684 $o = '';
e5403f8c 2685 $instance = $this->get_instance();
bbd0e548 2686
bbd0e548
DW
2687 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2688
e5403f8c 2689 // Need submit permission to submit an assignment.
bbd0e548
DW
2690 require_capability('mod/assign:grade', $this->context);
2691
e5403f8c
DW
2692 $header = new assign_header($instance,
2693 $this->get_context(),
2694 false,
2695 $this->get_course_module()->id,
2696 get_string('grading', 'assign'));
2697 $o .= $this->get_renderer()->render($header);
bbd0e548 2698
df211804 2699 // If userid is passed - we are only grading a single student.
d04557b3
DW
2700 $rownum = required_param('rownum', PARAM_INT);
2701 $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
df211804
DW
2702 $userid = optional_param('userid', 0, PARAM_INT);
2703 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2704
d04557b3 2705 $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
df211804
DW
2706 if (!$userid) {
2707 if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2708 $useridlist = $this->get_grading_userid_list();
2709 }
d04557b3 2710 $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
df211804
DW
2711 } else {
2712 $rownum = 0;
2713 $useridlist = array($userid);
bbd0e548 2714 }
d04557b3
DW
2715
2716 if ($rownum < 0 || $rownum > count($useridlist)) {
2717 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
bbd0e548 2718 }
d04557b3 2719
bbd0e548
DW
2720 $last = false;
2721 $userid = $useridlist[$rownum];
2722 if ($rownum == count($useridlist) - 1) {
2723 $last = true;
2724 }
bbd0e548
DW
2725 $user = $DB->get_record('user', array('id' => $userid));
2726 if ($user) {
e5403f8c
DW
2727 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2728 $usersummary = new assign_user_summary($user,
2729 $this->get_course()->id,
2730 $viewfullnames,
2731 $this->is_blind_marking(),
d08e6c31 2732 $this->get_uniqueid_for_user($user->id),
a69944eb 2733 get_extra_user_fields($this->get_context()),
1ecb8044 2734 !$this->is_active_user($userid));
e5403f8c 2735 $o .= $this->get_renderer()->render($usersummary);
bbd0e548 2736 }
df211804 2737 $submission = $this->get_user_submission($userid, false, $attemptnumber);
12a1a0da 2738 $submissiongroup = null;
12a1a0da
DW
2739 $teamsubmission = null;
2740 $notsubmitted = array();
e5403f8c 2741 if ($instance->teamsubmission) {
df211804 2742 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
12a1a0da
DW
2743 $submissiongroup = $this->get_submission_group($userid);
2744 $groupid = 0;
2745 if ($submissiongroup) {
2746 $groupid = $submissiongroup->id;
2747 }
2748 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2749
2750 }
2751
df211804
DW
2752 // Get the requested grade.
2753 $grade = $this->get_user_grade($userid, false, $attemptnumber);
2754 $flags = $this->get_user_flags($userid, false);
bbd0e548 2755 if ($this->can_view_submission($userid)) {
df211804 2756 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
9e795179 2757 $extensionduedate = null;
df211804
DW
2758 if ($flags) {
2759 $extensionduedate = $flags->extensionduedate;
9e795179 2760 }
88cfe469 2761 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
12a1a0da 2762 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
9e795179 2763
e5403f8c
DW
2764 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2765 $instance->alwaysshowdescription,
2766 $submission,
2767 $instance->teamsubmission,
2768 $teamsubmission,
2769 $submissiongroup,
2770 $notsubmitted,
2771 $this->is_any_submission_plugin_enabled(),
2772 $gradelocked,
2773 $this->is_graded($userid),
2774 $instance->duedate,
2775 $instance->cutoffdate,
2776 $this->get_submission_plugins(),
2777 $this->get_return_action(),
2778 $this->get_return_params(),
2779 $this->get_course_module()->id,
2780 $this->get_course()->id,
2781 assign_submission_status::GRADER_VIEW,
2782 $showedit,
19195b60 2783 false,
e5403f8c
DW
2784 $viewfullnames,
2785 $extensionduedate,
2786 $this->get_context(),
2787 $this->is_blind_marking(),
df211804
DW
2788 '',
2789 $instance->attemptreopenmethod,
2790 $instance->maxattempts);
e5403f8c 2791 $o .= $this->get_renderer()->render($submissionstatus);
bbd0e548 2792 }
df211804 2793
bbd0e548
DW
2794 if ($grade) {
2795 $data = new stdClass();
e5403f8c
DW
2796 if ($grade->grade !== null && $grade->grade >= 0) {
2797 $data->grade = format_float($grade->grade, 2);
bbd0e548 2798 }
f8d107b3
DM
2799 if (!empty($flags->workflowstate)) {
2800 $data->workflowstate = $flags->workflowstate;
2801 }
2802 if (!empty($flags->allocatedmarker)) {
2803 $data->allocatedmarker = $flags->allocatedmarker;
2804 }
bbd0e548
DW
2805 } else {
2806 $data = new stdClass();
2807 $data->grade = '';
2808 }
df211804
DW
2809 // Warning if required.
2810 $allsubmissions = $this->get_all_submissions($userid);
2811
2812 if ($attemptnumber != -1) {
2813 $params = array('attemptnumber'=>$attemptnumber + 1,
2814 'totalattempts'=>count($allsubmissions));
2815 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2816 $o .= $this->get_renderer()->notification($message);
2817 }
bbd0e548 2818
e5403f8c 2819 // Now show the grading form.
bbd0e548 2820 if (!$mform) {
df211804
DW
2821 $pagination = array('rownum'=>$rownum,
2822 'useridlistid'=>$useridlistid,
2823 'last'=>$last,
2824 'userid'=>optional_param('userid', 0, PARAM_INT),
2825 'attemptnumber'=>$attemptnumber);
12a1a0da
DW
2826 $formparams = array($this, $data, $pagination);
2827 $mform = new mod_assign_grade_form(null,
2828 $formparams,
2829 'post',
2830 '',
2831 array('class'=>'gradeform'));
bbd0e548 2832 }
df211804 2833 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
e5403f8c 2834 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
bbd0e548 2835
df211804
DW
2836 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2837 $allgrades = $this->get_all_grades($userid);
2838 $history = new assign_attempt_history($allsubmissions,
2839 $allgrades,
2840 $this->get_submission_plugins(),
2841 $this->get_feedback_plugins(),
2842 $this->get_course_module()->id,
2843 $this->get_return_action(),
2844 $this->get_return_params(),
2845 true);
2846
2847 $o .= $this->get_renderer()->render($history);
2848 }
2849
e5403f8c
DW
2850 $msg = get_string('viewgradingformforstudent',
2851 'assign',
2852 array('id'=>$user->id, 'fullname'=>fullname($user)));
12a1a0da 2853 $this->add_to_log('view grading form', $msg);
bbd0e548
DW
2854
2855 $o .= $this->view_footer();
2856 return $o;
2857 }
2858
b473171a 2859 /**
e5403f8c 2860 * Show a confirmation page to make sure they want to release student identities.
b473171a
DW
2861 *
2862 * @return string
2863 */
47f48152 2864 protected function view_reveal_identities_confirm() {
b473171a
DW
2865 global $CFG, $USER;
2866
2867 require_capability('mod/assign:revealidentities', $this->get_context());
2868
2869 $o = '';
e5403f8c
DW
2870 $header = new assign_header($this->get_instance(),
2871 $this->get_context(),
2872 false,
2873 $this->get_course_module()->id);
2874 $o .= $this->get_renderer()->render($header);
2875
2876 $urlparams = array('id'=>$this->get_course_module()->id,
2877 'action'=>'revealidentitiesconfirm',
2878 'sesskey'=>sesskey());
2879 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2880
2881 $urlparams = array('id'=>$this->get_course_module()->id,
2882 'action'=>'grading');
2883 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2884
2885 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2886 $confirmurl,
2887 $cancelurl);
b473171a
DW
2888 $o .= $this->view_footer();
2889 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2890 return $o;
2891 }
2892
bbd0e548
DW
2893 /**
2894 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2895 *
2896 * @return string
2897 */
47f48152 2898 protected function view_return_links() {
e5403f8c
DW
2899 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2900 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
bbd0e548
DW
2901
2902 $params = array();
d04557b3 2903 $returnparams = str_replace('&amp;', '&', $returnparams);
bbd0e548 2904 parse_str($returnparams, $params);
e5403f8c
DW
2905 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2906 $params = array_merge($newparams, $params);
bbd0e548 2907
e5403f8c
DW
2908 $url = new moodle_url('/mod/assign/view.php', $params);
2909 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
bbd0e548
DW
2910 }
2911
2912 /**
e5403f8c 2913 * View the grading table of all submissions for this assignment.
bbd0e548
DW
2914 *
2915 * @return string
2916 */
47f48152 2917 protected function view_grading_table() {
bbd0e548 2918 global $USER, $CFG;
e5403f8c
DW
2919
2920 // Include grading options form.
bbd0e548 2921 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
bf78ebd6 2922 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
bbd0e548
DW
2923 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2924 $o = '';
e5403f8c 2925 $cmid = $this->get_course_module()->id;
bbd0e548
DW
2926
2927 $links = array();
bbd0e548
DW
2928 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2929 has_capability('moodle/grade:viewall', $this->get_course_context())) {
a1e54f4d 2930 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
bbd0e548
DW
2931 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2932 }
9b7a5f65 2933 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
e5403f8c 2934 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
bbd0e548
DW
2935 $links[$downloadurl] = get_string('downloadall', 'assign');
2936 }
e5403f8c
DW
2937 if ($this->is_blind_marking() &&
2938 has_capability('mod/assign:revealidentities', $this->get_context())) {
2939 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
b473171a
DW
2940 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2941 }
df47b77f
DW
2942 foreach ($this->get_feedback_plugins() as $plugin) {
2943 if ($plugin->is_enabled() && $plugin->is_visible()) {
2944 foreach ($plugin->get_grading_actions() as $action => $description) {
2945 $url = '/mod/assign/view.php' .
e5403f8c 2946 '?id=' . $cmid .
df47b77f
DW
2947 '&plugin=' . $plugin->get_type() .
2948 '&pluginsubtype=assignfeedback' .
2949 '&action=viewpluginpage&pluginaction=' . $action;
2950 $links[$url] = $description;
2951 }
2952 }
2953 }
a1e54f4d 2954
0d416e9c
DW
2955 // Sort links alphabetically based on the link description.
2956 core_collator::asort($links);
2957
a1e54f4d 2958 $gradingactions = new url_select($links);
49f0c151 2959 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
bbd0e548 2960
bf78ebd6
DW
2961 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2962
bbd0e548
DW
2963 $perpage = get_user_preferences('assign_perpage', 10);
2964 $filter = get_user_preferences('assign_filter', '');
f8d107b3
DM
2965 $markerfilter = get_user_preferences('assign_markerfilter', '');
2966 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
bf78ebd6
DW
2967 $controller = $gradingmanager->get_active_controller();
2968 $showquickgrading = empty($controller);
bf78ebd6 2969 $quickgrading = get_user_preferences('assign_quickgrading', false);
4c4c7b3f 2970 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
bf78ebd6 2971
f8d107b3
DM
2972 $markingallocation = $this->get_instance()->markingallocation &&
2973 has_capability('mod/assign:manageallocations', $this->context);
2974 // Get markers to use in drop lists.
2975 $markingallocationoptions = array();
2976 if ($markingallocation) {
2977 $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2978 $markingallocationoptions[''] = get_string('filternone', 'assign');
2979 foreach ($markers as $marker) {
2980 $markingallocationoptions[$marker->id] = fullname($marker);
2981 }
2982 }
2983
2984 $markingworkflow = $this->get_instance()->markingworkflow;
2985 // Get marking states to show in form.
2986 $markingworkflowoptions = array();
2987 if ($markingworkflow) {
13e82f1c 2988 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
f8d107b3 2989 $markingworkflowoptions[''] = get_string('filternone', 'assign');
13e82f1c 2990 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
f8d107b3
DM
2991 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2992 }
2993
e5403f8c
DW
2994 // Print options for changing the filter and changing the number of results per page.
2995 $gradingoptionsformparams = array('cm'=>$cmid,
2996 'contextid'=>$this->context->id,
2997 'userid'=>$USER->id,
2998 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2999 'showquickgrading'=>$showquickgrading,
f8d107b3
DM
3000 'quickgrading'=>$quickgrading,
3001 'markingworkflowopt'=>$markingworkflowoptions,
4c4c7b3f
RT
3002 'markingallocationopt'=>$markingallocationoptions,
3003 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
1ecb8044 3004 'showonlyactiveenrol'=>$this->show_only_active_users());
e5403f8c
DW
3005
3006 $classoptions = array('class'=>'gradingoptionsform');
bbd0e548 3007 $gradingoptionsform = new mod_assign_grading_options_form(null,
e5403f8c
DW
3008 $gradingoptionsformparams,
3009 'post',
3010 '',
3011 $classoptions);
3012
3013 $batchformparams = array('cm'=>$cmid,
3014 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3015 'duedate'=>$this->get_instance()->duedate,
df211804 3016 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
c7e4403c 3017 'feedbackplugins'=>$this->get_feedback_plugins(),
f8d107b3
DM
3018 'context'=>$this->get_context(),
3019 'markingworkflow'=>$markingworkflow,
3020 'markingallocation'=>$markingallocation);
e5403f8c 3021 $classoptions = array('class'=>'gradingbatchoperationsform');
bbd0e548
DW
3022
3023 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
e5403f8c
DW
3024 $batchformparams,
3025 'post',
3026 '',
3027 $classoptions);
bbd0e548
DW
3028
3029 $gradingoptionsdata = new stdClass();
3030 $gradingoptionsdata->perpage = $perpage;
3031 $gradingoptionsdata->filter = $filter;
f8d107b3
DM
3032 $gradingoptionsdata->markerfilter = $markerfilter;
3033 $gradingoptionsdata->workflowfilter = $workflowfilter;
bbd0e548
DW
3034 $gradingoptionsform->set_data($gradingoptionsdata);
3035
49d83b9d 3036 $actionformtext = $this->get_renderer()->render($gradingactions);
e5403f8c
DW
3037 $header = new assign_header($this->get_instance(),
3038 $this->get_context(),
3039 false,
3040 $this->get_course_module()->id,
3041 get_string('grading', 'assign'),
3042 $actionformtext);
3043 $o .= $this->get_renderer()->render($header);
3044
3045 $currenturl = $CFG->wwwroot .
3046 '/mod/assign/view.php?id=' .
3047 $this->get_course_module()->id .
3048 '&action=grading';
3049
3050 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3051
3052 // Plagiarism update status apearring in the grading book.
bbd0e548 3053 if (!empty($CFG->enableplagiarism)) {
bbd0e548 3054 require_once($CFG->libdir . '/plagiarismlib.php');
9650334f 3055 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
bbd0e548
DW
3056 }
3057
e5403f8c 3058 // Load and print the table of submissions.
bf78ebd6 3059 if ($showquickgrading && $quickgrading) {
e5403f8c
DW
3060 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3061 $table = $this->get_renderer()->render($gradingtable);
3062 $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
3063 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3064
49d83b9d 3065 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
bf78ebd6 3066 } else {
e5403f8c
DW
3067 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3068 $o .= $this->get_renderer()->render($gradingtable);
bf78ebd6 3069 }
bbd0e548
DW
3070
3071 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3072 $users = array_keys($this->list_participants($currentgroup, true));
3073 if (count($users) != 0) {
e5403f8c
DW
3074 // If no enrolled user in a course then don't display the batch operations feature.
3075 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3076 $o .= $this->get_renderer()->render($assignform);
3077 }
3078 $assignform = new assign_form('gradingoptionsform',
3079 $gradingoptionsform,
3080 'M.mod_assign.init_grading_options');
3081 $o .= $this->get_renderer()->render($assignform);
bbd0e548
DW
3082 return $o;
3083 }
3084
3085 /**
3086 * View entire grading page.
3087 *
3088 * @return string
3089 */
47f48152 3090 protected function view_grading_page() {
bbd0e548
DW
3091 global $CFG;
3092
3093 $o = '';
e5403f8c 3094 // Need submit permission to submit an assignment.
bbd0e548
DW
3095 require_capability('mod/assign:grade', $this->context);
3096 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3097
e5403f8c 3098 // Only load this if it is.
bbd0e548 3099
bbd0e548
DW
3100 $o .= $this->view_grading_table();
3101
3102 $o .= $this->view_footer();
e5403f8c
DW
3103
3104 $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3105 $this->add_to_log('view submission grading table', $logmessage);
bbd0e548
DW
3106 return $o;
3107 }
3108
3109 /**
e5403f8c 3110 * Capture the output of the plagiarism plugins disclosures and return it as a string.
bbd0e548
DW
3111 *
3112 * @return void
3113 */
47f48152 3114 protected function plagiarism_print_disclosure() {
bbd0e548
DW
3115 global $CFG;
3116 $o = '';
3117
3118 if (!empty($CFG->enableplagiarism)) {
bbd0e548 3119 require_once($CFG->libdir . '/plagiarismlib.php');
bbd0e548 3120
9650334f 3121 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
bbd0e548
DW
3122 }
3123
3124 return $o;
3125 }
3126
3127 /**
e5403f8c 3128 * Message for students when assignment submissions have been closed.
bbd0e548
DW
3129 *
3130 * @return string
3131 */
47f48152 3132 protected function view_student_error_message() {
bbd0e548
DW
3133 global $CFG;
3134
3135 $o = '';
e5403f8c 3136 // Need submit permission to submit an assignment.
bbd0e548
DW
3137 require_capability('mod/assign:submit', $this->context);
3138
e5403f8c
DW
3139 $header = new assign_header($this->get_instance(),
3140 $this->get_context(),
3141 $this->show_intro(),
3142 $this->get_course_module()->id,
3143 get_string('editsubmission', 'assign'));
3144 $o .= $this->get_renderer()->render($header);
bbd0e548 3145
49d83b9d 3146 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
bbd0e548
DW
3147
3148 $o .= $this->view_footer();
3149
3150 return $o;
3151
3152 }
3153
3154 /**
3155 * View edit submissions page.
3156 *
3157 * @param moodleform $mform
e5403f8c
DW
3158 * @param array $notices A list of notices to display at the top of the
3159 * edit submission form (e.g. from plugins).
df211804 3160 * @return string The page output.
bbd0e548 3161 */
47f48152 3162 protected function view_edit_submission_page($mform, $notices) {
bbd0e548
DW
3163 global $CFG;
3164
3165 $o = '';
bbd0e548 3166 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
e5403f8c 3167 // Need submit permission to submit an assignment.
bbd0e548
DW
3168 require_capability('mod/assign:submit', $this->context);
3169
3170 if (!$this->submissions_open()) {
bf78ebd6 3171 return $this->view_student_error_message();
bbd0e548 3172 }
49d83b9d 3173 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
bbd0e548
DW
3174 $this->get_context(),
3175 $this->show_intro(),
3176 $this->get_course_module()->id,
3177