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