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