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