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