2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * This file contains the definition for the class assignment
20 * This class provides all the functionality for the new assign module.
23 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 // Assignment submission statuses.
30 define('ASSIGN_SUBMISSION_STATUS_REOPENED', 'reopened');
31 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
32 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
34 // Search filters for grading page.
35 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
36 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
37 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
39 // Reopen attempt methods.
40 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
41 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
42 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
44 // Special value means allow unlimited attempts.
45 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
47 // Marking workflow states.
48 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
49 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
50 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
51 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
52 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
53 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
55 require_once($CFG->libdir . '/accesslib.php');
56 require_once($CFG->libdir . '/formslib.php');
57 require_once($CFG->dirroot . '/repository/lib.php');
58 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
59 require_once($CFG->libdir . '/gradelib.php');
60 require_once($CFG->dirroot . '/grade/grading/lib.php');
61 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
62 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
63 require_once($CFG->dirroot . '/mod/assign/renderable.php');
64 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
65 require_once($CFG->libdir . '/eventslib.php');
66 require_once($CFG->libdir . '/portfolio/caller.php');
69 * Standard base class for mod_assign (assignment types).
72 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
77 /** @var stdClass the assignment record that contains the global settings for this assign instance */
80 /** @var context the context of the course module for this assign instance
81 * (or just the course if we are creating a new one)
85 /** @var stdClass the course this assign instance belongs to */
88 /** @var stdClass the admin config for all assign instances */
91 /** @var assign_renderer the custom renderer for this module */
94 /** @var stdClass the course module for this assign instance */
95 private $coursemodule;
97 /** @var array cache for things like the coursemodule name or the scale menu -
98 * only lives for a single request.
102 /** @var array list of the installed submission plugins */
103 private $submissionplugins;
105 /** @var array list of the installed feedback plugins */
106 private $feedbackplugins;
108 /** @var string action to be used to return to this page
109 * (without repeating any form submissions etc).
111 private $returnaction = 'view';
113 /** @var array params to be used to return to this page */
114 private $returnparams = array();
116 /** @var string modulename prevents excessive calls to get_string */
117 private static $modulename = null;
119 /** @var string modulenameplural prevents excessive calls to get_string */
120 private static $modulenameplural = null;
122 /** @var array of marking workflow states for the current user */
123 private $markingworkflowstates = null;
125 /** @var bool whether to exclude users with inactive enrolment */
126 private $showonlyactiveenrol = null;
128 /** @var array list of suspended user IDs in form of ([id1] => id1) */
129 public $susers = null;
132 * Constructor for the base assign class.
134 * @param mixed $coursemodulecontext context|null the course module context
135 * (or the course context if the coursemodule has not been
137 * @param mixed $coursemodule the current course module if it was already loaded,
138 * otherwise this class will load one from the context as required.
139 * @param mixed $course the current course if it was already loaded,
140 * otherwise this class will load one from the context as required.
142 public function __construct($coursemodulecontext, $coursemodule, $course) {
143 $this->context = $coursemodulecontext;
144 $this->coursemodule = $coursemodule;
145 $this->course = $course;
147 // Temporary cache only lives for a single request - used to reduce db lookups.
148 $this->cache = array();
150 $this->submissionplugins = $this->load_plugins('assignsubmission');
151 $this->feedbackplugins = $this->load_plugins('assignfeedback');
155 * Set the action and parameters that can be used to return to the current page.
157 * @param string $action The action for the current page
158 * @param array $params An array of name value pairs which form the parameters
159 * to return to the current page.
162 public function register_return_link($action, $params) {
164 $params['action'] = $action;
165 $currenturl = $PAGE->url;
167 $currenturl->params($params);
168 $PAGE->set_url($currenturl);
172 * Return an action that can be used to get back to the current page.
174 * @return string action
176 public function get_return_action() {
179 $params = $PAGE->url->params();
181 if (!empty($params['action'])) {
182 return $params['action'];
188 * Based on the current assignment settings should we display the intro.
190 * @return bool showintro
192 protected function show_intro() {
193 if ($this->get_instance()->alwaysshowdescription ||
194 time() > $this->get_instance()->allowsubmissionsfromdate) {
201 * Return a list of parameters that can be used to get back to the current page.
203 * @return array params
205 public function get_return_params() {
208 $params = $PAGE->url->params();
209 unset($params['id']);
210 unset($params['action']);
215 * Set the submitted form data.
217 * @param stdClass $data The form data (instance)
219 public function set_instance(stdClass $data) {
220 $this->instance = $data;
226 * @param context $context The new context
228 public function set_context(context $context) {
229 $this->context = $context;
233 * Set the course data.
235 * @param stdClass $course The course data
237 public function set_course(stdClass $course) {
238 $this->course = $course;
242 * Get list of feedback plugins installed.
246 public function get_feedback_plugins() {
247 return $this->feedbackplugins;
251 * Get list of submission plugins installed.
255 public function get_submission_plugins() {
256 return $this->submissionplugins;
260 * Is blind marking enabled and reveal identities not set yet?
264 public function is_blind_marking() {
265 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
269 * Does an assignment have submission(s) or grade(s) already?
273 public function has_submissions_or_grades() {
274 $allgrades = $this->count_grades();
275 $allsubmissions = $this->count_submissions();
276 if (($allgrades == 0) && ($allsubmissions == 0)) {
283 * Get a specific submission plugin by its type.
285 * @param string $subtype assignsubmission | assignfeedback
286 * @param string $type
287 * @return mixed assign_plugin|null
289 public function get_plugin_by_type($subtype, $type) {
290 $shortsubtype = substr($subtype, strlen('assign'));
291 $name = $shortsubtype . 'plugins';
292 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
295 $pluginlist = $this->$name;
296 foreach ($pluginlist as $plugin) {
297 if ($plugin->get_type() == $type) {
305 * Get a feedback plugin by type.
307 * @param string $type - The type of plugin e.g comments
308 * @return mixed assign_feedback_plugin|null
310 public function get_feedback_plugin_by_type($type) {
311 return $this->get_plugin_by_type('assignfeedback', $type);
315 * Get a submission plugin by type.
317 * @param string $type - The type of plugin e.g comments
318 * @return mixed assign_submission_plugin|null
320 public function get_submission_plugin_by_type($type) {
321 return $this->get_plugin_by_type('assignsubmission', $type);
325 * Load the plugins from the sub folders under subtype.
327 * @param string $subtype - either submission or feedback
328 * @return array - The sorted list of plugins
330 protected function load_plugins($subtype) {
334 $names = core_component::get_plugin_list($subtype);
336 foreach ($names as $name => $path) {
337 if (file_exists($path . '/locallib.php')) {
338 require_once($path . '/locallib.php');
340 $shortsubtype = substr($subtype, strlen('assign'));
341 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
343 $plugin = new $pluginclass($this, $name);
345 if ($plugin instanceof assign_plugin) {
346 $idx = $plugin->get_sort_order();
347 while (array_key_exists($idx, $result)) {
350 $result[$idx] = $plugin;
359 * Display the assignment, used by view.php
361 * The assignment is displayed differently depending on your role,
362 * the settings for the assignment and the status of the assignment.
364 * @param string $action The current action if any.
365 * @return string - The page output.
367 public function view($action='') {
372 $nextpageparams = array();
374 if (!empty($this->get_course_module()->id)) {
375 $nextpageparams['id'] = $this->get_course_module()->id;
378 // Handle form submissions first.
379 if ($action == 'savesubmission') {
380 $action = 'editsubmission';
381 if ($this->process_save_submission($mform, $notices)) {
382 $action = 'redirect';
383 $nextpageparams['action'] = 'view';
385 } else if ($action == 'editprevioussubmission') {
386 $action = 'editsubmission';
387 if ($this->process_copy_previous_attempt($notices)) {
388 $action = 'redirect';
389 $nextpageparams['action'] = 'editsubmission';
391 } else if ($action == 'lock') {
392 $this->process_lock();
393 $action = 'redirect';
394 $nextpageparams['action'] = 'grading';
395 } else if ($action == 'addattempt') {
396 $this->process_add_attempt(required_param('userid', PARAM_INT));
397 $action = 'redirect';
398 $nextpageparams['action'] = 'grading';
399 } else if ($action == 'reverttodraft') {
400 $this->process_revert_to_draft();
401 $action = 'redirect';
402 $nextpageparams['action'] = 'grading';
403 } else if ($action == 'unlock') {
404 $this->process_unlock();
405 $action = 'redirect';
406 $nextpageparams['action'] = 'grading';
407 } else if ($action == 'setbatchmarkingworkflowstate') {
408 $this->process_set_batch_marking_workflow_state();
409 $action = 'redirect';
410 $nextpageparams['action'] = 'grading';
411 } else if ($action == 'setbatchmarkingallocation') {
412 $this->process_set_batch_marking_allocation();
413 $action = 'redirect';
414 $nextpageparams['action'] = 'grading';
415 } else if ($action == 'confirmsubmit') {
417 if ($this->process_submit_for_grading($mform)) {
418 $action = 'redirect';
419 $nextpageparams['action'] = 'view';
421 } else if ($action == 'gradingbatchoperation') {
422 $action = $this->process_grading_batch_operation($mform);
423 if ($action == 'grading') {
424 $action = 'redirect';
425 $nextpageparams['action'] = 'grading';
427 } else if ($action == 'submitgrade') {
428 if (optional_param('saveandshownext', null, PARAM_RAW)) {
429 // Save and show next.
431 if ($this->process_save_grade($mform)) {
432 $action = 'redirect';
433 $nextpageparams['action'] = 'grade';
434 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
435 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
437 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
438 $action = 'redirect';
439 $nextpageparams['action'] = 'grade';
440 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
441 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
442 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
443 $action = 'redirect';
444 $nextpageparams['action'] = 'grade';
445 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
446 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
447 } else if (optional_param('savegrade', null, PARAM_RAW)) {
448 // Save changes button.
450 if ($this->process_save_grade($mform)) {
451 $message = get_string('gradingchangessaved', 'assign');
452 $action = 'savegradingresult';
456 $action = 'redirect';
457 $nextpageparams['action'] = 'grading';
459 } else if ($action == 'quickgrade') {
460 $message = $this->process_save_quick_grades();
461 $action = 'quickgradingresult';
462 } else if ($action == 'saveoptions') {
463 $this->process_save_grading_options();
464 $action = 'redirect';
465 $nextpageparams['action'] = 'grading';
466 } else if ($action == 'saveextension') {
467 $action = 'grantextension';
468 if ($this->process_save_extension($mform)) {
469 $action = 'redirect';
470 $nextpageparams['action'] = 'grading';
472 } else if ($action == 'revealidentitiesconfirm') {
473 $this->process_reveal_identities();
474 $action = 'redirect';
475 $nextpageparams['action'] = 'grading';
478 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
479 'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
480 $this->register_return_link($action, $returnparams);
482 // Now show the right view page.
483 if ($action == 'redirect') {
484 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
485 redirect($nextpageurl);
487 } else if ($action == 'savegradingresult') {
488 $o .= $this->view_savegrading_result($message);
489 } else if ($action == 'quickgradingresult') {
491 $o .= $this->view_quickgrading_result($message);
492 } else if ($action == 'grade') {
493 $o .= $this->view_single_grade_page($mform);
494 } else if ($action == 'viewpluginassignfeedback') {
495 $o .= $this->view_plugin_content('assignfeedback');
496 } else if ($action == 'viewpluginassignsubmission') {
497 $o .= $this->view_plugin_content('assignsubmission');
498 } else if ($action == 'editsubmission') {
499 $o .= $this->view_edit_submission_page($mform, $notices);
500 } else if ($action == 'grading') {
501 $o .= $this->view_grading_page();
502 } else if ($action == 'downloadall') {
503 $o .= $this->download_submissions();
504 } else if ($action == 'submit') {
505 $o .= $this->check_submit_for_grading($mform);
506 } else if ($action == 'grantextension') {
507 $o .= $this->view_grant_extension($mform);
508 } else if ($action == 'revealidentities') {
509 $o .= $this->view_reveal_identities_confirm($mform);
510 } else if ($action == 'plugingradingbatchoperation') {
511 $o .= $this->view_plugin_grading_batch_operation($mform);
512 } else if ($action == 'viewpluginpage') {
513 $o .= $this->view_plugin_page();
514 } else if ($action == 'viewcourseindex') {
515 $o .= $this->view_course_index();
516 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
517 $o .= $this->view_batch_set_workflow_state($mform);
518 } else if ($action == 'viewbatchmarkingallocation') {
519 $o .= $this->view_batch_markingallocation($mform);
521 $o .= $this->view_submission_page();
528 * Add this instance to the database.
530 * @param stdClass $formdata The data submitted from the form
531 * @param bool $callplugins This is used to skip the plugin code
532 * when upgrading an old assignment to a new one (the plugins get called manually)
533 * @return mixed false if an error occurs or the int id of the new instance
535 public function add_instance(stdClass $formdata, $callplugins) {
540 // Add the database record.
541 $update = new stdClass();
542 $update->name = $formdata->name;
543 $update->timemodified = time();
544 $update->timecreated = time();
545 $update->course = $formdata->course;
546 $update->courseid = $formdata->course;
547 $update->intro = $formdata->intro;
548 $update->introformat = $formdata->introformat;
549 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
550 $update->submissiondrafts = $formdata->submissiondrafts;
551 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
552 $update->sendnotifications = $formdata->sendnotifications;
553 $update->sendlatenotifications = $formdata->sendlatenotifications;
554 $update->duedate = $formdata->duedate;
555 $update->cutoffdate = $formdata->cutoffdate;
556 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
557 $update->grade = $formdata->grade;
558 $update->completionsubmit = !empty($formdata->completionsubmit);
559 $update->teamsubmission = $formdata->teamsubmission;
560 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
561 if (isset($formdata->teamsubmissiongroupingid)) {
562 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
564 $update->blindmarking = $formdata->blindmarking;
565 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
566 if (!empty($formdata->attemptreopenmethod)) {
567 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
569 if (!empty($formdata->maxattempts)) {
570 $update->maxattempts = $formdata->maxattempts;
572 $update->markingworkflow = $formdata->markingworkflow;
573 $update->markingallocation = $formdata->markingallocation;
575 $returnid = $DB->insert_record('assign', $update);
576 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
577 // Cache the course record.
578 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
581 // Call save_settings hook for submission plugins.
582 foreach ($this->submissionplugins as $plugin) {
583 if (!$this->update_plugin_instance($plugin, $formdata)) {
584 print_error($plugin->get_error());
588 foreach ($this->feedbackplugins as $plugin) {
589 if (!$this->update_plugin_instance($plugin, $formdata)) {
590 print_error($plugin->get_error());
595 // In the case of upgrades the coursemodule has not been set,
596 // so we need to wait before calling these two.
597 $this->update_calendar($formdata->coursemodule);
598 $this->update_gradebook(false, $formdata->coursemodule);
602 $update = new stdClass();
603 $update->id = $this->get_instance()->id;
604 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
605 $DB->update_record('assign', $update);
611 * Delete all grades from the gradebook for this assignment.
615 protected function delete_grades() {
618 $result = grade_update('mod/assign',
619 $this->get_course()->id,
622 $this->get_instance()->id,
625 array('deleted'=>1));
626 return $result == GRADE_UPDATE_OK;
630 * Delete this instance from the database.
632 * @return bool false if an error occurs
634 public function delete_instance() {
638 foreach ($this->submissionplugins as $plugin) {
639 if (!$plugin->delete_instance()) {
640 print_error($plugin->get_error());
644 foreach ($this->feedbackplugins as $plugin) {
645 if (!$plugin->delete_instance()) {
646 print_error($plugin->get_error());
651 // Delete files associated with this assignment.
652 $fs = get_file_storage();
653 if (! $fs->delete_area_files($this->context->id) ) {
657 // Delete_records will throw an exception if it fails - so no need for error checking here.
658 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
659 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
660 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
662 // Delete items from the gradebook.
663 if (! $this->delete_grades()) {
667 // Delete the instance.
668 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
674 * Actual implementation of the reset course functionality, delete all the
675 * assignment submissions for course $data->courseid.
677 * @param $data the data submitted from the reset course.
678 * @return array status array
680 public function reset_userdata($data) {
683 $componentstr = get_string('modulenameplural', 'assign');
686 $fs = get_file_storage();
687 if (!empty($data->reset_assign_submissions)) {
688 // Delete files associated with this assignment.
689 foreach ($this->submissionplugins as $plugin) {
690 $fileareas = array();
691 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
692 $fileareas = $plugin->get_file_areas();
693 foreach ($fileareas as $filearea) {
694 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
697 if (!$plugin->delete_instance()) {
698 $status[] = array('component'=>$componentstr,
699 'item'=>get_string('deleteallsubmissions', 'assign'),
700 'error'=>$plugin->get_error());
704 foreach ($this->feedbackplugins as $plugin) {
705 $fileareas = array();
706 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
707 $fileareas = $plugin->get_file_areas();
708 foreach ($fileareas as $filearea) {
709 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
712 if (!$plugin->delete_instance()) {
713 $status[] = array('component'=>$componentstr,
714 'item'=>get_string('deleteallsubmissions', 'assign'),
715 'error'=>$plugin->get_error());
719 $assignssql = 'SELECT a.id
721 WHERE a.course=:course';
722 $params = array('course'=>$data->courseid);
724 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
726 $status[] = array('component'=>$componentstr,
727 'item'=>get_string('deleteallsubmissions', 'assign'),
730 if (!empty($data->reset_gradebook_grades)) {
731 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
732 // Remove all grades from gradebook.
733 require_once($CFG->dirroot.'/mod/assign/lib.php');
734 assign_reset_gradebook($data->courseid);
737 // Updating dates - shift may be negative too.
738 if ($data->timeshift) {
739 shift_course_mod_dates('assign',
740 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
743 $status[] = array('component'=>$componentstr,
744 'item'=>get_string('datechanged'),
752 * Update the settings for a single plugin.
754 * @param assign_plugin $plugin The plugin to update
755 * @param stdClass $formdata The form data
756 * @return bool false if an error occurs
758 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
759 if ($plugin->is_visible()) {
760 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
761 if (!empty($formdata->$enabledname)) {
763 if (!$plugin->save_settings($formdata)) {
764 print_error($plugin->get_error());
775 * Update the gradebook information for this assignment.
777 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
778 * @param int $coursemoduleid This is required because it might not exist in the database yet
781 public function update_gradebook($reset, $coursemoduleid) {
784 require_once($CFG->dirroot.'/mod/assign/lib.php');
785 $assign = clone $this->get_instance();
786 $assign->cmidnumber = $coursemoduleid;
792 return assign_grade_item_update($assign, $param);
796 * Load and cache the admin config for this module.
798 * @return stdClass the plugin config
800 public function get_admin_config() {
801 if ($this->adminconfig) {
802 return $this->adminconfig;
804 $this->adminconfig = get_config('assign');
805 return $this->adminconfig;
809 * Update the calendar entries for this assignment.
811 * @param int $coursemoduleid - Required to pass this in because it might
812 * not exist in the database yet.
815 public function update_calendar($coursemoduleid) {
817 require_once($CFG->dirroot.'/calendar/lib.php');
819 // Special case for add_instance as the coursemodule has not been set yet.
820 $instance = $this->get_instance();
822 if ($instance->duedate) {
823 $event = new stdClass();
825 $params = array('modulename'=>'assign', 'instance'=>$instance->id);
826 $event->id = $DB->get_field('event',
831 $event->name = $instance->name;
832 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
833 $event->timestart = $instance->duedate;
835 $calendarevent = calendar_event::load($event->id);
836 $calendarevent->update($event);
838 $event = new stdClass();
839 $event->name = $instance->name;
840 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
841 $event->courseid = $instance->course;
844 $event->modulename = 'assign';
845 $event->instance = $instance->id;
846 $event->eventtype = 'due';
847 $event->timestart = $instance->duedate;
848 $event->timeduration = 0;
850 calendar_event::create($event);
853 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
859 * Update this instance in the database.
861 * @param stdClass $formdata - the data submitted from the form
862 * @return bool false if an error occurs
864 public function update_instance($formdata) {
867 $update = new stdClass();
868 $update->id = $formdata->instance;
869 $update->name = $formdata->name;
870 $update->timemodified = time();
871 $update->course = $formdata->course;
872 $update->intro = $formdata->intro;
873 $update->introformat = $formdata->introformat;
874 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
875 $update->submissiondrafts = $formdata->submissiondrafts;
876 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
877 $update->sendnotifications = $formdata->sendnotifications;
878 $update->sendlatenotifications = $formdata->sendlatenotifications;
879 $update->duedate = $formdata->duedate;
880 $update->cutoffdate = $formdata->cutoffdate;
881 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
882 $update->grade = $formdata->grade;
883 if (!empty($formdata->completionunlocked)) {
884 $update->completionsubmit = !empty($formdata->completionsubmit);
886 $update->teamsubmission = $formdata->teamsubmission;
887 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
888 if (isset($formdata->teamsubmissiongroupingid)) {
889 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
891 $update->blindmarking = $formdata->blindmarking;
892 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
893 if (!empty($formdata->attemptreopenmethod)) {
894 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
896 if (!empty($formdata->maxattempts)) {
897 $update->maxattempts = $formdata->maxattempts;
899 $update->markingworkflow = $formdata->markingworkflow;
900 $update->markingallocation = $formdata->markingallocation;
902 $result = $DB->update_record('assign', $update);
903 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
905 // Load the assignment so the plugins have access to it.
907 // Call save_settings hook for submission plugins.
908 foreach ($this->submissionplugins as $plugin) {
909 if (!$this->update_plugin_instance($plugin, $formdata)) {
910 print_error($plugin->get_error());
914 foreach ($this->feedbackplugins as $plugin) {
915 if (!$this->update_plugin_instance($plugin, $formdata)) {
916 print_error($plugin->get_error());
921 $this->update_calendar($this->get_course_module()->id);
922 $this->update_gradebook(false, $this->get_course_module()->id);
924 $update = new stdClass();
925 $update->id = $this->get_instance()->id;
926 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
927 $DB->update_record('assign', $update);
933 * Add elements in grading plugin form.
935 * @param mixed $grade stdClass|null
936 * @param MoodleQuickForm $mform
937 * @param stdClass $data
938 * @param int $userid - The userid we are grading
941 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
942 foreach ($this->feedbackplugins as $plugin) {
943 if ($plugin->is_enabled() && $plugin->is_visible()) {
944 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
945 $mform->setExpanded('header_' . $plugin->get_type());
946 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
947 $mform->removeElement('header_' . $plugin->get_type());
956 * Add one plugins settings to edit plugin form.
958 * @param assign_plugin $plugin The plugin to add the settings from
959 * @param MoodleQuickForm $mform The form to add the configuration settings to.
960 * This form is modified directly (not returned).
961 * @param array $pluginsenabled A list of form elements to be added to a group.
962 * The new element is added to this array by this function.
965 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
967 if ($plugin->is_visible()) {
969 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
970 $label = $plugin->get_name();
971 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
972 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
974 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
975 if ($plugin->get_config('enabled') !== false) {
976 $default = $plugin->is_enabled();
978 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
980 $plugin->get_settings($mform);
986 * Add settings to edit plugin form.
988 * @param MoodleQuickForm $mform The form to add the configuration settings to.
989 * This form is modified directly (not returned).
992 public function add_all_plugin_settings(MoodleQuickForm $mform) {
993 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
995 $submissionpluginsenabled = array();
996 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
997 foreach ($this->submissionplugins as $plugin) {
998 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1000 $group->setElements($submissionpluginsenabled);
1002 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1003 $feedbackpluginsenabled = array();
1004 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1005 foreach ($this->feedbackplugins as $plugin) {
1006 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1008 $group->setElements($feedbackpluginsenabled);
1009 $mform->setExpanded('submissiontypes');
1013 * Allow each plugin an opportunity to update the defaultvalues
1014 * passed in to the settings form (needed to set up draft areas for
1015 * editor and filemanager elements)
1017 * @param array $defaultvalues
1019 public function plugin_data_preprocessing(&$defaultvalues) {
1020 foreach ($this->submissionplugins as $plugin) {
1021 if ($plugin->is_visible()) {
1022 $plugin->data_preprocessing($defaultvalues);
1025 foreach ($this->feedbackplugins as $plugin) {
1026 if ($plugin->is_visible()) {
1027 $plugin->data_preprocessing($defaultvalues);
1033 * Get the name of the current module.
1035 * @return string the module name (Assignment)
1037 protected function get_module_name() {
1038 if (isset(self::$modulename)) {
1039 return self::$modulename;
1041 self::$modulename = get_string('modulename', 'assign');
1042 return self::$modulename;
1046 * Get the plural name of the current module.
1048 * @return string the module name plural (Assignments)
1050 protected function get_module_name_plural() {
1051 if (isset(self::$modulenameplural)) {
1052 return self::$modulenameplural;
1054 self::$modulenameplural = get_string('modulenameplural', 'assign');
1055 return self::$modulenameplural;
1059 * Has this assignment been constructed from an instance?
1063 public function has_instance() {
1064 return $this->instance || $this->get_course_module();
1068 * Get the settings for the current instance of this assignment
1070 * @return stdClass The settings
1072 public function get_instance() {
1074 if ($this->instance) {
1075 return $this->instance;
1077 if ($this->get_course_module()) {
1078 $params = array('id' => $this->get_course_module()->instance);
1079 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1081 if (!$this->instance) {
1082 throw new coding_exception('Improper use of the assignment class. ' .
1083 'Cannot load the assignment record.');
1085 return $this->instance;
1089 * Get the context of the current course.
1091 * @return mixed context|null The course context
1093 public function get_course_context() {
1094 if (!$this->context && !$this->course) {
1095 throw new coding_exception('Improper use of the assignment class. ' .
1096 'Cannot load the course context.');
1098 if ($this->context) {
1099 return $this->context->get_course_context();
1101 return context_course::instance($this->course->id);
1107 * Get the current course module.
1109 * @return mixed stdClass|null The course module
1111 public function get_course_module() {
1112 if ($this->coursemodule) {
1113 return $this->coursemodule;
1115 if (!$this->context) {
1119 if ($this->context->contextlevel == CONTEXT_MODULE) {
1120 $this->coursemodule = get_coursemodule_from_id('assign',
1121 $this->context->instanceid,
1125 return $this->coursemodule;
1131 * Get context module.
1135 public function get_context() {
1136 return $this->context;
1140 * Get the current course.
1142 * @return mixed stdClass|null The course
1144 public function get_course() {
1147 if ($this->course) {
1148 return $this->course;
1151 if (!$this->context) {
1154 $params = array('id' => $this->get_course_context()->instanceid);
1155 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1157 return $this->course;
1161 * Return a grade in user-friendly form, whether it's a scale or not.
1163 * @param mixed $grade int|null
1164 * @param boolean $editing Are we allowing changes to this grade?
1165 * @param int $userid The user id the grade belongs to
1166 * @param int $modified Timestamp from when the grade was last modified
1167 * @return string User-friendly representation of grade
1169 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1172 static $scalegrades = array();
1176 if ($this->get_instance()->grade >= 0) {
1178 if ($editing && $this->get_instance()->grade > 0) {
1182 $displaygrade = format_float($grade, 2);
1184 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1185 get_string('usergrade', 'assign') .
1187 $o .= '<input type="text"
1188 id="quickgrade_' . $userid . '"
1189 name="quickgrade_' . $userid . '"
1190 value="' . $displaygrade . '"
1193 class="quickgrade"/>';
1194 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1195 $o .= '<input type="hidden"
1196 name="grademodified_' . $userid . '"
1197 value="' . $modified . '"/>';
1200 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1201 if ($grade == -1 || $grade === null) {
1205 $o .= format_float($grade, 2) .
1207 format_float($this->get_instance()->grade, 2);
1214 if (empty($this->cache['scale'])) {
1215 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1216 $this->cache['scale'] = make_menu_from_list($scale->scale);
1223 $o .= '<label class="accesshide"
1224 for="quickgrade_' . $userid . '">' .
1225 get_string('usergrade', 'assign') .
1227 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1228 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1229 foreach ($this->cache['scale'] as $optionid => $option) {
1231 if ($grade == $optionid) {
1232 $selected = 'selected="selected"';
1234 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1237 $o .= '<input type="hidden" ' .
1238 'name="grademodified_' . $userid . '" ' .
1239 'value="' . $modified . '"/>';
1242 $scaleid = (int)$grade;
1243 if (isset($this->cache['scale'][$scaleid])) {
1244 $o .= $this->cache['scale'][$scaleid];
1254 * Load a list of users enrolled in the current course with the specified permission and group.
1257 * @param int $currentgroup
1258 * @param bool $idsonly
1259 * @return array List of user records
1261 public function list_participants($currentgroup, $idsonly) {
1263 return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id', null, null, null,
1264 $this->show_only_active_users());
1266 return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1267 $this->show_only_active_users());
1272 * Load a count of valid teams for this assignment.
1274 * @return int number of valid teams
1276 public function count_teams() {
1278 $groups = groups_get_all_groups($this->get_course()->id,
1280 $this->get_instance()->teamsubmissiongroupingid,
1282 $count = count($groups);
1284 // See if there are any users in the default group.
1285 $defaultusers = $this->get_submission_group_members(0, true);
1286 if (count($defaultusers) > 0) {
1293 * Load a count of active users enrolled in the current course with the specified permission and group.
1296 * @param int $currentgroup
1297 * @return int number of matching users
1299 public function count_participants($currentgroup) {
1300 return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, true);
1304 * Load a count of active users submissions in the current module that require grading
1305 * This means the submission modification time is more recent than the
1306 * grading modification time and the status is SUBMITTED.
1308 * @return int number of matching submissions
1310 public function count_submissions_need_grading() {
1313 if ($this->get_instance()->teamsubmission) {
1314 // This does not make sense for group assignment because the submission is shared.
1318 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1319 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1321 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1322 FROM {assign_submission} mxs
1323 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1324 $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1325 FROM {assign_grades} mxg
1326 WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1328 $params['assignid'] = $this->get_instance()->id;
1329 $params['assignid2'] = $this->get_instance()->id;
1330 $params['assignid3'] = $this->get_instance()->id;
1331 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1333 $sql = 'SELECT COUNT(s.userid)
1334 FROM {assign_submission} s
1335 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1336 LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1337 LEFT JOIN {assign_grades} g ON
1338 s.assignment = g.assignment AND
1339 s.userid = g.userid AND
1340 g.attemptnumber = gmx.maxattempt
1341 JOIN(' . $esql . ') e ON e.id = s.userid
1343 s.attemptnumber = smx.maxattempt AND
1344 s.assignment = :assignid AND
1345 s.timemodified IS NOT NULL AND
1346 s.status = :submitted AND
1347 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1349 return $DB->count_records_sql($sql, $params);
1353 * Load a count of grades.
1355 * @return int number of grades
1357 public function count_grades() {
1360 if (!$this->has_instance()) {
1364 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1365 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1367 $params['assignid'] = $this->get_instance()->id;
1369 $sql = 'SELECT COUNT(g.userid)
1370 FROM {assign_grades} g
1371 JOIN(' . $esql . ') e ON e.id = g.userid
1372 WHERE g.assignment = :assignid';
1374 return $DB->count_records_sql($sql, $params);
1378 * Load a count of submissions.
1380 * @return int number of submissions
1382 public function count_submissions() {
1385 if (!$this->has_instance()) {
1391 if ($this->get_instance()->teamsubmission) {
1392 // We cannot join on the enrolment tables for group submissions (no userid).
1393 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1394 FROM {assign_submission} s
1396 s.assignment = :assignid AND
1397 s.timemodified IS NOT NULL AND
1398 s.userid = :groupuserid';
1400 $params['assignid'] = $this->get_instance()->id;
1401 $params['groupuserid'] = 0;
1403 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1404 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1406 $params['assignid'] = $this->get_instance()->id;
1408 $sql = 'SELECT COUNT(DISTINCT s.userid)
1409 FROM {assign_submission} s
1410 JOIN(' . $esql . ') e ON e.id = s.userid
1412 s.assignment = :assignid AND
1413 s.timemodified IS NOT NULL';
1417 return $DB->count_records_sql($sql, $params);
1421 * Load a count of submissions with a specified status.
1423 * @param string $status The submission status - should match one of the constants
1424 * @return int number of matching submissions
1426 public function count_submissions_with_status($status) {
1429 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1430 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1432 $params['assignid'] = $this->get_instance()->id;
1433 $params['assignid2'] = $this->get_instance()->id;
1434 $params['submissionstatus'] = $status;
1436 if ($this->get_instance()->teamsubmission) {
1437 $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1438 FROM {assign_submission} mxs
1439 WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1441 $sql = 'SELECT COUNT(s.groupid)
1442 FROM {assign_submission} s
1443 JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1445 s.attemptnumber = smx.maxattempt AND
1446 s.assignment = :assignid AND
1447 s.timemodified IS NOT NULL AND
1448 s.userid = :groupuserid AND
1449 s.status = :submissionstatus';
1450 $params['groupuserid'] = 0;
1452 $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1453 FROM {assign_submission} mxs
1454 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1456 $sql = 'SELECT COUNT(s.userid)
1457 FROM {assign_submission} s
1458 JOIN(' . $esql . ') e ON e.id = s.userid
1459 JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1461 s.attemptnumber = smx.maxattempt AND
1462 s.assignment = :assignid AND
1463 s.timemodified IS NOT NULL AND
1464 s.status = :submissionstatus';
1468 return $DB->count_records_sql($sql, $params);
1472 * Utility function to get the userid for every row in the grading table
1473 * so the order can be frozen while we iterate it.
1475 * @return array An array of userids
1477 protected function get_grading_userid_list() {
1478 $filter = get_user_preferences('assign_filter', '');
1479 $table = new assign_grading_table($this, 0, $filter, 0, false);
1481 $useridlist = $table->get_column_data('userid');
1487 * Generate zip file from array of given files.
1489 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1490 * This array is indexed by the final file name and each
1491 * element in the array is an instance of a stored_file object.
1492 * @return path of temp file - note this returned file does
1493 * not have a .zip extension - it is a temp file.
1495 protected function pack_files($filesforzipping) {
1497 // Create path for new zip file.
1498 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1500 $zipper = new zip_packer();
1501 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1508 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1510 * Cron function to be run periodically according to the moodle cron.
1514 public static function cron() {
1517 // Only ever send a max of one days worth of updates.
1518 $yesterday = time() - (24 * 3600);
1521 // Collect all submissions from the past 24 hours that require mailing.
1522 $sql = 'SELECT a.course, a.name, a.blindmarking, a.revealidentities,
1523 g.*, g.id as gradeid, g.timemodified as lastmodified
1525 JOIN {assign_grades} g ON g.assignment = a.id
1526 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1527 WHERE g.timemodified >= :yesterday AND
1528 g.timemodified <= :today AND
1531 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1532 $submissions = $DB->get_records_sql($sql, $params);
1534 if (empty($submissions)) {
1538 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1540 // Preload courses we are going to need those.
1541 $courseids = array();
1542 foreach ($submissions as $submission) {
1543 $courseids[] = $submission->course;
1546 // Filter out duplicates.
1547 $courseids = array_unique($courseids);
1548 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1549 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1550 $sql = 'SELECT c.*, ' . $ctxselect .
1552 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1553 WHERE c.id ' . $courseidsql;
1555 $params['contextlevel'] = CONTEXT_COURSE;
1556 $courses = $DB->get_records_sql($sql, $params);
1558 // Clean up... this could go on for a while.
1561 unset($courseidsql);
1564 // Simple array we'll use for caching modules.
1565 $modcache = array();
1567 // Message students about new feedback.
1568 foreach ($submissions as $submission) {
1570 mtrace("Processing assignment submission $submission->id ...");
1572 // Do not cache user lookups - could be too many.
1573 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1574 mtrace('Could not find user ' . $submission->userid);
1578 // Use a cache to prevent the same DB queries happening over and over.
1579 if (!array_key_exists($submission->course, $courses)) {
1580 mtrace('Could not find course ' . $submission->course);
1583 $course = $courses[$submission->course];
1584 if (isset($course->ctxid)) {
1585 // Context has not yet been preloaded. Do so now.
1586 context_helper::preload_from_record($course);
1589 // Override the language and timezone of the "current" user, so that
1590 // mail is customised for the receiver.
1591 cron_setup_user($user, $course);
1593 // Context lookups are already cached.
1594 $coursecontext = context_course::instance($course->id);
1595 if (!is_enrolled($coursecontext, $user->id)) {
1596 $courseshortname = format_string($course->shortname,
1598 array('context' => $coursecontext));
1599 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1603 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1604 mtrace('Could not find grader ' . $submission->grader);
1608 if (!array_key_exists($submission->assignment, $modcache)) {
1609 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1611 mtrace('Could not find course module for assignment id ' . $submission->assignment);
1614 $modcache[$submission->assignment] = $mod;
1616 $mod = $modcache[$submission->assignment];
1618 // Context lookups are already cached.
1619 $contextmodule = context_module::instance($mod->id);
1621 if (!$mod->visible) {
1622 // Hold mail notification for hidden assignments until later.
1626 // Need to send this to the student.
1627 $messagetype = 'feedbackavailable';
1628 $eventtype = 'assign_notification';
1629 $updatetime = $submission->lastmodified;
1630 $modulename = get_string('modulename', 'assign');
1633 if ($submission->blindmarking && !$submission->revealidentities) {
1634 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1636 $showusers = $submission->blindmarking && !$submission->revealidentities;
1637 self::send_assignment_notification($grader,
1650 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1653 $DB->update_record('assign_user_flags', $flags);
1655 $flags = new stdClass();
1656 $flags->userid = $user->id;
1657 $flags->assignment = $submission->assignment;
1659 $DB->insert_record('assign_user_flags', $flags);
1664 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1668 // Free up memory just to be sure.
1676 * Mark in the database that this grade record should have an update notification sent by cron.
1678 * @param stdClass $grade a grade record keyed on id
1679 * @return bool true for success
1681 public function notify_grade_modified($grade) {
1684 $flags = $this->get_user_flags($grade->userid, true);
1685 if ($flags->mailed != 1) {
1689 return $this->update_user_flags($flags);
1693 * Update user flags for this user in this assignment.
1695 * @param stdClass $flags a flags record keyed on id
1696 * @return bool true for success
1698 public function update_user_flags($flags) {
1700 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1704 $result = $DB->update_record('assign_user_flags', $flags);
1709 * Update a grade in the grade table for the assignment and in the gradebook.
1711 * @param stdClass $grade a grade record keyed on id
1712 * @return bool true for success
1714 public function update_grade($grade) {
1717 $grade->timemodified = time();
1719 if (!empty($grade->workflowstate)) {
1720 $validstates = $this->get_marking_workflow_states_for_current_user();
1721 if (!array_key_exists($grade->workflowstate, $validstates)) {
1726 if ($grade->grade && $grade->grade != -1) {
1727 if ($this->get_instance()->grade > 0) {
1728 if (!is_numeric($grade->grade)) {
1730 } else if ($grade->grade > $this->get_instance()->grade) {
1732 } else if ($grade->grade < 0) {
1737 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1738 $scaleoptions = make_menu_from_list($scale->scale);
1739 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1746 if (empty($grade->attemptnumber)) {
1747 // Set it to the default.
1748 $grade->attemptnumber = 0;
1750 $result = $DB->update_record('assign_grades', $grade);
1752 // Only push to gradebook if the update is for the latest attempt.
1754 if ($this->get_instance()->teamsubmission) {
1755 $submission = $this->get_group_submission($grade->userid, 0, false);
1757 $submission = $this->get_user_submission($grade->userid, false);
1759 // Not the latest attempt.
1760 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1765 $this->gradebook_item_update(null, $grade);
1771 * View the grant extension date page.
1773 * Uses url parameters 'userid'
1774 * or from parameter 'selectedusers'
1776 * @param moodleform $mform - Used for validation of the submitted data
1779 protected function view_grant_extension($mform) {
1781 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1784 $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1785 $data = new stdClass();
1786 $data->extensionduedate = null;
1789 $userid = required_param('userid', PARAM_INT);
1791 $grade = $this->get_user_grade($userid, false);
1793 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1796 $data->extensionduedate = $grade->extensionduedate;
1798 $data->userid = $userid;
1800 $data->batchusers = $batchusers;
1802 $header = new assign_header($this->get_instance(),
1803 $this->get_context(),
1804 $this->show_intro(),
1805 $this->get_course_module()->id,
1806 get_string('grantextension', 'assign'));
1807 $o .= $this->get_renderer()->render($header);
1810 $formparams = array($this->get_course_module()->id,
1813 $this->get_instance(),
1815 $mform = new mod_assign_extension_form(null, $formparams);
1817 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1818 $o .= $this->view_footer();
1823 * Get a list of the users in the same group as this user.
1825 * @param int $groupid The id of the group whose members we want or 0 for the default group
1826 * @param bool $onlyids Whether to retrieve only the user id's
1827 * @return array The users (possibly id's only)
1829 public function get_submission_group_members($groupid, $onlyids) {
1831 if ($groupid != 0) {
1833 $allusers = groups_get_members($groupid, 'u.id');
1835 $allusers = groups_get_members($groupid);
1837 foreach ($allusers as $user) {
1838 if ($this->get_submission_group($user->id)) {
1843 $allusers = $this->list_participants(null, $onlyids);
1844 foreach ($allusers as $user) {
1845 if ($this->get_submission_group($user->id) == null) {
1850 // Exclude suspended users, if user can't see them.
1851 if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1852 foreach ($members as $key => $member) {
1853 if (!$this->is_active_user($member->id)) {
1854 unset($members[$key]);
1862 * Get a list of the users in the same group as this user that have not submitted the assignment.
1864 * @param int $groupid The id of the group whose members we want or 0 for the default group
1865 * @param bool $onlyids Whether to retrieve only the user id's
1866 * @return array The users (possibly id's only)
1868 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1869 $instance = $this->get_instance();
1870 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1873 $members = $this->get_submission_group_members($groupid, $onlyids);
1875 foreach ($members as $id => $member) {
1876 $submission = $this->get_user_submission($member->id, false);
1877 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1878 unset($members[$id]);
1880 if ($this->is_blind_marking()) {
1881 $members[$id]->alias = get_string('hiddenuser', 'assign') .
1882 $this->get_uniqueid_for_user($id);
1890 * Load the group submission object for a particular user, optionally creating it if required.
1892 * @param int $userid The id of the user whose submission we want
1893 * @param int $groupid The id of the group for this user - may be 0 in which
1894 * case it is determined from the userid.
1895 * @param bool $create If set to true a new submission object will be created in the database
1896 * @param int $attemptnumber - -1 means the latest attempt
1897 * @return stdClass The submission
1899 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1902 if ($groupid == 0) {
1903 $group = $this->get_submission_group($userid);
1905 $groupid = $group->id;
1909 // Now get the group submission.
1910 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1911 if ($attemptnumber >= 0) {
1912 $params['attemptnumber'] = $attemptnumber;
1915 // Only return the row with the highest attemptnumber.
1917 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1919 $submission = reset($submissions);
1926 $submission = new stdClass();
1927 $submission->assignment = $this->get_instance()->id;
1928 $submission->userid = 0;
1929 $submission->groupid = $groupid;
1930 $submission->timecreated = time();
1931 $submission->timemodified = $submission->timecreated;
1932 if ($attemptnumber >= 0) {
1933 $submission->attemptnumber = $attemptnumber;
1935 $submission->attemptnumber = 0;
1938 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1939 $sid = $DB->insert_record('assign_submission', $submission);
1940 $submission->id = $sid;
1947 * View a summary listing of all assignments in the current course.
1951 private function view_course_index() {
1956 $course = $this->get_course();
1957 $strplural = get_string('modulenameplural', 'assign');
1959 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1960 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1961 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1965 $strsectionname = get_string('sectionname', 'format_'.$course->format);
1966 $usesections = course_format_uses_sections($course->format);
1967 $modinfo = get_fast_modinfo($course);
1970 $sections = $modinfo->get_section_info_all();
1972 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1976 $currentsection = '';
1977 foreach ($modinfo->instances['assign'] as $cm) {
1978 if (!$cm->uservisible) {
1982 $timedue = $cms[$cm->id]->duedate;
1985 if ($usesections && $cm->sectionnum) {
1986 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1990 $context = context_module::instance($cm->id);
1992 $assignment = new assign($context, $cm, $course);
1994 if (has_capability('mod/assign:grade', $context)) {
1995 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1997 } else if (has_capability('mod/assign:submit', $context)) {
1998 $usersubmission = $assignment->get_user_submission($USER->id, false);
2000 if (!empty($usersubmission->status)) {
2001 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2003 $submitted = get_string('submissionstatus_', 'assign');
2006 $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2007 if (isset($grading_info->items[0]->grades[$USER->id]) &&
2008 !$grading_info->items[0]->grades[$USER->id]->hidden ) {
2009 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
2014 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2018 $o .= $this->get_renderer()->render($courseindexsummary);
2019 $o .= $this->view_footer();
2025 * View a page rendered by a plugin.
2027 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2031 protected function view_plugin_page() {
2036 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2037 $plugintype = required_param('plugin', PARAM_TEXT);
2038 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2040 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2042 print_error('invalidformdata', '');
2046 $o .= $plugin->view_page($pluginaction);
2053 * This is used for team assignments to get the group for the specified user.
2054 * If the user is a member of multiple or no groups this will return false
2056 * @param int $userid The id of the user whose submission we want
2057 * @return mixed The group or false
2059 public function get_submission_group($userid) {
2060 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2061 $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2062 if (count($groups) != 1) {
2065 return array_pop($groups);
2070 * Display the submission that is used by a plugin.
2072 * Uses url parameters 'sid', 'gid' and 'plugin'.
2074 * @param string $pluginsubtype
2077 protected function view_plugin_content($pluginsubtype) {
2082 $submissionid = optional_param('sid', 0, PARAM_INT);
2083 $gradeid = optional_param('gid', 0, PARAM_INT);
2084 $plugintype = required_param('plugin', PARAM_TEXT);
2086 if ($pluginsubtype == 'assignsubmission') {
2087 $plugin = $this->get_submission_plugin_by_type($plugintype);
2088 if ($submissionid <= 0) {
2089 throw new coding_exception('Submission id should not be 0');
2091 $item = $this->get_submission($submissionid);
2093 // Check permissions.
2094 if ($item->userid != $USER->id) {
2095 require_capability('mod/assign:grade', $this->context);
2097 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2098 $this->get_context(),
2099 $this->show_intro(),
2100 $this->get_course_module()->id,
2101 $plugin->get_name()));
2102 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2104 assign_submission_plugin_submission::FULL,
2105 $this->get_course_module()->id,
2106 $this->get_return_action(),
2107 $this->get_return_params()));
2109 $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2110 $this->add_to_log('view submission', $logmessage);
2112 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2113 if ($gradeid <= 0) {
2114 throw new coding_exception('Grade id should not be 0');
2116 $item = $this->get_grade($gradeid);
2117 // Check permissions.
2118 if ($item->userid != $USER->id) {
2119 require_capability('mod/assign:grade', $this->context);
2121 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2122 $this->get_context(),
2123 $this->show_intro(),
2124 $this->get_course_module()->id,
2125 $plugin->get_name()));
2126 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2128 assign_feedback_plugin_feedback::FULL,
2129 $this->get_course_module()->id,
2130 $this->get_return_action(),
2131 $this->get_return_params()));
2132 $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2133 $this->add_to_log('view feedback', $logmessage);
2136 $o .= $this->view_return_links();
2138 $o .= $this->view_footer();
2143 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2145 * @param stdClass $user - The user record
2146 * @param assign_plugin $plugin - The assignment plugin
2148 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2149 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2152 $groupid = groups_get_activity_group($this->get_course_module(), true);
2153 $groupname = groups_get_group_name($groupid).'-';
2156 if ($this->is_blind_marking()) {
2157 $prefix = $groupname . get_string('participant', 'assign');
2158 $prefix = str_replace('_', ' ', $prefix);
2159 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2161 $prefix = $groupname . fullname($user);
2162 $prefix = str_replace('_', ' ', $prefix);
2163 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2166 $subtype = $plugin->get_subtype();
2167 $type = $plugin->get_type();
2168 $prefix = $prefix . $subtype . '_' . $type . '_';
2170 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2176 * Render the content in editor that is often used by plugin.
2178 * @param string $filearea
2179 * @param int $submissionid
2180 * @param string $plugintype
2181 * @param string $editor
2182 * @param string $component
2185 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2190 $plugin = $this->get_submission_plugin_by_type($plugintype);
2192 $text = $plugin->get_editor_text($editor, $submissionid);
2193 $format = $plugin->get_editor_format($editor, $submissionid);
2195 $finaltext = file_rewrite_pluginfile_urls($text,
2197 $this->get_context()->id,
2201 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2202 $result .= format_text($finaltext, $format, $params);
2204 if ($CFG->enableportfolios) {
2205 require_once($CFG->libdir . '/portfoliolib.php');
2207 $button = new portfolio_add_button();
2208 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2209 'sid' => $submissionid,
2210 'plugin' => $plugintype,
2211 'editor' => $editor,
2213 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2214 $fs = get_file_storage();
2216 if ($files = $fs->get_area_files($this->context->id,
2222 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2224 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2226 $result .= $button->to_html();
2232 * Display a continue page.
2236 protected function view_savegrading_result($message) {
2238 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2239 $this->get_context(),
2240 $this->show_intro(),
2241 $this->get_course_module()->id,
2242 get_string('savegradingresult', 'assign')));
2243 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2245 $this->get_course_module()->id);
2246 $o .= $this->get_renderer()->render($gradingresult);
2247 $o .= $this->view_footer();
2251 * Display a grading error.
2253 * @param string $message - The description of the result
2256 protected function view_quickgrading_result($message) {
2258 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2259 $this->get_context(),
2260 $this->show_intro(),
2261 $this->get_course_module()->id,
2262 get_string('quickgradingresult', 'assign')));
2263 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2265 $this->get_course_module()->id);
2266 $o .= $this->get_renderer()->render($gradingresult);
2267 $o .= $this->view_footer();
2272 * Display the page footer.
2276 protected function view_footer() {
2277 return $this->get_renderer()->render_footer();
2281 * Does this user have grade permission for this assignment?
2285 protected function can_grade() {
2286 // Permissions check.
2287 if (!has_capability('mod/assign:grade', $this->context)) {
2295 * Download a zip file of all assignment submissions.
2297 * @return string - If an error occurs, this will contain the error page.
2299 protected function download_submissions() {
2302 // More efficient to load this here.
2303 require_once($CFG->libdir.'/filelib.php');
2305 require_capability('mod/assign:grade', $this->context);
2307 // Load all users with submit.
2308 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2309 $this->show_only_active_users());
2311 // Build a list of files to zip.
2312 $filesforzipping = array();
2313 $fs = get_file_storage();
2315 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2320 $groupid = groups_get_activity_group($this->get_course_module(), true);
2321 $groupname = groups_get_group_name($groupid).'-';
2324 // Construct the zip file name.
2325 $filename = clean_filename($this->get_course()->shortname . '-' .
2326 $this->get_instance()->name . '-' .
2327 $groupname.$this->get_course_module()->id . '.zip');
2329 // Get all the files for each student.
2330 foreach ($students as $student) {
2331 $userid = $student->id;
2333 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2334 // Get the plugins to add their own files to the zip.
2336 $submissiongroup = false;
2338 if ($this->get_instance()->teamsubmission) {
2339 $submission = $this->get_group_submission($userid, 0, false);
2340 $submissiongroup = $this->get_submission_group($userid);
2341 if ($submissiongroup) {
2342 $groupname = $submissiongroup->name . '-';
2344 $groupname = get_string('defaultteam', 'assign') . '-';
2347 $submission = $this->get_user_submission($userid, false);
2350 if ($this->is_blind_marking()) {
2351 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2352 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2354 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2355 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2359 foreach ($this->submissionplugins as $plugin) {
2360 if ($plugin->is_enabled() && $plugin->is_visible()) {
2361 $pluginfiles = $plugin->get_files($submission, $student);
2362 foreach ($pluginfiles as $zipfilename => $file) {
2363 $subtype = $plugin->get_subtype();
2364 $type = $plugin->get_type();
2365 $prefixedfilename = clean_filename($prefix .
2371 $filesforzipping[$prefixedfilename] = $file;
2379 if (count($filesforzipping) == 0) {
2380 $header = new assign_header($this->get_instance(),
2381 $this->get_context(),
2383 $this->get_course_module()->id,
2384 get_string('downloadall', 'assign'));
2385 $result .= $this->get_renderer()->render($header);
2386 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2387 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2388 'action'=>'grading'));
2389 $result .= $this->get_renderer()->continue_button($url);
2390 $result .= $this->view_footer();
2391 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2392 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2393 // Send file and delete after sending.
2394 send_temp_file($zipfile, $filename);
2395 // We will not get here - send_temp_file calls exit.
2401 * Util function to add a message to the log.
2403 * @param string $action The current action
2404 * @param string $info A detailed description of the change. But no more than 255 characters.
2405 * @param string $url The url to the assign module instance.
2406 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2407 * retrieve the arguments to use them with the new event system (Event 2).
2408 * @return void|array
2410 public function add_to_log($action = '', $info = '', $url='', $return = false) {
2413 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2415 $fullurl .= '&' . $url;
2419 $this->get_course()->id,
2424 $this->get_course_module()->id,
2431 call_user_func_array('add_to_log', $args);
2435 * Lazy load the page renderer and expose the renderer to plugins.
2437 * @return assign_renderer
2439 public function get_renderer() {
2441 if ($this->output) {
2442 return $this->output;
2444 $this->output = $PAGE->get_renderer('mod_assign');
2445 return $this->output;
2449 * Load the submission object for a particular user, optionally creating it if required.
2451 * For team assignments there are 2 submissions - the student submission and the team submission
2452 * All files are associated with the team submission but the status of the students contribution is
2453 * recorded separately.
2455 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2456 * @param bool $create optional - defaults to false. If set to true a new submission object
2457 * will be created in the database.
2458 * @param int $attemptnumber - -1 means the latest attempt
2459 * @return stdClass The submission
2461 public function get_user_submission($userid, $create, $attemptnumber=-1) {
2465 $userid = $USER->id;
2467 // If the userid is not null then use userid.
2468 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2469 if ($attemptnumber >= 0) {
2470 $params['attemptnumber'] = $attemptnumber;
2473 // Only return the row with the highest attemptnumber.
2475 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2477 $submission = reset($submissions);
2484 $submission = new stdClass();
2485 $submission->assignment = $this->get_instance()->id;
2486 $submission->userid = $userid;
2487 $submission->timecreated = time();
2488 $submission->timemodified = $submission->timecreated;
2489 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2490 if ($attemptnumber >= 0) {
2491 $submission->attemptnumber = $attemptnumber;
2493 $submission->attemptnumber = 0;
2495 $sid = $DB->insert_record('assign_submission', $submission);
2496 $submission->id = $sid;
2503 * Load the submission object from it's id.
2505 * @param int $submissionid The id of the submission we want
2506 * @return stdClass The submission
2508 protected function get_submission($submissionid) {
2511 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2512 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2516 * This will retrieve a user flags object from the db optionally creating it if required.
2517 * The user flags was split from the user_grades table in 2.5.
2519 * @param int $userid The user we are getting the flags for.
2520 * @param bool $create If true the flags record will be created if it does not exist
2521 * @return stdClass The flags record
2523 public function get_user_flags($userid, $create) {
2526 // If the userid is not null then use userid.
2528 $userid = $USER->id;
2531 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2533 $flags = $DB->get_record('assign_user_flags', $params);
2539 $flags = new stdClass();
2540 $flags->assignment = $this->get_instance()->id;
2541 $flags->userid = $userid;
2543 $flags->extensionduedate = 0;
2544 $flags->workflowstate = '';
2545 $flags->allocatedmarker = 0;
2547 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2548 // This is because students only want to be notified about certain types of update (grades and feedback).
2551 $fid = $DB->insert_record('assign_user_flags', $flags);
2559 * This will retrieve a grade object from the db, optionally creating it if required.
2561 * @param int $userid The user we are grading
2562 * @param bool $create If true the grade will be created if it does not exist
2563 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2564 * @return stdClass The grade record
2566 public function get_user_grade($userid, $create, $attemptnumber=-1) {
2569 // If the userid is not null then use userid.
2571 $userid = $USER->id;
2574 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2575 if ($attemptnumber < 0) {
2576 // Make sure this grade matches the latest submission attempt.
2577 if ($this->get_instance()->teamsubmission) {
2578 $submission = $this->get_group_submission($userid, 0, false);
2580 $submission = $this->get_user_submission($userid, false);
2583 $attemptnumber = $submission->attemptnumber;
2587 if ($attemptnumber >= 0) {
2588 $params['attemptnumber'] = $attemptnumber;
2591 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2594 return reset($grades);
2597 $grade = new stdClass();
2598 $grade->assignment = $this->get_instance()->id;
2599 $grade->userid = $userid;
2600 $grade->timecreated = time();
2601 $grade->timemodified = $grade->timecreated;
2603 $grade->grader = $USER->id;
2604 if ($attemptnumber >= 0) {
2605 $grade->attemptnumber = $attemptnumber;
2608 $gid = $DB->insert_record('assign_grades', $grade);
2616 * This will retrieve a grade object from the db.
2618 * @param int $gradeid The id of the grade
2619 * @return stdClass The grade record
2621 protected function get_grade($gradeid) {
2624 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2625 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2629 * Print the grading page for a single user submission.
2631 * @param moodleform $mform
2634 protected function view_single_grade_page($mform) {
2638 $instance = $this->get_instance();
2640 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2642 // Need submit permission to submit an assignment.
2643 require_capability('mod/assign:grade', $this->context);
2645 $header = new assign_header($instance,
2646 $this->get_context(),
2648 $this->get_course_module()->id,
2649 get_string('grading', 'assign'));
2650 $o .= $this->get_renderer()->render($header);
2652 // If userid is passed - we are only grading a single student.
2653 $rownum = required_param('rownum', PARAM_INT);
2654 $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2655 $userid = optional_param('userid', 0, PARAM_INT);
2656 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2658 $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2660 if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2661 $useridlist = $this->get_grading_userid_list();
2663 $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2666 $useridlist = array($userid);
2669 if ($rownum < 0 || $rownum > count($useridlist)) {
2670 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2674 $userid = $useridlist[$rownum];
2675 if ($rownum == count($useridlist) - 1) {
2678 $user = $DB->get_record('user', array('id' => $userid));
2680 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2681 $usersummary = new assign_user_summary($user,
2682 $this->get_course()->id,
2684 $this->is_blind_marking(),
2685 $this->get_uniqueid_for_user($user->id),
2686 get_extra_user_fields($this->get_context()),
2687 !$this->is_active_user($userid));
2688 $o .= $this->get_renderer()->render($usersummary);
2690 $submission = $this->get_user_submission($userid, false, $attemptnumber);
2691 $submissiongroup = null;
2692 $teamsubmission = null;
2693 $notsubmitted = array();
2694 if ($instance->teamsubmission) {
2695 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2696 $submissiongroup = $this->get_submission_group($userid);
2698 if ($submissiongroup) {
2699 $groupid = $submissiongroup->id;
2701 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2705 // Get the requested grade.
2706 $grade = $this->get_user_grade($userid, false, $attemptnumber);
2707 $flags = $this->get_user_flags($userid, false);
2708 if ($this->can_view_submission($userid)) {
2709 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2710 $extensionduedate = null;
2712 $extensionduedate = $flags->extensionduedate;
2714 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2716 if ($teamsubmission) {
2717 $showsubmit = $showedit &&
2719 ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2721 $showsubmit = $showedit &&
2723 ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2725 if (!$this->get_instance()->submissiondrafts) {
2726 $showsubmit = false;
2728 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2730 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2731 $instance->alwaysshowdescription,
2733 $instance->teamsubmission,
2737 $this->is_any_submission_plugin_enabled(),
2739 $this->is_graded($userid),
2741 $instance->cutoffdate,
2742 $this->get_submission_plugins(),
2743 $this->get_return_action(),
2744 $this->get_return_params(),
2745 $this->get_course_module()->id,
2746 $this->get_course()->id,
2747 assign_submission_status::GRADER_VIEW,
2752 $this->get_context(),
2753 $this->is_blind_marking(),
2755 $instance->attemptreopenmethod,
2756 $instance->maxattempts);
2757 $o .= $this->get_renderer()->render($submissionstatus);
2761 $data = new stdClass();
2762 if ($grade->grade !== null && $grade->grade >= 0) {
2763 $data->grade = format_float($grade->grade, 2);
2765 if (!empty($flags->workflowstate)) {
2766 $data->workflowstate = $flags->workflowstate;
2768 if (!empty($flags->allocatedmarker)) {
2769 $data->allocatedmarker = $flags->allocatedmarker;
2772 $data = new stdClass();
2775 // Warning if required.
2776 $allsubmissions = $this->get_all_submissions($userid);
2778 if ($attemptnumber != -1) {
2779 $params = array('attemptnumber'=>$attemptnumber + 1,
2780 'totalattempts'=>count($allsubmissions));
2781 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2782 $o .= $this->get_renderer()->notification($message);
2785 // Now show the grading form.
2787 $pagination = array('rownum'=>$rownum,
2788 'useridlistid'=>$useridlistid,
2790 'userid'=>optional_param('userid', 0, PARAM_INT),
2791 'attemptnumber'=>$attemptnumber);
2792 $formparams = array($this, $data, $pagination);
2793 $mform = new mod_assign_grade_form(null,
2797 array('class'=>'gradeform'));
2799 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2800 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2802 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2803 $allgrades = $this->get_all_grades($userid);
2804 $history = new assign_attempt_history($allsubmissions,
2806 $this->get_submission_plugins(),
2807 $this->get_feedback_plugins(),
2808 $this->get_course_module()->id,
2809 $this->get_return_action(),
2810 $this->get_return_params(),
2813 $o .= $this->get_renderer()->render($history);
2816 $msg = get_string('viewgradingformforstudent',
2818 array('id'=>$user->id, 'fullname'=>fullname($user)));
2819 $this->add_to_log('view grading form', $msg);
2821 $o .= $this->view_footer();
2826 * Show a confirmation page to make sure they want to release student identities.
2830 protected function view_reveal_identities_confirm() {
2833 require_capability('mod/assign:revealidentities', $this->get_context());
2836 $header = new assign_header($this->get_instance(),
2837 $this->get_context(),
2839 $this->get_course_module()->id);
2840 $o .= $this->get_renderer()->render($header);
2842 $urlparams = array('id'=>$this->get_course_module()->id,
2843 'action'=>'revealidentitiesconfirm',
2844 'sesskey'=>sesskey());
2845 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2847 $urlparams = array('id'=>$this->get_course_module()->id,
2848 'action'=>'grading');
2849 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2851 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2854 $o .= $this->view_footer();
2855 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2860 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2864 protected function view_return_links() {
2865 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2866 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2869 $returnparams = str_replace('&', '&', $returnparams);
2870 parse_str($returnparams, $params);
2871 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2872 $params = array_merge($newparams, $params);
2874 $url = new moodle_url('/mod/assign/view.php', $params);
2875 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2879 * View the grading table of all submissions for this assignment.
2883 protected function view_grading_table() {
2886 // Include grading options form.
2887 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2888 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2889 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2891 $cmid = $this->get_course_module()->id;
2894 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2895 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2896 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2897 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2899 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2900 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2901 $links[$downloadurl] = get_string('downloadall', 'assign');
2903 if ($this->is_blind_marking() &&
2904 has_capability('mod/assign:revealidentities', $this->get_context())) {
2905 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2906 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2908 foreach ($this->get_feedback_plugins() as $plugin) {
2909 if ($plugin->is_enabled() && $plugin->is_visible()) {
2910 foreach ($plugin->get_grading_actions() as $action => $description) {
2911 $url = '/mod/assign/view.php' .
2913 '&plugin=' . $plugin->get_type() .
2914 '&pluginsubtype=assignfeedback' .
2915 '&action=viewpluginpage&pluginaction=' . $action;
2916 $links[$url] = $description;
2921 $gradingactions = new url_select($links);
2922 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2924 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2926 $perpage = get_user_preferences('assign_perpage', 10);
2927 $filter = get_user_preferences('assign_filter', '');
2928 $markerfilter = get_user_preferences('assign_markerfilter', '');
2929 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2930 $controller = $gradingmanager->get_active_controller();
2931 $showquickgrading = empty($controller);
2932 $quickgrading = get_user_preferences('assign_quickgrading', false);
2933 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
2935 $markingallocation = $this->get_instance()->markingallocation &&
2936 has_capability('mod/assign:manageallocations', $this->context);
2937 // Get markers to use in drop lists.
2938 $markingallocationoptions = array();
2939 if ($markingallocation) {
2940 $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2941 $markingallocationoptions[''] = get_string('filternone', 'assign');
2942 foreach ($markers as $marker) {
2943 $markingallocationoptions[$marker->id] = fullname($marker);
2947 $markingworkflow = $this->get_instance()->markingworkflow;
2948 // Get marking states to show in form.
2949 $markingworkflowoptions = array();
2950 if ($markingworkflow) {
2951 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
2952 $markingworkflowoptions[''] = get_string('filternone', 'assign');
2953 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
2954 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2957 // Print options for changing the filter and changing the number of results per page.
2958 $gradingoptionsformparams = array('cm'=>$cmid,
2959 'contextid'=>$this->context->id,
2960 'userid'=>$USER->id,
2961 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2962 'showquickgrading'=>$showquickgrading,
2963 'quickgrading'=>$quickgrading,
2964 'markingworkflowopt'=>$markingworkflowoptions,
2965 'markingallocationopt'=>$markingallocationoptions,
2966 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
2967 'showonlyactiveenrol'=>$this->show_only_active_users());
2969 $classoptions = array('class'=>'gradingoptionsform');
2970 $gradingoptionsform = new mod_assign_grading_options_form(null,
2971 $gradingoptionsformparams,
2976 $batchformparams = array('cm'=>$cmid,
2977 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2978 'duedate'=>$this->get_instance()->duedate,
2979 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
2980 'feedbackplugins'=>$this->get_feedback_plugins(),
2981 'context'=>$this->get_context(),
2982 'markingworkflow'=>$markingworkflow,
2983 'markingallocation'=>$markingallocation);
2984 $classoptions = array('class'=>'gradingbatchoperationsform');
2986 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2992 $gradingoptionsdata = new stdClass();
2993 $gradingoptionsdata->perpage = $perpage;
2994 $gradingoptionsdata->filter = $filter;
2995 $gradingoptionsdata->markerfilter = $markerfilter;
2996 $gradingoptionsdata->workflowfilter = $workflowfilter;
2997 $gradingoptionsform->set_data($gradingoptionsdata);
2999 $actionformtext = $this->get_renderer()->render($gradingactions);
3000 $header = new assign_header($this->get_instance(),
3001 $this->get_context(),
3003 $this->get_course_module()->id,
3004 get_string('grading', 'assign'),
3006 $o .= $this->get_renderer()->render($header);
3008 $currenturl = $CFG->wwwroot .
3009 '/mod/assign/view.php?id=' .
3010 $this->get_course_module()->id .
3013 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3015 // Plagiarism update status apearring in the grading book.
3016 if (!empty($CFG->enableplagiarism)) {
3017 require_once($CFG->libdir . '/plagiarismlib.php');
3018 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3021 // Load and print the table of submissions.
3022 if ($showquickgrading && $quickgrading) {
3023 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3024 $table = $this->get_renderer()->render($gradingtable);
3025 $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
3026 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3028 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3030 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3031 $o .= $this->get_renderer()->render($gradingtable);
3034 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3035 $users = array_keys($this->list_participants($currentgroup, true));
3036 if (count($users) != 0) {
3037 // If no enrolled user in a course then don't display the batch operations feature.
3038 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3039 $o .= $this->get_renderer()->render($assignform);
3041 $assignform = new assign_form('gradingoptionsform',
3042 $gradingoptionsform,
3043 'M.mod_assign.init_grading_options');
3044 $o .= $this->get_renderer()->render($assignform);
3049 * View entire grading page.
3053 protected function view_grading_page() {
3057 // Need submit permission to submit an assignment.
3058 require_capability('mod/assign:grade', $this->context);
3059 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3061 // Only load this if it is.
3063 $o .= $this->view_grading_table();
3065 $o .= $this->view_footer();
3067 $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3068 $this->add_to_log('view submission grading table', $logmessage);
3073 * Capture the output of the plagiarism plugins disclosures and return it as a string.
3077 protected function plagiarism_print_disclosure() {
3081 if (!empty($CFG->enableplagiarism)) {
3082 require_once($CFG->libdir . '/plagiarismlib.php');
3084 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3091 * Message for students when assignment submissions have been closed.
3095 protected function view_student_error_message() {
3099 // Need submit permission to submit an assignment.
3100 require_capability('mod/assign:submit', $this->context);
3102 $header = new assign_header($this->get_instance(),
3103 $this->get_context(),
3104 $this->show_intro(),
3105 $this->get_course_module()->id,
3106 get_string('editsubmission', 'assign'));
3107 $o .= $this->get_renderer()->render($header);
3109 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3111 $o .= $this->view_footer();
3118 * View edit submissions page.
3120 * @param moodleform $mform
3121 * @param array $notices A list of notices to display at the top of the
3122 * edit submission form (e.g. from plugins).
3123 * @return string The page output.
3125 protected function view_edit_submission_page($mform, $notices) {
3129 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3130 // Need submit permission to submit an assignment.
3131 require_capability('mod/assign:submit', $this->context);
3133 if (!$this->submissions_open()) {
3134 return $this->view_student_error_message();
3136 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3137 $this->get_context(),
3138 $this->show_intro(),
3139 $this->get_course_module()->id,
3140 get_string('editsubmission', 'assign')));
3141 $o .= $this->plagiarism_print_disclosure();
3142 $data = new stdClass();
3145 $mform = new mod_assign_submission_form(null, array($this, $data));
3148 foreach ($notices as $notice) {
3149 $o .= $this->get_renderer()->notification($notice);
3152 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3154 $o .= $this->view_footer();
3155 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3161 * See if this assignment has a grade yet.
3163 * @param int $userid
3166 protected function is_graded($userid) {
3167 $grade = $this->get_user_grade($userid, false);
3169 return ($grade->grade !== null && $grade->grade >= 0);
3175 * Perform an access check to see if the current $USER can view this group submission.
3177 * @param int $groupid
3180 public function can_view_group_submission($groupid) {
3183 if (!is_enrolled($this->get_course_context(), $USER->id)) {
3186 if (has_capability('mod/assign:grade', $this->context)) {
3189 $members = $this->get_submission_group_members($groupid, true);
3190 foreach ($members as $member) {
3191 if ($member->id == $USER->id) {
3199 * Perform an access check to see if the current $USER can view this users submission.
3201 * @param int $userid
3204 public function can_view_submission($userid) {
3207 if (is_siteadmin()) {
3210 if (!is_enrolled($this->get_course_context(), $userid)) {
3213 if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3216 if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
3219 if (has_capability('mod/assign:grade', $this->context)) {
3226 * Allows the plugin to show a batch grading operation page.
3230 protected function view_plugin_grading_batch_operation($mform) {
3231 require_capability('mod/assign:grade', $this->context);
3232 $prefix = 'plugingradingbatchoperation_';
3234 if ($data = $mform->get_data()) {
3235 $tail = substr($data->operation, strlen($prefix));
3236 list($plugintype, $action) = explode('_', $tail, 2);
3238 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3240 $users = $data->selectedusers;
3241 $userlist = explode(',', $users);
3242 echo $plugin->grading_batch_operation($action, $userlist);
3246 print_error('invalidformdata', '');
3250 * Ask the user to confirm they want to perform this batch operation
3252 * @param moodleform $mform Set to a grading batch operations form
3253 * @return string - the page to view after processing these actions
3255 protected function process_grading_batch_operation(& $mform) {
3257 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3260 $markingallocation = $this->get_instance()->markingallocation &&
3261 has_capability('mod/assign:manageallocations', $this->context);
3263 $batchformparams = array('cm'=>$this->get_course_module()->id,
3264 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3265 'duedate'=>$this->get_instance()->duedate,