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;
126 * Constructor for the base assign class.
128 * @param mixed $coursemodulecontext context|null the course module context
129 * (or the course context if the coursemodule has not been
131 * @param mixed $coursemodule the current course module if it was already loaded,
132 * otherwise this class will load one from the context as required.
133 * @param mixed $course the current course if it was already loaded,
134 * otherwise this class will load one from the context as required.
136 public function __construct($coursemodulecontext, $coursemodule, $course) {
139 $this->context = $coursemodulecontext;
140 $this->coursemodule = $coursemodule;
141 $this->course = $course;
143 // Temporary cache only lives for a single request - used to reduce db lookups.
144 $this->cache = array();
146 $this->submissionplugins = $this->load_plugins('assignsubmission');
147 $this->feedbackplugins = $this->load_plugins('assignfeedback');
151 * Set the action and parameters that can be used to return to the current page.
153 * @param string $action The action for the current page
154 * @param array $params An array of name value pairs which form the parameters
155 * to return to the current page.
158 public function register_return_link($action, $params) {
160 $params['action'] = $action;
161 $currenturl = $PAGE->url;
163 $currenturl->params($params);
164 $PAGE->set_url($currenturl);
168 * Return an action that can be used to get back to the current page.
170 * @return string action
172 public function get_return_action() {
175 $params = $PAGE->url->params();
177 if (!empty($params['action'])) {
178 return $params['action'];
184 * Based on the current assignment settings should we display the intro.
186 * @return bool showintro
188 protected function show_intro() {
189 if ($this->get_instance()->alwaysshowdescription ||
190 time() > $this->get_instance()->allowsubmissionsfromdate) {
197 * Return a list of parameters that can be used to get back to the current page.
199 * @return array params
201 public function get_return_params() {
204 $params = $PAGE->url->params();
205 unset($params['id']);
206 unset($params['action']);
211 * Set the submitted form data.
213 * @param stdClass $data The form data (instance)
215 public function set_instance(stdClass $data) {
216 $this->instance = $data;
222 * @param context $context The new context
224 public function set_context(context $context) {
225 $this->context = $context;
229 * Set the course data.
231 * @param stdClass $course The course data
233 public function set_course(stdClass $course) {
234 $this->course = $course;
238 * Get list of feedback plugins installed.
242 public function get_feedback_plugins() {
243 return $this->feedbackplugins;
247 * Get list of submission plugins installed.
251 public function get_submission_plugins() {
252 return $this->submissionplugins;
256 * Is blind marking enabled and reveal identities not set yet?
260 public function is_blind_marking() {
261 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
265 * Does an assignment have submission(s) or grade(s) already?
269 public function has_submissions_or_grades() {
270 $allgrades = $this->count_grades();
271 $allsubmissions = $this->count_submissions();
272 if (($allgrades == 0) && ($allsubmissions == 0)) {
279 * Get a specific submission plugin by its type.
281 * @param string $subtype assignsubmission | assignfeedback
282 * @param string $type
283 * @return mixed assign_plugin|null
285 public function get_plugin_by_type($subtype, $type) {
286 $shortsubtype = substr($subtype, strlen('assign'));
287 $name = $shortsubtype . 'plugins';
288 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
291 $pluginlist = $this->$name;
292 foreach ($pluginlist as $plugin) {
293 if ($plugin->get_type() == $type) {
301 * Get a feedback plugin by type.
303 * @param string $type - The type of plugin e.g comments
304 * @return mixed assign_feedback_plugin|null
306 public function get_feedback_plugin_by_type($type) {
307 return $this->get_plugin_by_type('assignfeedback', $type);
311 * Get a submission plugin by type.
313 * @param string $type - The type of plugin e.g comments
314 * @return mixed assign_submission_plugin|null
316 public function get_submission_plugin_by_type($type) {
317 return $this->get_plugin_by_type('assignsubmission', $type);
321 * Load the plugins from the sub folders under subtype.
323 * @param string $subtype - either submission or feedback
324 * @return array - The sorted list of plugins
326 protected function load_plugins($subtype) {
330 $names = get_plugin_list($subtype);
332 foreach ($names as $name => $path) {
333 if (file_exists($path . '/locallib.php')) {
334 require_once($path . '/locallib.php');
336 $shortsubtype = substr($subtype, strlen('assign'));
337 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
339 $plugin = new $pluginclass($this, $name);
341 if ($plugin instanceof assign_plugin) {
342 $idx = $plugin->get_sort_order();
343 while (array_key_exists($idx, $result)) {
346 $result[$idx] = $plugin;
355 * Display the assignment, used by view.php
357 * The assignment is displayed differently depending on your role,
358 * the settings for the assignment and the status of the assignment.
360 * @param string $action The current action if any.
361 * @return string - The page output.
363 public function view($action='') {
368 $nextpageparams = array();
370 if (!empty($this->get_course_module()->id)) {
371 $nextpageparams['id'] = $this->get_course_module()->id;
374 // Handle form submissions first.
375 if ($action == 'savesubmission') {
376 $action = 'editsubmission';
377 if ($this->process_save_submission($mform, $notices)) {
378 $action = 'redirect';
379 $nextpageparams['action'] = 'view';
381 } else if ($action == 'editprevioussubmission') {
382 $action = 'editsubmission';
383 if ($this->process_copy_previous_attempt($notices)) {
384 $action = 'redirect';
385 $nextpageparams['action'] = 'editsubmission';
387 } else if ($action == 'lock') {
388 $this->process_lock();
389 $action = 'redirect';
390 $nextpageparams['action'] = 'grading';
391 } else if ($action == 'addattempt') {
392 $this->process_add_attempt(required_param('userid', PARAM_INT));
393 $action = 'redirect';
394 $nextpageparams['action'] = 'grading';
395 } else if ($action == 'reverttodraft') {
396 $this->process_revert_to_draft();
397 $action = 'redirect';
398 $nextpageparams['action'] = 'grading';
399 } else if ($action == 'unlock') {
400 $this->process_unlock();
401 $action = 'redirect';
402 $nextpageparams['action'] = 'grading';
403 } else if ($action == 'setbatchmarkingworkflowstate') {
404 $this->process_set_batch_marking_workflow_state();
405 $action = 'redirect';
406 $nextpageparams['action'] = 'grading';
407 } else if ($action == 'setbatchmarkingallocation') {
408 $this->process_set_batch_marking_allocation();
409 $action = 'redirect';
410 $nextpageparams['action'] = 'grading';
411 } else if ($action == 'confirmsubmit') {
413 if ($this->process_submit_for_grading($mform)) {
414 $action = 'redirect';
415 $nextpageparams['action'] = 'view';
417 } else if ($action == 'gradingbatchoperation') {
418 $action = $this->process_grading_batch_operation($mform);
419 if ($action == 'grading') {
420 $action = 'redirect';
421 $nextpageparams['action'] = 'grading';
423 } else if ($action == 'submitgrade') {
424 if (optional_param('saveandshownext', null, PARAM_RAW)) {
425 // Save and show next.
427 if ($this->process_save_grade($mform)) {
428 $action = 'redirect';
429 $nextpageparams['action'] = 'grade';
430 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
431 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
433 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
434 $action = 'redirect';
435 $nextpageparams['action'] = 'grade';
436 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
437 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
438 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
439 $action = 'redirect';
440 $nextpageparams['action'] = 'grade';
441 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
442 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
443 } else if (optional_param('savegrade', null, PARAM_RAW)) {
444 // Save changes button.
446 if ($this->process_save_grade($mform)) {
447 $message = get_string('gradingchangessaved', 'assign');
448 $action = 'savegradingresult';
452 $action = 'redirect';
453 $nextpageparams['action'] = 'grading';
455 } else if ($action == 'quickgrade') {
456 $message = $this->process_save_quick_grades();
457 $action = 'quickgradingresult';
458 } else if ($action == 'saveoptions') {
459 $this->process_save_grading_options();
460 $action = 'redirect';
461 $nextpageparams['action'] = 'grading';
462 } else if ($action == 'saveextension') {
463 $action = 'grantextension';
464 if ($this->process_save_extension($mform)) {
465 $action = 'redirect';
466 $nextpageparams['action'] = 'grading';
468 } else if ($action == 'revealidentitiesconfirm') {
469 $this->process_reveal_identities();
470 $action = 'redirect';
471 $nextpageparams['action'] = 'grading';
474 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
475 'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
476 $this->register_return_link($action, $returnparams);
478 // Now show the right view page.
479 if ($action == 'redirect') {
480 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
481 redirect($nextpageurl);
483 } else if ($action == 'savegradingresult') {
484 $o .= $this->view_savegrading_result($message);
485 } else if ($action == 'quickgradingresult') {
487 $o .= $this->view_quickgrading_result($message);
488 } else if ($action == 'grade') {
489 $o .= $this->view_single_grade_page($mform);
490 } else if ($action == 'viewpluginassignfeedback') {
491 $o .= $this->view_plugin_content('assignfeedback');
492 } else if ($action == 'viewpluginassignsubmission') {
493 $o .= $this->view_plugin_content('assignsubmission');
494 } else if ($action == 'editsubmission') {
495 $o .= $this->view_edit_submission_page($mform, $notices);
496 } else if ($action == 'grading') {
497 $o .= $this->view_grading_page();
498 } else if ($action == 'downloadall') {
499 $o .= $this->download_submissions();
500 } else if ($action == 'submit') {
501 $o .= $this->check_submit_for_grading($mform);
502 } else if ($action == 'grantextension') {
503 $o .= $this->view_grant_extension($mform);
504 } else if ($action == 'revealidentities') {
505 $o .= $this->view_reveal_identities_confirm($mform);
506 } else if ($action == 'plugingradingbatchoperation') {
507 $o .= $this->view_plugin_grading_batch_operation($mform);
508 } else if ($action == 'viewpluginpage') {
509 $o .= $this->view_plugin_page();
510 } else if ($action == 'viewcourseindex') {
511 $o .= $this->view_course_index();
512 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
513 $o .= $this->view_batch_set_workflow_state($mform);
514 } else if ($action == 'viewbatchmarkingallocation') {
515 $o .= $this->view_batch_markingallocation($mform);
517 $o .= $this->view_submission_page();
524 * Add this instance to the database.
526 * @param stdClass $formdata The data submitted from the form
527 * @param bool $callplugins This is used to skip the plugin code
528 * when upgrading an old assignment to a new one (the plugins get called manually)
529 * @return mixed false if an error occurs or the int id of the new instance
531 public function add_instance(stdClass $formdata, $callplugins) {
536 // Add the database record.
537 $update = new stdClass();
538 $update->name = $formdata->name;
539 $update->timemodified = time();
540 $update->timecreated = time();
541 $update->course = $formdata->course;
542 $update->courseid = $formdata->course;
543 $update->intro = $formdata->intro;
544 $update->introformat = $formdata->introformat;
545 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
546 $update->submissiondrafts = $formdata->submissiondrafts;
547 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
548 $update->sendnotifications = $formdata->sendnotifications;
549 $update->sendlatenotifications = $formdata->sendlatenotifications;
550 $update->duedate = $formdata->duedate;
551 $update->cutoffdate = $formdata->cutoffdate;
552 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
553 $update->grade = $formdata->grade;
554 $update->completionsubmit = !empty($formdata->completionsubmit);
555 $update->teamsubmission = $formdata->teamsubmission;
556 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
557 if (isset($formdata->teamsubmissiongroupingid)) {
558 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
560 $update->blindmarking = $formdata->blindmarking;
561 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
562 if (!empty($formdata->attemptreopenmethod)) {
563 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
565 if (!empty($formdata->maxattempts)) {
566 $update->maxattempts = $formdata->maxattempts;
568 $update->markingworkflow = $formdata->markingworkflow;
569 $update->markingallocation = $formdata->markingallocation;
571 $returnid = $DB->insert_record('assign', $update);
572 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
573 // Cache the course record.
574 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
577 // Call save_settings hook for submission plugins.
578 foreach ($this->submissionplugins as $plugin) {
579 if (!$this->update_plugin_instance($plugin, $formdata)) {
580 print_error($plugin->get_error());
584 foreach ($this->feedbackplugins as $plugin) {
585 if (!$this->update_plugin_instance($plugin, $formdata)) {
586 print_error($plugin->get_error());
591 // In the case of upgrades the coursemodule has not been set,
592 // so we need to wait before calling these two.
593 $this->update_calendar($formdata->coursemodule);
594 $this->update_gradebook(false, $formdata->coursemodule);
598 $update = new stdClass();
599 $update->id = $this->get_instance()->id;
600 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
601 $DB->update_record('assign', $update);
607 * Delete all grades from the gradebook for this assignment.
611 protected function delete_grades() {
614 $result = grade_update('mod/assign',
615 $this->get_course()->id,
618 $this->get_instance()->id,
621 array('deleted'=>1));
622 return $result == GRADE_UPDATE_OK;
626 * Delete this instance from the database.
628 * @return bool false if an error occurs
630 public function delete_instance() {
634 foreach ($this->submissionplugins as $plugin) {
635 if (!$plugin->delete_instance()) {
636 print_error($plugin->get_error());
640 foreach ($this->feedbackplugins as $plugin) {
641 if (!$plugin->delete_instance()) {
642 print_error($plugin->get_error());
647 // Delete files associated with this assignment.
648 $fs = get_file_storage();
649 if (! $fs->delete_area_files($this->context->id) ) {
653 // Delete_records will throw an exception if it fails - so no need for error checking here.
654 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
655 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
656 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
658 // Delete items from the gradebook.
659 if (! $this->delete_grades()) {
663 // Delete the instance.
664 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
670 * Actual implementation of the reset course functionality, delete all the
671 * assignment submissions for course $data->courseid.
673 * @param $data the data submitted from the reset course.
674 * @return array status array
676 public function reset_userdata($data) {
679 $componentstr = get_string('modulenameplural', 'assign');
682 $fs = get_file_storage();
683 if (!empty($data->reset_assign_submissions)) {
684 // Delete files associated with this assignment.
685 foreach ($this->submissionplugins as $plugin) {
686 $fileareas = array();
687 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
688 $fileareas = $plugin->get_file_areas();
689 foreach ($fileareas as $filearea) {
690 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
693 if (!$plugin->delete_instance()) {
694 $status[] = array('component'=>$componentstr,
695 'item'=>get_string('deleteallsubmissions', 'assign'),
696 'error'=>$plugin->get_error());
700 foreach ($this->feedbackplugins as $plugin) {
701 $fileareas = array();
702 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
703 $fileareas = $plugin->get_file_areas();
704 foreach ($fileareas as $filearea) {
705 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
708 if (!$plugin->delete_instance()) {
709 $status[] = array('component'=>$componentstr,
710 'item'=>get_string('deleteallsubmissions', 'assign'),
711 'error'=>$plugin->get_error());
715 $assignssql = 'SELECT a.id
717 WHERE a.course=:course';
718 $params = array('course'=>$data->courseid);
720 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
722 $status[] = array('component'=>$componentstr,
723 'item'=>get_string('deleteallsubmissions', 'assign'),
726 if (!empty($data->reset_gradebook_grades)) {
727 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
728 // Remove all grades from gradebook.
729 require_once($CFG->dirroot.'/mod/assign/lib.php');
730 assign_reset_gradebook($data->courseid);
733 // Updating dates - shift may be negative too.
734 if ($data->timeshift) {
735 shift_course_mod_dates('assign',
736 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
739 $status[] = array('component'=>$componentstr,
740 'item'=>get_string('datechanged'),
748 * Update the settings for a single plugin.
750 * @param assign_plugin $plugin The plugin to update
751 * @param stdClass $formdata The form data
752 * @return bool false if an error occurs
754 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
755 if ($plugin->is_visible()) {
756 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
757 if (!empty($formdata->$enabledname)) {
759 if (!$plugin->save_settings($formdata)) {
760 print_error($plugin->get_error());
771 * Update the gradebook information for this assignment.
773 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
774 * @param int $coursemoduleid This is required because it might not exist in the database yet
777 public function update_gradebook($reset, $coursemoduleid) {
780 require_once($CFG->dirroot.'/mod/assign/lib.php');
781 $assign = clone $this->get_instance();
782 $assign->cmidnumber = $coursemoduleid;
788 return assign_grade_item_update($assign, $param);
792 * Load and cache the admin config for this module.
794 * @return stdClass the plugin config
796 public function get_admin_config() {
797 if ($this->adminconfig) {
798 return $this->adminconfig;
800 $this->adminconfig = get_config('assign');
801 return $this->adminconfig;
805 * Update the calendar entries for this assignment.
807 * @param int $coursemoduleid - Required to pass this in because it might
808 * not exist in the database yet.
811 public function update_calendar($coursemoduleid) {
813 require_once($CFG->dirroot.'/calendar/lib.php');
815 // Special case for add_instance as the coursemodule has not been set yet.
816 $instance = $this->get_instance();
818 if ($instance->duedate) {
819 $event = new stdClass();
821 $params = array('modulename'=>'assign', 'instance'=>$instance->id);
822 $event->id = $DB->get_field('event',
827 $event->name = $instance->name;
828 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
829 $event->timestart = $instance->duedate;
831 $calendarevent = calendar_event::load($event->id);
832 $calendarevent->update($event);
834 $event = new stdClass();
835 $event->name = $instance->name;
836 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
837 $event->courseid = $instance->course;
840 $event->modulename = 'assign';
841 $event->instance = $instance->id;
842 $event->eventtype = 'due';
843 $event->timestart = $instance->duedate;
844 $event->timeduration = 0;
846 calendar_event::create($event);
849 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
855 * Update this instance in the database.
857 * @param stdClass $formdata - the data submitted from the form
858 * @return bool false if an error occurs
860 public function update_instance($formdata) {
863 $update = new stdClass();
864 $update->id = $formdata->instance;
865 $update->name = $formdata->name;
866 $update->timemodified = time();
867 $update->course = $formdata->course;
868 $update->intro = $formdata->intro;
869 $update->introformat = $formdata->introformat;
870 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
871 $update->submissiondrafts = $formdata->submissiondrafts;
872 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
873 $update->sendnotifications = $formdata->sendnotifications;
874 $update->sendlatenotifications = $formdata->sendlatenotifications;
875 $update->duedate = $formdata->duedate;
876 $update->cutoffdate = $formdata->cutoffdate;
877 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
878 $update->grade = $formdata->grade;
879 if (!empty($formdata->completionunlocked)) {
880 $update->completionsubmit = !empty($formdata->completionsubmit);
882 $update->teamsubmission = $formdata->teamsubmission;
883 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
884 if (isset($formdata->teamsubmissiongroupingid)) {
885 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
887 $update->blindmarking = $formdata->blindmarking;
888 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
889 if (!empty($formdata->attemptreopenmethod)) {
890 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
892 if (!empty($formdata->maxattempts)) {
893 $update->maxattempts = $formdata->maxattempts;
895 $update->markingworkflow = $formdata->markingworkflow;
896 $update->markingallocation = $formdata->markingallocation;
898 $result = $DB->update_record('assign', $update);
899 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
901 // Load the assignment so the plugins have access to it.
903 // Call save_settings hook for submission plugins.
904 foreach ($this->submissionplugins as $plugin) {
905 if (!$this->update_plugin_instance($plugin, $formdata)) {
906 print_error($plugin->get_error());
910 foreach ($this->feedbackplugins as $plugin) {
911 if (!$this->update_plugin_instance($plugin, $formdata)) {
912 print_error($plugin->get_error());
917 $this->update_calendar($this->get_course_module()->id);
918 $this->update_gradebook(false, $this->get_course_module()->id);
920 $update = new stdClass();
921 $update->id = $this->get_instance()->id;
922 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
923 $DB->update_record('assign', $update);
929 * Add elements in grading plugin form.
931 * @param mixed $grade stdClass|null
932 * @param MoodleQuickForm $mform
933 * @param stdClass $data
934 * @param int $userid - The userid we are grading
937 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
938 foreach ($this->feedbackplugins as $plugin) {
939 if ($plugin->is_enabled() && $plugin->is_visible()) {
940 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
941 $mform->setExpanded('header_' . $plugin->get_type());
942 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
943 $mform->removeElement('header_' . $plugin->get_type());
952 * Add one plugins settings to edit plugin form.
954 * @param assign_plugin $plugin The plugin to add the settings from
955 * @param MoodleQuickForm $mform The form to add the configuration settings to.
956 * This form is modified directly (not returned).
957 * @param array $pluginsenabled A list of form elements to be added to a group.
958 * The new element is added to this array by this function.
961 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
963 if ($plugin->is_visible()) {
965 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
966 $label = $plugin->get_name();
967 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
968 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
970 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
971 if ($plugin->get_config('enabled') !== false) {
972 $default = $plugin->is_enabled();
974 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
976 $plugin->get_settings($mform);
982 * Add settings to edit plugin form.
984 * @param MoodleQuickForm $mform The form to add the configuration settings to.
985 * This form is modified directly (not returned).
988 public function add_all_plugin_settings(MoodleQuickForm $mform) {
989 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
991 $submissionpluginsenabled = array();
992 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
993 foreach ($this->submissionplugins as $plugin) {
994 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
996 $group->setElements($submissionpluginsenabled);
998 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
999 $feedbackpluginsenabled = array();
1000 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1001 foreach ($this->feedbackplugins as $plugin) {
1002 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1004 $group->setElements($feedbackpluginsenabled);
1005 $mform->setExpanded('submissiontypes');
1009 * Allow each plugin an opportunity to update the defaultvalues
1010 * passed in to the settings form (needed to set up draft areas for
1011 * editor and filemanager elements)
1013 * @param array $defaultvalues
1015 public function plugin_data_preprocessing(&$defaultvalues) {
1016 foreach ($this->submissionplugins as $plugin) {
1017 if ($plugin->is_visible()) {
1018 $plugin->data_preprocessing($defaultvalues);
1021 foreach ($this->feedbackplugins as $plugin) {
1022 if ($plugin->is_visible()) {
1023 $plugin->data_preprocessing($defaultvalues);
1029 * Get the name of the current module.
1031 * @return string the module name (Assignment)
1033 protected function get_module_name() {
1034 if (isset(self::$modulename)) {
1035 return self::$modulename;
1037 self::$modulename = get_string('modulename', 'assign');
1038 return self::$modulename;
1042 * Get the plural name of the current module.
1044 * @return string the module name plural (Assignments)
1046 protected function get_module_name_plural() {
1047 if (isset(self::$modulenameplural)) {
1048 return self::$modulenameplural;
1050 self::$modulenameplural = get_string('modulenameplural', 'assign');
1051 return self::$modulenameplural;
1055 * Has this assignment been constructed from an instance?
1059 public function has_instance() {
1060 return $this->instance || $this->get_course_module();
1064 * Get the settings for the current instance of this assignment
1066 * @return stdClass The settings
1068 public function get_instance() {
1070 if ($this->instance) {
1071 return $this->instance;
1073 if ($this->get_course_module()) {
1074 $params = array('id' => $this->get_course_module()->instance);
1075 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1077 if (!$this->instance) {
1078 throw new coding_exception('Improper use of the assignment class. ' .
1079 'Cannot load the assignment record.');
1081 return $this->instance;
1085 * Get the context of the current course.
1087 * @return mixed context|null The course context
1089 public function get_course_context() {
1090 if (!$this->context && !$this->course) {
1091 throw new coding_exception('Improper use of the assignment class. ' .
1092 'Cannot load the course context.');
1094 if ($this->context) {
1095 return $this->context->get_course_context();
1097 return context_course::instance($this->course->id);
1103 * Get the current course module.
1105 * @return mixed stdClass|null The course module
1107 public function get_course_module() {
1108 if ($this->coursemodule) {
1109 return $this->coursemodule;
1111 if (!$this->context) {
1115 if ($this->context->contextlevel == CONTEXT_MODULE) {
1116 $this->coursemodule = get_coursemodule_from_id('assign',
1117 $this->context->instanceid,
1121 return $this->coursemodule;
1127 * Get context module.
1131 public function get_context() {
1132 return $this->context;
1136 * Get the current course.
1138 * @return mixed stdClass|null The course
1140 public function get_course() {
1143 if ($this->course) {
1144 return $this->course;
1147 if (!$this->context) {
1150 $params = array('id' => $this->get_course_context()->instanceid);
1151 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1153 return $this->course;
1157 * Return a grade in user-friendly form, whether it's a scale or not.
1159 * @param mixed $grade int|null
1160 * @param boolean $editing Are we allowing changes to this grade?
1161 * @param int $userid The user id the grade belongs to
1162 * @param int $modified Timestamp from when the grade was last modified
1163 * @return string User-friendly representation of grade
1165 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1168 static $scalegrades = array();
1172 if ($this->get_instance()->grade >= 0) {
1174 if ($editing && $this->get_instance()->grade > 0) {
1178 $displaygrade = format_float($grade);
1180 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1181 get_string('usergrade', 'assign') .
1183 $o .= '<input type="text"
1184 id="quickgrade_' . $userid . '"
1185 name="quickgrade_' . $userid . '"
1186 value="' . $displaygrade . '"
1189 class="quickgrade"/>';
1190 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1191 $o .= '<input type="hidden"
1192 name="grademodified_' . $userid . '"
1193 value="' . $modified . '"/>';
1196 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1197 if ($grade == -1 || $grade === null) {
1201 $o .= format_float($grade, 2) .
1203 format_float($this->get_instance()->grade, 2);
1210 if (empty($this->cache['scale'])) {
1211 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1212 $this->cache['scale'] = make_menu_from_list($scale->scale);
1219 $o .= '<label class="accesshide"
1220 for="quickgrade_' . $userid . '">' .
1221 get_string('usergrade', 'assign') .
1223 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1224 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1225 foreach ($this->cache['scale'] as $optionid => $option) {
1227 if ($grade == $optionid) {
1228 $selected = 'selected="selected"';
1230 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1233 $o .= '<input type="hidden" ' .
1234 'name="grademodified_' . $userid . '" ' .
1235 'value="' . $modified . '"/>';
1238 $scaleid = (int)$grade;
1239 if (isset($this->cache['scale'][$scaleid])) {
1240 $o .= $this->cache['scale'][$scaleid];
1250 * Load a list of users enrolled in the current course with the specified permission and group.
1253 * @param int $currentgroup
1254 * @param bool $idsonly
1255 * @return array List of user records
1257 public function list_participants($currentgroup, $idsonly) {
1259 return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id');
1261 return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1266 * Load a count of valid teams for this assignment.
1268 * @return int number of valid teams
1270 public function count_teams() {
1272 $groups = groups_get_all_groups($this->get_course()->id,
1274 $this->get_instance()->teamsubmissiongroupingid,
1276 $count = count($groups);
1278 // See if there are any users in the default group.
1279 $defaultusers = $this->get_submission_group_members(0, true);
1280 if (count($defaultusers) > 0) {
1287 * Load a count of users enrolled in the current course with the specified permission and group.
1290 * @param int $currentgroup
1291 * @return int number of matching users
1293 public function count_participants($currentgroup) {
1294 return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1298 * Load a count of users submissions in the current module that require grading
1299 * This means the submission modification time is more recent than the
1300 * grading modification time and the status is SUBMITTED.
1302 * @return int number of matching submissions
1304 public function count_submissions_need_grading() {
1307 if ($this->get_instance()->teamsubmission) {
1308 // This does not make sense for group assignment because the submission is shared.
1312 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1313 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1315 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1316 FROM {assign_submission} mxs
1317 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1318 $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1319 FROM {assign_grades} mxg
1320 WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1322 $params['assignid'] = $this->get_instance()->id;
1323 $params['assignid2'] = $this->get_instance()->id;
1324 $params['assignid3'] = $this->get_instance()->id;
1325 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1327 $sql = 'SELECT COUNT(s.userid)
1328 FROM {assign_submission} s
1329 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1330 LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1331 LEFT JOIN {assign_grades} g ON
1332 s.assignment = g.assignment AND
1333 s.userid = g.userid AND
1334 g.attemptnumber = gmx.maxattempt
1335 JOIN(' . $esql . ') e ON e.id = s.userid
1337 s.attemptnumber = smx.maxattempt AND
1338 s.assignment = :assignid AND
1339 s.timemodified IS NOT NULL AND
1340 s.status = :submitted AND
1341 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1343 return $DB->count_records_sql($sql, $params);
1347 * Load a count of grades.
1349 * @return int number of grades
1351 public function count_grades() {
1354 if (!$this->has_instance()) {
1358 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1359 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1361 $params['assignid'] = $this->get_instance()->id;
1363 $sql = 'SELECT COUNT(g.userid)
1364 FROM {assign_grades} g
1365 JOIN(' . $esql . ') e ON e.id = g.userid
1366 WHERE g.assignment = :assignid';
1368 return $DB->count_records_sql($sql, $params);
1372 * Load a count of submissions.
1374 * @return int number of submissions
1376 public function count_submissions() {
1379 if (!$this->has_instance()) {
1385 if ($this->get_instance()->teamsubmission) {
1386 // We cannot join on the enrolment tables for group submissions (no userid).
1387 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1388 FROM {assign_submission} s
1390 s.assignment = :assignid AND
1391 s.timemodified IS NOT NULL AND
1392 s.userid = :groupuserid';
1394 $params['assignid'] = $this->get_instance()->id;
1395 $params['groupuserid'] = 0;
1397 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1398 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1400 $params['assignid'] = $this->get_instance()->id;
1402 $sql = 'SELECT COUNT(DISTINCT s.userid)
1403 FROM {assign_submission} s
1404 JOIN(' . $esql . ') e ON e.id = s.userid
1406 s.assignment = :assignid AND
1407 s.timemodified IS NOT NULL';
1410 return $DB->count_records_sql($sql, $params);
1414 * Load a count of submissions with a specified status.
1416 * @param string $status The submission status - should match one of the constants
1417 * @return int number of matching submissions
1419 public function count_submissions_with_status($status) {
1422 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1423 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1425 $params['assignid'] = $this->get_instance()->id;
1426 $params['assignid2'] = $this->get_instance()->id;
1427 $params['submissionstatus'] = $status;
1429 if ($this->get_instance()->teamsubmission) {
1430 $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1431 FROM {assign_submission} mxs
1432 WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1434 $sql = 'SELECT COUNT(s.groupid)
1435 FROM {assign_submission} s
1436 JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1438 s.attemptnumber = smx.maxattempt AND
1439 s.assignment = :assignid AND
1440 s.timemodified IS NOT NULL AND
1441 s.userid = :groupuserid AND
1442 s.status = :submissionstatus';
1443 $params['groupuserid'] = 0;
1445 $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1446 FROM {assign_submission} mxs
1447 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1449 $sql = 'SELECT COUNT(s.userid)
1450 FROM {assign_submission} s
1451 JOIN(' . $esql . ') e ON e.id = s.userid
1452 JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1454 s.attemptnumber = smx.maxattempt AND
1455 s.assignment = :assignid AND
1456 s.timemodified IS NOT NULL AND
1457 s.status = :submissionstatus';
1460 return $DB->count_records_sql($sql, $params);
1464 * Utility function to get the userid for every row in the grading table
1465 * so the order can be frozen while we iterate it.
1467 * @return array An array of userids
1469 protected function get_grading_userid_list() {
1470 $filter = get_user_preferences('assign_filter', '');
1471 $table = new assign_grading_table($this, 0, $filter, 0, false);
1473 $useridlist = $table->get_column_data('userid');
1479 * Generate zip file from array of given files.
1481 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1482 * This array is indexed by the final file name and each
1483 * element in the array is an instance of a stored_file object.
1484 * @return path of temp file - note this returned file does
1485 * not have a .zip extension - it is a temp file.
1487 protected function pack_files($filesforzipping) {
1489 // Create path for new zip file.
1490 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1492 $zipper = new zip_packer();
1493 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1500 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1502 * Cron function to be run periodically according to the moodle cron.
1506 public static function cron() {
1509 // Only ever send a max of one days worth of updates.
1510 $yesterday = time() - (24 * 3600);
1513 // Collect all submissions from the past 24 hours that require mailing.
1514 $sql = 'SELECT a.course, a.name, a.blindmarking, a.revealidentities,
1515 g.*, g.id as gradeid, g.timemodified as lastmodified
1517 JOIN {assign_grades} g ON g.assignment = a.id
1518 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1519 WHERE g.timemodified >= :yesterday AND
1520 g.timemodified <= :today AND
1523 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1524 $submissions = $DB->get_records_sql($sql, $params);
1526 if (empty($submissions)) {
1530 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1532 // Preload courses we are going to need those.
1533 $courseids = array();
1534 foreach ($submissions as $submission) {
1535 $courseids[] = $submission->course;
1538 // Filter out duplicates.
1539 $courseids = array_unique($courseids);
1540 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1541 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1542 $sql = 'SELECT c.*, ' . $ctxselect .
1544 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1545 WHERE c.id ' . $courseidsql;
1547 $params['contextlevel'] = CONTEXT_COURSE;
1548 $courses = $DB->get_records_sql($sql, $params);
1550 // Clean up... this could go on for a while.
1553 unset($courseidsql);
1556 // Simple array we'll use for caching modules.
1557 $modcache = array();
1559 // Message students about new feedback.
1560 foreach ($submissions as $submission) {
1562 mtrace("Processing assignment submission $submission->id ...");
1564 // Do not cache user lookups - could be too many.
1565 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1566 mtrace('Could not find user ' . $submission->userid);
1570 // Use a cache to prevent the same DB queries happening over and over.
1571 if (!array_key_exists($submission->course, $courses)) {
1572 mtrace('Could not find course ' . $submission->course);
1575 $course = $courses[$submission->course];
1576 if (isset($course->ctxid)) {
1577 // Context has not yet been preloaded. Do so now.
1578 context_helper::preload_from_record($course);
1581 // Override the language and timezone of the "current" user, so that
1582 // mail is customised for the receiver.
1583 cron_setup_user($user, $course);
1585 // Context lookups are already cached.
1586 $coursecontext = context_course::instance($course->id);
1587 if (!is_enrolled($coursecontext, $user->id)) {
1588 $courseshortname = format_string($course->shortname,
1590 array('context' => $coursecontext));
1591 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1595 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1596 mtrace('Could not find grader ' . $submission->grader);
1600 if (!array_key_exists($submission->assignment, $modcache)) {
1601 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1603 mtrace('Could not find course module for assignment id ' . $submission->assignment);
1606 $modcache[$submission->assignment] = $mod;
1608 $mod = $modcache[$submission->assignment];
1610 // Context lookups are already cached.
1611 $contextmodule = context_module::instance($mod->id);
1613 if (!$mod->visible) {
1614 // Hold mail notification for hidden assignments until later.
1618 // Need to send this to the student.
1619 $messagetype = 'feedbackavailable';
1620 $eventtype = 'assign_notification';
1621 $updatetime = $submission->lastmodified;
1622 $modulename = get_string('modulename', 'assign');
1625 if ($submission->blindmarking && !$submission->revealidentities) {
1626 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1628 $showusers = $submission->blindmarking && !$submission->revealidentities;
1629 self::send_assignment_notification($grader,
1642 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1645 $DB->update_record('assign_user_flags', $flags);
1647 $flags = new stdClass();
1648 $flags->userid = $user->id;
1649 $flags->assignment = $submission->assignment;
1651 $DB->insert_record('assign_user_flags', $flags);
1656 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1660 // Free up memory just to be sure.
1668 * Mark in the database that this grade record should have an update notification sent by cron.
1670 * @param stdClass $grade a grade record keyed on id
1671 * @return bool true for success
1673 public function notify_grade_modified($grade) {
1676 $flags = $this->get_user_flags($grade->userid, true);
1677 if ($flags->mailed != 1) {
1681 return $this->update_user_flags($flags);
1685 * Update user flags for this user in this assignment.
1687 * @param stdClass $flags a flags record keyed on id
1688 * @return bool true for success
1690 public function update_user_flags($flags) {
1692 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1696 $result = $DB->update_record('assign_user_flags', $flags);
1701 * Update a grade in the grade table for the assignment and in the gradebook.
1703 * @param stdClass $grade a grade record keyed on id
1704 * @return bool true for success
1706 public function update_grade($grade) {
1709 $grade->timemodified = time();
1711 if (!empty($grade->workflowstate)) {
1712 $validstates = $this->get_marking_workflow_states_for_current_user();
1713 if (!array_key_exists($grade->workflowstate, $validstates)) {
1718 if ($grade->grade && $grade->grade != -1) {
1719 if ($this->get_instance()->grade > 0) {
1720 if (!is_numeric($grade->grade)) {
1722 } else if ($grade->grade > $this->get_instance()->grade) {
1724 } else if ($grade->grade < 0) {
1729 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1730 $scaleoptions = make_menu_from_list($scale->scale);
1731 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1738 if (empty($grade->attemptnumber)) {
1739 // Set it to the default.
1740 $grade->attemptnumber = 0;
1742 $result = $DB->update_record('assign_grades', $grade);
1744 // Only push to gradebook if the update is for the latest attempt.
1746 if ($this->get_instance()->teamsubmission) {
1747 $submission = $this->get_group_submission($grade->userid, 0, false);
1749 $submission = $this->get_user_submission($grade->userid, false);
1751 // Not the latest attempt.
1752 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1757 $this->gradebook_item_update(null, $grade);
1763 * View the grant extension date page.
1765 * Uses url parameters 'userid'
1766 * or from parameter 'selectedusers'
1768 * @param moodleform $mform - Used for validation of the submitted data
1771 protected function view_grant_extension($mform) {
1773 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1776 $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1777 $data = new stdClass();
1778 $data->extensionduedate = null;
1781 $userid = required_param('userid', PARAM_INT);
1783 $grade = $this->get_user_grade($userid, false);
1785 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1788 $data->extensionduedate = $grade->extensionduedate;
1790 $data->userid = $userid;
1792 $data->batchusers = $batchusers;
1794 $header = new assign_header($this->get_instance(),
1795 $this->get_context(),
1796 $this->show_intro(),
1797 $this->get_course_module()->id,
1798 get_string('grantextension', 'assign'));
1799 $o .= $this->get_renderer()->render($header);
1802 $formparams = array($this->get_course_module()->id,
1805 $this->get_instance(),
1807 $mform = new mod_assign_extension_form(null, $formparams);
1809 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1810 $o .= $this->view_footer();
1815 * Get a list of the users in the same group as this user.
1817 * @param int $groupid The id of the group whose members we want or 0 for the default group
1818 * @param bool $onlyids Whether to retrieve only the user id's
1819 * @return array The users (possibly id's only)
1821 public function get_submission_group_members($groupid, $onlyids) {
1823 if ($groupid != 0) {
1825 $allusers = groups_get_members($groupid, 'u.id');
1827 $allusers = groups_get_members($groupid);
1829 foreach ($allusers as $user) {
1830 if ($this->get_submission_group($user->id)) {
1835 $allusers = $this->list_participants(null, $onlyids);
1836 foreach ($allusers as $user) {
1837 if ($this->get_submission_group($user->id) == null) {
1846 * Get a list of the users in the same group as this user that have not submitted the assignment.
1848 * @param int $groupid The id of the group whose members we want or 0 for the default group
1849 * @param bool $onlyids Whether to retrieve only the user id's
1850 * @return array The users (possibly id's only)
1852 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1853 $instance = $this->get_instance();
1854 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1857 $members = $this->get_submission_group_members($groupid, $onlyids);
1859 foreach ($members as $id => $member) {
1860 $submission = $this->get_user_submission($member->id, false);
1861 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1862 unset($members[$id]);
1864 if ($this->is_blind_marking()) {
1865 $members[$id]->alias = get_string('hiddenuser', 'assign') .
1866 $this->get_uniqueid_for_user($id);
1874 * Load the group submission object for a particular user, optionally creating it if required.
1876 * @param int $userid The id of the user whose submission we want
1877 * @param int $groupid The id of the group for this user - may be 0 in which
1878 * case it is determined from the userid.
1879 * @param bool $create If set to true a new submission object will be created in the database
1880 * @param int $attemptnumber - -1 means the latest attempt
1881 * @return stdClass The submission
1883 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1886 if ($groupid == 0) {
1887 $group = $this->get_submission_group($userid);
1889 $groupid = $group->id;
1893 // Now get the group submission.
1894 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1895 if ($attemptnumber >= 0) {
1896 $params['attemptnumber'] = $attemptnumber;
1899 // Only return the row with the highest attemptnumber.
1901 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1903 $submission = reset($submissions);
1910 $submission = new stdClass();
1911 $submission->assignment = $this->get_instance()->id;
1912 $submission->userid = 0;
1913 $submission->groupid = $groupid;
1914 $submission->timecreated = time();
1915 $submission->timemodified = $submission->timecreated;
1916 if ($attemptnumber >= 0) {
1917 $submission->attemptnumber = $attemptnumber;
1919 $submission->attemptnumber = 0;
1922 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1923 $sid = $DB->insert_record('assign_submission', $submission);
1924 $submission->id = $sid;
1931 * View a summary listing of all assignments in the current course.
1935 private function view_course_index() {
1940 $course = $this->get_course();
1941 $strplural = get_string('modulenameplural', 'assign');
1943 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1944 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1945 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1949 $strsectionname = get_string('sectionname', 'format_'.$course->format);
1950 $usesections = course_format_uses_sections($course->format);
1951 $modinfo = get_fast_modinfo($course);
1954 $sections = $modinfo->get_section_info_all();
1956 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1960 $currentsection = '';
1961 foreach ($modinfo->instances['assign'] as $cm) {
1962 if (!$cm->uservisible) {
1966 $timedue = $cms[$cm->id]->duedate;
1969 if ($usesections && $cm->sectionnum) {
1970 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1974 $context = context_module::instance($cm->id);
1976 $assignment = new assign($context, $cm, $course);
1978 if (has_capability('mod/assign:grade', $context)) {
1979 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1981 } else if (has_capability('mod/assign:submit', $context)) {
1982 $usersubmission = $assignment->get_user_submission($USER->id, false);
1984 if (!empty($usersubmission->status)) {
1985 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1987 $submitted = get_string('submissionstatus_', 'assign');
1990 $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1991 if (isset($grading_info->items[0]->grades[$USER->id]) &&
1992 !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1993 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1998 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2002 $o .= $this->get_renderer()->render($courseindexsummary);
2003 $o .= $this->view_footer();
2009 * View a page rendered by a plugin.
2011 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2015 protected function view_plugin_page() {
2020 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2021 $plugintype = required_param('plugin', PARAM_TEXT);
2022 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2024 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2026 print_error('invalidformdata', '');
2030 $o .= $plugin->view_page($pluginaction);
2037 * This is used for team assignments to get the group for the specified user.
2038 * If the user is a member of multiple or no groups this will return false
2040 * @param int $userid The id of the user whose submission we want
2041 * @return mixed The group or false
2043 public function get_submission_group($userid) {
2044 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2045 $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2046 if (count($groups) != 1) {
2049 return array_pop($groups);
2054 * Display the submission that is used by a plugin.
2056 * Uses url parameters 'sid', 'gid' and 'plugin'.
2058 * @param string $pluginsubtype
2061 protected function view_plugin_content($pluginsubtype) {
2066 $submissionid = optional_param('sid', 0, PARAM_INT);
2067 $gradeid = optional_param('gid', 0, PARAM_INT);
2068 $plugintype = required_param('plugin', PARAM_TEXT);
2070 if ($pluginsubtype == 'assignsubmission') {
2071 $plugin = $this->get_submission_plugin_by_type($plugintype);
2072 if ($submissionid <= 0) {
2073 throw new coding_exception('Submission id should not be 0');
2075 $item = $this->get_submission($submissionid);
2077 // Check permissions.
2078 if ($item->userid != $USER->id) {
2079 require_capability('mod/assign:grade', $this->context);
2081 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2082 $this->get_context(),
2083 $this->show_intro(),
2084 $this->get_course_module()->id,
2085 $plugin->get_name()));
2086 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2088 assign_submission_plugin_submission::FULL,
2089 $this->get_course_module()->id,
2090 $this->get_return_action(),
2091 $this->get_return_params()));
2093 $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2094 $this->add_to_log('view submission', $logmessage);
2096 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2097 if ($gradeid <= 0) {
2098 throw new coding_exception('Grade id should not be 0');
2100 $item = $this->get_grade($gradeid);
2101 // Check permissions.
2102 if ($item->userid != $USER->id) {
2103 require_capability('mod/assign:grade', $this->context);
2105 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2106 $this->get_context(),
2107 $this->show_intro(),
2108 $this->get_course_module()->id,
2109 $plugin->get_name()));
2110 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2112 assign_feedback_plugin_feedback::FULL,
2113 $this->get_course_module()->id,
2114 $this->get_return_action(),
2115 $this->get_return_params()));
2116 $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2117 $this->add_to_log('view feedback', $logmessage);
2120 $o .= $this->view_return_links();
2122 $o .= $this->view_footer();
2127 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2129 * @param stdClass $user - The user record
2130 * @param assign_plugin $plugin - The assignment plugin
2132 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2133 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2136 $groupid = groups_get_activity_group($this->get_course_module(), true);
2137 $groupname = groups_get_group_name($groupid).'-';
2140 if ($this->is_blind_marking()) {
2141 $prefix = $groupname . get_string('participant', 'assign');
2142 $prefix = str_replace('_', ' ', $prefix);
2143 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2145 $prefix = $groupname . fullname($user);
2146 $prefix = str_replace('_', ' ', $prefix);
2147 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2150 $subtype = $plugin->get_subtype();
2151 $type = $plugin->get_type();
2152 $prefix = $prefix . $subtype . '_' . $type . '_';
2154 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2160 * Render the content in editor that is often used by plugin.
2162 * @param string $filearea
2163 * @param int $submissionid
2164 * @param string $plugintype
2165 * @param string $editor
2166 * @param string $component
2169 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2174 $plugin = $this->get_submission_plugin_by_type($plugintype);
2176 $text = $plugin->get_editor_text($editor, $submissionid);
2177 $format = $plugin->get_editor_format($editor, $submissionid);
2179 $finaltext = file_rewrite_pluginfile_urls($text,
2181 $this->get_context()->id,
2185 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2186 $result .= format_text($finaltext, $format, $params);
2188 if ($CFG->enableportfolios) {
2189 require_once($CFG->libdir . '/portfoliolib.php');
2191 $button = new portfolio_add_button();
2192 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2193 'sid' => $submissionid,
2194 'plugin' => $plugintype,
2195 'editor' => $editor,
2197 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2198 $fs = get_file_storage();
2200 if ($files = $fs->get_area_files($this->context->id,
2206 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2208 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2210 $result .= $button->to_html();
2216 * Display a continue page.
2220 protected function view_savegrading_result($message) {
2222 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2223 $this->get_context(),
2224 $this->show_intro(),
2225 $this->get_course_module()->id,
2226 get_string('savegradingresult', 'assign')));
2227 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2229 $this->get_course_module()->id);
2230 $o .= $this->get_renderer()->render($gradingresult);
2231 $o .= $this->view_footer();
2235 * Display a grading error.
2237 * @param string $message - The description of the result
2240 protected function view_quickgrading_result($message) {
2242 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2243 $this->get_context(),
2244 $this->show_intro(),
2245 $this->get_course_module()->id,
2246 get_string('quickgradingresult', 'assign')));
2247 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2249 $this->get_course_module()->id);
2250 $o .= $this->get_renderer()->render($gradingresult);
2251 $o .= $this->view_footer();
2256 * Display the page footer.
2260 protected function view_footer() {
2261 return $this->get_renderer()->render_footer();
2265 * Does this user have grade permission for this assignment?
2269 protected function can_grade() {
2270 // Permissions check.
2271 if (!has_capability('mod/assign:grade', $this->context)) {
2279 * Download a zip file of all assignment submissions.
2281 * @return string - If an error occurs, this will contain the error page.
2283 protected function download_submissions() {
2286 // More efficient to load this here.
2287 require_once($CFG->libdir.'/filelib.php');
2289 require_capability('mod/assign:grade', $this->context);
2291 // Load all users with submit.
2292 $students = get_enrolled_users($this->context, "mod/assign:submit");
2294 // Build a list of files to zip.
2295 $filesforzipping = array();
2296 $fs = get_file_storage();
2298 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2303 $groupid = groups_get_activity_group($this->get_course_module(), true);
2304 $groupname = groups_get_group_name($groupid).'-';
2307 // Construct the zip file name.
2308 $filename = clean_filename($this->get_course()->shortname . '-' .
2309 $this->get_instance()->name . '-' .
2310 $groupname.$this->get_course_module()->id . '.zip');
2312 // Get all the files for each student.
2313 foreach ($students as $student) {
2314 $userid = $student->id;
2316 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2317 // Get the plugins to add their own files to the zip.
2319 $submissiongroup = false;
2321 if ($this->get_instance()->teamsubmission) {
2322 $submission = $this->get_group_submission($userid, 0, false);
2323 $submissiongroup = $this->get_submission_group($userid);
2324 if ($submissiongroup) {
2325 $groupname = $submissiongroup->name . '-';
2327 $groupname = get_string('defaultteam', 'assign') . '-';
2330 $submission = $this->get_user_submission($userid, false);
2333 if ($this->is_blind_marking()) {
2334 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2335 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2337 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2338 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2342 foreach ($this->submissionplugins as $plugin) {
2343 if ($plugin->is_enabled() && $plugin->is_visible()) {
2344 $pluginfiles = $plugin->get_files($submission, $student);
2345 foreach ($pluginfiles as $zipfilename => $file) {
2346 $subtype = $plugin->get_subtype();
2347 $type = $plugin->get_type();
2348 $prefixedfilename = clean_filename($prefix .
2354 $filesforzipping[$prefixedfilename] = $file;
2362 if (count($filesforzipping) == 0) {
2363 $header = new assign_header($this->get_instance(),
2364 $this->get_context(),
2366 $this->get_course_module()->id,
2367 get_string('downloadall', 'assign'));
2368 $result .= $this->get_renderer()->render($header);
2369 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2370 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2371 'action'=>'grading'));
2372 $result .= $this->get_renderer()->continue_button($url);
2373 $result .= $this->view_footer();
2374 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2375 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2376 // Send file and delete after sending.
2377 send_temp_file($zipfile, $filename);
2378 // We will not get here - send_temp_file calls exit.
2384 * Util function to add a message to the log.
2386 * @param string $action The current action
2387 * @param string $info A detailed description of the change. But no more than 255 characters.
2388 * @param string $url The url to the assign module instance.
2391 public function add_to_log($action = '', $info = '', $url='') {
2394 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2396 $fullurl .= '&' . $url;
2399 add_to_log($this->get_course()->id,
2404 $this->get_course_module()->id,
2409 * Lazy load the page renderer and expose the renderer to plugins.
2411 * @return assign_renderer
2413 public function get_renderer() {
2415 if ($this->output) {
2416 return $this->output;
2418 $this->output = $PAGE->get_renderer('mod_assign');
2419 return $this->output;
2423 * Load the submission object for a particular user, optionally creating it if required.
2425 * For team assignments there are 2 submissions - the student submission and the team submission
2426 * All files are associated with the team submission but the status of the students contribution is
2427 * recorded separately.
2429 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2430 * @param bool $create optional - defaults to false. If set to true a new submission object
2431 * will be created in the database.
2432 * @param int $attemptnumber - -1 means the latest attempt
2433 * @return stdClass The submission
2435 public function get_user_submission($userid, $create, $attemptnumber=-1) {
2439 $userid = $USER->id;
2441 // If the userid is not null then use userid.
2442 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2443 if ($attemptnumber >= 0) {
2444 $params['attemptnumber'] = $attemptnumber;
2447 // Only return the row with the highest attemptnumber.
2449 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2451 $submission = reset($submissions);
2458 $submission = new stdClass();
2459 $submission->assignment = $this->get_instance()->id;
2460 $submission->userid = $userid;
2461 $submission->timecreated = time();
2462 $submission->timemodified = $submission->timecreated;
2463 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2464 if ($attemptnumber >= 0) {
2465 $submission->attemptnumber = $attemptnumber;
2467 $submission->attemptnumber = 0;
2469 $sid = $DB->insert_record('assign_submission', $submission);
2470 $submission->id = $sid;
2477 * Load the submission object from it's id.
2479 * @param int $submissionid The id of the submission we want
2480 * @return stdClass The submission
2482 protected function get_submission($submissionid) {
2485 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2486 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2490 * This will retrieve a user flags object from the db optionally creating it if required.
2491 * The user flags was split from the user_grades table in 2.5.
2493 * @param int $userid The user we are getting the flags for.
2494 * @param bool $create If true the flags record will be created if it does not exist
2495 * @return stdClass The flags record
2497 public function get_user_flags($userid, $create) {
2500 // If the userid is not null then use userid.
2502 $userid = $USER->id;
2505 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2507 $flags = $DB->get_record('assign_user_flags', $params);
2513 $flags = new stdClass();
2514 $flags->assignment = $this->get_instance()->id;
2515 $flags->userid = $userid;
2517 $flags->extensionduedate = 0;
2518 $flags->workflowstate = '';
2519 $flags->allocatedmarker = 0;
2521 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2522 // This is because students only want to be notified about certain types of update (grades and feedback).
2525 $fid = $DB->insert_record('assign_user_flags', $flags);
2533 * This will retrieve a grade object from the db, optionally creating it if required.
2535 * @param int $userid The user we are grading
2536 * @param bool $create If true the grade will be created if it does not exist
2537 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2538 * @return stdClass The grade record
2540 public function get_user_grade($userid, $create, $attemptnumber=-1) {
2543 // If the userid is not null then use userid.
2545 $userid = $USER->id;
2548 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2549 if ($attemptnumber < 0) {
2550 // Make sure this grade matches the latest submission attempt.
2551 if ($this->get_instance()->teamsubmission) {
2552 $submission = $this->get_group_submission($userid, 0, false);
2554 $submission = $this->get_user_submission($userid, false);
2557 $attemptnumber = $submission->attemptnumber;
2561 if ($attemptnumber >= 0) {
2562 $params['attemptnumber'] = $attemptnumber;
2565 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2568 return reset($grades);
2571 $grade = new stdClass();
2572 $grade->assignment = $this->get_instance()->id;
2573 $grade->userid = $userid;
2574 $grade->timecreated = time();
2575 $grade->timemodified = $grade->timecreated;
2577 $grade->grader = $USER->id;
2578 if ($attemptnumber >= 0) {
2579 $grade->attemptnumber = $attemptnumber;
2582 $gid = $DB->insert_record('assign_grades', $grade);
2590 * This will retrieve a grade object from the db.
2592 * @param int $gradeid The id of the grade
2593 * @return stdClass The grade record
2595 protected function get_grade($gradeid) {
2598 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2599 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2603 * Print the grading page for a single user submission.
2605 * @param moodleform $mform
2608 protected function view_single_grade_page($mform) {
2612 $instance = $this->get_instance();
2614 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2616 // Need submit permission to submit an assignment.
2617 require_capability('mod/assign:grade', $this->context);
2619 $header = new assign_header($instance,
2620 $this->get_context(),
2622 $this->get_course_module()->id,
2623 get_string('grading', 'assign'));
2624 $o .= $this->get_renderer()->render($header);
2626 // If userid is passed - we are only grading a single student.
2627 $rownum = required_param('rownum', PARAM_INT);
2628 $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2629 $userid = optional_param('userid', 0, PARAM_INT);
2630 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2632 $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2634 if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2635 $useridlist = $this->get_grading_userid_list();
2637 $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2640 $useridlist = array($userid);
2643 if ($rownum < 0 || $rownum > count($useridlist)) {
2644 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2648 $userid = $useridlist[$rownum];
2649 if ($rownum == count($useridlist) - 1) {
2652 $user = $DB->get_record('user', array('id' => $userid));
2654 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2655 $usersummary = new assign_user_summary($user,
2656 $this->get_course()->id,
2658 $this->is_blind_marking(),
2659 $this->get_uniqueid_for_user($user->id),
2660 get_extra_user_fields($this->get_context()));
2661 $o .= $this->get_renderer()->render($usersummary);
2663 $submission = $this->get_user_submission($userid, false, $attemptnumber);
2664 $submissiongroup = null;
2665 $submissiongroupmemberswhohavenotsubmitted = array();
2666 $teamsubmission = null;
2667 $notsubmitted = array();
2668 if ($instance->teamsubmission) {
2669 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2670 $submissiongroup = $this->get_submission_group($userid);
2672 if ($submissiongroup) {
2673 $groupid = $submissiongroup->id;
2675 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2679 // Get the requested grade.
2680 $grade = $this->get_user_grade($userid, false, $attemptnumber);
2681 $flags = $this->get_user_flags($userid, false);
2682 if ($this->can_view_submission($userid)) {
2683 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2684 $extensionduedate = null;
2686 $extensionduedate = $flags->extensionduedate;
2688 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2690 if ($teamsubmission) {
2691 $showsubmit = $showedit &&
2693 ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2695 $showsubmit = $showedit &&
2697 ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2699 if (!$this->get_instance()->submissiondrafts) {
2700 $showsubmit = false;
2702 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2704 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2705 $instance->alwaysshowdescription,
2707 $instance->teamsubmission,
2711 $this->is_any_submission_plugin_enabled(),
2713 $this->is_graded($userid),
2715 $instance->cutoffdate,
2716 $this->get_submission_plugins(),
2717 $this->get_return_action(),
2718 $this->get_return_params(),
2719 $this->get_course_module()->id,
2720 $this->get_course()->id,
2721 assign_submission_status::GRADER_VIEW,
2726 $this->get_context(),
2727 $this->is_blind_marking(),
2729 $instance->attemptreopenmethod,
2730 $instance->maxattempts);
2731 $o .= $this->get_renderer()->render($submissionstatus);
2735 $data = new stdClass();
2736 if ($grade->grade !== null && $grade->grade >= 0) {
2737 $data->grade = format_float($grade->grade, 2);
2739 if (!empty($flags->workflowstate)) {
2740 $data->workflowstate = $flags->workflowstate;
2742 if (!empty($flags->allocatedmarker)) {
2743 $data->allocatedmarker = $flags->allocatedmarker;
2746 $data = new stdClass();
2749 // Warning if required.
2750 $allsubmissions = $this->get_all_submissions($userid);
2752 if ($attemptnumber != -1) {
2753 $params = array('attemptnumber'=>$attemptnumber + 1,
2754 'totalattempts'=>count($allsubmissions));
2755 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2756 $o .= $this->get_renderer()->notification($message);
2759 // Now show the grading form.
2761 $pagination = array('rownum'=>$rownum,
2762 'useridlistid'=>$useridlistid,
2764 'userid'=>optional_param('userid', 0, PARAM_INT),
2765 'attemptnumber'=>$attemptnumber);
2766 $formparams = array($this, $data, $pagination);
2767 $mform = new mod_assign_grade_form(null,
2771 array('class'=>'gradeform'));
2773 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2774 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2776 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2777 $allgrades = $this->get_all_grades($userid);
2778 $history = new assign_attempt_history($allsubmissions,
2780 $this->get_submission_plugins(),
2781 $this->get_feedback_plugins(),
2782 $this->get_course_module()->id,
2783 $this->get_return_action(),
2784 $this->get_return_params(),
2787 $o .= $this->get_renderer()->render($history);
2790 $msg = get_string('viewgradingformforstudent',
2792 array('id'=>$user->id, 'fullname'=>fullname($user)));
2793 $this->add_to_log('view grading form', $msg);
2795 $o .= $this->view_footer();
2800 * Show a confirmation page to make sure they want to release student identities.
2804 protected function view_reveal_identities_confirm() {
2807 require_capability('mod/assign:revealidentities', $this->get_context());
2810 $header = new assign_header($this->get_instance(),
2811 $this->get_context(),
2813 $this->get_course_module()->id);
2814 $o .= $this->get_renderer()->render($header);
2816 $urlparams = array('id'=>$this->get_course_module()->id,
2817 'action'=>'revealidentitiesconfirm',
2818 'sesskey'=>sesskey());
2819 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2821 $urlparams = array('id'=>$this->get_course_module()->id,
2822 'action'=>'grading');
2823 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2825 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2828 $o .= $this->view_footer();
2829 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2834 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2838 protected function view_return_links() {
2839 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2840 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2843 $returnparams = str_replace('&', '&', $returnparams);
2844 parse_str($returnparams, $params);
2845 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2846 $params = array_merge($newparams, $params);
2848 $url = new moodle_url('/mod/assign/view.php', $params);
2849 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2853 * View the grading table of all submissions for this assignment.
2857 protected function view_grading_table() {
2860 // Include grading options form.
2861 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2862 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2863 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2865 $cmid = $this->get_course_module()->id;
2868 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2869 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2870 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2871 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2873 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2874 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2875 $links[$downloadurl] = get_string('downloadall', 'assign');
2877 if ($this->is_blind_marking() &&
2878 has_capability('mod/assign:revealidentities', $this->get_context())) {
2879 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2880 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2882 foreach ($this->get_feedback_plugins() as $plugin) {
2883 if ($plugin->is_enabled() && $plugin->is_visible()) {
2884 foreach ($plugin->get_grading_actions() as $action => $description) {
2885 $url = '/mod/assign/view.php' .
2887 '&plugin=' . $plugin->get_type() .
2888 '&pluginsubtype=assignfeedback' .
2889 '&action=viewpluginpage&pluginaction=' . $action;
2890 $links[$url] = $description;
2895 $gradingactions = new url_select($links);
2896 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2898 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2900 $perpage = get_user_preferences('assign_perpage', 10);
2901 $filter = get_user_preferences('assign_filter', '');
2902 $markerfilter = get_user_preferences('assign_markerfilter', '');
2903 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2904 $controller = $gradingmanager->get_active_controller();
2905 $showquickgrading = empty($controller);
2906 $quickgrading = get_user_preferences('assign_quickgrading', false);
2908 $markingallocation = $this->get_instance()->markingallocation &&
2909 has_capability('mod/assign:manageallocations', $this->context);
2910 // Get markers to use in drop lists.
2911 $markingallocationoptions = array();
2912 if ($markingallocation) {
2913 $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2914 $markingallocationoptions[''] = get_string('filternone', 'assign');
2915 foreach ($markers as $marker) {
2916 $markingallocationoptions[$marker->id] = fullname($marker);
2920 $markingworkflow = $this->get_instance()->markingworkflow;
2921 // Get marking states to show in form.
2922 $markingworkflowoptions = array();
2923 if ($markingworkflow) {
2924 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
2925 $markingworkflowoptions[''] = get_string('filternone', 'assign');
2926 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
2927 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
2930 // Print options for changing the filter and changing the number of results per page.
2931 $gradingoptionsformparams = array('cm'=>$cmid,
2932 'contextid'=>$this->context->id,
2933 'userid'=>$USER->id,
2934 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2935 'showquickgrading'=>$showquickgrading,
2936 'quickgrading'=>$quickgrading,
2937 'markingworkflowopt'=>$markingworkflowoptions,
2938 'markingallocationopt'=>$markingallocationoptions);
2940 $classoptions = array('class'=>'gradingoptionsform');
2941 $gradingoptionsform = new mod_assign_grading_options_form(null,
2942 $gradingoptionsformparams,
2947 $batchformparams = array('cm'=>$cmid,
2948 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2949 'duedate'=>$this->get_instance()->duedate,
2950 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
2951 'feedbackplugins'=>$this->get_feedback_plugins(),
2952 'context'=>$this->get_context(),
2953 'markingworkflow'=>$markingworkflow,
2954 'markingallocation'=>$markingallocation);
2955 $classoptions = array('class'=>'gradingbatchoperationsform');
2957 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2963 $gradingoptionsdata = new stdClass();
2964 $gradingoptionsdata->perpage = $perpage;
2965 $gradingoptionsdata->filter = $filter;
2966 $gradingoptionsdata->markerfilter = $markerfilter;
2967 $gradingoptionsdata->workflowfilter = $workflowfilter;
2968 $gradingoptionsform->set_data($gradingoptionsdata);
2970 $actionformtext = $this->get_renderer()->render($gradingactions);
2971 $header = new assign_header($this->get_instance(),
2972 $this->get_context(),
2974 $this->get_course_module()->id,
2975 get_string('grading', 'assign'),
2977 $o .= $this->get_renderer()->render($header);
2979 $currenturl = $CFG->wwwroot .
2980 '/mod/assign/view.php?id=' .
2981 $this->get_course_module()->id .
2984 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
2986 // Plagiarism update status apearring in the grading book.
2987 if (!empty($CFG->enableplagiarism)) {
2988 require_once($CFG->libdir . '/plagiarismlib.php');
2989 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2992 // Load and print the table of submissions.
2993 if ($showquickgrading && $quickgrading) {
2994 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
2995 $table = $this->get_renderer()->render($gradingtable);
2996 $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
2997 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
2999 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3001 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3002 $o .= $this->get_renderer()->render($gradingtable);
3005 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3006 $users = array_keys($this->list_participants($currentgroup, true));
3007 if (count($users) != 0) {
3008 // If no enrolled user in a course then don't display the batch operations feature.
3009 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3010 $o .= $this->get_renderer()->render($assignform);
3012 $assignform = new assign_form('gradingoptionsform',
3013 $gradingoptionsform,
3014 'M.mod_assign.init_grading_options');
3015 $o .= $this->get_renderer()->render($assignform);
3020 * View entire grading page.
3024 protected function view_grading_page() {
3028 // Need submit permission to submit an assignment.
3029 require_capability('mod/assign:grade', $this->context);
3030 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3032 // Only load this if it is.
3034 $o .= $this->view_grading_table();
3036 $o .= $this->view_footer();
3038 $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3039 $this->add_to_log('view submission grading table', $logmessage);
3044 * Capture the output of the plagiarism plugins disclosures and return it as a string.
3048 protected function plagiarism_print_disclosure() {
3052 if (!empty($CFG->enableplagiarism)) {
3053 require_once($CFG->libdir . '/plagiarismlib.php');
3055 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3062 * Message for students when assignment submissions have been closed.
3066 protected function view_student_error_message() {
3070 // Need submit permission to submit an assignment.
3071 require_capability('mod/assign:submit', $this->context);
3073 $header = new assign_header($this->get_instance(),
3074 $this->get_context(),
3075 $this->show_intro(),
3076 $this->get_course_module()->id,
3077 get_string('editsubmission', 'assign'));
3078 $o .= $this->get_renderer()->render($header);
3080 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3082 $o .= $this->view_footer();
3089 * View edit submissions page.
3091 * @param moodleform $mform
3092 * @param array $notices A list of notices to display at the top of the
3093 * edit submission form (e.g. from plugins).
3094 * @return string The page output.
3096 protected function view_edit_submission_page($mform, $notices) {
3100 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3101 // Need submit permission to submit an assignment.
3102 require_capability('mod/assign:submit', $this->context);
3104 if (!$this->submissions_open()) {
3105 return $this->view_student_error_message();
3107 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3108 $this->get_context(),
3109 $this->show_intro(),
3110 $this->get_course_module()->id,
3111 get_string('editsubmission', 'assign')));
3112 $o .= $this->plagiarism_print_disclosure();
3113 $data = new stdClass();
3116 $mform = new mod_assign_submission_form(null, array($this, $data));
3119 foreach ($notices as $notice) {
3120 $o .= $this->get_renderer()->notification($notice);
3123 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3125 $o .= $this->view_footer();
3126 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3132 * See if this assignment has a grade yet.
3134 * @param int $userid
3137 protected function is_graded($userid) {
3138 $grade = $this->get_user_grade($userid, false);
3140 return ($grade->grade !== null && $grade->grade >= 0);
3146 * Perform an access check to see if the current $USER can view this group submission.
3148 * @param int $groupid
3151 public function can_view_group_submission($groupid) {
3154 if (!is_enrolled($this->get_course_context(), $USER->id)) {
3157 if (has_capability('mod/assign:grade', $this->context)) {
3160 $members = $this->get_submission_group_members($groupid, true);
3161 foreach ($members as $member) {
3162 if ($member->id == $USER->id) {
3170 * Perform an access check to see if the current $USER can view this users submission.
3172 * @param int $userid
3175 public function can_view_submission($userid) {
3178 if (is_siteadmin()) {
3181 if (!is_enrolled($this->get_course_context(), $userid)) {
3184 if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
3187 if (has_capability('mod/assign:grade', $this->context)) {
3194 * Allows the plugin to show a batch grading operation page.
3198 protected function view_plugin_grading_batch_operation($mform) {
3199 require_capability('mod/assign:grade', $this->context);
3200 $prefix = 'plugingradingbatchoperation_';
3202 if ($data = $mform->get_data()) {
3203 $tail = substr($data->operation, strlen($prefix));
3204 list($plugintype, $action) = explode('_', $tail, 2);
3206 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3208 $users = $data->selectedusers;
3209 $userlist = explode(',', $users);
3210 echo $plugin->grading_batch_operation($action, $userlist);
3214 print_error('invalidformdata', '');
3218 * Ask the user to confirm they want to perform this batch operation
3220 * @param moodleform $mform Set to a grading batch operations form
3221 * @return string - the page to view after processing these actions
3223 protected function process_grading_batch_operation(& $mform) {
3225 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3228 $markingallocation = $this->get_instance()->markingallocation &&
3229 has_capability('mod/assign:manageallocations', $this->context);
3231 $batchformparams = array('cm'=>$this->get_course_module()->id,
3232 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3233 'duedate'=>$this->get_instance()->duedate,
3234 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3235 'feedbackplugins'=>$this->get_feedback_plugins(),
3236 'context'=>$this->get_context(),
3237 'markingworkflow'=>$this->get_instance()->markingworkflow,
3238 'markingallocation'=>$markingallocation);
3239 $formclasses = array('class'=>'gradingbatchoperationsform');
3240 $mform = new mod_assign_grading_batch_operations_form(null,
3246 if ($data = $mform->get_data()) {
3247 // Get the list of users.
3248 $users = $data->selectedusers;
3249 $userlist = explode(',', $users);
3251 $prefix = 'plugingradingbatchoperation_';
3253 if ($data->operation == 'grantextension') {
3254 // Reset the form so the grant extension page will create the extension form.
3256 return 'grantextension';
3257 } else if ($data->operation == 'setmarkingworkflowstate') {
3258 return 'viewbatchsetmarkingworkflowstate';
3259 } else if ($data->operation == 'setmarkingallocation') {
3260 return 'viewbatchmarkingallocation';