2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains the definition for the class assignment
20 * This class provides all the functionality for the new assign module.
23 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 // Assignment submission statuses.
30 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
31 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
33 // Search filters for grading page.
34 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
35 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
36 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
38 require_once($CFG->libdir . '/accesslib.php');
39 require_once($CFG->libdir . '/formslib.php');
40 require_once($CFG->dirroot . '/repository/lib.php');
41 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
42 require_once($CFG->libdir . '/gradelib.php');
43 require_once($CFG->dirroot . '/grade/grading/lib.php');
44 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
45 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
46 require_once($CFG->dirroot . '/mod/assign/renderable.php');
47 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
48 require_once($CFG->libdir . '/eventslib.php');
49 require_once($CFG->libdir . '/portfolio/caller.php');
52 * Standard base class for mod_assign (assignment types).
55 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 /** @var stdClass the assignment record that contains the global settings for this assign instance */
63 /** @var context the context of the course module for this assign instance
64 * (or just the course if we are creating a new one)
68 /** @var stdClass the course this assign instance belongs to */
71 /** @var stdClass the admin config for all assign instances */
74 /** @var assign_renderer the custom renderer for this module */
77 /** @var stdClass the course module for this assign instance */
78 private $coursemodule;
80 /** @var array cache for things like the coursemodule name or the scale menu -
81 * only lives for a single request.
85 /** @var array list of the installed submission plugins */
86 private $submissionplugins;
88 /** @var array list of the installed feedback plugins */
89 private $feedbackplugins;
91 /** @var string action to be used to return to this page
92 * (without repeating any form submissions etc).
94 private $returnaction = 'view';
96 /** @var array params to be used to return to this page */
97 private $returnparams = array();
99 /** @var string modulename prevents excessive calls to get_string */
100 private static $modulename = null;
102 /** @var string modulenameplural prevents excessive calls to get_string */
103 private static $modulenameplural = null;
106 * Constructor for the base assign class.
108 * @param mixed $coursemodulecontext context|null the course module context
109 * (or the course context if the coursemodule has not been
111 * @param mixed $coursemodule the current course module if it was already loaded,
112 * otherwise this class will load one from the context as required.
113 * @param mixed $course the current course if it was already loaded,
114 * otherwise this class will load one from the context as required.
116 public function __construct($coursemodulecontext, $coursemodule, $course) {
119 $this->context = $coursemodulecontext;
120 $this->coursemodule = $coursemodule;
121 $this->course = $course;
123 // Temporary cache only lives for a single request - used to reduce db lookups.
124 $this->cache = array();
126 $this->submissionplugins = $this->load_plugins('assignsubmission');
127 $this->feedbackplugins = $this->load_plugins('assignfeedback');
131 * Set the action and parameters that can be used to return to the current page.
133 * @param string $action The action for the current page
134 * @param array $params An array of name value pairs which form the parameters
135 * to return to the current page.
138 public function register_return_link($action, $params) {
139 $this->returnaction = $action;
140 $this->returnparams = $params;
144 * Return an action that can be used to get back to the current page.
146 * @return string action
148 public function get_return_action() {
149 return $this->returnaction;
153 * Based on the current assignment settings should we display the intro.
155 * @return bool showintro
157 protected function show_intro() {
158 if ($this->get_instance()->alwaysshowdescription ||
159 time() > $this->get_instance()->allowsubmissionsfromdate) {
166 * Return a list of parameters that can be used to get back to the current page.
168 * @return array params
170 public function get_return_params() {
171 return $this->returnparams;
175 * Set the submitted form data.
177 * @param stdClass $data The form data (instance)
179 public function set_instance(stdClass $data) {
180 $this->instance = $data;
186 * @param context $context The new context
188 public function set_context(context $context) {
189 $this->context = $context;
193 * Set the course data.
195 * @param stdClass $course The course data
197 public function set_course(stdClass $course) {
198 $this->course = $course;
202 * Get list of feedback plugins installed.
206 public function get_feedback_plugins() {
207 return $this->feedbackplugins;
211 * Get list of submission plugins installed.
215 public function get_submission_plugins() {
216 return $this->submissionplugins;
220 * Is blind marking enabled and reveal identities not set yet?
224 public function is_blind_marking() {
225 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
229 * Does an assignment have submission(s) or grade(s) already?
233 public function has_submissions_or_grades() {
234 $allgrades = $this->count_grades();
235 $allsubmissions = $this->count_submissions();
236 if (($allgrades == 0) && ($allsubmissions == 0)) {
243 * Get a specific submission plugin by its type.
245 * @param string $subtype assignsubmission | assignfeedback
246 * @param string $type
247 * @return mixed assign_plugin|null
249 public function get_plugin_by_type($subtype, $type) {
250 $shortsubtype = substr($subtype, strlen('assign'));
251 $name = $shortsubtype . 'plugins';
252 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
255 $pluginlist = $this->$name;
256 foreach ($pluginlist as $plugin) {
257 if ($plugin->get_type() == $type) {
265 * Get a feedback plugin by type.
267 * @param string $type - The type of plugin e.g comments
268 * @return mixed assign_feedback_plugin|null
270 public function get_feedback_plugin_by_type($type) {
271 return $this->get_plugin_by_type('assignfeedback', $type);
275 * Get a submission plugin by type.
277 * @param string $type - The type of plugin e.g comments
278 * @return mixed assign_submission_plugin|null
280 public function get_submission_plugin_by_type($type) {
281 return $this->get_plugin_by_type('assignsubmission', $type);
285 * Load the plugins from the sub folders under subtype.
287 * @param string $subtype - either submission or feedback
288 * @return array - The sorted list of plugins
290 protected function load_plugins($subtype) {
294 $names = get_plugin_list($subtype);
296 foreach ($names as $name => $path) {
297 if (file_exists($path . '/locallib.php')) {
298 require_once($path . '/locallib.php');
300 $shortsubtype = substr($subtype, strlen('assign'));
301 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
303 $plugin = new $pluginclass($this, $name);
305 if ($plugin instanceof assign_plugin) {
306 $idx = $plugin->get_sort_order();
307 while (array_key_exists($idx, $result)) {
310 $result[$idx] = $plugin;
319 * Display the assignment, used by view.php
321 * The assignment is displayed differently depending on your role,
322 * the settings for the assignment and the status of the assignment.
324 * @param string $action The current action if any.
327 public function view($action='') {
333 // Handle form submissions first.
334 if ($action == 'savesubmission') {
335 $action = 'editsubmission';
336 if ($this->process_save_submission($mform, $notices)) {
339 } else if ($action == 'lock') {
340 $this->process_lock();
342 } else if ($action == 'reverttodraft') {
343 $this->process_revert_to_draft();
345 } else if ($action == 'unlock') {
346 $this->process_unlock();
348 } else if ($action == 'confirmsubmit') {
350 if ($this->process_submit_for_grading($mform)) {
353 } else if ($action == 'gradingbatchoperation') {
354 $action = $this->process_grading_batch_operation($mform);
355 } else if ($action == 'submitgrade') {
356 if (optional_param('saveandshownext', null, PARAM_RAW)) {
357 // Save and show next.
359 if ($this->process_save_grade($mform)) {
360 $action = 'nextgrade';
362 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
363 $action = 'previousgrade';
364 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
366 $action = 'nextgrade';
367 } else if (optional_param('savegrade', null, PARAM_RAW)) {
368 // Save changes button.
370 if ($this->process_save_grade($mform)) {
377 } else if ($action == 'quickgrade') {
378 $message = $this->process_save_quick_grades();
379 $action = 'quickgradingresult';
380 } else if ($action == 'saveoptions') {
381 $this->process_save_grading_options();
383 } else if ($action == 'saveextension') {
384 $action = 'grantextension';
385 if ($this->process_save_extension($mform)) {
388 } else if ($action == 'revealidentitiesconfirm') {
389 $this->process_reveal_identities();
393 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
394 $this->register_return_link($action, $returnparams);
396 // Now show the right view page.
397 if ($action == 'previousgrade') {
399 $o .= $this->view_single_grade_page($mform, -1);
400 } else if ($action == 'quickgradingresult') {
402 $o .= $this->view_quickgrading_result($message);
403 } else if ($action == 'nextgrade') {
405 $o .= $this->view_single_grade_page($mform, 1);
406 } else if ($action == 'grade') {
407 $o .= $this->view_single_grade_page($mform);
408 } else if ($action == 'viewpluginassignfeedback') {
409 $o .= $this->view_plugin_content('assignfeedback');
410 } else if ($action == 'viewpluginassignsubmission') {
411 $o .= $this->view_plugin_content('assignsubmission');
412 } else if ($action == 'editsubmission') {
413 $o .= $this->view_edit_submission_page($mform, $notices);
414 } else if ($action == 'grading') {
415 $o .= $this->view_grading_page();
416 } else if ($action == 'downloadall') {
417 $o .= $this->download_submissions();
418 } else if ($action == 'submit') {
419 $o .= $this->check_submit_for_grading($mform);
420 } else if ($action == 'grantextension') {
421 $o .= $this->view_grant_extension($mform);
422 } else if ($action == 'revealidentities') {
423 $o .= $this->view_reveal_identities_confirm($mform);
424 } else if ($action == 'plugingradingbatchoperation') {
425 $o .= $this->view_plugin_grading_batch_operation($mform);
426 } else if ($action == 'viewpluginpage') {
427 $o .= $this->view_plugin_page();
428 } else if ($action == 'viewcourseindex') {
429 $o .= $this->view_course_index();
431 $o .= $this->view_submission_page();
438 * Add this instance to the database.
440 * @param stdClass $formdata The data submitted from the form
441 * @param bool $callplugins This is used to skip the plugin code
442 * when upgrading an old assignment to a new one (the plugins get called manually)
443 * @return mixed false if an error occurs or the int id of the new instance
445 public function add_instance(stdClass $formdata, $callplugins) {
450 // Add the database record.
451 $update = new stdClass();
452 $update->name = $formdata->name;
453 $update->timemodified = time();
454 $update->timecreated = time();
455 $update->course = $formdata->course;
456 $update->courseid = $formdata->course;
457 $update->intro = $formdata->intro;
458 $update->introformat = $formdata->introformat;
459 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
460 $update->submissiondrafts = $formdata->submissiondrafts;
461 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
462 $update->sendnotifications = $formdata->sendnotifications;
463 $update->sendlatenotifications = $formdata->sendlatenotifications;
464 $update->duedate = $formdata->duedate;
465 $update->cutoffdate = $formdata->cutoffdate;
466 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
467 $update->grade = $formdata->grade;
468 $update->completionsubmit = !empty($formdata->completionsubmit);
469 $update->teamsubmission = $formdata->teamsubmission;
470 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
471 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
472 $update->blindmarking = $formdata->blindmarking;
474 $returnid = $DB->insert_record('assign', $update);
475 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
476 // Cache the course record.
477 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
480 // Call save_settings hook for submission plugins.
481 foreach ($this->submissionplugins as $plugin) {
482 if (!$this->update_plugin_instance($plugin, $formdata)) {
483 print_error($plugin->get_error());
487 foreach ($this->feedbackplugins as $plugin) {
488 if (!$this->update_plugin_instance($plugin, $formdata)) {
489 print_error($plugin->get_error());
494 // In the case of upgrades the coursemodule has not been set,
495 // so we need to wait before calling these two.
496 $this->update_calendar($formdata->coursemodule);
497 $this->update_gradebook(false, $formdata->coursemodule);
501 $update = new stdClass();
502 $update->id = $this->get_instance()->id;
503 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
504 $DB->update_record('assign', $update);
510 * Delete all grades from the gradebook for this assignment.
514 protected function delete_grades() {
517 $result = grade_update('mod/assign',
518 $this->get_course()->id,
521 $this->get_instance()->id,
524 array('deleted'=>1));
525 return $result == GRADE_UPDATE_OK;
529 * Delete this instance from the database.
531 * @return bool false if an error occurs
533 public function delete_instance() {
537 foreach ($this->submissionplugins as $plugin) {
538 if (!$plugin->delete_instance()) {
539 print_error($plugin->get_error());
543 foreach ($this->feedbackplugins as $plugin) {
544 if (!$plugin->delete_instance()) {
545 print_error($plugin->get_error());
550 // Delete files associated with this assignment.
551 $fs = get_file_storage();
552 if (! $fs->delete_area_files($this->context->id) ) {
556 // Delete_records will throw an exception if it fails - so no need for error checking here.
557 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
558 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
559 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
561 // Delete items from the gradebook.
562 if (! $this->delete_grades()) {
566 // Delete the instance.
567 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
573 * Actual implementation of the reset course functionality, delete all the
574 * assignment submissions for course $data->courseid.
576 * @param $data the data submitted from the reset course.
577 * @return array status array
579 public function reset_userdata($data) {
582 $componentstr = get_string('modulenameplural', 'assign');
585 $fs = get_file_storage();
586 if (!empty($data->reset_assign_submissions)) {
587 // Delete files associated with this assignment.
588 foreach ($this->submissionplugins as $plugin) {
589 $fileareas = array();
590 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
591 $fileareas = $plugin->get_file_areas();
592 foreach ($fileareas as $filearea) {
593 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
596 if (!$plugin->delete_instance()) {
597 $status[] = array('component'=>$componentstr,
598 'item'=>get_string('deleteallsubmissions', 'assign'),
599 'error'=>$plugin->get_error());
603 foreach ($this->feedbackplugins as $plugin) {
604 $fileareas = array();
605 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
606 $fileareas = $plugin->get_file_areas();
607 foreach ($fileareas as $filearea) {
608 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
611 if (!$plugin->delete_instance()) {
612 $status[] = array('component'=>$componentstr,
613 'item'=>get_string('deleteallsubmissions', 'assign'),
614 'error'=>$plugin->get_error());
618 $assignssql = 'SELECT a.id
620 WHERE a.course=:course';
621 $params = array('course'=>$data->courseid);
623 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
625 $status[] = array('component'=>$componentstr,
626 'item'=>get_string('deleteallsubmissions', 'assign'),
629 if (!empty($data->reset_gradebook_grades)) {
630 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
631 // Remove all grades from gradebook.
632 require_once($CFG->dirroot.'/mod/assign/lib.php');
633 assign_reset_gradebook($data->courseid);
636 // Updating dates - shift may be negative too.
637 if ($data->timeshift) {
638 shift_course_mod_dates('assign',
639 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
642 $status[] = array('component'=>$componentstr,
643 'item'=>get_string('datechanged'),
651 * Update the settings for a single plugin.
653 * @param assign_plugin $plugin The plugin to update
654 * @param stdClass $formdata The form data
655 * @return bool false if an error occurs
657 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
658 if ($plugin->is_visible()) {
659 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
660 if ($formdata->$enabledname) {
662 if (!$plugin->save_settings($formdata)) {
663 print_error($plugin->get_error());
674 * Update the gradebook information for this assignment.
676 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
677 * @param int $coursemoduleid This is required because it might not exist in the database yet
680 public function update_gradebook($reset, $coursemoduleid) {
683 require_once($CFG->dirroot.'/mod/assign/lib.php');
684 $assign = clone $this->get_instance();
685 $assign->cmidnumber = $coursemoduleid;
691 return assign_grade_item_update($assign, $param);
695 * Load and cache the admin config for this module.
697 * @return stdClass the plugin config
699 public function get_admin_config() {
700 if ($this->adminconfig) {
701 return $this->adminconfig;
703 $this->adminconfig = get_config('assign');
704 return $this->adminconfig;
708 * Update the calendar entries for this assignment.
710 * @param int $coursemoduleid - Required to pass this in because it might
711 * not exist in the database yet.
714 public function update_calendar($coursemoduleid) {
716 require_once($CFG->dirroot.'/calendar/lib.php');
718 // Special case for add_instance as the coursemodule has not been set yet.
719 $instance = $this->get_instance();
721 if ($instance->duedate) {
722 $event = new stdClass();
724 $params = array('modulename'=>'assign', 'instance'=>$instance->id);
725 $event->id = $DB->get_field('event',
730 $event->name = $instance->name;
731 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
732 $event->timestart = $instance->duedate;
734 $calendarevent = calendar_event::load($event->id);
735 $calendarevent->update($event);
737 $event = new stdClass();
738 $event->name = $instance->name;
739 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
740 $event->courseid = $instance->course;
743 $event->modulename = 'assign';
744 $event->instance = $instance->id;
745 $event->eventtype = 'due';
746 $event->timestart = $instance->duedate;
747 $event->timeduration = 0;
749 calendar_event::create($event);
752 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
758 * Update this instance in the database.
760 * @param stdClass $formdata - the data submitted from the form
761 * @return bool false if an error occurs
763 public function update_instance($formdata) {
766 $update = new stdClass();
767 $update->id = $formdata->instance;
768 $update->name = $formdata->name;
769 $update->timemodified = time();
770 $update->course = $formdata->course;
771 $update->intro = $formdata->intro;
772 $update->introformat = $formdata->introformat;
773 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
774 $update->submissiondrafts = $formdata->submissiondrafts;
775 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
776 $update->sendnotifications = $formdata->sendnotifications;
777 $update->sendlatenotifications = $formdata->sendlatenotifications;
778 $update->duedate = $formdata->duedate;
779 $update->cutoffdate = $formdata->cutoffdate;
780 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
781 $update->grade = $formdata->grade;
782 $update->completionsubmit = !empty($formdata->completionsubmit);
783 $update->teamsubmission = $formdata->teamsubmission;
784 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
785 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
786 $update->blindmarking = $formdata->blindmarking;
788 $result = $DB->update_record('assign', $update);
789 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
791 // Load the assignment so the plugins have access to it.
793 // Call save_settings hook for submission plugins.
794 foreach ($this->submissionplugins as $plugin) {
795 if (!$this->update_plugin_instance($plugin, $formdata)) {
796 print_error($plugin->get_error());
800 foreach ($this->feedbackplugins as $plugin) {
801 if (!$this->update_plugin_instance($plugin, $formdata)) {
802 print_error($plugin->get_error());
807 $this->update_calendar($this->get_course_module()->id);
808 $this->update_gradebook(false, $this->get_course_module()->id);
810 $update = new stdClass();
811 $update->id = $this->get_instance()->id;
812 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
813 $DB->update_record('assign', $update);
819 * Add elements in grading plugin form.
821 * @param mixed $grade stdClass|null
822 * @param MoodleQuickForm $mform
823 * @param stdClass $data
824 * @param int $userid - The userid we are grading
827 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
828 foreach ($this->feedbackplugins as $plugin) {
829 if ($plugin->is_enabled() && $plugin->is_visible()) {
830 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
831 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
832 $mform->removeElement('header_' . $plugin->get_type());
841 * Add one plugins settings to edit plugin form.
843 * @param assign_plugin $plugin The plugin to add the settings from
844 * @param MoodleQuickForm $mform The form to add the configuration settings to.
845 * This form is modified directly (not returned).
848 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
850 if ($plugin->is_visible()) {
851 $mform->addElement('selectyesno',
852 $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled',
853 $plugin->get_name());
854 $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled',
856 $plugin->get_subtype() . '_' . $plugin->get_type());
858 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
859 if ($plugin->get_config('enabled') !== false) {
860 $default = $plugin->is_enabled();
862 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
864 $plugin->get_settings($mform);
870 * Add settings to edit plugin form.
872 * @param MoodleQuickForm $mform The form to add the configuration settings to.
873 * This form is modified directly (not returned).
876 public function add_all_plugin_settings(MoodleQuickForm $mform) {
877 $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
879 foreach ($this->submissionplugins as $plugin) {
880 $this->add_plugin_settings($plugin, $mform);
883 $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
884 foreach ($this->feedbackplugins as $plugin) {
885 $this->add_plugin_settings($plugin, $mform);
890 * Allow each plugin an opportunity to update the defaultvalues
891 * passed in to the settings form (needed to set up draft areas for
892 * editor and filemanager elements)
894 * @param array $defaultvalues
896 public function plugin_data_preprocessing(&$defaultvalues) {
897 foreach ($this->submissionplugins as $plugin) {
898 if ($plugin->is_visible()) {
899 $plugin->data_preprocessing($defaultvalues);
902 foreach ($this->feedbackplugins as $plugin) {
903 if ($plugin->is_visible()) {
904 $plugin->data_preprocessing($defaultvalues);
910 * Get the name of the current module.
912 * @return string the module name (Assignment)
914 protected function get_module_name() {
915 if (isset(self::$modulename)) {
916 return self::$modulename;
918 self::$modulename = get_string('modulename', 'assign');
919 return self::$modulename;
923 * Get the plural name of the current module.
925 * @return string the module name plural (Assignments)
927 protected function get_module_name_plural() {
928 if (isset(self::$modulenameplural)) {
929 return self::$modulenameplural;
931 self::$modulenameplural = get_string('modulenameplural', 'assign');
932 return self::$modulenameplural;
936 * Has this assignment been constructed from an instance?
940 public function has_instance() {
941 return $this->instance || $this->get_course_module();
945 * Get the settings for the current instance of this assignment
947 * @return stdClass The settings
949 public function get_instance() {
951 if ($this->instance) {
952 return $this->instance;
954 if ($this->get_course_module()) {
955 $params = array('id' => $this->get_course_module()->instance);
956 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
958 if (!$this->instance) {
959 throw new coding_exception('Improper use of the assignment class. ' .
960 'Cannot load the assignment record.');
962 return $this->instance;
966 * Get the context of the current course.
968 * @return mixed context|null The course context
970 public function get_course_context() {
971 if (!$this->context && !$this->course) {
972 throw new coding_exception('Improper use of the assignment class. ' .
973 'Cannot load the course context.');
975 if ($this->context) {
976 return $this->context->get_course_context();
978 return context_course::instance($this->course->id);
984 * Get the current course module.
986 * @return mixed stdClass|null The course module
988 public function get_course_module() {
989 if ($this->coursemodule) {
990 return $this->coursemodule;
992 if (!$this->context) {
996 if ($this->context->contextlevel == CONTEXT_MODULE) {
997 $this->coursemodule = get_coursemodule_from_id('assign',
998 $this->context->instanceid,
1002 return $this->coursemodule;
1008 * Get context module.
1012 public function get_context() {
1013 return $this->context;
1017 * Get the current course.
1019 * @return mixed stdClass|null The course
1021 public function get_course() {
1024 if ($this->course) {
1025 return $this->course;
1028 if (!$this->context) {
1031 $params = array('id' => $this->get_course_context()->instanceid);
1032 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1034 return $this->course;
1038 * Return a grade in user-friendly form, whether it's a scale or not.
1040 * @param mixed $grade int|null
1041 * @param boolean $editing Are we allowing changes to this grade?
1042 * @param int $userid The user id the grade belongs to
1043 * @param int $modified Timestamp from when the grade was last modified
1044 * @return string User-friendly representation of grade
1046 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1049 static $scalegrades = array();
1053 if ($this->get_instance()->grade >= 0) {
1055 if ($editing && $this->get_instance()->grade > 0) {
1059 $displaygrade = format_float($grade);
1061 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1062 get_string('usergrade', 'assign') .
1064 $o .= '<input type="text"
1065 id="quickgrade_' . $userid . '"
1066 name="quickgrade_' . $userid . '"
1067 value="' . $displaygrade . '"
1070 class="quickgrade"/>';
1071 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1072 $o .= '<input type="hidden"
1073 name="grademodified_' . $userid . '"
1074 value="' . $modified . '"/>';
1077 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1078 if ($grade == -1 || $grade === null) {
1082 $o .= format_float($grade, 2) .
1084 format_float($this->get_instance()->grade, 2);
1091 if (empty($this->cache['scale'])) {
1092 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1093 $this->cache['scale'] = make_menu_from_list($scale->scale);
1100 $o .= '<label class="accesshide"
1101 for="quickgrade_' . $userid . '">' .
1102 get_string('usergrade', 'assign') .
1104 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1105 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1106 foreach ($this->cache['scale'] as $optionid => $option) {
1108 if ($grade == $optionid) {
1109 $selected = 'selected="selected"';
1111 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1114 $o .= '<input type="hidden" ' .
1115 'name="grademodified_' . $userid . '" ' .
1116 'value="' . $modified . '"/>';
1119 $scaleid = (int)$grade;
1120 if (isset($this->cache['scale'][$scaleid])) {
1121 $o .= $this->cache['scale'][$scaleid];
1131 * Load a list of users enrolled in the current course with the specified permission and group.
1134 * @param int $currentgroup
1135 * @param bool $idsonly
1136 * @return array List of user records
1138 public function list_participants($currentgroup, $idsonly) {
1140 return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id');
1142 return get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1147 * Load a count of valid teams for this assignment.
1149 * @return int number of valid teams
1151 public function count_teams() {
1153 $groups = groups_get_all_groups($this->get_course()->id,
1155 $this->get_instance()->teamsubmissiongroupingid,
1157 $count = count($groups);
1159 // See if there are any users in the default group.
1160 $defaultusers = $this->get_submission_group_members(0, true);
1161 if (count($defaultusers) > 0) {
1168 * Load a count of users enrolled in the current course with the specified permission and group.
1171 * @param int $currentgroup
1172 * @return int number of matching users
1174 public function count_participants($currentgroup) {
1175 return count_enrolled_users($this->context, 'mod/assign:submit', $currentgroup);
1179 * Load a count of users submissions in the current module that require grading
1180 * This means the submission modification time is more recent than the
1181 * grading modification time and the status is SUBMITTED.
1183 * @return int number of matching submissions
1185 public function count_submissions_need_grading() {
1188 if ($this->get_instance()->teamsubmission) {
1189 // This does not make sense for group assignment because the submission is shared.
1193 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1194 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1196 $params['assignid'] = $this->get_instance()->id;
1197 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1199 $sql = 'SELECT COUNT(s.userid)
1200 FROM {assign_submission} s
1201 LEFT JOIN {assign_grades} g ON
1202 s.assignment = g.assignment AND
1204 JOIN(' . $esql . ') e ON e.id = s.userid
1206 s.assignment = :assignid AND
1207 s.timemodified IS NOT NULL AND
1208 s.status = :submitted AND
1209 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1211 return $DB->count_records_sql($sql, $params);
1215 * Load a count of grades.
1217 * @return int number of grades
1219 public function count_grades() {
1222 if (!$this->has_instance()) {
1226 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1227 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1229 $params['assignid'] = $this->get_instance()->id;
1231 $sql = 'SELECT COUNT(g.userid)
1232 FROM {assign_grades} g
1233 JOIN(' . $esql . ') e ON e.id = g.userid
1234 WHERE g.assignment = :assignid';
1236 return $DB->count_records_sql($sql, $params);
1240 * Load a count of submissions.
1242 * @return int number of submissions
1244 public function count_submissions() {
1247 if (!$this->has_instance()) {
1253 if ($this->get_instance()->teamsubmission) {
1254 // We cannot join on the enrolment tables for group submissions (no userid).
1255 $sql = 'SELECT COUNT(s.groupid)
1256 FROM {assign_submission} s
1258 s.assignment = :assignid AND
1259 s.timemodified IS NOT NULL AND
1260 s.userid = :groupuserid';
1262 $params['assignid'] = $this->get_instance()->id;
1263 $params['groupuserid'] = 0;
1265 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1266 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1268 $params['assignid'] = $this->get_instance()->id;
1270 $sql = 'SELECT COUNT(s.userid)
1271 FROM {assign_submission} s
1272 JOIN(' . $esql . ') e ON e.id = s.userid
1274 s.assignment = :assignid AND
1275 s.timemodified IS NOT NULL';
1278 return $DB->count_records_sql($sql, $params);
1282 * Load a count of submissions with a specified status.
1284 * @param string $status The submission status - should match one of the constants
1285 * @return int number of matching submissions
1287 public function count_submissions_with_status($status) {
1290 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1291 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, false);
1293 $params['assignid'] = $this->get_instance()->id;
1294 $params['submissionstatus'] = $status;
1296 if ($this->get_instance()->teamsubmission) {
1297 $sql = 'SELECT COUNT(s.groupid)
1298 FROM {assign_submission} s
1300 s.assignment = :assignid AND
1301 s.timemodified IS NOT NULL AND
1302 s.userid = :groupuserid AND
1303 s.status = :submissionstatus';
1304 $params['groupuserid'] = 0;
1306 $sql = 'SELECT COUNT(s.userid)
1307 FROM {assign_submission} s
1308 JOIN(' . $esql . ') e ON e.id = s.userid
1310 s.assignment = :assignid AND
1311 s.timemodified IS NOT NULL AND
1312 s.status = :submissionstatus';
1315 return $DB->count_records_sql($sql, $params);
1319 * Utility function to get the userid for every row in the grading table
1320 * so the order can be frozen while we iterate it.
1322 * @return array An array of userids
1324 protected function get_grading_userid_list() {
1325 $filter = get_user_preferences('assign_filter', '');
1326 $table = new assign_grading_table($this, 0, $filter, 0, false);
1328 $useridlist = $table->get_column_data('userid');
1334 * Generate zip file from array of given files.
1336 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1337 * This array is indexed by the final file name and each
1338 * element in the array is an instance of a stored_file object.
1339 * @return path of temp file - note this returned file does
1340 * not have a .zip extension - it is a temp file.
1342 protected function pack_files($filesforzipping) {
1344 // Create path for new zip file.
1345 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1347 $zipper = new zip_packer();
1348 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1355 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1357 * Cron function to be run periodically according to the moodle cron.
1361 public static function cron() {
1364 // Only ever send a max of one days worth of updates.
1365 $yesterday = time() - (24 * 3600);
1368 // Collect all submissions from the past 24 hours that require mailing.
1369 $sql = 'SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
1370 g.*, g.id as gradeid, g.timemodified as lastmodified
1372 JOIN {assign_grades} g ON g.assignment = a.id
1373 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1374 WHERE g.timemodified >= :yesterday AND
1375 g.timemodified <= :today AND
1378 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1379 $submissions = $DB->get_records_sql($sql, $params);
1381 if (empty($submissions)) {
1385 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1387 // Preload courses we are going to need those.
1388 $courseids = array();
1389 foreach ($submissions as $submission) {
1390 $courseids[] = $submission->course;
1393 // Filter out duplicates.
1394 $courseids = array_unique($courseids);
1395 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1396 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1397 $sql = 'SELECT c.*, ' . $ctxselect .
1399 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1400 WHERE c.id ' . $courseidsql;
1402 $params['contextlevel'] = CONTEXT_COURSE;
1403 $courses = $DB->get_records_sql($sql, $params);
1405 // Clean up... this could go on for a while.
1408 unset($courseidsql);
1411 // Simple array we'll use for caching modules.
1412 $modcache = array();
1414 // Message students about new feedback.
1415 foreach ($submissions as $submission) {
1417 mtrace("Processing assignment submission $submission->id ...");
1419 // Do not cache user lookups - could be too many.
1420 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1421 mtrace('Could not find user ' . $submission->userid);
1425 // Use a cache to prevent the same DB queries happening over and over.
1426 if (!array_key_exists($submission->course, $courses)) {
1427 mtrace('Could not find course ' . $submission->course);
1430 $course = $courses[$submission->course];
1431 if (isset($course->ctxid)) {
1432 // Context has not yet been preloaded. Do so now.
1433 context_helper::preload_from_record($course);
1436 // Override the language and timezone of the "current" user, so that
1437 // mail is customised for the receiver.
1438 cron_setup_user($user, $course);
1440 // Context lookups are already cached.
1441 $coursecontext = context_course::instance($course->id);
1442 if (!is_enrolled($coursecontext, $user->id)) {
1443 $courseshortname = format_string($course->shortname,
1445 array('context' => $coursecontext));
1446 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1450 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1451 mtrace('Could not find grader ' . $submission->grader);
1455 if (!array_key_exists($submission->assignment, $modcache)) {
1456 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1458 mtrace('Could not find course module for assignment id ' . $submission->assignment);
1461 $modcache[$submission->assignment] = $mod;
1463 $mod = $modcache[$submission->assignment];
1465 // Context lookups are already cached.
1466 $contextmodule = context_module::instance($mod->id);
1468 if (!$mod->visible) {
1469 // Hold mail notification for hidden assignments until later.
1473 // Need to send this to the student.
1474 $messagetype = 'feedbackavailable';
1475 $eventtype = 'assign_notification';
1476 $updatetime = $submission->lastmodified;
1477 $modulename = get_string('modulename', 'assign');
1480 if ($submission->blindmarking && !$submission->revealidentities) {
1481 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1483 $showusers = $submission->blindmarking && !$submission->revealidentities;
1484 self::send_assignment_notification($grader,
1497 $grade = new stdClass();
1498 $grade->id = $submission->gradeid;
1500 $DB->update_record('assign_grades', $grade);
1504 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1508 // Free up memory just to be sure.
1516 * Update a grade in the grade table for the assignment and in the gradebook.
1518 * @param stdClass $grade a grade record keyed on id
1519 * @return bool true for success
1521 public function update_grade($grade) {
1524 $grade->timemodified = time();
1526 if ($grade->grade && $grade->grade != -1) {
1527 if ($this->get_instance()->grade > 0) {
1528 if (!is_numeric($grade->grade)) {
1530 } else if ($grade->grade > $this->get_instance()->grade) {
1532 } else if ($grade->grade < 0) {
1537 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1538 $scaleoptions = make_menu_from_list($scale->scale);
1539 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1546 $result = $DB->update_record('assign_grades', $grade);
1548 $this->gradebook_item_update(null, $grade);
1554 * View the grant extension date page.
1556 * Uses url parameters 'userid'
1557 * or from parameter 'selectedusers'
1559 * @param moodleform $mform - Used for validation of the submitted data
1562 protected function view_grant_extension($mform) {
1564 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1567 $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
1568 $data = new stdClass();
1569 $data->extensionduedate = null;
1572 $userid = required_param('userid', PARAM_INT);
1574 $grade = $this->get_user_grade($userid, false);
1576 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1579 $data->extensionduedate = $grade->extensionduedate;
1581 $data->userid = $userid;
1583 $data->batchusers = $batchusers;
1585 $header = new assign_header($this->get_instance(),
1586 $this->get_context(),
1587 $this->show_intro(),
1588 $this->get_course_module()->id,
1589 get_string('grantextension', 'assign'));
1590 $o .= $this->get_renderer()->render($header);
1593 $formparams = array($this->get_course_module()->id,
1596 $this->get_instance(),
1598 $mform = new mod_assign_extension_form(null, $formparams);
1600 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1601 $o .= $this->view_footer();
1606 * Get a list of the users in the same group as this user.
1608 * @param int $groupid The id of the group whose members we want or 0 for the default group
1609 * @param bool $onlyids Whether to retrieve only the user id's
1610 * @return array The users (possibly id's only)
1612 public function get_submission_group_members($groupid, $onlyids) {
1614 if ($groupid != 0) {
1616 $allusers = groups_get_members($groupid, 'u.id');
1618 $allusers = groups_get_members($groupid);
1620 foreach ($allusers as $user) {
1621 if ($this->get_submission_group($user->id)) {
1626 $allusers = $this->list_participants(null, $onlyids);
1627 foreach ($allusers as $user) {
1628 if ($this->get_submission_group($user->id) == null) {
1637 * Get a list of the users in the same group as this user that have not submitted the assignment.
1639 * @param int $groupid The id of the group whose members we want or 0 for the default group
1640 * @param bool $onlyids Whether to retrieve only the user id's
1641 * @return array The users (possibly id's only)
1643 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1644 $instance = $this->get_instance();
1645 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1648 $members = $this->get_submission_group_members($groupid, $onlyids);
1650 foreach ($members as $id => $member) {
1651 $submission = $this->get_user_submission($member->id, false);
1652 if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
1653 unset($members[$id]);
1655 if ($this->is_blind_marking()) {
1656 $members[$id]->alias = get_string('hiddenuser', 'assign') .
1657 $this->get_uniqueid_for_user($id);
1665 * Load the group submission object for a particular user, optionally creating it if required.
1667 * @param int $userid The id of the user whose submission we want
1668 * @param int $groupid The id of the group for this user - may be 0 in which
1669 * case it is determined from the userid.
1670 * @param bool $create If set to true a new submission object will be created in the database
1671 * @return stdClass The submission
1673 public function get_group_submission($userid, $groupid, $create) {
1676 if ($groupid == 0) {
1677 $group = $this->get_submission_group($userid);
1679 $groupid = $group->id;
1684 // Make sure there is a submission for this user.
1685 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
1686 $submission = $DB->get_record('assign_submission', $params);
1689 $submission = new stdClass();
1690 $submission->assignment = $this->get_instance()->id;
1691 $submission->userid = $userid;
1692 $submission->groupid = 0;
1693 $submission->timecreated = time();
1694 $submission->timemodified = $submission->timecreated;
1696 if ($this->get_instance()->submissiondrafts) {
1697 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1699 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1701 $DB->insert_record('assign_submission', $submission);
1704 // Now get the group submission.
1705 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1706 $submission = $DB->get_record('assign_submission', $params);
1712 $submission = new stdClass();
1713 $submission->assignment = $this->get_instance()->id;
1714 $submission->userid = 0;
1715 $submission->groupid = $groupid;
1716 $submission->timecreated = time();
1717 $submission->timemodified = $submission->timecreated;
1719 if ($this->get_instance()->submissiondrafts) {
1720 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1722 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1724 $sid = $DB->insert_record('assign_submission', $submission);
1725 $submission->id = $sid;
1732 * View a summary listing of all assignments in the current course.
1736 private function view_course_index() {
1741 $course = $this->get_course();
1742 $strplural = get_string('modulenameplural', 'assign');
1744 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1745 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1746 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
1750 $strsectionname = get_string('sectionname', 'format_'.$course->format);
1751 $usesections = course_format_uses_sections($course->format);
1752 $modinfo = get_fast_modinfo($course);
1755 $sections = $modinfo->get_section_info_all();
1757 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
1761 $currentsection = '';
1762 foreach ($modinfo->instances['assign'] as $cm) {
1763 if (!$cm->uservisible) {
1767 $timedue = $cms[$cm->id]->duedate;
1770 if ($usesections && $cm->sectionnum) {
1771 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
1775 $context = context_module::instance($cm->id);
1777 $assignment = new assign($context, $cm, $course);
1779 if (has_capability('mod/assign:grade', $context)) {
1780 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
1782 } else if (has_capability('mod/assign:submit', $context)) {
1783 $usersubmission = $assignment->get_user_submission($USER->id, false);
1785 if (!empty($usersubmission->status)) {
1786 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
1788 $submitted = get_string('submissionstatus_', 'assign');
1791 $grading_info = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
1792 if (isset($grading_info->items[0]) && !$grading_info->items[0]->grades[$USER->id]->hidden ) {
1793 $grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
1798 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
1802 $o .= $this->get_renderer()->render($courseindexsummary);
1803 $o .= $this->view_footer();
1809 * View a page rendered by a plugin.
1811 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
1815 protected function view_plugin_page() {
1820 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
1821 $plugintype = required_param('plugin', PARAM_TEXT);
1822 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
1824 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
1826 print_error('invalidformdata', '');
1830 $o .= $plugin->view_page($pluginaction);
1837 * This is used for team assignments to get the group for the specified user.
1838 * If the user is a member of multiple or no groups this will return false
1840 * @param int $userid The id of the user whose submission we want
1841 * @return mixed The group or false
1843 public function get_submission_group($userid) {
1844 $grouping = $this->get_instance()->teamsubmissiongroupingid;
1845 $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
1846 if (count($groups) != 1) {
1849 return array_pop($groups);
1854 * Display the submission that is used by a plugin.
1856 * Uses url parameters 'sid', 'gid' and 'plugin'.
1858 * @param string $pluginsubtype
1861 protected function view_plugin_content($pluginsubtype) {
1866 $submissionid = optional_param('sid', 0, PARAM_INT);
1867 $gradeid = optional_param('gid', 0, PARAM_INT);
1868 $plugintype = required_param('plugin', PARAM_TEXT);
1870 if ($pluginsubtype == 'assignsubmission') {
1871 $plugin = $this->get_submission_plugin_by_type($plugintype);
1872 if ($submissionid <= 0) {
1873 throw new coding_exception('Submission id should not be 0');
1875 $item = $this->get_submission($submissionid);
1877 // Check permissions.
1878 if ($item->userid != $USER->id) {
1879 require_capability('mod/assign:grade', $this->context);
1881 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1882 $this->get_context(),
1883 $this->show_intro(),
1884 $this->get_course_module()->id,
1885 $plugin->get_name()));
1886 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
1888 assign_submission_plugin_submission::FULL,
1889 $this->get_course_module()->id,
1890 $this->get_return_action(),
1891 $this->get_return_params()));
1893 $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
1894 $this->add_to_log('view submission', $logmessage);
1896 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1897 if ($gradeid <= 0) {
1898 throw new coding_exception('Grade id should not be 0');
1900 $item = $this->get_grade($gradeid);
1901 // Check permissions.
1902 if ($item->userid != $USER->id) {
1903 require_capability('mod/assign:grade', $this->context);
1905 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1906 $this->get_context(),
1907 $this->show_intro(),
1908 $this->get_course_module()->id,
1909 $plugin->get_name()));
1910 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
1912 assign_feedback_plugin_feedback::FULL,
1913 $this->get_course_module()->id,
1914 $this->get_return_action(),
1915 $this->get_return_params()));
1916 $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
1917 $this->add_to_log('view feedback', $logmessage);
1920 $o .= $this->view_return_links();
1922 $o .= $this->view_footer();
1927 * Render the content in editor that is often used by plugin.
1929 * @param string $filearea
1930 * @param int $submissionid
1931 * @param string $plugintype
1932 * @param string $editor
1933 * @param string $component
1936 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1941 $plugin = $this->get_submission_plugin_by_type($plugintype);
1943 $text = $plugin->get_editor_text($editor, $submissionid);
1944 $format = $plugin->get_editor_format($editor, $submissionid);
1946 $finaltext = file_rewrite_pluginfile_urls($text,
1948 $this->get_context()->id,
1952 $params = array('overflowdiv' => true, 'context' => $this->get_context());
1953 $result .= format_text($finaltext, $format, $params);
1955 if ($CFG->enableportfolios) {
1956 require_once($CFG->libdir . '/portfoliolib.php');
1958 $button = new portfolio_add_button();
1959 $portfolioparams = array('cmid' => $this->get_course_module()->id,
1960 'sid' => $submissionid,
1961 'plugin' => $plugintype,
1962 'editor' => $editor,
1964 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
1965 $fs = get_file_storage();
1967 if ($files = $fs->get_area_files($this->context->id,
1973 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1975 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1977 $result .= $button->to_html();
1983 * Display a grading error.
1985 * @param string $message - The description of the result
1988 protected function view_quickgrading_result($message) {
1990 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
1991 $this->get_context(),
1992 $this->show_intro(),
1993 $this->get_course_module()->id,
1994 get_string('quickgradingresult', 'assign')));
1995 $gradingresult = new assign_quickgrading_result($message, $this->get_course_module()->id);
1996 $o .= $this->get_renderer()->render($gradingresult);
1997 $o .= $this->view_footer();
2002 * Display the page footer.
2006 protected function view_footer() {
2007 return $this->get_renderer()->render_footer();
2011 * Does this user have grade permission for this assignment?
2015 protected function can_grade() {
2016 // Permissions check.
2017 if (!has_capability('mod/assign:grade', $this->context)) {
2025 * Download a zip file of all assignment submissions.
2029 protected function download_submissions() {
2032 // More efficient to load this here.
2033 require_once($CFG->libdir.'/filelib.php');
2035 // Load all users with submit.
2036 $students = get_enrolled_users($this->context, "mod/assign:submit");
2038 // Build a list of files to zip.
2039 $filesforzipping = array();
2040 $fs = get_file_storage();
2042 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2047 $groupid = groups_get_activity_group($this->get_course_module(), true);
2048 $groupname = groups_get_group_name($groupid).'-';
2051 // Construct the zip file name.
2052 $filename = clean_filename($this->get_course()->shortname . '-' .
2053 $this->get_instance()->name . '-' .
2054 $groupname.$this->get_course_module()->id . '.zip');
2056 // Get all the files for each student.
2057 foreach ($students as $student) {
2058 $userid = $student->id;
2060 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2061 // Get the plugins to add their own files to the zip.
2063 $submissiongroup = false;
2065 if ($this->get_instance()->teamsubmission) {
2066 $submission = $this->get_group_submission($userid, 0, false);
2067 $submissiongroup = $this->get_submission_group($userid);
2068 if ($submissiongroup) {
2069 $groupname = $submissiongroup->name . '-';
2071 $groupname = get_string('defaultteam', 'assign') . '-';
2074 $submission = $this->get_user_submission($userid, false);
2077 if ($this->is_blind_marking()) {
2078 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2079 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2081 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2082 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2086 foreach ($this->submissionplugins as $plugin) {
2087 if ($plugin->is_enabled() && $plugin->is_visible()) {
2088 $pluginfiles = $plugin->get_files($submission);
2089 foreach ($pluginfiles as $zipfilename => $file) {
2090 $subtype = $plugin->get_subtype();
2091 $type = $plugin->get_type();
2092 $prefixedfilename = clean_filename($prefix .
2098 $filesforzipping[$prefixedfilename] = $file;
2106 if (count($filesforzipping) == 0) {
2107 $header = new assign_header($this->get_instance(),
2108 $this->get_context(),
2110 $this->get_course_module()->id,
2111 get_string('downloadall', 'assign'));
2112 $result .= $this->get_renderer()->render($header);
2113 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2114 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2115 'action'=>'grading'));
2116 $result .= $this->get_renderer()->continue_button($url);
2117 $result .= $this->view_footer();
2118 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2119 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
2120 // Send file and delete after sending.
2121 send_temp_file($zipfile, $filename);
2122 // We will not get here - send_temp_file calls exit.
2128 * Util function to add a message to the log.
2130 * @param string $action The current action
2131 * @param string $info A detailed description of the change. But no more than 255 characters.
2132 * @param string $url The url to the assign module instance.
2135 public function add_to_log($action = '', $info = '', $url='') {
2138 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2140 $fullurl .= '&' . $url;
2143 add_to_log($this->get_course()->id,
2148 $this->get_course_module()->id,
2153 * Lazy load the page renderer and expose the renderer to plugins.
2155 * @return assign_renderer
2157 public function get_renderer() {
2159 if ($this->output) {
2160 return $this->output;
2162 $this->output = $PAGE->get_renderer('mod_assign');
2163 return $this->output;
2167 * Load the submission object for a particular user, optionally creating it if required.
2169 * For team assignments there are 2 submissions - the student submission and the team submission
2170 * All files are associated with the team submission but the status of the students contribution is
2171 * recorded separately.
2173 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2174 * @param bool $create optional - defaults to false. If set to true a new submission object
2175 * will be created in the database.
2176 * @return stdClass The submission
2178 public function get_user_submission($userid, $create) {
2182 $userid = $USER->id;
2184 // If the userid is not null then use userid.
2185 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2186 $submission = $DB->get_record('assign_submission', $params);
2192 $submission = new stdClass();
2193 $submission->assignment = $this->get_instance()->id;
2194 $submission->userid = $userid;
2195 $submission->timecreated = time();
2196 $submission->timemodified = $submission->timecreated;
2197 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2198 $sid = $DB->insert_record('assign_submission', $submission);
2199 $submission->id = $sid;
2206 * Load the submission object from it's id.
2208 * @param int $submissionid The id of the submission we want
2209 * @return stdClass The submission
2211 protected function get_submission($submissionid) {
2214 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2215 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2219 * This will retrieve a grade object from the db, optionally creating it if required.
2221 * @param int $userid The user we are grading
2222 * @param bool $create If true the grade will be created if it does not exist
2223 * @return stdClass The grade record
2225 public function get_user_grade($userid, $create) {
2229 $userid = $USER->id;
2232 // If the userid is not null then use userid.
2233 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
2239 $grade = new stdClass();
2240 $grade->assignment = $this->get_instance()->id;
2241 $grade->userid = $userid;
2242 $grade->timecreated = time();
2243 $grade->timemodified = $grade->timecreated;
2246 $grade->grader = $USER->id;
2247 $grade->extensionduedate = 0;
2248 $gid = $DB->insert_record('assign_grades', $grade);
2256 * This will retrieve a grade object from the db.
2258 * @param int $gradeid The id of the grade
2259 * @return stdClass The grade record
2261 protected function get_grade($gradeid) {
2264 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2265 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2269 * Print the grading page for a single user submission.
2271 * @param moodleform $mform
2272 * @param int $offset
2275 protected function view_single_grade_page($mform, $offset=0) {
2279 $instance = $this->get_instance();
2281 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2283 // Need submit permission to submit an assignment.
2284 require_capability('mod/assign:grade', $this->context);
2286 $header = new assign_header($instance,
2287 $this->get_context(),
2289 $this->get_course_module()->id,
2290 get_string('grading', 'assign'));
2291 $o .= $this->get_renderer()->render($header);
2293 $rownum = required_param('rownum', PARAM_INT) + $offset;
2294 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
2296 $useridlist = explode(',', $useridlist);
2298 $useridlist = $this->get_grading_userid_list();
2301 $userid = $useridlist[$rownum];
2302 if ($rownum == count($useridlist) - 1) {
2306 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2308 $user = $DB->get_record('user', array('id' => $userid));
2310 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2311 $usersummary = new assign_user_summary($user,
2312 $this->get_course()->id,
2314 $this->is_blind_marking(),
2315 $this->get_uniqueid_for_user($user->id));
2316 $o .= $this->get_renderer()->render($usersummary);
2318 $submission = $this->get_user_submission($userid, false);
2319 $submissiongroup = null;
2320 $submissiongroupmemberswhohavenotsubmitted = array();
2321 $teamsubmission = null;
2322 $notsubmitted = array();
2323 if ($instance->teamsubmission) {
2324 $teamsubmission = $this->get_group_submission($userid, 0, false);
2325 $submissiongroup = $this->get_submission_group($userid);
2327 if ($submissiongroup) {
2328 $groupid = $submissiongroup->id;
2330 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2334 // Get the current grade.
2335 $grade = $this->get_user_grade($userid, false);
2336 if ($this->can_view_submission($userid)) {
2337 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
2338 $extensionduedate = null;
2340 $extensionduedate = $grade->extensionduedate;
2342 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2344 if ($teamsubmission) {
2345 $showsubmit = $showedit &&
2347 ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2349 $showsubmit = $showedit &&
2351 ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
2353 if (!$this->get_instance()->submissiondrafts) {
2354 $showsubmit = false;
2356 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2358 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2359 $instance->alwaysshowdescription,
2361 $instance->teamsubmission,
2365 $this->is_any_submission_plugin_enabled(),
2367 $this->is_graded($userid),
2369 $instance->cutoffdate,
2370 $this->get_submission_plugins(),
2371 $this->get_return_action(),
2372 $this->get_return_params(),
2373 $this->get_course_module()->id,
2374 $this->get_course()->id,
2375 assign_submission_status::GRADER_VIEW,
2380 $this->get_context(),
2381 $this->is_blind_marking(),
2383 $o .= $this->get_renderer()->render($submissionstatus);
2386 $data = new stdClass();
2387 if ($grade->grade !== null && $grade->grade >= 0) {
2388 $data->grade = format_float($grade->grade, 2);
2391 $data = new stdClass();
2395 // Now show the grading form.
2397 $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
2398 $formparams = array($this, $data, $pagination);
2399 $mform = new mod_assign_grade_form(null,
2403 array('class'=>'gradeform'));
2405 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2407 $msg = get_string('viewgradingformforstudent',
2409 array('id'=>$user->id, 'fullname'=>fullname($user)));
2410 $this->add_to_log('view grading form', $msg);
2412 $o .= $this->view_footer();
2417 * Show a confirmation page to make sure they want to release student identities.
2421 protected function view_reveal_identities_confirm() {
2424 require_capability('mod/assign:revealidentities', $this->get_context());
2427 $header = new assign_header($this->get_instance(),
2428 $this->get_context(),
2430 $this->get_course_module()->id);
2431 $o .= $this->get_renderer()->render($header);
2433 $urlparams = array('id'=>$this->get_course_module()->id,
2434 'action'=>'revealidentitiesconfirm',
2435 'sesskey'=>sesskey());
2436 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2438 $urlparams = array('id'=>$this->get_course_module()->id,
2439 'action'=>'grading');
2440 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2442 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2445 $o .= $this->view_footer();
2446 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2451 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2455 protected function view_return_links() {
2456 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2457 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2460 parse_str($returnparams, $params);
2461 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2462 $params = array_merge($newparams, $params);
2464 $url = new moodle_url('/mod/assign/view.php', $params);
2465 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2469 * View the grading table of all submissions for this assignment.
2473 protected function view_grading_table() {
2476 // Include grading options form.
2477 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2478 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2479 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2481 $cmid = $this->get_course_module()->id;
2484 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2485 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2486 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2487 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2489 if ($this->is_any_submission_plugin_enabled()) {
2490 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2491 $links[$downloadurl] = get_string('downloadall', 'assign');
2493 if ($this->is_blind_marking() &&
2494 has_capability('mod/assign:revealidentities', $this->get_context())) {
2495 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2496 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2498 foreach ($this->get_feedback_plugins() as $plugin) {
2499 if ($plugin->is_enabled() && $plugin->is_visible()) {
2500 foreach ($plugin->get_grading_actions() as $action => $description) {
2501 $url = '/mod/assign/view.php' .
2503 '&plugin=' . $plugin->get_type() .
2504 '&pluginsubtype=assignfeedback' .
2505 '&action=viewpluginpage&pluginaction=' . $action;
2506 $links[$url] = $description;
2511 $gradingactions = new url_select($links);
2512 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2514 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2516 $perpage = get_user_preferences('assign_perpage', 10);
2517 $filter = get_user_preferences('assign_filter', '');
2518 $controller = $gradingmanager->get_active_controller();
2519 $showquickgrading = empty($controller);
2520 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
2521 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
2522 set_user_preference('assign_quickgrading', $quickgrading);
2524 $quickgrading = get_user_preferences('assign_quickgrading', false);
2526 // Print options for changing the filter and changing the number of results per page.
2527 $gradingoptionsformparams = array('cm'=>$cmid,
2528 'contextid'=>$this->context->id,
2529 'userid'=>$USER->id,
2530 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2531 'showquickgrading'=>$showquickgrading,
2532 'quickgrading'=>$quickgrading);
2534 $classoptions = array('class'=>'gradingoptionsform');
2535 $gradingoptionsform = new mod_assign_grading_options_form(null,
2536 $gradingoptionsformparams,
2541 $batchformparams = array('cm'=>$cmid,
2542 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2543 'duedate'=>$this->get_instance()->duedate,
2544 'feedbackplugins'=>$this->get_feedback_plugins());
2545 $classoptions = array('class'=>'gradingbatchoperationsform');
2547 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2553 $gradingoptionsdata = new stdClass();
2554 $gradingoptionsdata->perpage = $perpage;
2555 $gradingoptionsdata->filter = $filter;
2556 $gradingoptionsform->set_data($gradingoptionsdata);
2558 $actionformtext = $this->get_renderer()->render($gradingactions);
2559 $header = new assign_header($this->get_instance(),
2560 $this->get_context(),
2562 $this->get_course_module()->id,
2563 get_string('grading', 'assign'),
2565 $o .= $this->get_renderer()->render($header);
2567 $currenturl = $CFG->wwwroot .
2568 '/mod/assign/view.php?id=' .
2569 $this->get_course_module()->id .
2572 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
2574 // Plagiarism update status apearring in the grading book.
2575 if (!empty($CFG->enableplagiarism)) {
2576 require_once($CFG->libdir . '/plagiarismlib.php');
2577 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
2580 // Load and print the table of submissions.
2581 if ($showquickgrading && $quickgrading) {
2582 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
2583 $table = $this->get_renderer()->render($gradingtable);
2584 $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
2585 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
2587 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
2589 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
2590 $o .= $this->get_renderer()->render($gradingtable);
2593 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2594 $users = array_keys($this->list_participants($currentgroup, true));
2595 if (count($users) != 0) {
2596 // If no enrolled user in a course then don't display the batch operations feature.
2597 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
2598 $o .= $this->get_renderer()->render($assignform);
2600 $assignform = new assign_form('gradingoptionsform',
2601 $gradingoptionsform,
2602 'M.mod_assign.init_grading_options');
2603 $o .= $this->get_renderer()->render($assignform);
2608 * View entire grading page.
2612 protected function view_grading_page() {
2616 // Need submit permission to submit an assignment.
2617 require_capability('mod/assign:grade', $this->context);
2618 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2620 // Only load this if it is.
2622 $o .= $this->view_grading_table();
2624 $o .= $this->view_footer();
2626 $logmessage = get_string('viewsubmissiongradingtable', 'assign');
2627 $this->add_to_log('view submission grading table', $logmessage);
2632 * Capture the output of the plagiarism plugins disclosures and return it as a string.
2636 protected function plagiarism_print_disclosure() {
2640 if (!empty($CFG->enableplagiarism)) {
2641 require_once($CFG->libdir . '/plagiarismlib.php');
2643 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
2650 * Message for students when assignment submissions have been closed.
2654 protected function view_student_error_message() {
2658 // Need submit permission to submit an assignment.
2659 require_capability('mod/assign:submit', $this->context);
2661 $header = new assign_header($this->get_instance(),
2662 $this->get_context(),
2663 $this->show_intro(),
2664 $this->get_course_module()->id,
2665 get_string('editsubmission', 'assign'));
2666 $o .= $this->get_renderer()->render($header);
2668 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
2670 $o .= $this->view_footer();
2677 * View edit submissions page.
2679 * @param moodleform $mform
2680 * @param array $notices A list of notices to display at the top of the
2681 * edit submission form (e.g. from plugins).
2684 protected function view_edit_submission_page($mform, $notices) {
2688 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2689 // Need submit permission to submit an assignment.
2690 require_capability('mod/assign:submit', $this->context);
2692 if (!$this->submissions_open()) {
2693 return $this->view_student_error_message();
2695 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2696 $this->get_context(),
2697 $this->show_intro(),
2698 $this->get_course_module()->id,
2699 get_string('editsubmission', 'assign')));
2700 $o .= $this->plagiarism_print_disclosure();
2701 $data = new stdClass();
2704 $mform = new mod_assign_submission_form(null, array($this, $data));
2707 foreach ($notices as $notice) {
2708 $o .= $this->get_renderer()->notification($notice);
2711 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
2713 $o .= $this->view_footer();
2714 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
2720 * See if this assignment has a grade yet.
2722 * @param int $userid
2725 protected function is_graded($userid) {
2726 $grade = $this->get_user_grade($userid, false);
2728 return ($grade->grade !== null && $grade->grade >= 0);
2734 * Perform an access check to see if the current $USER can view this users submission.
2736 * @param int $userid
2739 public function can_view_submission($userid) {
2742 if (!is_enrolled($this->get_course_context(), $userid)) {
2745 if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
2748 if (has_capability('mod/assign:grade', $this->context)) {
2755 * Allows the plugin to show a batch grading operation page.
2759 protected function view_plugin_grading_batch_operation($mform) {
2760 require_capability('mod/assign:grade', $this->context);
2761 $prefix = 'plugingradingbatchoperation_';
2763 if ($data = $mform->get_data()) {
2764 $tail = substr($data->operation, strlen($prefix));
2765 list($plugintype, $action) = explode('_', $tail, 2);
2767 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2769 $users = $data->selectedusers;
2770 $userlist = explode(',', $users);
2771 echo $plugin->grading_batch_operation($action, $userlist);
2775 print_error('invalidformdata', '');
2779 * Ask the user to confirm they want to perform this batch operation
2781 * @param moodleform $mform Set to a grading batch operations form
2782 * @return string - the page to view after processing these actions
2784 protected function process_grading_batch_operation(& $mform) {
2786 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2789 $batchformparams = array('cm'=>$this->get_course_module()->id,
2790 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
2791 'duedate'=>$this->get_instance()->duedate,
2792 'feedbackplugins'=>$this->get_feedback_plugins());
2793 $formclasses = array('class'=>'gradingbatchoperationsform');
2794 $mform = new mod_assign_grading_batch_operations_form(null,
2800 if ($data = $mform->get_data()) {
2801 // Get the list of users.
2802 $users = $data->selectedusers;
2803 $userlist = explode(',', $users);
2805 $prefix = 'plugingradingbatchoperation_';
2807 if ($data->operation == 'grantextension') {
2808 // Reset the form so the grant extension page will create the extension form.
2810 return 'grantextension';
2811 } else if (strpos($data->operation, $prefix) === 0) {
2812 $tail = substr($data->operation, strlen($prefix));
2813 list($plugintype, $action) = explode('_', $tail, 2);
2815 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2817 return 'plugingradingbatchoperation';
2821 foreach ($userlist as $userid) {
2822 if ($data->operation == 'lock') {
2823 $this->process_lock($userid);
2824 } else if ($data->operation == 'unlock') {
2825 $this->process_unlock($userid);
2826 } else if ($data->operation == 'reverttodraft') {
2827 $this->process_revert_to_draft($userid);
2836 * Ask the user to confirm they want to submit their work for grading.
2838 * @param $mform moodleform - null unless form validation has failed
2841 protected function check_submit_for_grading($mform) {
2844 require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
2846 // Check that all of the submission plugins are ready for this submission.
2847 $notifications = array();
2848 $submission = $this->get_user_submission($USER->id, false);
2849 $plugins = $this->get_submission_plugins();
2850 foreach ($plugins as $plugin) {
2851 if ($plugin->is_enabled() && $plugin->is_visible()) {
2852 $check = $plugin->precheck_submission($submission);
2853 if ($check !== true) {
2854 $notifications[] = $check;
2859 $data = new stdClass();
2860 $adminconfig = $this->get_admin_config();
2861 $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
2862 $this->get_instance()->requiresubmissionstatement) &&
2863 !empty($adminconfig->submissionstatement);
2865 $submissionstatement = '';
2866 if (!empty($adminconfig->submissionstatement)) {
2867 $submissionstatement = $adminconfig->submissionstatement;
2870 if ($mform == null) {
2871 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
2872 $submissionstatement,
2873 $this->get_course_module()->id,
2877 $o .= $this->get_renderer()->header();
2878 $submitforgradingpage = new assign_submit_for_grading_page($notifications,
2879 $this->get_course_module()->id,
2881 $o .= $this->get_renderer()->render($submitforgradingpage);
2882 $o .= $this->view_footer();
2884 $logmessage = get_string('viewownsubmissionform', 'assign');
2885 $this->add_to_log('view confirm submit assignment form', $logmessage);
2891 * Print 2 tables of information with no action links -
2892 * the submission summary and the grading summary.
2894 * @param stdClass $user the user to print the report for
2895 * @param bool $showlinks - Return plain text or links to the profile
2896 * @return string - the html summary
2898 public function view_student_summary($user, $showlinks) {
2899 global $CFG, $DB, $PAGE;
2901 $instance = $this->get_instance();
2902 $grade = $this->get_user_grade($user->id, false);
2903 $submission = $this->get_user_submission($user->id, false);
2906 $teamsubmission = null;
2907 $submissiongroup = null;
2908 $notsubmitted = array();
2909 if ($instance->teamsubmission) {
2910 $teamsubmission = $this->get_group_submission($user->id, 0, false);
2911 $submissiongroup = $this->get_submission_group($user->id);
2913 if ($submissiongroup) {
2914 $groupid = $submissiongroup->id;
2916 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2919 if ($this->can_view_submission($user->id)) {
2920 $showedit = has_capability('mod/assign:submit', $this->context) &&
2921 $this->submissions_open($user->id) &&
2922 ($this->is_any_submission_plugin_enabled()) &&
2925 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2927 // Grading criteria preview.
2928 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2929 $gradingcontrollerpreview = '';
2930 if ($gradingmethod = $gradingmanager->get_active_method()) {
2931 $controller = $gradingmanager->get_controller($gradingmethod);
2932 if ($controller->is_form_defined()) {
2933 $gradingcontrollerpreview = $controller->render_preview($PAGE);
2937 $showsubmit = ($submission || $teamsubmission) && $showlinks;
2938 if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2939 $showsubmit = false;
2941 if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
2942 $showsubmit = false;
2944 if (!$this->get_instance()->submissiondrafts) {
2945 $showsubmit = false;
2947 $extensionduedate = null;
2949 $extensionduedate = $grade->extensionduedate;
2951 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2953 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2954 $instance->alwaysshowdescription,
2956 $instance->teamsubmission,
2960 $this->is_any_submission_plugin_enabled(),
2962 $this->is_graded($user->id),
2964 $instance->cutoffdate,
2965 $this->get_submission_plugins(),
2966 $this->get_return_action(),
2967 $this->get_return_params(),
2968 $this->get_course_module()->id,
2969 $this->get_course()->id,
2970 assign_submission_status::STUDENT_VIEW,
2975 $this->get_context(),
2976 $this->is_blind_marking(),
2977 $gradingcontrollerpreview);
2978 $o .= $this->get_renderer()->render($submissionstatus);
2980 require_once($CFG->libdir.'/gradelib.php');
2981 require_once($CFG->dirroot.'/grade/grading/lib.php');
2983 $gradinginfo = grade_get_grades($this->get_course()->id,
2989 $gradingitem = $gradinginfo->items[0];
2990 $gradebookgrade = $gradingitem->grades[$user->id];
2992 // Check to see if all feedback plugins are empty.
2993 $emptyplugins = true;
2995 foreach ($this->get_feedback_plugins() as $plugin) {
2996 if ($plugin->is_visible() && $plugin->is_enabled()) {
2997 if (!$plugin->is_empty($grade)) {
2998 $emptyplugins = false;
3004 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
3006 $gradefordisplay = '';
3007 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3009 if ($controller = $gradingmanager->get_active_controller()) {
3010 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
3011 $cangrade = has_capability('mod/assign:grade', $this->get_context());
3012 $gradefordisplay = $controller->render_grade($PAGE,
3015 $gradebookgrade->str_long_grade,
3018 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
3021 $gradeddate = $gradebookgrade->dategraded;
3022 $grader = $DB->get_record('user', array('id'=>$grade->grader));
3024 $feedbackstatus = new assign_feedback_status($gradefordisplay,
3027 $this->get_feedback_plugins(),
3029 $this->get_course_module()->id,
3030 $this->get_return_action(),
3031 $this->get_return_params());
3033 $o .= $this->get_renderer()->render($feedbackstatus);
3041 * View submissions page (contains details of current submission).
3045 protected function view_submission_page() {
3046 global $CFG, $DB, $USER, $PAGE;
3048 $instance = $this->get_instance();
3051 $o .= $this->get_renderer()->render(new assign_header($instance,
3052 $this->get_context(),
3053 $this->show_intro(),
3054 $this->get_course_module()->id));
3056 if ($this->can_grade()) {
3057 $draft = ASSIGN_SUBMISSION_STATUS_DRAFT;
3058 $submitted = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3059 if ($instance->teamsubmission) {
3060 $summary = new assign_grading_summary($this->count_teams(),
3061 $instance->submissiondrafts,
3062 $this->count_submissions_with_status($draft),
3063 $this->is_any_submission_plugin_enabled(),
3064 $this->count_submissions_with_status($submitted),
3065 $instance->cutoffdate,
3067 $this->get_course_module()->id,
3068 $this->count_submissions_need_grading(),
3069 $instance->teamsubmission);
3070 $o .= $this->get_renderer()->render($summary);
3072 $summary = new assign_grading_summary($this->count_participants(0),
3073 $instance->submissiondrafts,
3074 $this->count_submissions_with_status($draft),
3075 $this->is_any_submission_plugin_enabled(),
3076 $this->count_submissions_with_status($submitted),
3077 $instance->cutoffdate,
3079 $this->get_course_module()->id,
3080 $this->count_submissions_need_grading(),
3081 $instance->teamsubmission);
3082 $o .= $this->get_renderer()->render($summary);
3085 $grade = $this->get_user_grade($USER->id, false);
3086 $submission = $this->get_user_submission($USER->id, false);
3088 if ($this->can_view_submission($USER->id)) {
3089 $o .= $this->view_student_summary($USER, true);
3092 $o .= $this->view_footer();
3093 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
3098 * Convert the final raw grade(s) in the grading table for the gradebook.
3100 * @param stdClass $grade
3103 protected function convert_grade_for_gradebook(stdClass $grade) {
3104 $gradebookgrade = array();
3105 if ($grade->grade >= 0) {
3106 $gradebookgrade['rawgrade'] = $grade->grade;
3108 $gradebookgrade['userid'] = $grade->userid;
3109 $gradebookgrade['usermodified'] = $grade->grader;
3110 $gradebookgrade['datesubmitted'] = null;
3111 $gradebookgrade['dategraded'] = $grade->timemodified;
3112 if (isset($grade->feedbackformat)) {
3113 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
3115 if (isset($grade->feedbacktext)) {
3116 $gradebookgrade['feedback'] = $grade->feedbacktext;
3119 return $gradebookgrade;
3123 * Convert submission details for the gradebook.
3125 * @param stdClass $submission
3128 protected function convert_submission_for_gradebook(stdClass $submission) {
3129 $gradebookgrade = array();
3131 $gradebookgrade['userid'] = $submission->userid;
3132 $gradebookgrade['usermodified'] = $submission->userid;
3133 $gradebookgrade['datesubmitted'] = $submission->timemodified;
3135 return $gradebookgrade;
3139 * Update grades in the gradebook.
3141 * @param mixed $submission stdClass|null
3142 * @param mixed $grade stdClass|null
3145 protected function gradebook_item_update($submission=null, $grade=null) {
3147 // Do not push grade to gradebook if blind marking is active as
3148 // the gradebook would reveal the students.
3149 if ($this->is_blind_marking()) {
3152 if ($submission != null) {
3153 if ($submission->userid == 0) {
3154 // This is a group submission update.
3155 $team = groups_get_members($submission->groupid, 'u.id');
3157 foreach ($team as $member) {
3158 $submission->groupid = 0;
3159 $submission->userid = $member->id;
3160 $this->gradebook_item_update($submission, null);
3165 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
3168 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
3170 // Grading is disabled, return.
3171 if ($this->grading_disabled($gradebookgrade['userid'])) {
3174 $assign = clone $this->get_instance();
3175 $assign->cmidnumber = $this->get_course_module()->id;
3177 return assign_grade_item_update($assign, $gradebookgrade);
3181 * Update team submission.
3183 * @param stdClass $submission
3184 * @param int $userid
3185 * @param bool $updatetime
3188 protected function update_team_submission(stdClass $submission, $userid, $updatetime) {
3192 $submission->timemodified = time();
3195 // First update the submission for the current user.
3196 $mysubmission = $this->get_user_submission($userid, true);
3197 $mysubmission->status = $submission->status;
3199 $this->update_submission($mysubmission, 0, $updatetime, false);
3201 // Now check the team settings to see if this assignment qualifies as submitted or draft.
3202 $team = $this->get_submission_group_members($submission->groupid, true);
3204 $allsubmitted = true;
3205 $anysubmitted = false;
3206 foreach ($team as $member) {
3207 $membersubmission = $this->get_user_submission($member->id, false);
3209 if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
3210 $allsubmitted = false;
3211 if ($anysubmitted) {
3215 $anysubmitted = true;
3218 if ($this->get_instance()->requireallteammemberssubmit) {
3219 if ($allsubmitted) {
3220 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3222 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3224 $result= $DB->update_record('assign_submission', $submission);
3226 if ($anysubmitted) {
3227 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
3229 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3231 $result= $DB->update_record('assign_submission', $submission);
3234 $this->gradebook_item_update($submission);