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();
30 * Assignment submission statuses
32 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft'); // student thinks it is a draft
33 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished
36 * Search filters for grading page
38 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
39 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
40 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
42 /** Include accesslib.php */
43 require_once($CFG->libdir.'/accesslib.php');
44 /** Include formslib.php */
45 require_once($CFG->libdir.'/formslib.php');
46 /** Include repository/lib.php */
47 require_once($CFG->dirroot . '/repository/lib.php');
48 /** Include local mod_form.php */
49 require_once($CFG->dirroot.'/mod/assign/mod_form.php');
51 require_once($CFG->libdir.'/gradelib.php');
52 /** grading lib.php */
53 require_once($CFG->dirroot.'/grade/grading/lib.php');
54 /** Include feedbackplugin.php */
55 require_once($CFG->dirroot.'/mod/assign/feedbackplugin.php');
56 /** Include submissionplugin.php */
57 require_once($CFG->dirroot.'/mod/assign/submissionplugin.php');
58 /** Include renderable.php */
59 require_once($CFG->dirroot.'/mod/assign/renderable.php');
60 /** Include gradingtable.php */
61 require_once($CFG->dirroot.'/mod/assign/gradingtable.php');
62 /** Include eventslib.php */
63 require_once($CFG->libdir.'/eventslib.php');
64 /** Include portfolio caller.php */
65 require_once($CFG->libdir . '/portfolio/caller.php');
68 * Standard base class for mod_assign (assignment types).
71 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
72 * @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 (or just the course if we are
81 creating a new one) */
84 /** @var stdClass the course this assign instance belongs to */
87 /** @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 - only lives for a single
101 /** @var array list of the installed submission plugins */
102 private $submissionplugins;
104 /** @var array list of the installed feedback plugins */
105 private $feedbackplugins;
107 /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
108 private $returnaction = 'view';
110 /** @var array params to be used to return to this page */
111 private $returnparams = array();
113 /** @var string modulename prevents excessive calls to get_string */
114 private static $modulename = null;
116 /** @var string modulenameplural prevents excessive calls to get_string */
117 private static $modulenameplural = null;
120 * Constructor for the base assign class
122 * @param mixed $coursemodulecontext context|null the course module context (or the course context if the coursemodule has not been created yet)
123 * @param mixed $coursemodule the current course module if it was already loaded - otherwise this class will load one from the context as required
124 * @param mixed $course the current course if it was already loaded - otherwise this class will load one from the context as required
126 public function __construct($coursemodulecontext, $coursemodule, $course) {
129 $this->context = $coursemodulecontext;
130 $this->coursemodule = $coursemodule;
131 $this->course = $course;
132 $this->cache = array(); // temporary cache only lives for a single request - used to reduce db lookups
134 $this->submissionplugins = $this->load_plugins('assignsubmission');
135 $this->feedbackplugins = $this->load_plugins('assignfeedback');
139 * Set the action and parameters that can be used to return to the current page
141 * @param string $action The action for the current page
142 * @param array $params An array of name value pairs which form the parameters to return to the current page
145 public function register_return_link($action, $params) {
146 $this->returnaction = $action;
147 $this->returnparams = $params;
151 * Return an action that can be used to get back to the current page
152 * @return string action
154 public function get_return_action() {
155 return $this->returnaction;
159 * Based on the current assignment settings should we display the intro
160 * @return bool showintro
162 private function show_intro() {
163 if ($this->get_instance()->alwaysshowdescription ||
164 time() > $this->get_instance()->allowsubmissionsfromdate) {
171 * Return a list of parameters that can be used to get back to the current page
172 * @return array params
174 public function get_return_params() {
175 return $this->returnparams;
179 * Set the submitted form data
180 * @param stdClass $data The form data (instance)
182 public function set_instance(stdClass $data) {
183 $this->instance = $data;
188 * @param context $context The new context
190 public function set_context(context $context) {
191 $this->context = $context;
195 * Set the course data
196 * @param stdClass $course The course data
198 public function set_course(stdClass $course) {
199 $this->course = $course;
203 * get list of feedback plugins installed
206 public function get_feedback_plugins() {
207 return $this->feedbackplugins;
211 * get list of submission plugins installed
214 public function get_submission_plugins() {
215 return $this->submissionplugins;
219 * Is blind marking enabled and reveal identities not set yet?
223 public function is_blind_marking() {
224 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
228 * Does an assignment have submission(s) or grade(s) already?
232 public function has_submissions_or_grades() {
233 $allgrades = $this->count_grades();
234 $allsubmissions = $this->count_submissions();
235 if (($allgrades == 0) && ($allsubmissions == 0)) {
242 * get a specific submission plugin by its type
243 * @param string $subtype assignsubmission | assignfeedback
244 * @param string $type
245 * @return mixed assign_plugin|null
247 public function get_plugin_by_type($subtype, $type) {
248 $shortsubtype = substr($subtype, strlen('assign'));
249 $name = $shortsubtype . 'plugins';
250 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
253 $pluginlist = $this->$name;
254 foreach ($pluginlist as $plugin) {
255 if ($plugin->get_type() == $type) {
263 * Get a feedback plugin by type
264 * @param string $type - The type of plugin e.g comments
265 * @return mixed assign_feedback_plugin|null
267 public function get_feedback_plugin_by_type($type) {
268 return $this->get_plugin_by_type('assignfeedback', $type);
272 * Get a submission plugin by type
273 * @param string $type - The type of plugin e.g comments
274 * @return mixed assign_submission_plugin|null
276 public function get_submission_plugin_by_type($type) {
277 return $this->get_plugin_by_type('assignsubmission', $type);
281 * Load the plugins from the sub folders under subtype
282 * @param string $subtype - either submission or feedback
283 * @return array - The sorted list of plugins
285 private function load_plugins($subtype) {
289 $names = get_plugin_list($subtype);
291 foreach ($names as $name => $path) {
292 if (file_exists($path . '/locallib.php')) {
293 require_once($path . '/locallib.php');
295 $shortsubtype = substr($subtype, strlen('assign'));
296 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
298 $plugin = new $pluginclass($this, $name);
300 if ($plugin instanceof assign_plugin) {
301 $idx = $plugin->get_sort_order();
302 while (array_key_exists($idx, $result)) $idx +=1;
303 $result[$idx] = $plugin;
312 * Display the assignment, used by view.php
314 * The assignment is displayed differently depending on your role,
315 * the settings for the assignment and the status of the assignment.
316 * @param string $action The current action if any.
319 public function view($action='') {
325 // Handle form submissions first.
326 if ($action == 'savesubmission') {
327 $action = 'editsubmission';
328 if ($this->process_save_submission($mform, $notices)) {
331 } else if ($action == 'lock') {
332 $this->process_lock();
334 } else if ($action == 'reverttodraft') {
335 $this->process_revert_to_draft();
337 } else if ($action == 'unlock') {
338 $this->process_unlock();
340 } else if ($action == 'confirmsubmit') {
342 if ($this->process_submit_for_grading($mform)) {
345 } else if ($action == 'gradingbatchoperation') {
346 $action = $this->process_grading_batch_operation($mform);
347 } else if ($action == 'submitgrade') {
348 if (optional_param('saveandshownext', null, PARAM_RAW)) {
351 if ($this->process_save_grade($mform)) {
352 $action = 'nextgrade';
354 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
355 $action = 'previousgrade';
356 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
358 $action = 'nextgrade';
359 } else if (optional_param('savegrade', null, PARAM_RAW)) {
360 //save changes button
362 if ($this->process_save_grade($mform)) {
369 } else if ($action == 'quickgrade') {
370 $message = $this->process_save_quick_grades();
371 $action = 'quickgradingresult';
372 } else if ($action == 'saveoptions') {
373 $this->process_save_grading_options();
375 } else if ($action == 'saveextension') {
376 $action = 'grantextension';
377 if ($this->process_save_extension($mform)) {
380 } else if ($action == 'revealidentitiesconfirm') {
381 $this->process_reveal_identities();
385 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
386 $this->register_return_link($action, $returnparams);
388 // Now show the right view page.
389 if ($action == 'previousgrade') {
391 $o .= $this->view_single_grade_page($mform, -1);
392 } else if ($action == 'quickgradingresult') {
394 $o .= $this->view_quickgrading_result($message);
395 } else if ($action == 'nextgrade') {
397 $o .= $this->view_single_grade_page($mform, 1);
398 } else if ($action == 'grade') {
399 $o .= $this->view_single_grade_page($mform);
400 } else if ($action == 'viewpluginassignfeedback') {
401 $o .= $this->view_plugin_content('assignfeedback');
402 } else if ($action == 'viewpluginassignsubmission') {
403 $o .= $this->view_plugin_content('assignsubmission');
404 } else if ($action == 'editsubmission') {
405 $o .= $this->view_edit_submission_page($mform, $notices);
406 } else if ($action == 'grading') {
407 $o .= $this->view_grading_page();
408 } else if ($action == 'downloadall') {
409 $o .= $this->download_submissions();
410 } else if ($action == 'submit') {
411 $o .= $this->check_submit_for_grading($mform);
412 } else if ($action == 'grantextension') {
413 $o .= $this->view_grant_extension($mform);
414 } else if ($action == 'revealidentities') {
415 $o .= $this->view_reveal_identities_confirm($mform);
416 } else if ($action == 'plugingradingbatchoperation') {
417 $o .= $this->view_plugin_grading_batch_operation($mform);
418 } else if ($action == 'viewpluginpage') {
419 $o .= $this->view_plugin_page();
420 } else if ($action == 'viewcourseindex') {
421 $o .= $this->view_course_index();
423 $o .= $this->view_submission_page();
431 * Add this instance to the database
433 * @param stdClass $formdata The data submitted from the form
434 * @param bool $callplugins This is used to skip the plugin code
435 * when upgrading an old assignment to a new one (the plugins get called manually)
436 * @return mixed false if an error occurs or the int id of the new instance
438 public function add_instance(stdClass $formdata, $callplugins) {
443 // add the database record
444 $update = new stdClass();
445 $update->name = $formdata->name;
446 $update->timemodified = time();
447 $update->timecreated = time();
448 $update->course = $formdata->course;
449 $update->courseid = $formdata->course;
450 $update->intro = $formdata->intro;
451 $update->introformat = $formdata->introformat;
452 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
453 $update->submissiondrafts = $formdata->submissiondrafts;
454 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
455 $update->sendnotifications = $formdata->sendnotifications;
456 $update->sendlatenotifications = $formdata->sendlatenotifications;
457 $update->duedate = $formdata->duedate;
458 $update->cutoffdate = $formdata->cutoffdate;
459 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
460 $update->grade = $formdata->grade;
461 $update->completionsubmit = !empty($formdata->completionsubmit);
462 $update->teamsubmission = $formdata->teamsubmission;
463 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
464 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
465 $update->blindmarking = $formdata->blindmarking;
467 $returnid = $DB->insert_record('assign', $update);
468 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
469 // cache the course record
470 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
473 // call save_settings hook for submission plugins
474 foreach ($this->submissionplugins as $plugin) {
475 if (!$this->update_plugin_instance($plugin, $formdata)) {
476 print_error($plugin->get_error());
480 foreach ($this->feedbackplugins as $plugin) {
481 if (!$this->update_plugin_instance($plugin, $formdata)) {
482 print_error($plugin->get_error());
487 // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
488 // TODO: add event to the calendar
489 $this->update_calendar($formdata->coursemodule);
490 // TODO: add the item in the gradebook
491 $this->update_gradebook(false, $formdata->coursemodule);
495 $update = new stdClass();
496 $update->id = $this->get_instance()->id;
497 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
498 $DB->update_record('assign', $update);
504 * Delete all grades from the gradebook for this assignment
508 private function delete_grades() {
511 return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
515 * Delete this instance from the database
517 * @return bool false if an error occurs
519 public function delete_instance() {
523 foreach ($this->submissionplugins as $plugin) {
524 if (!$plugin->delete_instance()) {
525 print_error($plugin->get_error());
529 foreach ($this->feedbackplugins as $plugin) {
530 if (!$plugin->delete_instance()) {
531 print_error($plugin->get_error());
536 // delete files associated with this assignment
537 $fs = get_file_storage();
538 if (! $fs->delete_area_files($this->context->id) ) {
542 // delete_records will throw an exception if it fails - so no need for error checking here
544 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
545 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
546 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
548 // delete items from the gradebook
549 if (! $this->delete_grades()) {
553 // delete the instance
554 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
560 * Actual implementation of the reset course functionality, delete all the
561 * assignment submissions for course $data->courseid.
563 * @param $data the data submitted from the reset course.
564 * @return array status array
566 public function reset_userdata($data) {
569 $componentstr = get_string('modulenameplural', 'assign');
572 $fs = get_file_storage();
573 if (!empty($data->reset_assign_submissions)) {
574 // Delete files associated with this assignment.
575 foreach ($this->submissionplugins as $plugin) {
576 $fileareas = array();
577 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
578 $fileareas = $plugin->get_file_areas();
579 foreach ($fileareas as $filearea) {
580 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
583 if (!$plugin->delete_instance()) {
584 $status[] = array('component'=>$componentstr,
585 'item'=>get_string('deleteallsubmissions','assign'),
586 'error'=>$plugin->get_error());
590 foreach ($this->feedbackplugins as $plugin) {
591 $fileareas = array();
592 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
593 $fileareas = $plugin->get_file_areas();
594 foreach ($fileareas as $filearea) {
595 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
598 if (!$plugin->delete_instance()) {
599 $status[] = array('component'=>$componentstr,
600 'item'=>get_string('deleteallsubmissions','assign'),
601 'error'=>$plugin->get_error());
605 $assignssql = "SELECT a.id
607 WHERE a.course=:course";
608 $params = array ("course" => $data->courseid);
610 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
611 $status[] = array('component'=>$componentstr,
612 'item'=>get_string('deleteallsubmissions','assign'),
615 if (empty($data->reset_gradebook_grades)) {
616 // Remove all grades from gradebook.
617 require_once($CFG->dirroot.'/mod/assign/lib.php');
618 assign_reset_gradebook($data->courseid);
621 // Updating dates - shift may be negative too.
622 if ($data->timeshift) {
623 shift_course_mod_dates('assign',
624 array('duedate', 'allowsubmissionsfromdate','cutoffdate'),
627 $status[] = array('component'=>$componentstr,
628 'item'=>get_string('datechanged'),
636 * Update the settings for a single plugin
638 * @param assign_plugin $plugin The plugin to update
639 * @param stdClass $formdata The form data
640 * @return bool false if an error occurs
642 private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
643 if ($plugin->is_visible()) {
644 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
645 if ($formdata->$enabledname) {
647 if (!$plugin->save_settings($formdata)) {
648 print_error($plugin->get_error());
659 * Update the gradebook information for this assignment
661 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
662 * @param int $coursemoduleid This is required because it might not exist in the database yet
665 public function update_gradebook($reset, $coursemoduleid) {
667 /** Include lib.php */
668 require_once($CFG->dirroot.'/mod/assign/lib.php');
669 $assign = clone $this->get_instance();
670 $assign->cmidnumber = $coursemoduleid;
676 return assign_grade_item_update($assign, $param);
679 /** Load and cache the admin config for this module
681 * @return stdClass the plugin config
683 public function get_admin_config() {
684 if ($this->adminconfig) {
685 return $this->adminconfig;
687 $this->adminconfig = get_config('assign');
688 return $this->adminconfig;
693 * Update the calendar entries for this assignment
695 * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
698 public function update_calendar($coursemoduleid) {
700 require_once($CFG->dirroot.'/calendar/lib.php');
702 // special case for add_instance as the coursemodule has not been set yet.
704 if ($this->get_instance()->duedate) {
705 $event = new stdClass();
707 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
709 $event->name = $this->get_instance()->name;
711 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
712 $event->timestart = $this->get_instance()->duedate;
714 $calendarevent = calendar_event::load($event->id);
715 $calendarevent->update($event);
717 $event = new stdClass();
718 $event->name = $this->get_instance()->name;
719 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
720 $event->courseid = $this->get_instance()->course;
723 $event->modulename = 'assign';
724 $event->instance = $this->get_instance()->id;
725 $event->eventtype = 'due';
726 $event->timestart = $this->get_instance()->duedate;
727 $event->timeduration = 0;
729 calendar_event::create($event);
732 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
738 * Update this instance in the database
740 * @param stdClass $formdata - the data submitted from the form
741 * @return bool false if an error occurs
743 public function update_instance($formdata) {
746 $update = new stdClass();
747 $update->id = $formdata->instance;
748 $update->name = $formdata->name;
749 $update->timemodified = time();
750 $update->course = $formdata->course;
751 $update->intro = $formdata->intro;
752 $update->introformat = $formdata->introformat;
753 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
754 $update->submissiondrafts = $formdata->submissiondrafts;
755 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
756 $update->sendnotifications = $formdata->sendnotifications;
757 $update->sendlatenotifications = $formdata->sendlatenotifications;
758 $update->duedate = $formdata->duedate;
759 $update->cutoffdate = $formdata->cutoffdate;
760 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
761 $update->grade = $formdata->grade;
762 $update->completionsubmit = !empty($formdata->completionsubmit);
763 $update->teamsubmission = $formdata->teamsubmission;
764 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
765 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
766 $update->blindmarking = $formdata->blindmarking;
768 $result = $DB->update_record('assign', $update);
769 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
771 // load the assignment so the plugins have access to it
773 // call save_settings hook for submission plugins
774 foreach ($this->submissionplugins as $plugin) {
775 if (!$this->update_plugin_instance($plugin, $formdata)) {
776 print_error($plugin->get_error());
780 foreach ($this->feedbackplugins as $plugin) {
781 if (!$this->update_plugin_instance($plugin, $formdata)) {
782 print_error($plugin->get_error());
788 // update the database record
791 // update all the calendar events
792 $this->update_calendar($this->get_course_module()->id);
794 $this->update_gradebook(false, $this->get_course_module()->id);
796 $update = new stdClass();
797 $update->id = $this->get_instance()->id;
798 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
799 $DB->update_record('assign', $update);
809 * add elements in grading plugin form
811 * @param mixed $grade stdClass|null
812 * @param MoodleQuickForm $mform
813 * @param stdClass $data
814 * @param int $userid - The userid we are grading
817 private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
818 foreach ($this->feedbackplugins as $plugin) {
819 if ($plugin->is_enabled() && $plugin->is_visible()) {
820 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
821 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
822 $mform->removeElement('header_' . $plugin->get_type());
831 * Add one plugins settings to edit plugin form
833 * @param assign_plugin $plugin The plugin to add the settings from
834 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
837 private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
839 if ($plugin->is_visible()) {
841 //tied disableIf rule to this select element
842 $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
843 $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
846 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
847 if ($plugin->get_config('enabled') !== false) {
848 $default = $plugin->is_enabled();
850 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
852 $plugin->get_settings($mform);
860 * Add settings to edit plugin form
862 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
865 public function add_all_plugin_settings(MoodleQuickForm $mform) {
866 $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
868 foreach ($this->submissionplugins as $plugin) {
869 $this->add_plugin_settings($plugin, $mform);
872 $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
873 foreach ($this->feedbackplugins as $plugin) {
874 $this->add_plugin_settings($plugin, $mform);
879 * Allow each plugin an opportunity to update the defaultvalues
880 * passed in to the settings form (needed to set up draft areas for
881 * editor and filemanager elements)
882 * @param array $defaultvalues
884 public function plugin_data_preprocessing(&$defaultvalues) {
885 foreach ($this->submissionplugins as $plugin) {
886 if ($plugin->is_visible()) {
887 $plugin->data_preprocessing($defaultvalues);
890 foreach ($this->feedbackplugins as $plugin) {
891 if ($plugin->is_visible()) {
892 $plugin->data_preprocessing($defaultvalues);
898 * Get the name of the current module.
900 * @return string the module name (Assignment)
902 protected function get_module_name() {
903 if (isset(self::$modulename)) {
904 return self::$modulename;
906 self::$modulename = get_string('modulename', 'assign');
907 return self::$modulename;
911 * Get the plural name of the current module.
913 * @return string the module name plural (Assignments)
915 protected function get_module_name_plural() {
916 if (isset(self::$modulenameplural)) {
917 return self::$modulenameplural;
919 self::$modulenameplural = get_string('modulenameplural', 'assign');
920 return self::$modulenameplural;
924 * Has this assignment been constructed from an instance?
928 public function has_instance() {
929 return $this->instance || $this->get_course_module();
933 * Get the settings for the current instance of this assignment
935 * @return stdClass The settings
937 public function get_instance() {
939 if ($this->instance) {
940 return $this->instance;
942 if ($this->get_course_module()) {
943 $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
945 if (!$this->instance) {
946 throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
948 return $this->instance;
952 * Get the context of the current course
953 * @return mixed context|null The course context
955 public function get_course_context() {
956 if (!$this->context && !$this->course) {
957 throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
959 if ($this->context) {
960 return $this->context->get_course_context();
962 return context_course::instance($this->course->id);
968 * Get the current course module
970 * @return mixed stdClass|null The course module
972 public function get_course_module() {
973 if ($this->coursemodule) {
974 return $this->coursemodule;
976 if (!$this->context) {
980 if ($this->context->contextlevel == CONTEXT_MODULE) {
981 $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
982 return $this->coursemodule;
992 public function get_context() {
993 return $this->context;
997 * Get the current course
998 * @return mixed stdClass|null The course
1000 public function get_course() {
1002 if ($this->course) {
1003 return $this->course;
1006 if (!$this->context) {
1009 $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
1010 return $this->course;
1014 * Return a grade in user-friendly form, whether it's a scale or not
1016 * @param mixed $grade int|null
1017 * @param boolean $editing Are we allowing changes to this grade?
1018 * @param int $userid The user id the grade belongs to
1019 * @param int $modified Timestamp from when the grade was last modified
1020 * @return string User-friendly representation of grade
1022 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1025 static $scalegrades = array();
1029 if ($this->get_instance()->grade >= 0) {
1031 if ($editing && $this->get_instance()->grade > 0) {
1035 $displaygrade = format_float($grade);
1037 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' . get_string('usergrade', 'assign') . '</label>';
1038 $o .= '<input type="text" id="quickgrade_' . $userid . '" name="quickgrade_' . $userid . '" value="' .
1039 $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
1040 $o .= ' / ' . format_float($this->get_instance()->grade,2);
1041 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1044 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1045 if ($grade == -1 || $grade === null) {
1049 $o .= format_float(($grade),2) .' / '. format_float($this->get_instance()->grade,2);
1056 if (empty($this->cache['scale'])) {
1057 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1058 $this->cache['scale'] = make_menu_from_list($scale->scale);
1065 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' . get_string('usergrade', 'assign') . '</label>';
1066 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1067 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1068 foreach ($this->cache['scale'] as $optionid => $option) {
1070 if ($grade == $optionid) {
1071 $selected = 'selected="selected"';
1073 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1076 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1079 $scaleid = (int)$grade;
1080 if (isset($this->cache['scale'][$scaleid])) {
1081 $o .= $this->cache['scale'][$scaleid];
1091 * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1093 * @param int $currentgroup
1094 * @param bool $idsonly
1095 * @return array List of user records
1097 public function list_participants($currentgroup, $idsonly) {
1099 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1101 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1106 * Load a count of valid teams for this assignment
1108 * @return int number of valid teams
1110 public function count_teams() {
1112 $groups = groups_get_all_groups($this->get_course()->id, 0, $this->get_instance()->teamsubmissiongroupingid, 'g.id');
1113 $count = count($groups);
1115 // See if there are any users in the default group.
1116 $defaultusers = $this->get_submission_group_members(0, true);
1117 if (count($defaultusers) > 0) {
1124 * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1126 * @param int $currentgroup
1127 * @return int number of matching users
1129 public function count_participants($currentgroup) {
1130 return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1134 * Load a count of users submissions in the current module that require grading
1135 * This means the submission modification time is more recent than the
1136 * grading modification time and the status is SUBMITTED.
1138 * @return int number of matching submissions
1140 public function count_submissions_need_grading() {
1143 if ($this->get_instance()->teamsubmission) {
1144 // This does not make sense for group assignment because the submission is shared.
1148 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1149 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1151 $params['assignid'] = $this->get_instance()->id;
1152 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1154 $sql = 'SELECT COUNT(s.userid)
1155 FROM {assign_submission} s
1156 LEFT JOIN {assign_grades} g ON
1157 s.assignment = g.assignment AND
1159 JOIN(' . $esql . ') e ON e.id = s.userid
1161 s.assignment = :assignid AND
1162 s.timemodified IS NOT NULL AND
1163 s.status = :submitted AND
1164 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1166 return $DB->count_records_sql($sql, $params);
1170 * Load a count of grades
1172 * @return int number of grades
1174 public function count_grades() {
1177 if (!$this->has_instance()) {
1181 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1182 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1184 $params['assignid'] = $this->get_instance()->id;
1186 $sql = 'SELECT COUNT(g.userid)
1187 FROM {assign_grades} g
1188 JOIN(' . $esql . ') e ON e.id = g.userid
1189 WHERE g.assignment = :assignid';
1191 return $DB->count_records_sql($sql, $params);
1195 * Load a count of submissions
1197 * @return int number of submissions
1199 public function count_submissions() {
1202 if (!$this->has_instance()) {
1208 if ($this->get_instance()->teamsubmission) {
1209 // We cannot join on the enrolment tables for group submissions (no userid).
1210 $sql = 'SELECT COUNT(s.groupid)
1211 FROM {assign_submission} s
1213 s.assignment = :assignid AND
1214 s.timemodified IS NOT NULL AND
1215 s.userid = :groupuserid';
1217 $params['assignid'] = $this->get_instance()->id;
1218 $params['groupuserid'] = 0;
1220 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1221 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1223 $params['assignid'] = $this->get_instance()->id;
1225 $sql = 'SELECT COUNT(s.userid)
1226 FROM {assign_submission} s
1227 JOIN(' . $esql . ') e ON e.id = s.userid
1229 s.assignment = :assignid AND
1230 s.timemodified IS NOT NULL';
1233 return $DB->count_records_sql($sql, $params);
1237 * Load a count of submissions with a specified status
1239 * @param string $status The submission status - should match one of the constants
1240 * @return int number of matching submissions
1242 public function count_submissions_with_status($status) {
1245 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1246 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1248 $params['assignid'] = $this->get_instance()->id;
1249 $params['submissionstatus'] = $status;
1251 if ($this->get_instance()->teamsubmission) {
1252 $sql = 'SELECT COUNT(s.groupid)
1253 FROM {assign_submission} s
1255 s.assignment = :assignid AND
1256 s.timemodified IS NOT NULL AND
1257 s.userid = :groupuserid AND
1258 s.status = :submissionstatus';
1259 $params['groupuserid'] = 0;
1261 $sql = 'SELECT COUNT(s.userid)
1262 FROM {assign_submission} s
1263 JOIN(' . $esql . ') e ON e.id = s.userid
1265 s.assignment = :assignid AND
1266 s.timemodified IS NOT NULL AND
1267 s.status = :submissionstatus';
1270 return $DB->count_records_sql($sql, $params);
1274 * Utility function to get the userid for every row in the grading table
1275 * so the order can be frozen while we iterate it
1277 * @return array An array of userids
1279 private function get_grading_userid_list() {
1280 $filter = get_user_preferences('assign_filter', '');
1281 $table = new assign_grading_table($this, 0, $filter, 0, false);
1283 $useridlist = $table->get_column_data('userid');
1290 * Utility function get the userid based on the row number of the grading table.
1291 * This takes into account any active filters on the table.
1293 * @param int $num The row number of the user
1294 * @param bool $last This is set to true if this is the last user in the table
1295 * @return mixed The user id of the matching user or false if there was an error
1297 private function get_userid_for_row($num, $last) {
1298 if (!array_key_exists('userid_for_row', $this->cache)) {
1299 $this->cache['userid_for_row'] = array();
1301 if (array_key_exists($num, $this->cache['userid_for_row'])) {
1302 list($userid, $last) = $this->cache['userid_for_row'][$num];
1306 $filter = get_user_preferences('assign_filter', '');
1307 $table = new assign_grading_table($this, 0, $filter, 0, false);
1309 $userid = $table->get_cell_data($num, 'userid', $last);
1311 $this->cache['userid_for_row'][$num] = array($userid, $last);
1316 * Generate zip file from array of given files
1318 * @param array $filesforzipping - array of files to pass into archive_to_pathname - this array is indexed by the final file name and each element in the array is an instance of a stored_file object
1319 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1321 private function pack_files($filesforzipping) {
1323 //create path for new zip file.
1324 $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1326 $zipper = new zip_packer();
1327 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1334 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1336 * Cron function to be run periodically according to the moodle cron
1340 static function cron() {
1343 // only ever send a max of one days worth of updates
1344 $yesterday = time() - (24 * 3600);
1347 // Collect all submissions from the past 24 hours that require mailing.
1348 $sql = "SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
1349 g.*, g.id as gradeid, g.timemodified as lastmodified
1351 JOIN {assign_grades} g ON g.assignment = a.id
1352 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1353 WHERE g.timemodified >= :yesterday AND
1354 g.timemodified <= :today AND
1356 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1357 $submissions = $DB->get_records_sql($sql, $params);
1359 if (empty($submissions)) {
1364 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1366 // Preload courses we are going to need those.
1367 $courseids = array();
1368 foreach ($submissions as $submission) {
1369 $courseids[] = $submission->course;
1371 // Filter out duplicates
1372 $courseids = array_unique($courseids);
1373 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1374 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1375 $sql = "SELECT c.*, {$ctxselect}
1377 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1378 WHERE c.id {$courseidsql}";
1379 $params['contextlevel'] = CONTEXT_COURSE;
1380 $courses = $DB->get_records_sql($sql, $params);
1381 // Clean up... this could go on for a while.
1384 unset($courseidsql);
1387 // Simple array we'll use for caching modules.
1388 $modcache = array();
1390 // Message students about new feedback
1391 foreach ($submissions as $submission) {
1393 mtrace("Processing assignment submission $submission->id ...");
1395 // do not cache user lookups - could be too many
1396 if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
1397 mtrace("Could not find user $submission->userid");
1401 // use a cache to prevent the same DB queries happening over and over
1402 if (!array_key_exists($submission->course, $courses)) {
1403 mtrace("Could not find course $submission->course");
1406 $course = $courses[$submission->course];
1407 if (isset($course->ctxid)) {
1408 // Context has not yet been preloaded. Do so now.
1409 context_helper::preload_from_record($course);
1412 // Override the language and timezone of the "current" user, so that
1413 // mail is customised for the receiver.
1414 cron_setup_user($user, $course);
1416 // context lookups are already cached
1417 $coursecontext = context_course::instance($course->id);
1418 if (!is_enrolled($coursecontext, $user->id)) {
1419 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1420 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1424 if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1425 mtrace("Could not find grader $submission->grader");
1429 if (!array_key_exists($submission->assignment, $modcache)) {
1430 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1431 mtrace("Could not find course module for assignment id $submission->assignment");
1434 $modcache[$submission->assignment] = $mod;
1436 $mod = $modcache[$submission->assignment];
1438 // context lookups are already cached
1439 $contextmodule = context_module::instance($mod->id);
1441 if (!$mod->visible) {
1442 // Hold mail notification for hidden assignments until later
1446 // need to send this to the student
1447 $messagetype = 'feedbackavailable';
1448 $eventtype = 'assign_notification';
1449 $updatetime = $submission->lastmodified;
1450 $modulename = get_string('modulename', 'assign');
1453 if ($submission->blindmarking && !$submission->revealidentities) {
1454 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1456 self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime,
1457 $mod, $contextmodule, $course, $modulename, $submission->name,
1458 $submission->blindmarking && !$submission->revealidentities,
1461 $grade = new stdClass();
1462 $grade->id = $submission->gradeid;
1464 $DB->update_record('assign_grades', $grade);
1468 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1472 // Free up memory just to be sure
1480 * Update a grade in the grade table for the assignment and in the gradebook
1482 * @param stdClass $grade a grade record keyed on id
1483 * @return bool true for success
1485 public function update_grade($grade) {
1488 $grade->timemodified = time();
1490 if ($grade->grade && $grade->grade != -1) {
1491 if ($this->get_instance()->grade > 0) {
1492 if (!is_numeric($grade->grade)) {
1494 } else if ($grade->grade > $this->get_instance()->grade) {
1496 } else if ($grade->grade < 0) {
1501 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1502 $scaleoptions = make_menu_from_list($scale->scale);
1503 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1510 $result = $DB->update_record('assign_grades', $grade);
1512 $this->gradebook_item_update(null, $grade);
1518 * View the grant extension date page
1520 * Uses url parameters 'userid'
1521 * or from parameter 'selectedusers'
1522 * @param moodleform $mform - Used for validation of the submitted data
1525 private function view_grant_extension($mform) {
1527 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1530 $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
1531 $data = new stdClass();
1532 $data->extensionduedate = null;
1535 $userid = required_param('userid', PARAM_INT);
1537 $grade = $this->get_user_grade($userid, false);
1539 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1542 $data->extensionduedate = $grade->extensionduedate;
1544 $data->userid = $userid;
1546 $data->batchusers = $batchusers;
1548 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1549 $this->get_context(),
1550 $this->show_intro(),
1551 $this->get_course_module()->id,
1552 get_string('grantextension', 'assign')));
1555 $mform = new mod_assign_extension_form(null, array($this->get_course_module()->id,
1558 $this->get_instance(),
1561 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1562 $o .= $this->view_footer();
1567 * Get a list of the users in the same group as this user
1569 * @param int $groupid The id of the group whose members we want or 0 for the default group
1570 * @param bool $onlyids Whether to retrieve only the user id's
1571 * @return array The users (possibly id's only)
1573 public function get_submission_group_members($groupid, $onlyids) {
1575 if ($groupid != 0) {
1577 $allusers = groups_get_members($groupid, 'u.id');
1579 $allusers = groups_get_members($groupid);
1581 foreach ($allusers as $user) {
1582 if ($this->get_submission_group($user->id)) {
1587 $allusers = $this->list_participants(null, $onlyids);
1588 foreach ($allusers as $user) {
1589 if ($this->get_submission_group($user->id) == null) {
1598 * Get a list of the users in the same group as this user that have not submitted the assignment
1600 * @param int $groupid The id of the group whose members we want or 0 for the default group
1601 * @param bool $onlyids Whether to retrieve only the user id's
1602 * @return array The users (possibly id's only)
1604 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1605 if (!$this->get_instance()->teamsubmission || !$this->get_instance()->requireallteammemberssubmit) {
1608 $members = $this->get_submission_group_members($groupid, $onlyids);
1610 foreach ($members as $id => $member) {
1611 $submission = $this->get_user_submission($member->id, false);
1612 if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
1613 unset($members[$id]);
1615 if ($this->is_blind_marking()) {
1616 $members[$id]->alias = get_string('hiddenuser', 'assign') . $this->get_uniqueid_for_user($id);
1624 * Load the group submission object for a particular user, optionally creating it if required
1626 * This will create the user submission and the group submission if required
1628 * @param int $userid The id of the user whose submission we want
1629 * @param int $groupid The id of the group for this user - may be 0 in which case it is determined from the userid
1630 * @param bool $create If set to true a new submission object will be created in the database
1631 * @return stdClass The submission
1633 public function get_group_submission($userid, $groupid, $create) {
1636 if ($groupid == 0) {
1637 $group = $this->get_submission_group($userid);
1639 $groupid = $group->id;
1644 // Make sure there is a submission for this user.
1645 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
1646 $submission = $DB->get_record('assign_submission', $params);
1649 $submission = new stdClass();
1650 $submission->assignment = $this->get_instance()->id;
1651 $submission->userid = $userid;
1652 $submission->groupid = 0;
1653 $submission->timecreated = time();
1654 $submission->timemodified = $submission->timecreated;
1656 if ($this->get_instance()->submissiondrafts) {
1657 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1659 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1661 $DB->insert_record('assign_submission', $submission);
1664 // Now get the group submission.
1665 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1666 $submission = $DB->get_record('assign_submission', $params);
1672 $submission = new stdClass();
1673 $submission->assignment = $this->get_instance()->id;
1674 $submission->userid = 0;
1675 $submission->groupid = $groupid;
1676 $submission->timecreated = time();
1677 $submission->timemodified = $submission->timecreated;
1679 if ($this->get_instance()->submissiondrafts) {
1680 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1682 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1684 $sid = $DB->insert_record('assign_submission', $submission);
1685 $submission->id = $sid;
1692 * View a summary listing of all assignments in the current course.
1696 private function view_course_index() {
1701 $course = $this->get_course();
1702 $strplural = get_string('modulenameplural', 'assign');
1704 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1705 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1706 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1710 $strsectionname = get_string('sectionname', 'format_'.$course->format);
1711 $usesections = course_format_uses_sections($course->format);
1712 $modinfo = get_fast_modinfo($course);
1715 $sections = $modinfo->get_section_info_all();
1717 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1721 $currentsection = '';
1722 foreach ($modinfo->instances['assign'] as $cm) {
1723 if (!$cm->uservisible) {
1727 $timedue = $cms[$cm->id]->duedate;
1730 if ($usesections && $cm->sectionnum) {
1731 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1735 $context = context_module::instance($cm->id);
1737 $assignment = new assign($context, $cm, $course);
1739 if (has_capability('mod/assign:grade', $context)) {
1740 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1742 } else if (has_capability('mod/assign:submit', $context)) {
1743 $usersubmission = $assignment->get_user_submission($USER->id, false);
1745 if (!empty($usersubmission->status)) {
1746 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1748 $submitted = get_string('submissionstatus_', 'assign');
1751 $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1752 if (isset($grading_info->items[0]) && !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1753 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1758 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
1762 $o .= $this->get_renderer()->render($courseindexsummary);
1763 $o .= $this->view_footer();
1769 * View a page rendered by a plugin.
1771 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'
1775 private function view_plugin_page() {
1780 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
1781 $plugintype = required_param('plugin', PARAM_TEXT);
1782 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
1784 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
1786 print_error('invalidformdata', '');
1790 $o .= $plugin->view_page($pluginaction);
1797 * This is used for team assignments to get the group for the specified user.
1798 * If the user is a member of multiple or no groups this will return false
1800 * @param int $userid The id of the user whose submission we want
1801 * @return mixed The group or false
1803 public function get_submission_group($userid) {
1804 $groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_instance()->teamsubmissiongroupingid);
1805 if (count($groups) != 1) {
1808 return array_pop($groups);
1813 * display the submission that is used by a plugin
1814 * Uses url parameters 'sid', 'gid' and 'plugin'
1815 * @param string $pluginsubtype
1818 private function view_plugin_content($pluginsubtype) {
1823 $submissionid = optional_param('sid', 0, PARAM_INT);
1824 $gradeid = optional_param('gid', 0, PARAM_INT);
1825 $plugintype = required_param('plugin', PARAM_TEXT);
1827 if ($pluginsubtype == 'assignsubmission') {
1828 $plugin = $this->get_submission_plugin_by_type($plugintype);
1829 if ($submissionid <= 0) {
1830 throw new coding_exception('Submission id should not be 0');
1832 $item = $this->get_submission($submissionid);
1835 if ($item->userid != $USER->id) {
1836 require_capability('mod/assign:grade', $this->context);
1838 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1839 $this->get_context(),
1840 $this->show_intro(),
1841 $this->get_course_module()->id,
1842 $plugin->get_name()));
1843 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
1845 assign_submission_plugin_submission::FULL,
1846 $this->get_course_module()->id,
1847 $this->get_return_action(),
1848 $this->get_return_params()));
1850 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1852 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1853 if ($gradeid <= 0) {
1854 throw new coding_exception('Grade id should not be 0');
1856 $item = $this->get_grade($gradeid);
1858 if ($item->userid != $USER->id) {
1859 require_capability('mod/assign:grade', $this->context);
1861 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1862 $this->get_context(),
1863 $this->show_intro(),
1864 $this->get_course_module()->id,
1865 $plugin->get_name()));
1866 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
1868 assign_feedback_plugin_feedback::FULL,
1869 $this->get_course_module()->id,
1870 $this->get_return_action(),
1871 $this->get_return_params()));
1872 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1876 $o .= $this->view_return_links();
1878 $o .= $this->view_footer();
1883 * Rewrite plugin file urls so they resolve correctly in an exported zip.
1885 * @param stdClass $user - The user record
1886 * @param assign_plugin $plugin - The assignment plugin
1888 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
1889 $groupmode = groups_get_activity_groupmode($this->get_course_module());
1892 $groupid = groups_get_activity_group($this->get_course_module(), true);
1893 $groupname = groups_get_group_name($groupid).'-';
1896 if ($this->is_blind_marking()) {
1897 $prefix = $groupname . get_string('participant', 'assign');
1898 $prefix = str_replace('_', ' ', $prefix);
1899 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
1901 $prefix = $groupname . fullname($user);
1902 $prefix = str_replace('_', ' ', $prefix);
1903 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
1906 $subtype = $plugin->get_subtype();
1907 $type = $plugin->get_type();
1908 $prefix = $prefix . $subtype . '_' . $type . '_';
1910 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
1916 * render the content in editor that is often used by plugin
1918 * @param string $filearea
1919 * @param int $submissionid
1920 * @param string $plugintype
1921 * @param string $editor
1922 * @param string $component
1925 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1930 $plugin = $this->get_submission_plugin_by_type($plugintype);
1932 $text = $plugin->get_editor_text($editor, $submissionid);
1933 $format = $plugin->get_editor_format($editor, $submissionid);
1935 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1936 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1940 if ($CFG->enableportfolios) {
1941 require_once($CFG->libdir . '/portfoliolib.php');
1943 $button = new portfolio_add_button();
1944 $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id,
1945 'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea),
1947 $fs = get_file_storage();
1949 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1950 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1952 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1954 $result .= $button->to_html();
1960 * Display a grading error
1962 * @param string $message - The description of the result
1965 private function view_quickgrading_result($message) {
1967 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1968 $this->get_context(),
1969 $this->show_intro(),
1970 $this->get_course_module()->id,
1971 get_string('quickgradingresult', 'assign')));
1972 $o .= $this->get_renderer()->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1973 $o .= $this->view_footer();
1978 * Display the page footer
1982 private function view_footer() {
1983 return $this->get_renderer()->render_footer();
1987 * Does this user have grade permission for this assignment
1991 private function can_grade() {
1992 // Permissions check
1993 if (!has_capability('mod/assign:grade', $this->context)) {
2001 * Download a zip file of all assignment submissions
2005 private function download_submissions() {
2008 // More efficient to load this here.
2009 require_once($CFG->libdir.'/filelib.php');
2011 // Load all users with submit.
2012 $students = get_enrolled_users($this->context, "mod/assign:submit");
2014 // Build a list of files to zip.
2015 $filesforzipping = array();
2016 $fs = get_file_storage();
2018 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2023 $groupid = groups_get_activity_group($this->get_course_module(), true);
2024 $groupname = groups_get_group_name($groupid).'-';
2027 // Construct the zip file name.
2028 $filename = clean_filename($this->get_course()->shortname.'-'.
2029 $this->get_instance()->name.'-'.
2030 $groupname.$this->get_course_module()->id.".zip");
2032 // Get all the files for each student.
2033 foreach ($students as $student) {
2034 $userid = $student->id;
2036 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2037 // Get the plugins to add their own files to the zip.
2039 $submissiongroup = false;
2041 if ($this->get_instance()->teamsubmission) {
2042 $submission = $this->get_group_submission($userid, 0, false);
2043 $submissiongroup = $this->get_submission_group($userid);
2044 if ($submissiongroup) {
2045 $groupname = $submissiongroup->name . '-';
2047 $groupname = get_string('defaultteam', 'assign') . '-';
2050 $submission = $this->get_user_submission($userid, false);
2053 if ($this->is_blind_marking()) {
2054 $prefix = clean_filename(str_replace('_', ' ', $groupname . get_string('participant', 'assign')) .
2055 "_" . $this->get_uniqueid_for_user($userid) . "_");
2057 $prefix = clean_filename(str_replace('_', ' ', $groupname . fullname($student)) .
2058 "_" . $this->get_uniqueid_for_user($userid) . "_");
2062 foreach ($this->submissionplugins as $plugin) {
2063 if ($plugin->is_enabled() && $plugin->is_visible()) {
2064 $pluginfiles = $plugin->get_files($submission, $student);
2065 foreach ($pluginfiles as $zipfilename => $file) {
2066 $subtype = $plugin->get_subtype();
2067 $type = $plugin->get_type();
2068 $prefixedfilename = $prefix . $subtype . '_' . $type . '_' . $zipfilename;
2069 $filesforzipping[$prefixedfilename] = $file;
2076 if ($zipfile = $this->pack_files($filesforzipping)) {
2077 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2078 // Send file and delete after sending.
2079 send_temp_file($zipfile, $filename);
2084 * Util function to add a message to the log
2086 * @param string $action The current action
2087 * @param string $info A detailed description of the change. But no more than 255 characters.
2088 * @param string $url The url to the assign module instance.
2091 public function add_to_log($action = '', $info = '', $url='') {
2094 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2096 $fullurl .= '&' . $url;
2099 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
2103 * Lazy load the page renderer and expose the renderer to plugins
2105 * @return assign_renderer
2107 public function get_renderer() {
2109 if ($this->output) {
2110 return $this->output;
2112 $this->output = $PAGE->get_renderer('mod_assign');
2113 return $this->output;
2117 * Load the submission object for a particular user, optionally creating it if required
2119 * For team assignments there are 2 submissions - the student submission and the team submission
2120 * All files are associated with the team submission but the status of the students contribution is
2121 * recorded separately.
2123 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2124 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
2125 * @return stdClass The submission
2127 public function get_user_submission($userid, $create) {
2131 $userid = $USER->id;
2133 // If the userid is not null then use userid.
2134 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2135 $submission = $DB->get_record('assign_submission', $params);
2141 $submission = new stdClass();
2142 $submission->assignment = $this->get_instance()->id;
2143 $submission->userid = $userid;
2144 $submission->timecreated = time();
2145 $submission->timemodified = $submission->timecreated;
2146 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2147 $sid = $DB->insert_record('assign_submission', $submission);
2148 $submission->id = $sid;
2155 * Load the submission object from it's id
2157 * @param int $submissionid The id of the submission we want
2158 * @return stdClass The submission
2160 private function get_submission($submissionid) {
2163 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
2167 * This will retrieve a grade object from the db, optionally creating it if required
2169 * @param int $userid The user we are grading
2170 * @param bool $create If true the grade will be created if it does not exist
2171 * @return stdClass The grade record
2173 public function get_user_grade($userid, $create) {
2177 $userid = $USER->id;
2180 // if the userid is not null then use userid
2181 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
2187 $grade = new stdClass();
2188 $grade->assignment = $this->get_instance()->id;
2189 $grade->userid = $userid;
2190 $grade->timecreated = time();
2191 $grade->timemodified = $grade->timecreated;
2194 $grade->grader = $USER->id;
2195 $grade->extensionduedate = 0;
2196 $gid = $DB->insert_record('assign_grades', $grade);
2204 * This will retrieve a grade object from the db
2206 * @param int $gradeid The id of the grade
2207 * @return stdClass The grade record
2209 private function get_grade($gradeid) {
2212 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
2216 * Print the grading page for a single user submission
2218 * @param moodleform $mform
2219 * @param int $offset
2222 private function view_single_grade_page($mform, $offset=0) {
2227 // Include grade form
2228 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2230 // Need submit permission to submit an assignment
2231 require_capability('mod/assign:grade', $this->context);
2233 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2234 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
2236 $rownum = required_param('rownum', PARAM_INT) + $offset;
2237 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
2239 $useridlist = explode(',', $useridlist);
2241 $useridlist = $this->get_grading_userid_list();
2244 $userid = $useridlist[$rownum];
2245 if ($rownum == count($useridlist) - 1) {
2249 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2251 $user = $DB->get_record('user', array('id' => $userid));
2253 $o .= $this->get_renderer()->render(new assign_user_summary($user,
2254 $this->get_course()->id,
2255 has_capability('moodle/site:viewfullnames',
2256 $this->get_course_context()),
2257 $this->is_blind_marking(),
2258 $this->get_uniqueid_for_user($user->id)));
2260 $submission = $this->get_user_submission($userid, false);
2261 $submissiongroup = null;
2262 $submissiongroupmemberswhohavenotsubmitted = array();
2263 $teamsubmission = null;
2264 $notsubmitted = array();
2265 if ($this->get_instance()->teamsubmission) {
2266 $teamsubmission = $this->get_group_submission($userid, 0, false);
2267 $submissiongroup = $this->get_submission_group($userid);
2269 if ($submissiongroup) {
2270 $groupid = $submissiongroup->id;
2272 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2276 // get the current grade
2277 $grade = $this->get_user_grade($userid, false);
2278 if ($this->can_view_submission($userid)) {
2279 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
2280 $extensionduedate = null;
2282 $extensionduedate = $grade->extensionduedate;
2284 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2286 if ($teamsubmission) {
2287 $showsubmit = $showedit && $teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2289 $showsubmit = $showedit && $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2291 if (!$this->get_instance()->submissiondrafts) {
2292 $showsubmit = false;
2294 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2296 $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2297 $this->get_instance()->alwaysshowdescription,
2299 $this->get_instance()->teamsubmission,
2303 $this->is_any_submission_plugin_enabled(),
2305 $this->is_graded($userid),
2306 $this->get_instance()->duedate,
2307 $this->get_instance()->cutoffdate,
2308 $this->get_submission_plugins(),
2309 $this->get_return_action(),
2310 $this->get_return_params(),
2311 $this->get_course_module()->id,
2312 $this->get_course()->id,
2313 assign_submission_status::GRADER_VIEW,
2318 $this->get_context(),
2319 $this->is_blind_marking(),
2323 $data = new stdClass();
2324 if ($grade->grade !== NULL && $grade->grade >= 0) {
2325 $data->grade = format_float($grade->grade,2);
2328 $data = new stdClass();
2332 // now show the grading form
2334 $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
2335 $formparams = array($this, $data, $pagination);
2336 $mform = new mod_assign_grade_form(null,
2340 array('class'=>'gradeform'));
2342 $o .= $this->get_renderer()->render(new assign_form('gradingform',$mform));
2344 $msg = get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2345 $this->add_to_log('view grading form', $msg);
2347 $o .= $this->view_footer();
2352 * Show a confirmation page to make sure they want to release student identities
2356 private function view_reveal_identities_confirm() {
2359 require_capability('mod/assign:revealidentities', $this->get_context());
2362 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2363 $this->get_context(), false, $this->get_course_module()->id));
2365 $confirmurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2366 'action'=>'revealidentitiesconfirm',
2367 'sesskey'=>sesskey()));
2369 $cancelurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2370 'action'=>'grading'));
2372 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'), $confirmurl, $cancelurl);
2373 $o .= $this->view_footer();
2374 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2382 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2386 private function view_return_links() {
2388 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
2389 $returnparams = optional_param('returnparams','', PARAM_TEXT);
2392 parse_str($returnparams, $params);
2393 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
2395 return $this->get_renderer()->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
2400 * View the grading table of all submissions for this assignment
2404 private function view_grading_table() {
2406 // Include grading options form
2407 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2408 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2409 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2413 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2414 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2415 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2416 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2418 if ($this->is_any_submission_plugin_enabled()) {
2419 $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
2420 $links[$downloadurl] = get_string('downloadall', 'assign');
2422 if ($this->is_blind_marking() && has_capability('mod/assign:revealidentities', $this->get_context())) {
2423 $revealidentitiesurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=revealidentities';
2424 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2426 foreach ($this->get_feedback_plugins() as $plugin) {
2427 if ($plugin->is_enabled() && $plugin->is_visible()) {
2428 foreach ($plugin->get_grading_actions() as $action => $description) {
2429 $url = '/mod/assign/view.php' .
2430 '?id=' . $this->get_course_module()->id .
2431 '&plugin=' . $plugin->get_type() .
2432 '&pluginsubtype=assignfeedback' .
2433 '&action=viewpluginpage&pluginaction=' . $action;
2434 $links[$url] = $description;
2439 $gradingactions = new url_select($links);
2440 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2442 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2444 $perpage = get_user_preferences('assign_perpage', 10);
2445 $filter = get_user_preferences('assign_filter', '');
2446 $controller = $gradingmanager->get_active_controller();
2447 $showquickgrading = empty($controller);
2448 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
2449 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
2450 set_user_preference('assign_quickgrading', $quickgrading);
2452 $quickgrading = get_user_preferences('assign_quickgrading', false);
2454 // print options for changing the filter and changing the number of results per page
2455 $gradingoptionsform = new mod_assign_grading_options_form(null,
2456 array('cm'=>$this->get_course_module()->id,
2457 'contextid'=>$this->context->id,
2458 'userid'=>$USER->id,
2459 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2460 'showquickgrading'=>$showquickgrading,
2461 'quickgrading'=>$quickgrading),
2463 array('class'=>'gradingoptionsform'));
2465 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2466 array('cm'=>$this->get_course_module()->id,
2467 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2468 'duedate'=>$this->get_instance()->duedate,
2469 'feedbackplugins'=>$this->get_feedback_plugins()),
2471 array('class'=>'gradingbatchoperationsform'));
2473 $gradingoptionsdata = new stdClass();
2474 $gradingoptionsdata->perpage = $perpage;
2475 $gradingoptionsdata->filter = $filter;
2476 $gradingoptionsform->set_data($gradingoptionsdata);
2478 $actionformtext = $this->get_renderer()->render($gradingactions);
2479 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2480 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
2481 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
2483 // plagiarism update status apearring in the grading book
2484 if (!empty($CFG->enableplagiarism)) {
2485 /** Include plagiarismlib.php */
2486 require_once($CFG->libdir . '/plagiarismlib.php');
2487 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2490 // load and print the table of submissions
2491 if ($showquickgrading && $quickgrading) {
2492 $table = $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, true));
2493 $quickgradingform = new mod_assign_quick_grading_form(null,
2494 array('cm'=>$this->get_course_module()->id,
2495 'gradingtable'=>$table));
2496 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2498 $o .= $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, false));
2501 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2502 $users = array_keys($this->list_participants($currentgroup, true));
2503 if (count($users) != 0) {
2504 // if no enrolled user in a course then don't display the batch operations feature
2505 $o .= $this->get_renderer()->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
2507 $o .= $this->get_renderer()->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
2512 * View entire grading page.
2516 private function view_grading_page() {
2520 // Need submit permission to submit an assignment
2521 require_capability('mod/assign:grade', $this->context);
2522 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2524 // only load this if it is
2526 $o .= $this->view_grading_table();
2528 $o .= $this->view_footer();
2529 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
2534 * Capture the output of the plagiarism plugins disclosures and return it as a string
2538 private function plagiarism_print_disclosure() {
2542 if (!empty($CFG->enableplagiarism)) {
2543 /** Include plagiarismlib.php */
2544 require_once($CFG->libdir . '/plagiarismlib.php');
2546 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
2553 * message for students when assignment submissions have been closed
2557 private function view_student_error_message() {
2561 // Need submit permission to submit an assignment
2562 require_capability('mod/assign:submit', $this->context);
2564 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2565 $this->get_context(),
2566 $this->show_intro(),
2567 $this->get_course_module()->id,
2568 get_string('editsubmission', 'assign')));
2570 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
2572 $o .= $this->view_footer();
2579 * View edit submissions page.
2581 * @param moodleform $mform
2582 * @param array $notices A list of notices to display at the top of the edit submission form (e.g. from plugins).
2585 private function view_edit_submission_page($mform, $notices) {
2589 // Include submission form
2590 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2591 // Need submit permission to submit an assignment
2592 require_capability('mod/assign:submit', $this->context);
2594 if (!$this->submissions_open()) {
2595 return $this->view_student_error_message();
2597 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2598 $this->get_context(),
2599 $this->show_intro(),
2600 $this->get_course_module()->id,
2601 get_string('editsubmission', 'assign')));
2602 $o .= $this->plagiarism_print_disclosure();
2603 $data = new stdClass();
2606 $mform = new mod_assign_submission_form(null, array($this, $data));
2609 foreach ($notices as $notice) {
2610 $o .= $this->get_renderer()->notification($notice);
2613 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform',$mform));
2615 $o .= $this->view_footer();
2616 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2622 * See if this assignment has a grade yet
2624 * @param int $userid
2627 private function is_graded($userid) {
2628 $grade = $this->get_user_grade($userid, false);
2630 return ($grade->grade !== NULL && $grade->grade >= 0);
2637 * Perform an access check to see if the current $USER can view this users submission
2639 * @param int $userid
2642 public function can_view_submission($userid) {
2645 if (!is_enrolled($this->get_course_context(), $userid)) {
2648 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2651 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2658 * Allows the plugin to show a batch grading operation page.
2662 private function view_plugin_grading_batch_operation($mform) {
2663 require_capability('mod/assign:grade', $this->context);
2664 $prefix = 'plugingradingbatchoperation_';
2666 if ($data = $mform->get_data()) {
2667 $tail = substr($data->operation, strlen($prefix));
2668 list($plugintype, $action) = explode('_', $tail, 2);
2670 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2672 $users = $data->selectedusers;
2673 $userlist = explode(',', $users);
2674 echo $plugin->grading_batch_operation($action, $userlist);
2678 print_error('invalidformdata', '');
2682 * Ask the user to confirm they want to perform this batch operation
2683 * @param moodleform $mform Set to a grading batch operations form
2684 * @return string - the page to view after processing these actions
2686 private function process_grading_batch_operation(& $mform) {
2688 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2691 $mform = new mod_assign_grading_batch_operations_form(null,
2692 array('cm'=>$this->get_course_module()->id,
2693 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2694 'duedate'=>$this->get_instance()->duedate,
2695 'feedbackplugins'=>$this->get_feedback_plugins()),
2698 array('class'=>'gradingbatchoperationsform'));
2700 if ($data = $mform->get_data()) {
2701 // get the list of users
2702 $users = $data->selectedusers;
2703 $userlist = explode(',', $users);
2705 $prefix = 'plugingradingbatchoperation_';
2707 if ($data->operation == 'grantextension') {
2708 // Reset the form so the grant extension page will create the extension form.
2710 return 'grantextension';
2711 } else if (strpos($data->operation, $prefix) === 0) {
2712 $tail = substr($data->operation, strlen($prefix));
2713 list($plugintype, $action) = explode('_', $tail, 2);
2715 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2717 return 'plugingradingbatchoperation';
2721 foreach ($userlist as $userid) {
2722 if ($data->operation == 'lock') {
2723 $this->process_lock($userid);
2724 } else if ($data->operation == 'unlock') {
2725 $this->process_unlock($userid);
2726 } else if ($data->operation == 'reverttodraft') {
2727 $this->process_revert_to_draft($userid);
2736 * Ask the user to confirm they want to submit their work for grading
2737 * @param $mform moodleform - null unless form validation has failed
2740 private function check_submit_for_grading($mform) {
2743 require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
2745 // Check that all of the submission plugins are ready for this submission
2746 $notifications = array();
2747 $submission = $this->get_user_submission($USER->id, false);
2748 $plugins = $this->get_submission_plugins();
2749 foreach ($plugins as $plugin) {
2750 if ($plugin->is_enabled() && $plugin->is_visible()) {
2751 $check = $plugin->precheck_submission($submission);
2752 if ($check !== true) {
2753 $notifications[] = $check;
2758 $data = new stdClass();
2759 $adminconfig = $this->get_admin_config();
2760 $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
2761 $this->get_instance()->requiresubmissionstatement) &&
2762 !empty($adminconfig->submissionstatement);
2764 $submissionstatement = '';
2765 if (!empty($adminconfig->submissionstatement)) {
2766 $submissionstatement = $adminconfig->submissionstatement;
2769 if ($mform == null) {
2770 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
2771 $submissionstatement,
2772 $this->get_course_module()->id,
2776 $o .= $this->get_renderer()->header();
2777 $o .= $this->get_renderer()->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id, $mform));
2778 $o .= $this->view_footer();
2780 $this->add_to_log('view confirm submit assignment form', get_string('viewownsubmissionform', 'assign'));
2786 * Print 2 tables of information with no action links -
2787 * the submission summary and the grading summary
2789 * @param stdClass $user the user to print the report for
2790 * @param bool $showlinks - Return plain text or links to the profile
2791 * @return string - the html summary
2793 public function view_student_summary($user, $showlinks) {
2794 global $CFG, $DB, $PAGE;
2796 $grade = $this->get_user_grade($user->id, false);
2797 $submission = $this->get_user_submission($user->id, false);
2800 $teamsubmission = null;
2801 $submissiongroup = null;
2802 $notsubmitted = array();
2803 if ($this->get_instance()->teamsubmission) {
2804 $teamsubmission = $this->get_group_submission($user->id, 0, false);
2805 $submissiongroup = $this->get_submission_group($user->id);
2807 if ($submissiongroup) {
2808 $groupid = $submissiongroup->id;
2810 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2813 if ($this->can_view_submission($user->id)) {
2814 $showedit = has_capability('mod/assign:submit', $this->context) &&
2815 $this->submissions_open($user->id) && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2816 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2817 // Grading criteria preview.
2818 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2819 $gradingcontrollerpreview = '';
2820 if ($gradingmethod = $gradingmanager->get_active_method()) {
2821 $controller = $gradingmanager->get_controller($gradingmethod);
2822 if ($controller->is_form_defined()) {
2823 $gradingcontrollerpreview = $controller->render_preview($PAGE);
2827 $showsubmit = ($submission || $teamsubmission) && $showlinks;
2828 if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2829 $showsubmit = false;
2831 if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2832 $showsubmit = false;
2834 if (!$this->get_instance()->submissiondrafts) {
2835 $showsubmit = false;
2837 $extensionduedate = null;
2839 $extensionduedate = $grade->extensionduedate;
2841 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2842 $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2843 $this->get_instance()->alwaysshowdescription,
2845 $this->get_instance()->teamsubmission,
2849 $this->is_any_submission_plugin_enabled(),
2851 $this->is_graded($user->id),
2852 $this->get_instance()->duedate,
2853 $this->get_instance()->cutoffdate,
2854 $this->get_submission_plugins(),
2855 $this->get_return_action(),
2856 $this->get_return_params(),
2857 $this->get_course_module()->id,
2858 $this->get_course()->id,
2859 assign_submission_status::STUDENT_VIEW,
2864 $this->get_context(),
2865 $this->is_blind_marking(),
2866 $gradingcontrollerpreview));
2868 require_once($CFG->libdir.'/gradelib.php');
2869 require_once($CFG->dirroot.'/grade/grading/lib.php');
2871 $gradinginfo = grade_get_grades($this->get_course()->id,
2874 $this->get_instance()->id,
2877 $gradingitem = $gradinginfo->items[0];
2878 $gradebookgrade = $gradingitem->grades[$user->id];
2880 // check to see if all feedback plugins are empty
2881 $emptyplugins = true;
2883 foreach ($this->get_feedback_plugins() as $plugin) {
2884 if ($plugin->is_visible() && $plugin->is_enabled()) {
2885 if (!$plugin->is_empty($grade)) {
2886 $emptyplugins = false;
2893 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2895 $gradefordisplay = '';
2896 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2898 if ($controller = $gradingmanager->get_active_controller()) {
2899 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2900 $gradefordisplay = $controller->render_grade($PAGE,
2903 $gradebookgrade->str_long_grade,
2904 has_capability('mod/assign:grade', $this->get_context()));
2906 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2909 $gradeddate = $gradebookgrade->dategraded;
2910 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2912 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2915 $this->get_feedback_plugins(),
2917 $this->get_course_module()->id,
2918 $this->get_return_action(),
2919 $this->get_return_params());
2921 $o .= $this->get_renderer()->render($feedbackstatus);
2929 * View submissions page (contains details of current submission).
2933 private function view_submission_page() {
2934 global $CFG, $DB, $USER, $PAGE;
2937 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2938 $this->get_context(),
2939 $this->show_intro(),
2940 $this->get_course_module()->id));
2942 if ($this->can_grade()) {
2943 if ($this->get_instance()->teamsubmission) {
2944 $summary = new assign_grading_summary($this->count_teams(),
2945 $this->get_instance()->submissiondrafts,
2946 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2947 $this->is_any_submission_plugin_enabled(),
2948 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2949 $this->get_instance()->cutoffdate,
2950 $this->get_instance()->duedate,
2951 $this->get_course_module()->id,
2952 $this->count_submissions_need_grading(),
2953 $this->get_instance()->teamsubmission);
2954 $o .= $this->get_renderer()->render($summary);
2956 $summary = new assign_grading_summary($this->count_participants(0),
2957 $this->get_instance()->submissiondrafts,
2958 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2959 $this->is_any_submission_plugin_enabled(),
2960 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2961 $this->get_instance()->cutoffdate,
2962 $this->get_instance()->duedate,
2963 $this->get_course_module()->id,
2964 $this->count_submissions_need_grading(),
2965 $this->get_instance()->teamsubmission);
2966 $o .= $this->get_renderer()->render($summary);
2969 $grade = $this->get_user_grade($USER->id, false);
2970 $submission = $this->get_user_submission($USER->id, false);
2972 if ($this->can_view_submission($USER->id)) {
2973 $o .= $this->view_student_summary($USER, true);
2977 $o .= $this->view_footer();
2978 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2983 * convert the final raw grade(s) in the grading table for the gradebook
2985 * @param stdClass $grade
2988 private function convert_grade_for_gradebook(stdClass $grade) {
2989 $gradebookgrade = array();
2990 // trying to match those array keys in grade update function in gradelib.php
2991 // with keys in th database table assign_grades
2992 // starting around line 262
2993 if ($grade->grade >= 0) {
2994 $gradebookgrade['rawgrade'] = $grade->grade;
2996 $gradebookgrade['userid'] = $grade->userid;
2997 $gradebookgrade['usermodified'] = $grade->grader;
2998 $gradebookgrade['datesubmitted'] = NULL;
2999 $gradebookgrade['dategraded'] = $grade->timemodified;
3000 if (isset($grade->feedbackformat)) {
3001 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
3003 if (isset($grade->feedbacktext)) {
3004 $gradebookgrade['feedback'] = $grade->feedbacktext;
3007 return $gradebookgrade;
3011 * convert submission details for the gradebook
3013 * @param stdClass $submission
3016 private function convert_submission_for_gradebook(stdClass $submission) {
3017 $gradebookgrade = array();
3020 $gradebookgrade['userid'] = $submission->userid;
3021 $gradebookgrade['usermodified'] = $submission->userid;
3022 $gradebookgrade['datesubmitted'] = $submission->timemodified;
3024 return $gradebookgrade;
3028 * update grades in the gradebook
3030 * @param mixed $submission stdClass|null
3031 * @param mixed $grade stdClass|null
3034 private function gradebook_item_update($submission=NULL, $grade=NULL) {
3036 // Do not push grade to gradebook if blind marking is active as the gradebook would reveal the students.
3037 if ($this->is_blind_marking()) {
3040 if ($submission != NULL) {
3041 if ($submission->userid == 0) {
3042 // This is a group submission update.
3043 $team = groups_get_members($submission->groupid, 'u.id');
3045 foreach ($team as $member) {
3046 $submission->groupid = 0;
3047 $submission->userid = $member->id;
3048 $this->gradebook_item_update($submission, null);
3053 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
3056 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
3058 // Grading is disabled, return.
3059 if ($this->grading_disabled($gradebookgrade['userid'])) {
3062 $assign = clone $this->get_instance();
3063 $assign->cmidnumber = $this->get_course_module()->id;
3065 return assign_grade_item_update($assign, $gradebookgrade);
3069 * update team submission
3071 * @param stdClass $submission
3072 * @param int $userid
3073 * @param bool $updatetime
3076 private function update_team_submission(stdClass $submission, $userid, $updatetime) {
3080 $submission->timemodified = time();
3083 // First update the submission for the current user.
3084 $mysubmission = $this->get_user_submission($userid, true);
3085 $mysubmission->status = $submission->status;
3087 $this->update_submission($mysubmission, 0, $updatetime, false);
3089 // Now check the team settings to see if this assignment qualifies as submitted or draft.
3090 $team = $this->get_submission_group_members($submission->groupid, true);
3092 $allsubmitted = true;
3093 $anysubmitted = false;
3094 foreach ($team as $member) {
3095 $membersubmission = $this->get_user_submission($member->id, false);
3097 if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3098 $allsubmitted = false;
3099 if ($anysubmitted) {
3103 $anysubmitted = true;
3106 if ($this->get_instance()->requireallteammemberssubmit) {
3107 if ($allsubmitted) {
3108 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3110 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3112 $result= $DB->update_record('assign_submission', $submission);
3114 if ($anysubmitted) {
3115 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3117 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3119 $result= $DB->update_record('assign_submission', $submission);
3122 $this->gradebook_item_update($submission);
3128 * update grades in the gradebook based on submission time
3130 * @param stdClass $submission
3131 * @param int $userid
3132 * @param bool $updatetime
3133 * @param bool $teamsubmission
3136 private function update_submission(stdClass $submission, $userid, $updatetime, $teamsubmission) {
3139 if ($teamsubmission) {
3140 return $this->update_team_submission($submission, $userid, $updatetime);
3144 $submission->timemodified = time();
3146 $result= $DB->update_record('assign_submission', $submission);
3148 $this->gradebook_item_update($submission);
3154 * Is this assignment open for submissions?
3156 * Check the due date,
3157 * prevent late submissions,
3158 * has this person already submitted,
3159 * is the assignment locked?
3161 * @param int $userid - Optional userid so we can see if a different user can submit
3164 public function submissions_open($userid = 0) {
3168 $userid = $USER->id;
3174 if ($this->get_instance()->cutoffdate) {
3175 $finaldate = $this->get_instance()->cutoffdate;
3179 $grade = $this->get_user_grade($userid, false);
3180 if ($grade && $grade->extensionduedate) {
3181 // Extension can be before cut off date.
3182 if ($grade->extensionduedate > $finaldate) {
3183 $finaldate = $grade->extensionduedate;
3189 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $finaldate);
3191 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
3198 // Now check if this user has already submitted etc.
3199 if (!is_enrolled($this->get_course_context(), $userid)) {
3202 $submission = false;
3203 if ($this->get_instance()->teamsubmission) {
3204 $submission = $this->get_group_submission($userid, 0, false);
3206 $submission = $this->get_user_submission($userid, false);
3210 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3211 // drafts are tracked and the student has submitted the assignment
3215 if ($grade = $this->get_user_grade($userid, false)) {
3216 if ($grade->locked) {
3221 if ($this->grading_disabled($userid)) {
3229 * render the files in file area
3230 * @param string $component
3231 * @param string $area
3232 * @param int $submissionid
3235 public function render_area_files($component, $area, $submissionid) {
3238 $fs = get_file_storage();
3239 $browser = get_file_browser();
3240 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
3241 return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);
3246 * Returns a list of teachers that should be grading given submission
3248 * @param int $userid
3251 private function get_graders($userid) {
3253 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
3256 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
3257 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
3258 foreach ($groups as $group) {
3259 foreach ($potentialgraders as $grader) {
3260 if ($grader->id == $userid) {
3261 continue; // do not send self
3263 if (groups_is_member($group->id, $grader->id)) {
3264 $graders[$grader->id] = $grader;
3269 // user not in group, try to find graders without group
3270 foreach ($potentialgraders as $grader) {
3271 if ($grader->id == $userid) {