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