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');
67 * Standard base class for mod_assign (assignment types).
70 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
71 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
76 /** @var stdClass the assignment record that contains the global settings for this assign instance */
79 /** @var context the context of the course module for this assign instance (or just the course if we are
80 creating a new one) */
83 /** @var stdClass the course this assign instance belongs to */
86 /** @var stdClass the admin config for all assign instances */
90 /** @var assign_renderer the custom renderer for this module */
93 /** @var stdClass the course module for this assign instance */
94 private $coursemodule;
96 /** @var array cache for things like the coursemodule name or the scale menu - only lives for a single
100 /** @var array list of the installed submission plugins */
101 private $submissionplugins;
103 /** @var array list of the installed feedback plugins */
104 private $feedbackplugins;
106 /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
107 private $returnaction = 'view';
109 /** @var array params to be used to return to this page */
110 private $returnparams = array();
112 /** @var string modulename prevents excessive calls to get_string */
113 private static $modulename = null;
115 /** @var string modulenameplural prevents excessive calls to get_string */
116 private static $modulenameplural = null;
119 * Constructor for the base assign class
121 * @param mixed $coursemodulecontext context|null the course module context (or the course context if the coursemodule has not been created yet)
122 * @param mixed $coursemodule the current course module if it was already loaded - otherwise this class will load one from the context as required
123 * @param mixed $course the current course if it was already loaded - otherwise this class will load one from the context as required
125 public function __construct($coursemodulecontext, $coursemodule, $course) {
128 $this->context = $coursemodulecontext;
129 $this->coursemodule = $coursemodule;
130 $this->course = $course;
131 $this->cache = array(); // temporary cache only lives for a single request - used to reduce db lookups
133 $this->submissionplugins = $this->load_plugins('assignsubmission');
134 $this->feedbackplugins = $this->load_plugins('assignfeedback');
135 $this->output = $PAGE->get_renderer('mod_assign');
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;
220 * get a specific submission plugin by its type
221 * @param string $subtype assignsubmission | assignfeedback
222 * @param string $type
223 * @return mixed assign_plugin|null
225 private function get_plugin_by_type($subtype, $type) {
226 $shortsubtype = substr($subtype, strlen('assign'));
227 $name = $shortsubtype . 'plugins';
228 $pluginlist = $this->$name;
229 foreach ($pluginlist as $plugin) {
230 if ($plugin->get_type() == $type) {
238 * Get a feedback plugin by type
239 * @param string $type - The type of plugin e.g comments
240 * @return mixed assign_feedback_plugin|null
242 public function get_feedback_plugin_by_type($type) {
243 return $this->get_plugin_by_type('assignfeedback', $type);
247 * Get a submission plugin by type
248 * @param string $type - The type of plugin e.g comments
249 * @return mixed assign_submission_plugin|null
251 public function get_submission_plugin_by_type($type) {
252 return $this->get_plugin_by_type('assignsubmission', $type);
256 * Load the plugins from the sub folders under subtype
257 * @param string $subtype - either submission or feedback
258 * @return array - The sorted list of plugins
260 private function load_plugins($subtype) {
264 $names = get_plugin_list($subtype);
266 foreach ($names as $name => $path) {
267 if (file_exists($path . '/locallib.php')) {
268 require_once($path . '/locallib.php');
270 $shortsubtype = substr($subtype, strlen('assign'));
271 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
273 $plugin = new $pluginclass($this, $name);
275 if ($plugin instanceof assign_plugin) {
276 $idx = $plugin->get_sort_order();
277 while (array_key_exists($idx, $result)) $idx +=1;
278 $result[$idx] = $plugin;
288 * Display the assignment, used by view.php
290 * The assignment is displayed differently depending on your role,
291 * the settings for the assignment and the status of the assignment.
292 * @param string $action The current action if any.
295 public function view($action='') {
300 // handle form submissions first
301 if ($action == 'savesubmission') {
302 $action = 'editsubmission';
303 if ($this->process_save_submission($mform)) {
306 } else if ($action == 'lock') {
307 $this->process_lock();
309 } else if ($action == 'reverttodraft') {
310 $this->process_revert_to_draft();
312 } else if ($action == 'unlock') {
313 $this->process_unlock();
315 } else if ($action == 'confirmsubmit') {
316 $this->process_submit_for_grading();
317 // save and show next button
318 } else if ($action == 'batchgradingoperation') {
319 $this->process_batch_grading_operation();
321 } else if ($action == 'submitgrade') {
322 if (optional_param('saveandshownext', null, PARAM_RAW)) {
325 if ($this->process_save_grade($mform)) {
326 $action = 'nextgrade';
328 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
329 $action = 'previousgrade';
330 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
332 $action = 'nextgrade';
333 } else if (optional_param('savegrade', null, PARAM_RAW)) {
334 //save changes button
336 if ($this->process_save_grade($mform)) {
343 }else if ($action == 'quickgrade') {
344 $message = $this->process_save_quick_grades();
345 $action = 'quickgradingresult';
346 }else if ($action == 'saveoptions') {
347 $this->process_save_grading_options();
351 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
352 $this->register_return_link($action, $returnparams);
354 // now show the right view page
355 if ($action == 'previousgrade') {
357 $o .= $this->view_single_grade_page($mform, -1);
358 } else if ($action == 'quickgradingresult') {
360 $o .= $this->view_quickgrading_result($message);
361 } else if ($action == 'nextgrade') {
363 $o .= $this->view_single_grade_page($mform, 1);
364 } else if ($action == 'grade') {
365 $o .= $this->view_single_grade_page($mform);
366 } else if ($action == 'viewpluginassignfeedback') {
367 $o .= $this->view_plugin_content('assignfeedback');
368 } else if ($action == 'viewpluginassignsubmission') {
369 $o .= $this->view_plugin_content('assignsubmission');
370 } else if ($action == 'editsubmission') {
371 $o .= $this->view_edit_submission_page($mform);
372 } else if ($action == 'grading') {
373 $o .= $this->view_grading_page();
374 } else if ($action == 'downloadall') {
375 $o .= $this->download_submissions();
376 } else if ($action == 'submit') {
377 $o .= $this->check_submit_for_grading();
379 $o .= $this->view_submission_page();
387 * Add this instance to the database
389 * @param stdClass $formdata The data submitted from the form
390 * @param bool $callplugins This is used to skip the plugin code
391 * when upgrading an old assignment to a new one (the plugins get called manually)
392 * @return mixed false if an error occurs or the int id of the new instance
394 public function add_instance(stdClass $formdata, $callplugins) {
399 // add the database record
400 $update = new stdClass();
401 $update->name = $formdata->name;
402 $update->timemodified = time();
403 $update->timecreated = time();
404 $update->course = $formdata->course;
405 $update->courseid = $formdata->course;
406 $update->intro = $formdata->intro;
407 $update->introformat = $formdata->introformat;
408 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
409 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
410 $update->submissiondrafts = $formdata->submissiondrafts;
411 $update->sendnotifications = $formdata->sendnotifications;
412 $update->sendlatenotifications = $formdata->sendlatenotifications;
413 $update->duedate = $formdata->duedate;
414 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
415 $update->grade = $formdata->grade;
416 $returnid = $DB->insert_record('assign', $update);
417 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
418 // cache the course record
419 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
422 // call save_settings hook for submission plugins
423 foreach ($this->submissionplugins as $plugin) {
424 if (!$this->update_plugin_instance($plugin, $formdata)) {
425 print_error($plugin->get_error());
429 foreach ($this->feedbackplugins as $plugin) {
430 if (!$this->update_plugin_instance($plugin, $formdata)) {
431 print_error($plugin->get_error());
436 // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
437 // TODO: add event to the calendar
438 $this->update_calendar($formdata->coursemodule);
439 // TODO: add the item in the gradebook
440 $this->update_gradebook(false, $formdata->coursemodule);
444 $update = new stdClass();
445 $update->id = $this->get_instance()->id;
446 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
447 $DB->update_record('assign', $update);
453 * Delete all grades from the gradebook for this assignment
457 private function delete_grades() {
460 return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
464 * Delete this instance from the database
466 * @return bool false if an error occurs
468 public function delete_instance() {
472 foreach ($this->submissionplugins as $plugin) {
473 if (!$plugin->delete_instance()) {
474 print_error($plugin->get_error());
478 foreach ($this->feedbackplugins as $plugin) {
479 if (!$plugin->delete_instance()) {
480 print_error($plugin->get_error());
485 // delete files associated with this assignment
486 $fs = get_file_storage();
487 if (! $fs->delete_area_files($this->context->id) ) {
491 // delete_records will throw an exception if it fails - so no need for error checking here
493 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
494 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
495 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
497 // delete items from the gradebook
498 if (! $this->delete_grades()) {
502 // delete the instance
503 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
509 * Actual implementation of the reset course functionality, delete all the
510 * assignment submissions for course $data->courseid.
512 * @param $data the data submitted from the reset course.
513 * @return array status array
515 public function reset_userdata($data) {
518 $componentstr = get_string('modulenameplural', 'assign');
521 $fs = get_file_storage();
522 if (!empty($data->reset_assign_submissions)) {
523 // Delete files associated with this assignment.
524 foreach ($this->submissionplugins as $plugin) {
525 $fileareas = array();
526 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
527 $fileareas = $plugin->get_file_areas();
528 foreach ($fileareas as $filearea) {
529 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
532 if (!$plugin->delete_instance()) {
533 $status[] = array('component'=>$componentstr,
534 'item'=>get_string('deleteallsubmissions','assign'),
535 'error'=>$plugin->get_error());
539 foreach ($this->feedbackplugins as $plugin) {
540 $fileareas = array();
541 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
542 $fileareas = $plugin->get_file_areas();
543 foreach ($fileareas as $filearea) {
544 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
547 if (!$plugin->delete_instance()) {
548 $status[] = array('component'=>$componentstr,
549 'item'=>get_string('deleteallsubmissions','assign'),
550 'error'=>$plugin->get_error());
554 $assignssql = "SELECT a.id
556 WHERE a.course=:course";
557 $params = array ("course" => $data->courseid);
559 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
560 $status[] = array('component'=>$componentstr,
561 'item'=>get_string('deleteallsubmissions','assign'),
564 if (empty($data->reset_gradebook_grades)) {
565 // Remove all grades from gradebook.
566 require_once($CFG->dirroot.'/mod/assign/lib.php');
567 assign_reset_gradebook($data->courseid);
570 // Updating dates - shift may be negative too.
571 if ($data->timeshift) {
572 shift_course_mod_dates('assign',
573 array('duedate', 'allowsubmissionsfromdate'),
576 $status[] = array('component'=>$componentstr,
577 'item'=>get_string('datechanged'),
585 * Update the settings for a single plugin
587 * @param assign_plugin $plugin The plugin to update
588 * @param stdClass $formdata The form data
589 * @return bool false if an error occurs
591 private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
592 if ($plugin->is_visible()) {
593 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
594 if ($formdata->$enabledname) {
596 if (!$plugin->save_settings($formdata)) {
597 print_error($plugin->get_error());
608 * Update the gradebook information for this assignment
610 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
611 * @param int $coursemoduleid This is required because it might not exist in the database yet
614 public function update_gradebook($reset, $coursemoduleid) {
616 /** Include lib.php */
617 require_once($CFG->dirroot.'/mod/assign/lib.php');
618 $assign = clone $this->get_instance();
619 $assign->cmidnumber = $coursemoduleid;
625 return assign_grade_item_update($assign, $param);
628 /** Load and cache the admin config for this module
630 * @return stdClass the plugin config
632 public function get_admin_config() {
633 if ($this->adminconfig) {
634 return $this->adminconfig;
636 $this->adminconfig = get_config('assign');
637 return $this->adminconfig;
642 * Update the calendar entries for this assignment
644 * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
647 public function update_calendar($coursemoduleid) {
649 require_once($CFG->dirroot.'/calendar/lib.php');
651 // special case for add_instance as the coursemodule has not been set yet.
653 if ($this->get_instance()->duedate) {
654 $event = new stdClass();
656 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
658 $event->name = $this->get_instance()->name;
660 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
661 $event->timestart = $this->get_instance()->duedate;
663 $calendarevent = calendar_event::load($event->id);
664 $calendarevent->update($event);
666 $event = new stdClass();
667 $event->name = $this->get_instance()->name;
668 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
669 $event->courseid = $this->get_instance()->course;
672 $event->modulename = 'assign';
673 $event->instance = $this->get_instance()->id;
674 $event->eventtype = 'due';
675 $event->timestart = $this->get_instance()->duedate;
676 $event->timeduration = 0;
678 calendar_event::create($event);
681 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
687 * Update this instance in the database
689 * @param stdClass $formdata - the data submitted from the form
690 * @return bool false if an error occurs
692 public function update_instance($formdata) {
695 $update = new stdClass();
696 $update->id = $formdata->instance;
697 $update->name = $formdata->name;
698 $update->timemodified = time();
699 $update->course = $formdata->course;
700 $update->intro = $formdata->intro;
701 $update->introformat = $formdata->introformat;
702 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
703 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
704 $update->submissiondrafts = $formdata->submissiondrafts;
705 $update->sendnotifications = $formdata->sendnotifications;
706 $update->sendlatenotifications = $formdata->sendlatenotifications;
707 $update->duedate = $formdata->duedate;
708 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
709 $update->grade = $formdata->grade;
711 $result = $DB->update_record('assign', $update);
712 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
714 // load the assignment so the plugins have access to it
716 // call save_settings hook for submission plugins
717 foreach ($this->submissionplugins as $plugin) {
718 if (!$this->update_plugin_instance($plugin, $formdata)) {
719 print_error($plugin->get_error());
723 foreach ($this->feedbackplugins as $plugin) {
724 if (!$this->update_plugin_instance($plugin, $formdata)) {
725 print_error($plugin->get_error());
731 // update the database record
734 // update all the calendar events
735 $this->update_calendar($this->get_course_module()->id);
737 $this->update_gradebook(false, $this->get_course_module()->id);
739 $update = new stdClass();
740 $update->id = $this->get_instance()->id;
741 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
742 $DB->update_record('assign', $update);
752 * add elements in grading plugin form
754 * @param mixed $grade stdClass|null
755 * @param MoodleQuickForm $mform
756 * @param stdClass $data
757 * @param int $userid - The userid we are grading
760 private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
761 foreach ($this->feedbackplugins as $plugin) {
762 if ($plugin->is_enabled() && $plugin->is_visible()) {
763 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
764 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
765 $mform->removeElement('header_' . $plugin->get_type());
774 * Add one plugins settings to edit plugin form
776 * @param assign_plugin $plugin The plugin to add the settings from
777 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
780 private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
782 if ($plugin->is_visible()) {
784 //tied disableIf rule to this select element
785 $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
786 $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
789 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
790 if ($plugin->get_config('enabled') !== false) {
791 $default = $plugin->is_enabled();
793 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
795 $plugin->get_settings($mform);
803 * Add settings to edit plugin form
805 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
808 public function add_all_plugin_settings(MoodleQuickForm $mform) {
809 $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
811 foreach ($this->submissionplugins as $plugin) {
812 $this->add_plugin_settings($plugin, $mform);
815 $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
816 foreach ($this->feedbackplugins as $plugin) {
817 $this->add_plugin_settings($plugin, $mform);
822 * Allow each plugin an opportunity to update the defaultvalues
823 * passed in to the settings form (needed to set up draft areas for
824 * editor and filemanager elements)
825 * @param array $defaultvalues
827 public function plugin_data_preprocessing(&$defaultvalues) {
828 foreach ($this->submissionplugins as $plugin) {
829 if ($plugin->is_visible()) {
830 $plugin->data_preprocessing($defaultvalues);
833 foreach ($this->feedbackplugins as $plugin) {
834 if ($plugin->is_visible()) {
835 $plugin->data_preprocessing($defaultvalues);
841 * Get the name of the current module.
843 * @return string the module name (Assignment)
845 protected function get_module_name() {
846 if (isset(self::$modulename)) {
847 return self::$modulename;
849 self::$modulename = get_string('modulename', 'assign');
850 return self::$modulename;
854 * Get the plural name of the current module.
856 * @return string the module name plural (Assignments)
858 protected function get_module_name_plural() {
859 if (isset(self::$modulenameplural)) {
860 return self::$modulenameplural;
862 self::$modulenameplural = get_string('modulenameplural', 'assign');
863 return self::$modulenameplural;
867 * Has this assignment been constructed from an instance?
871 public function has_instance() {
872 return $this->instance || $this->get_course_module();
876 * Get the settings for the current instance of this assignment
878 * @return stdClass The settings
880 public function get_instance() {
882 if ($this->instance) {
883 return $this->instance;
885 if ($this->get_course_module()) {
886 $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
888 if (!$this->instance) {
889 throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
891 return $this->instance;
895 * Get the context of the current course
896 * @return mixed context|null The course context
898 public function get_course_context() {
899 if (!$this->context && !$this->course) {
900 throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
902 if ($this->context) {
903 return $this->context->get_course_context();
905 return context_course::instance($this->course->id);
911 * Get the current course module
913 * @return mixed stdClass|null The course module
915 public function get_course_module() {
916 if ($this->coursemodule) {
917 return $this->coursemodule;
919 if (!$this->context) {
923 if ($this->context->contextlevel == CONTEXT_MODULE) {
924 $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
925 return $this->coursemodule;
935 public function get_context() {
936 return $this->context;
940 * Get the current course
941 * @return mixed stdClass|null The course
943 public function get_course() {
946 return $this->course;
949 if (!$this->context) {
952 $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
953 return $this->course;
957 * Return a grade in user-friendly form, whether it's a scale or not
959 * @param mixed $grade int|null
960 * @param boolean $editing Are we allowing changes to this grade?
961 * @param int $userid The user id the grade belongs to
962 * @param int $modified Timestamp from when the grade was last modified
963 * @return string User-friendly representation of grade
965 public function display_grade($grade, $editing, $userid=0, $modified=0) {
968 static $scalegrades = array();
970 if ($this->get_instance()->grade >= 0) {
972 if ($editing && $this->get_instance()->grade > 0) {
976 $displaygrade = format_float($grade);
978 $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
979 $o .= ' / ' . format_float($this->get_instance()->grade,2);
980 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
983 if ($grade == -1 || $grade === null) {
986 return format_float(($grade),2) .' / '. format_float($this->get_instance()->grade,2);
992 if (empty($this->cache['scale'])) {
993 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
994 $this->cache['scale'] = make_menu_from_list($scale->scale);
1000 $o = '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1001 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1002 foreach ($this->cache['scale'] as $optionid => $option) {
1004 if ($grade == $optionid) {
1005 $selected = 'selected="selected"';
1007 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1010 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1013 $scaleid = (int)$grade;
1014 if (isset($this->cache['scale'][$scaleid])) {
1015 return $this->cache['scale'][$scaleid];
1023 * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
1025 * @param int $currentgroup
1026 * @param bool $idsonly
1027 * @return array List of user records
1029 public function list_participants($currentgroup, $idsonly) {
1031 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
1033 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1038 * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
1040 * @param int $currentgroup
1041 * @return int number of matching users
1043 public function count_participants($currentgroup) {
1044 return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
1048 * Load a count of users submissions in the current module that require grading
1049 * This means the submission modification time is more recent than the
1050 * grading modification time.
1052 * @return int number of matching submissions
1054 public function count_submissions_need_grading() {
1057 $params = array($this->get_course_module()->instance);
1059 return $DB->count_records_sql("SELECT COUNT('x')
1060 FROM {assign_submission} s
1061 LEFT JOIN {assign_grades} g ON s.assignment = g.assignment AND s.userid = g.userid
1062 WHERE s.assignment = ?
1063 AND s.timemodified IS NOT NULL
1064 AND (s.timemodified > g.timemodified OR g.timemodified IS NULL)",
1069 * Load a count of users enrolled in the current course with the specified permission and group (optional)
1071 * @param string $status The submission status - should match one of the constants
1072 * @return int number of matching submissions
1074 public function count_submissions_with_status($status) {
1076 return $DB->count_records_sql("SELECT COUNT('x')
1077 FROM {assign_submission}
1078 WHERE assignment = ? AND
1079 status = ?", array($this->get_course_module()->instance, $status));
1083 * Utility function to get the userid for every row in the grading table
1084 * so the order can be frozen while we iterate it
1086 * @return array An array of userids
1088 private function get_grading_userid_list(){
1089 $filter = get_user_preferences('assign_filter', '');
1090 $table = new assign_grading_table($this, 0, $filter, 0, false);
1092 $useridlist = $table->get_column_data('userid');
1099 * Utility function get the userid based on the row number of the grading table.
1100 * This takes into account any active filters on the table.
1102 * @param int $num The row number of the user
1103 * @param bool $last This is set to true if this is the last user in the table
1104 * @return mixed The user id of the matching user or false if there was an error
1106 private function get_userid_for_row($num, $last){
1107 if (!array_key_exists('userid_for_row', $this->cache)) {
1108 $this->cache['userid_for_row'] = array();
1110 if (array_key_exists($num, $this->cache['userid_for_row'])) {
1111 list($userid, $last) = $this->cache['userid_for_row'][$num];
1115 $filter = get_user_preferences('assign_filter', '');
1116 $table = new assign_grading_table($this, 0, $filter, 0, false);
1118 $userid = $table->get_cell_data($num, 'userid', $last);
1120 $this->cache['userid_for_row'][$num] = array($userid, $last);
1125 * Return all assignment submissions by ENROLLED students (even empty)
1127 * @param string $sort optional field names for the ORDER BY in the sql query
1128 * @param string $dir optional specifying the sort direction, defaults to DESC
1129 * @return array The submission objects indexed by id
1131 private function get_all_submissions( $sort="", $dir="DESC") {
1134 if ($sort == "lastname" or $sort == "firstname") {
1135 $sort = "u.$sort $dir";
1136 } else if (empty($sort)) {
1137 $sort = "a.timemodified DESC";
1139 $sort = "a.$sort $dir";
1142 return $DB->get_records_sql("SELECT a.*
1143 FROM {assign_submission} a, {user} u
1144 WHERE u.id = a.userid
1145 AND a.assignment = ?
1146 ORDER BY $sort", array($this->get_instance()->id));
1151 * Generate zip file from array of given files
1153 * @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
1154 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1156 private function pack_files($filesforzipping) {
1158 //create path for new zip file.
1159 $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1161 $zipper = new zip_packer();
1162 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1169 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1171 * Cron function to be run periodically according to the moodle cron
1175 static function cron() {
1178 // only ever send a max of one days worth of updates
1179 $yesterday = time() - (24 * 3600);
1182 // Collect all submissions from the past 24 hours that require mailing.
1183 $sql = "SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1185 JOIN {assign_grades} g ON g.assignment = a.id
1186 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1187 WHERE g.timemodified >= :yesterday AND
1188 g.timemodified <= :today AND
1190 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1191 $submissions = $DB->get_records_sql($sql, $params);
1193 if (empty($submissions)) {
1198 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1200 // Preload courses we are going to need those.
1201 $courseids = array();
1202 foreach ($submissions as $submission) {
1203 $courseids[] = $submission->course;
1205 // Filter out duplicates
1206 $courseids = array_unique($courseids);
1207 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1208 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1209 $sql = "SELECT c.*, {$ctxselect}
1211 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1212 WHERE c.id {$courseidsql}";
1213 $params['contextlevel'] = CONTEXT_COURSE;
1214 $courses = $DB->get_records_sql($sql, $params);
1215 // Clean up... this could go on for a while.
1218 unset($courseidsql);
1221 // Simple array we'll use for caching modules.
1222 $modcache = array();
1224 // Message students about new feedback
1225 foreach ($submissions as $submission) {
1227 mtrace("Processing assignment submission $submission->id ...");
1229 // do not cache user lookups - could be too many
1230 if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
1231 mtrace("Could not find user $submission->userid");
1235 // use a cache to prevent the same DB queries happening over and over
1236 if (!array_key_exists($submission->course, $courses)) {
1237 mtrace("Could not find course $submission->course");
1240 $course = $courses[$submission->course];
1241 if (isset($course->ctxid)) {
1242 // Context has not yet been preloaded. Do so now.
1243 context_helper::preload_from_record($course);
1246 // Override the language and timezone of the "current" user, so that
1247 // mail is customised for the receiver.
1248 cron_setup_user($user, $course);
1250 // context lookups are already cached
1251 $coursecontext = context_course::instance($course->id);
1252 if (!is_enrolled($coursecontext, $user->id)) {
1253 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1254 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1258 if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1259 mtrace("Could not find grader $submission->grader");
1263 if (!array_key_exists($submission->assignment, $modcache)) {
1264 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1265 mtrace("Could not find course module for assignment id $submission->assignment");
1268 $modcache[$submission->assignment] = $mod;
1270 $mod = $modcache[$submission->assignment];
1272 // context lookups are already cached
1273 $contextmodule = context_module::instance($mod->id);
1275 if (!$mod->visible) {
1276 // Hold mail notification for hidden assignments until later
1280 // need to send this to the student
1281 $messagetype = 'feedbackavailable';
1282 $eventtype = 'assign_notification';
1283 $updatetime = $submission->lastmodified;
1284 $modulename = get_string('modulename', 'assign');
1285 self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $mod, $contextmodule, $course, $modulename, $submission->name);
1287 $grade = new stdClass();
1288 $grade->id = $submission->gradeid;
1290 $DB->update_record('assign_grades', $grade);
1294 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1298 // Free up memory just to be sure
1306 * Update a grade in the grade table for the assignment and in the gradebook
1308 * @param stdClass $grade a grade record keyed on id
1309 * @return bool true for success
1311 private function update_grade($grade) {
1314 $grade->timemodified = time();
1316 if ($grade->grade && $grade->grade != -1) {
1317 if ($this->get_instance()->grade > 0) {
1318 if (!is_numeric($grade->grade)) {
1320 } else if ($grade->grade > $this->get_instance()->grade) {
1322 } else if ($grade->grade < 0) {
1327 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1328 $scaleoptions = make_menu_from_list($scale->scale);
1329 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1336 $result = $DB->update_record('assign_grades', $grade);
1338 $this->gradebook_item_update(null, $grade);
1344 * display the submission that is used by a plugin
1345 * Uses url parameters 'sid', 'gid' and 'plugin'
1346 * @param string $pluginsubtype
1349 private function view_plugin_content($pluginsubtype) {
1354 $submissionid = optional_param('sid', 0, PARAM_INT);
1355 $gradeid = optional_param('gid', 0, PARAM_INT);
1356 $plugintype = required_param('plugin', PARAM_TEXT);
1358 if ($pluginsubtype == 'assignsubmission') {
1359 $plugin = $this->get_submission_plugin_by_type($plugintype);
1360 if ($submissionid <= 0) {
1361 throw new coding_exception('Submission id should not be 0');
1363 $item = $this->get_submission($submissionid);
1366 if ($item->userid != $USER->id) {
1367 require_capability('mod/assign:grade', $this->context);
1369 $o .= $this->output->render(new assign_header($this->get_instance(),
1370 $this->get_context(),
1371 $this->show_intro(),
1372 $this->get_course_module()->id,
1373 $plugin->get_name()));
1374 $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1376 assign_submission_plugin_submission::FULL,
1377 $this->get_course_module()->id,
1378 $this->get_return_action(),
1379 $this->get_return_params()));
1381 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1383 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1384 if ($gradeid <= 0) {
1385 throw new coding_exception('Grade id should not be 0');
1387 $item = $this->get_grade($gradeid);
1389 if ($item->userid != $USER->id) {
1390 require_capability('mod/assign:grade', $this->context);
1392 $o .= $this->output->render(new assign_header($this->get_instance(),
1393 $this->get_context(),
1394 $this->show_intro(),
1395 $this->get_course_module()->id,
1396 $plugin->get_name()));
1397 $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1399 assign_feedback_plugin_feedback::FULL,
1400 $this->get_course_module()->id,
1401 $this->get_return_action(),
1402 $this->get_return_params()));
1403 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1407 $o .= $this->view_return_links();
1409 $o .= $this->view_footer();
1414 * render the content in editor that is often used by plugin
1416 * @param string $filearea
1417 * @param int $submissionid
1418 * @param string $plugintype
1419 * @param string $editor
1420 * @param string $component
1423 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1428 $plugin = $this->get_submission_plugin_by_type($plugintype);
1430 $text = $plugin->get_editor_text($editor, $submissionid);
1431 $format = $plugin->get_editor_format($editor, $submissionid);
1433 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1434 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1438 if ($CFG->enableportfolios) {
1439 require_once($CFG->libdir . '/portfoliolib.php');
1441 $button = new portfolio_add_button();
1442 $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id, 'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea), '/mod/assign/portfolio_callback.php');
1443 $fs = get_file_storage();
1445 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1446 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1448 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1450 $result .= $button->to_html();
1456 * Display a grading error
1458 * @param string $message - The description of the result
1461 private function view_quickgrading_result($message) {
1463 $o .= $this->output->render(new assign_header($this->get_instance(),
1464 $this->get_context(),
1465 $this->show_intro(),
1466 $this->get_course_module()->id,
1467 get_string('quickgradingresult', 'assign')));
1468 $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1469 $o .= $this->view_footer();
1474 * Display the page footer
1478 private function view_footer() {
1479 return $this->output->render_footer();
1483 * Does this user have grade permission for this assignment
1487 private function can_grade() {
1488 // Permissions check
1489 if (!has_capability('mod/assign:grade', $this->context)) {
1497 * Download a zip file of all assignment submissions
1501 private function download_submissions() {
1504 // more efficient to load this here
1505 require_once($CFG->libdir.'/filelib.php');
1507 // load all submissions
1508 $submissions = $this->get_all_submissions('','');
1510 if (empty($submissions)) {
1511 print_error('errornosubmissions', 'assign');
1515 // build a list of files to zip
1516 $filesforzipping = array();
1517 $fs = get_file_storage();
1519 $groupmode = groups_get_activity_groupmode($this->get_course_module());
1520 $groupid = 0; // All users
1523 $groupid = groups_get_activity_group($this->get_course_module(), true);
1524 $groupname = groups_get_group_name($groupid).'-';
1527 // construct the zip file name
1528 $filename = str_replace(' ', '_', clean_filename($this->get_course()->shortname.'-'.$this->get_instance()->name.'-'.$groupname.$this->get_course_module()->id.".zip")); //name of new zip file.
1530 // get all the files for each submission
1531 foreach ($submissions as $submission) {
1532 $userid = $submission->userid; //get userid
1533 if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1534 // get the plugins to add their own files to the zip
1536 $user = $DB->get_record("user", array("id"=>$userid),'id,username,firstname,lastname', MUST_EXIST);
1538 $prefix = clean_filename(fullname($user) . "_" .$userid . "_");
1540 foreach ($this->submissionplugins as $plugin) {
1541 if ($plugin->is_enabled() && $plugin->is_visible()) {
1542 $pluginfiles = $plugin->get_files($submission);
1545 foreach ($pluginfiles as $zipfilename => $file) {
1546 $filesforzipping[$prefix . $zipfilename] = $file;
1552 } // end of foreach loop
1553 if ($zipfile = $this->pack_files($filesforzipping)) {
1554 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1555 send_temp_file($zipfile, $filename); //send file and delete after sending.
1560 * Util function to add a message to the log
1562 * @param string $action The current action
1563 * @param string $info A detailed description of the change. But no more than 255 characters.
1564 * @param string $url The url to the assign module instance.
1567 public function add_to_log($action = '', $info = '', $url='') {
1570 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1572 $fullurl .= '&' . $url;
1575 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1579 * Load the submission object for a particular user, optionally creating it if required
1581 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1582 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1583 * @return stdClass The submission
1585 private function get_user_submission($userid, $create) {
1589 $userid = $USER->id;
1591 // if the userid is not null then use userid
1592 $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1598 $submission = new stdClass();
1599 $submission->assignment = $this->get_instance()->id;
1600 $submission->userid = $userid;
1601 $submission->timecreated = time();
1602 $submission->timemodified = $submission->timecreated;
1604 if ($this->get_instance()->submissiondrafts) {
1605 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1607 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1609 $sid = $DB->insert_record('assign_submission', $submission);
1610 $submission->id = $sid;
1617 * Load the submission object from it's id
1619 * @param int $submissionid The id of the submission we want
1620 * @return stdClass The submission
1622 private function get_submission($submissionid) {
1625 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1629 * This will retrieve a grade object from the db, optionally creating it if required
1631 * @param int $userid The user we are grading
1632 * @param bool $create If true the grade will be created if it does not exist
1633 * @return stdClass The grade record
1635 private function get_user_grade($userid, $create) {
1639 $userid = $USER->id;
1642 // if the userid is not null then use userid
1643 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1649 $grade = new stdClass();
1650 $grade->assignment = $this->get_instance()->id;
1651 $grade->userid = $userid;
1652 $grade->timecreated = time();
1653 $grade->timemodified = $grade->timecreated;
1656 $grade->grader = $USER->id;
1657 $gid = $DB->insert_record('assign_grades', $grade);
1665 * This will retrieve a grade object from the db
1667 * @param int $gradeid The id of the grade
1668 * @return stdClass The grade record
1670 private function get_grade($gradeid) {
1673 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1677 * Print the grading page for a single user submission
1679 * @param moodleform $mform
1680 * @param int $offset
1683 private function view_single_grade_page($mform, $offset=0) {
1688 // Include grade form
1689 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1691 // Need submit permission to submit an assignment
1692 require_capability('mod/assign:grade', $this->context);
1694 $o .= $this->output->render(new assign_header($this->get_instance(),
1695 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1697 $rownum = required_param('rownum', PARAM_INT) + $offset;
1698 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1700 $useridlist = explode(',', $useridlist);
1702 $useridlist = $this->get_grading_userid_list();
1705 $userid = $useridlist[$rownum];
1706 if ($rownum == count($useridlist) - 1) {
1710 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1712 $user = $DB->get_record('user', array('id' => $userid));
1714 $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1716 $submission = $this->get_user_submission($userid, false);
1717 // get the current grade
1718 $grade = $this->get_user_grade($userid, false);
1719 if ($this->can_view_submission($userid)) {
1720 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1721 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1722 $this->get_instance()->alwaysshowdescription,
1724 $this->is_any_submission_plugin_enabled(),
1726 $this->is_graded($userid),
1727 $this->get_instance()->duedate,
1728 $this->get_submission_plugins(),
1729 $this->get_return_action(),
1730 $this->get_return_params(),
1731 $this->get_course_module()->id,
1732 assign_submission_status::GRADER_VIEW,
1737 $data = new stdClass();
1738 if ($grade->grade !== NULL && $grade->grade >= 0) {
1739 $data->grade = format_float($grade->grade,2);
1742 $data = new stdClass();
1746 // now show the grading form
1748 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1750 $o .= $this->output->render(new assign_form('gradingform',$mform));
1752 $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1754 $o .= $this->view_footer();
1761 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1765 private function view_return_links() {
1767 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1768 $returnparams = optional_param('returnparams','', PARAM_TEXT);
1771 parse_str($returnparams, $params);
1772 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1774 return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1779 * View the grading table of all submissions for this assignment
1783 private function view_grading_table() {
1785 // Include grading options form
1786 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
1787 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
1788 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1792 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1793 has_capability('moodle/grade:viewall', $this->get_course_context())) {
1794 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
1795 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1797 if ($this->is_any_submission_plugin_enabled()) {
1798 $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
1799 $links[$downloadurl] = get_string('downloadall', 'assign');
1802 $gradingactions = new url_select($links);
1804 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1806 $perpage = get_user_preferences('assign_perpage', 10);
1807 $filter = get_user_preferences('assign_filter', '');
1808 $controller = $gradingmanager->get_active_controller();
1809 $showquickgrading = empty($controller);
1810 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1811 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1812 set_user_preference('assign_quickgrading', $quickgrading);
1814 $quickgrading = get_user_preferences('assign_quickgrading', false);
1816 // print options for changing the filter and changing the number of results per page
1817 $gradingoptionsform = new mod_assign_grading_options_form(null,
1818 array('cm'=>$this->get_course_module()->id,
1819 'contextid'=>$this->context->id,
1820 'userid'=>$USER->id,
1821 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
1822 'showquickgrading'=>$showquickgrading,
1823 'quickgrading'=>$quickgrading),
1825 array('class'=>'gradingoptionsform'));
1827 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1828 array('cm'=>$this->get_course_module()->id,
1829 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1831 array('class'=>'gradingbatchoperationsform'));
1833 $gradingoptionsdata = new stdClass();
1834 $gradingoptionsdata->perpage = $perpage;
1835 $gradingoptionsdata->filter = $filter;
1836 $gradingoptionsform->set_data($gradingoptionsdata);
1838 $actionformtext = $this->output->render($gradingactions);
1839 $o .= $this->output->render(new assign_header($this->get_instance(),
1840 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
1841 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1843 // plagiarism update status apearring in the grading book
1844 if (!empty($CFG->enableplagiarism)) {
1845 /** Include plagiarismlib.php */
1846 require_once($CFG->libdir . '/plagiarismlib.php');
1847 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
1850 // load and print the table of submissions
1851 if ($showquickgrading && $quickgrading) {
1852 $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1853 $quickgradingform = new mod_assign_quick_grading_form(null,
1854 array('cm'=>$this->get_course_module()->id,
1855 'gradingtable'=>$table));
1856 $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1858 $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1861 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1862 $users = array_keys($this->list_participants($currentgroup, true));
1863 if (count($users) != 0) {
1864 // if no enrolled user in a course then don't display the batch operations feature
1865 $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1867 $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
1872 * View entire grading page.
1876 private function view_grading_page() {
1880 // Need submit permission to submit an assignment
1881 require_capability('mod/assign:grade', $this->context);
1882 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1884 // only load this if it is
1886 $o .= $this->view_grading_table();
1888 $o .= $this->view_footer();
1889 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1894 * Capture the output of the plagiarism plugins disclosures and return it as a string
1898 private function plagiarism_print_disclosure() {
1902 if (!empty($CFG->enableplagiarism)) {
1903 /** Include plagiarismlib.php */
1904 require_once($CFG->libdir . '/plagiarismlib.php');
1906 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
1913 * message for students when assignment submissions have been closed
1917 private function view_student_error_message() {
1921 // Need submit permission to submit an assignment
1922 require_capability('mod/assign:submit', $this->context);
1924 $o .= $this->output->render(new assign_header($this->get_instance(),
1925 $this->get_context(),
1926 $this->show_intro(),
1927 $this->get_course_module()->id,
1928 get_string('editsubmission', 'assign')));
1930 $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
1932 $o .= $this->view_footer();
1939 * View edit submissions page.
1941 * @param moodleform $mform
1944 private function view_edit_submission_page($mform) {
1948 // Include submission form
1949 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1950 // Need submit permission to submit an assignment
1951 require_capability('mod/assign:submit', $this->context);
1953 if (!$this->submissions_open()) {
1954 return $this->view_student_error_message();
1956 $o .= $this->output->render(new assign_header($this->get_instance(),
1957 $this->get_context(),
1958 $this->show_intro(),
1959 $this->get_course_module()->id,
1960 get_string('editsubmission', 'assign')));
1961 $o .= $this->plagiarism_print_disclosure();
1962 $data = new stdClass();
1965 $mform = new mod_assign_submission_form(null, array($this, $data));
1968 $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1970 $o .= $this->view_footer();
1971 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1977 * See if this assignment has a grade yet
1979 * @param int $userid
1982 private function is_graded($userid) {
1983 $grade = $this->get_user_grade($userid, false);
1985 return ($grade->grade !== NULL && $grade->grade >= 0);
1992 * Perform an access check to see if the current $USER can view this users submission
1994 * @param int $userid
1997 public function can_view_submission($userid) {
2000 if (!is_enrolled($this->get_course_context(), $userid)) {
2003 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
2006 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
2013 * Ask the user to confirm they want to perform this batch operation
2016 private function process_batch_grading_operation() {
2018 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2021 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
2022 array('cm'=>$this->get_course_module()->id,
2023 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
2025 array('class'=>'gradingbatchoperationsform'));
2027 if ($data = $gradingbatchoperationsform->get_data()) {
2028 // get the list of users
2029 $users = $data->selectedusers;
2030 $userlist = explode(',', $users);
2032 foreach ($userlist as $userid) {
2033 if ($data->operation == 'lock') {
2034 $this->process_lock($userid);
2035 } else if ($data->operation == 'unlock') {
2036 $this->process_unlock($userid);
2037 } else if ($data->operation == 'reverttodraft') {
2038 $this->process_revert_to_draft($userid);
2047 * Ask the user to confirm they want to submit their work for grading
2050 private function check_submit_for_grading() {
2052 // Check that all of the submission plugins are ready for this submission
2053 $notifications = array();
2054 $submission = $this->get_user_submission($USER->id, false);
2055 $plugins = $this->get_submission_plugins();
2056 foreach ($plugins as $plugin) {
2057 if ($plugin->is_enabled() && $plugin->is_visible()) {
2058 $check = $plugin->precheck_submission($submission);
2059 if ($check !== true) {
2060 $notifications[] = $check;
2066 $o .= $this->output->header();
2067 $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
2068 $o .= $this->view_footer();
2073 * Print 2 tables of information with no action links -
2074 * the submission summary and the grading summary
2076 * @param stdClass $user the user to print the report for
2077 * @param bool $showlinks - Return plain text or links to the profile
2078 * @return string - the html summary
2080 public function view_student_summary($user, $showlinks) {
2081 global $CFG, $DB, $PAGE;
2083 $grade = $this->get_user_grade($user->id, false);
2084 $submission = $this->get_user_submission($user->id, false);
2087 if ($this->can_view_submission($user->id)) {
2088 $showedit = has_capability('mod/assign:submit', $this->context) &&
2089 $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2090 $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
2091 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2093 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2094 $this->get_instance()->alwaysshowdescription,
2096 $this->is_any_submission_plugin_enabled(),
2098 $this->is_graded($user->id),
2099 $this->get_instance()->duedate,
2100 $this->get_submission_plugins(),
2101 $this->get_return_action(),
2102 $this->get_return_params(),
2103 $this->get_course_module()->id,
2104 assign_submission_status::STUDENT_VIEW,
2107 require_once($CFG->libdir.'/gradelib.php');
2108 require_once($CFG->dirroot.'/grade/grading/lib.php');
2110 $gradinginfo = grade_get_grades($this->get_course()->id,
2113 $this->get_instance()->id,
2116 $gradingitem = $gradinginfo->items[0];
2117 $gradebookgrade = $gradingitem->grades[$user->id];
2119 // check to see if all feedback plugins are empty
2120 $emptyplugins = true;
2122 foreach ($this->get_feedback_plugins() as $plugin) {
2123 if ($plugin->is_visible() && $plugin->is_enabled()) {
2124 if (!$plugin->is_empty($grade)) {
2125 $emptyplugins = false;
2132 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2134 $gradefordisplay = '';
2135 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2137 if ($controller = $gradingmanager->get_active_controller()) {
2138 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2139 $gradefordisplay = $controller->render_grade($PAGE,
2142 $gradebookgrade->str_long_grade,
2143 has_capability('mod/assign:grade', $this->get_context()));
2145 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2148 $gradeddate = $gradebookgrade->dategraded;
2149 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2151 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2154 $this->get_feedback_plugins(),
2156 $this->get_course_module()->id,
2157 $this->get_return_action(),
2158 $this->get_return_params());
2160 $o .= $this->output->render($feedbackstatus);
2168 * View submissions page (contains details of current submission).
2172 private function view_submission_page() {
2173 global $CFG, $DB, $USER, $PAGE;
2176 $o .= $this->output->render(new assign_header($this->get_instance(),
2177 $this->get_context(),
2178 $this->show_intro(),
2179 $this->get_course_module()->id));
2181 if ($this->can_grade()) {
2182 $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2183 $this->get_instance()->submissiondrafts,
2184 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2185 $this->is_any_submission_plugin_enabled(),
2186 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2187 $this->get_instance()->duedate,
2188 $this->get_course_module()->id,
2189 $this->count_submissions_need_grading()
2192 $grade = $this->get_user_grade($USER->id, false);
2193 $submission = $this->get_user_submission($USER->id, false);
2195 if ($this->can_view_submission($USER->id)) {
2196 $o .= $this->view_student_summary($USER, true);
2200 $o .= $this->view_footer();
2201 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2206 * convert the final raw grade(s) in the grading table for the gradebook
2208 * @param stdClass $grade
2211 private function convert_grade_for_gradebook(stdClass $grade) {
2212 $gradebookgrade = array();
2213 // trying to match those array keys in grade update function in gradelib.php
2214 // with keys in th database table assign_grades
2215 // starting around line 262
2216 if ($grade->grade >= 0) {
2217 $gradebookgrade['rawgrade'] = $grade->grade;
2219 $gradebookgrade['userid'] = $grade->userid;
2220 $gradebookgrade['usermodified'] = $grade->grader;
2221 $gradebookgrade['datesubmitted'] = NULL;
2222 $gradebookgrade['dategraded'] = $grade->timemodified;
2223 if (isset($grade->feedbackformat)) {
2224 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2226 if (isset($grade->feedbacktext)) {
2227 $gradebookgrade['feedback'] = $grade->feedbacktext;
2230 return $gradebookgrade;
2234 * convert submission details for the gradebook
2236 * @param stdClass $submission
2239 private function convert_submission_for_gradebook(stdClass $submission) {
2240 $gradebookgrade = array();
2243 $gradebookgrade['userid'] = $submission->userid;
2244 $gradebookgrade['usermodified'] = $submission->userid;
2245 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2247 return $gradebookgrade;
2251 * update grades in the gradebook
2253 * @param mixed $submission stdClass|null
2254 * @param mixed $grade stdClass|null
2257 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2259 if($submission != NULL){
2260 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2262 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2264 // Grading is disabled, return.
2265 if ($this->grading_disabled($gradebookgrade['userid'])) {
2268 $assign = clone $this->get_instance();
2269 $assign->cmidnumber = $this->get_course_module()->id;
2271 return assign_grade_item_update($assign, $gradebookgrade);
2275 * update grades in the gradebook based on submission time
2277 * @param stdClass $submission
2278 * @param bool $updatetime
2281 private function update_submission(stdClass $submission, $updatetime=true) {
2285 $submission->timemodified = time();
2287 $result= $DB->update_record('assign_submission', $submission);
2289 $this->gradebook_item_update($submission);
2295 * Is this assignment open for submissions?
2297 * Check the due date,
2298 * prevent late submissions,
2299 * has this person already submitted,
2300 * is the assignment locked?
2304 private function submissions_open() {
2309 if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2310 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2312 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2319 // now check if this user has already submitted etc.
2320 if (!is_enrolled($this->get_course_context(), $USER)) {
2323 if ($submission = $this->get_user_submission($USER->id, false)) {
2324 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2325 // drafts are tracked and the student has submitted the assignment
2329 if ($grade = $this->get_user_grade($USER->id, false)) {
2330 if ($grade->locked) {
2335 if ($this->grading_disabled($USER->id)) {
2343 * render the files in file area
2344 * @param string $component
2345 * @param string $area
2346 * @param int $submissionid
2349 public function render_area_files($component, $area, $submissionid) {
2352 if (!$submissionid) {
2353 $submission = $this->get_user_submission($USER->id,false);
2354 $submissionid = $submission->id;
2357 $fs = get_file_storage();
2358 $browser = get_file_browser();
2359 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2360 return $this->output->assign_files($this->context, $submissionid, $area, $component);
2365 * Returns a list of teachers that should be grading given submission
2367 * @param int $userid
2370 private function get_graders($userid) {
2372 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
2375 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
2376 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
2377 foreach ($groups as $group) {
2378 foreach ($potentialgraders as $grader) {
2379 if ($grader->id == $userid) {
2380 continue; // do not send self
2382 if (groups_is_member($group->id, $grader->id)) {
2383 $graders[$grader->id] = $grader;
2388 // user not in group, try to find graders without group
2389 foreach ($potentialgraders as $grader) {
2390 if ($grader->id == $userid) {
2391 continue; // do not send self
2393 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2394 $graders[$grader->id] = $grader;
2399 foreach ($potentialgraders as $grader) {
2400 if ($grader->id == $userid) {
2401 continue; // do not send self
2404 if (is_enrolled($this->get_course_context(), $grader->id)) {
2405 $graders[$grader->id] = $grader;
2413 * Format a notification for plain text
2415 * @param string $messagetype
2416 * @param stdClass $info
2417 * @param stdClass $course
2418 * @param stdClass $context
2419 * @param string $modulename
2420 * @param string $assignmentname
2422 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2423 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2425 format_string($assignmentname, true, array('context' => $context))."\n";
2426 $posttext .= '---------------------------------------------------------------------'."\n";
2427 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
2428 $posttext .= "\n---------------------------------------------------------------------\n";
2433 * Format a notification for HTML
2435 * @param string $messagetype
2436 * @param stdClass $info
2437 * @param stdClass $course
2438 * @param stdClass $context
2439 * @param string $modulename
2440 * @param stdClass $coursemodule
2441 * @param string $assignmentname
2442 * @param stdClass $info
2444 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
2446 $posthtml = '<p><font face="sans-serif">'.
2447 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
2448 '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2449 '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
2450 $posthtml .= '<hr /><font face="sans-serif">';
2451 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
2452 $posthtml .= '</font><hr />';
2457 * Message someone about something (static so it can be called from cron)
2459 * @param stdClass $userfrom
2460 * @param stdClass $userto
2461 * @param string $messagetype
2462 * @param string $eventtype
2463 * @param int $updatetime
2464 * @param stdClass $coursemodule
2465 * @param stdClass $context
2466 * @param stdClass $course
2467 * @param string $modulename
2468 * @param string $assignmentname
2471 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2472 $updatetime, $coursemodule, $context, $course,
2473 $modulename, $assignmentname) {
2476 $info = new stdClass();
2477 $info->username = fullname($userfrom, true);
2478 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2479 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2480 $info->timeupdated = strftime('%c',$updatetime);
2482 $postsubject = get_string($messagetype . 'small', 'assign', $info);
2483 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2484 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2486 $eventdata = new stdClass();
2487 $eventdata->modulename = 'assign';
2488 $eventdata->userfrom = $userfrom;
2489 $eventdata->userto = $userto;
2490 $eventdata->subject = $postsubject;
2491 $eventdata->fullmessage = $posttext;
2492 $eventdata->fullmessageformat = FORMAT_PLAIN;
2493 $eventdata->fullmessagehtml = $posthtml;
2494 $eventdata->smallmessage = $postsubject;
2496 $eventdata->name = $eventtype;
2497 $eventdata->component = 'mod_assign';
2498 $eventdata->notification = 1;
2499 $eventdata->contexturl = $info->url;
2500 $eventdata->contexturlname = $info->assignment;
2502 message_send($eventdata);
2506 * Message someone about something
2508 * @param stdClass $userfrom
2509 * @param stdClass $userto
2510 * @param string $messagetype
2511 * @param string $eventtype
2512 * @param int $updatetime
2515 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2516 self::send_assignment_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime, $this->get_course_module(), $this->get_context(), $this->get_course(), $this->get_module_name(), $this->get_instance()->name);
2520 * Notify student upon successful submission
2522 * @global moodle_database $DB
2523 * @param stdClass $submission
2526 private function notify_student_submission_receipt(stdClass $submission) {
2529 $adminconfig = $this->get_admin_config();
2530 if (!$adminconfig->submissionreceipts) {
2531 // No need to do anything
2534 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2535 $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
2539 * Send notifications to graders upon student submissions
2541 * @global moodle_database $DB
2542 * @param stdClass $submission
2545 private function notify_graders(stdClass $submission) {
2548 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
2550 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
2554 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2555 if ($teachers = $this->get_graders($user->id)) {
2556 foreach ($teachers as $teacher) {
2557 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
2563 * assignment submission is processed before grading
2567 private function process_submit_for_grading() {
2570 // Need submit permission to submit an assignment
2571 require_capability('mod/assign:submit', $this->context);
2574 $submission = $this->get_user_submission($USER->id,true);
2575 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2576 // Give each submission plugin a chance to process the submission
2577 $plugins = $this->get_submission_plugins();
2578 foreach ($plugins as $plugin) {
2579 $plugin->submit_for_grading();
2582 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2583 $this->update_submission($submission);
2584 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
2585 $this->notify_graders($submission);
2586 $this->notify_student_submission_receipt($submission);
2593 * @global moodle_database $DB
2594 * @return string The result of the save operation
2596 private function process_save_quick_grades() {
2597 global $USER, $DB, $CFG;
2599 // Need grade permission
2600 require_capability('mod/assign:grade', $this->context);
2602 // make sure advanced grading is disabled
2603 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2604 $controller = $gradingmanager->get_active_controller();
2605 if (!empty($controller)) {
2606 return get_string('errorquickgradingvsadvancedgrading', 'assign');
2610 // first check all the last modified values
2611 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2612 $participants = $this->list_participants($currentgroup, true);
2614 // gets a list of possible users and look for values based upon that.
2615 foreach ($participants as $userid => $unused) {
2616 $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
2617 if ($modified >= 0) {
2618 // gather the userid, updated grade and last modified value
2619 $record = new stdClass();
2620 $record->userid = $userid;
2621 $record->grade = unformat_float(required_param('quickgrade_' . $record->userid, PARAM_TEXT));
2622 $record->lastmodified = $modified;
2623 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2624 $users[$userid] = $record;
2627 if (empty($users)) {
2628 // Quick check to see whether we have any users to update and we don't
2629 return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2632 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2633 $params['assignment'] = $this->get_instance()->id;
2634 // check them all for currency
2635 $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2637 LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2638 WHERE u.id ' . $userids;
2639 $currentgrades = $DB->get_recordset_sql($sql, $params);
2641 $modifiedusers = array();
2642 foreach ($currentgrades as $current) {
2643 $modified = $users[(int)$current->userid];
2644 $grade = $this->get_user_grade($userid, false);
2646 // check to see if the outcomes were modified
2647 if ($CFG->enableoutcomes) {
2648 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2649 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2650 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_FLOAT);
2651 if ($oldoutcome != $newoutcome) {
2652 // can't check modified time for outcomes because it is not reported
2653 $modifiedusers[$modified->userid] = $modified;
2659 // let plugins participate
2660 foreach ($this->feedbackplugins as $plugin) {
2661 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2662 if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
2663 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2664 return get_string('errorrecordmodified', 'assign');
2666 $modifiedusers[$modified->userid] = $modified;
2674 if (($current->grade < 0 || $current->grade === NULL) &&
2675 ($modified->grade < 0 || $modified->grade === NULL)) {
2676 // different ways to indicate no grade
2679 // Treat 0 and null as different values
2680 if ($current->grade !== null) {
2681 $current->grade = floatval($current->grade);
2683 if ($current->grade !== $modified->grade) {
2685 if ($this->grading_disabled($modified->userid)) {
2688 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2689 // error - record has been modified since viewing the page
2690 return get_string('errorrecordmodified', 'assign');
2692 $modifiedusers[$modified->userid] = $modified;
2697 $currentgrades->close();
2699 $adminconfig = $this->get_admin_config();
2700 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
2702 // ok - ready to process the updates
2703 foreach ($modifiedusers as $userid => $modified) {
2704 $grade = $this->get_user_grade($userid, true);
2705 $grade->grade= grade_floatval(unformat_float($modified->grade));
2706 $grade->grader= $USER->id;
2708 // save plugins data
2709 foreach ($this->feedbackplugins as $plugin) {
2710 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2711 $plugin->save_quickgrading_changes($userid, $grade);
2712 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
2713 // This is the feedback plugin chose to push comments to the gradebook.
2714 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
2715 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
2720 $this->update_grade($grade);
2723 if ($CFG->enableoutcomes) {
2725 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2726 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2727 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2728 if ($oldoutcome != $newoutcome) {
2729 $data[$outcomeid] = $newoutcome;
2732 if (count($data) > 0) {
2733 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2737 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2740 return get_string('quickgradingchangessaved', 'assign');
2744 * save grading options
2748 private function process_save_grading_options() {
2751 // Include grading options form
2752 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2754 // Need submit permission to submit an assignment
2755 require_capability('mod/assign:grade', $this->context);
2757 $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id,
2758 'contextid'=>$this->context->id,
2759 'userid'=>$USER->id,
2760 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
2761 'showquickgrading'=>false));
2762 if ($formdata = $mform->get_data()) {
2763 set_user_preference('assign_perpage', $formdata->perpage);
2764 set_user_preference('assign_filter', $formdata->filter);
2769 * Take a grade object and print a short summary for the log file.
2770 * The size limit for the log file is 255 characters, so be careful not
2771 * to include too much information.
2773 * @param stdClass $grade
2776 private function format_grade_for_log(stdClass $grade) {
2779 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2781 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2782 if ($grade->grade != '') {
2783 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
2785 $info .= get_string('nograde', 'assign');
2787 if ($grade->locked) {
2788 $info .= get_string('submissionslocked', 'assign') . '. ';
2794 * Take a submission object and print a short summary for the log file.
2795 * The size limit for the log file is 255 characters, so be careful not
2796 * to include too much information.
2798 * @param stdClass $submission
2801 private function format_submission_for_log(stdClass $submission) {
2803 $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2804 // format_for_log here iterating every single log INFO from either submission or grade in every assignment plugin
2806 foreach ($this->submissionplugins as $plugin) {
2807 if ($plugin->is_enabled() && $plugin->is_visible()) {
2810 $info .= "<br>" . $plugin->format_for_log($submission);
2819 * save assignment submission
2821 * @param moodleform $mform
2824 private function process_save_submission(&$mform) {
2827 // Include submission form
2828 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2830 // Need submit permission to submit an assignment
2831 require_capability('mod/assign:submit', $this->context);
2834 $data = new stdClass();
2835 $mform = new mod_assign_submission_form(null, array($this, $data));
2836 if ($mform->is_cancelled()) {
2839 if ($data = $mform->get_data()) {
2840 $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2841 $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2842 if ($grade && $grade->locked) {
2843 print_error('submissionslocked', 'assign');
2848 foreach ($this->submissionplugins as $plugin) {
2849 if ($plugin->is_enabled()) {
2850 if (!$plugin->save($submission, $data)) {
2851 print_error($plugin->get_error());
2856 $this->update_submission($submission);
2859 $this->add_to_log('submit', $this->format_submission_for_log($submission));
2861 if (!$this->get_instance()->submissiondrafts) {
2862 $this->notify_student_submission_receipt($submission);
2863 $this->notify_graders($submission);
2872 * Determine if this users grade is locked or overridden
2874 * @param int $userid - The student userid
2875 * @return bool $gradingdisabled
2877 public function grading_disabled($userid) {
2880 $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2881 if (!$gradinginfo) {
2885 if (!isset($gradinginfo->items[0]->grades[$userid])) {
2888 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2889 return $gradingdisabled;
2894 * Get an instance of a grading form if advanced grading is enabled
2895 * This is specific to the assignment, marker and student
2897 * @param int $userid - The student userid
2898 * @param bool $gradingdisabled
2899 * @return mixed gradingform_instance|null $gradinginstance
2901 private function get_grading_instance($userid, $gradingdisabled) {
2904 $grade = $this->get_user_grade($userid, false);
2905 $grademenu = make_grades_menu($this->get_instance()->grade);
2907 $advancedgradingwarning = false;
2908 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2909 $gradinginstance = null;
2910 if ($gradingmethod = $gradingmanager->get_active_method()) {
2911 $controller = $gradingmanager->get_controller($gradingmethod);
2912 if ($controller->is_form_available()) {
2915 $itemid = $grade->id;
2917 if ($gradingdisabled && $itemid) {
2918 $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2919 } else if (!$gradingdisabled) {
2920 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2921 $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2924 $advancedgradingwarning = $controller->form_unavailable_notification();
2927 if ($gradinginstance) {
2928 $gradinginstance->get_controller()->set_grade_range($grademenu);
2930 return $gradinginstance;
2934 * add elements to grade form
2936 * @param MoodleQuickForm $mform
2937 * @param stdClass $data
2938 * @param array $params
2941 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2943 $settings = $this->get_instance();
2945 $rownum = $params['rownum'];
2946 $last = $params['last'];
2947 $useridlist = $params['useridlist'];
2948 $userid = $useridlist[$rownum];
2949 $grade = $this->get_user_grade($userid, false);
2951 // add advanced grading
2952 $gradingdisabled = $this->grading_disabled($userid);
2953 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2955 if ($gradinginstance) {
2956 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2957 if ($gradingdisabled) {
2958 $gradingelement->freeze();
2960 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2963 // use simple direct grading
2964 if ($this->get_instance()->grade > 0) {
2965 $gradingelement = $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
2966 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2967 $mform->setType('grade', PARAM_TEXT);
2968 if ($gradingdisabled) {
2969 $gradingelement->freeze();
2972 $grademenu = make_grades_menu($this->get_instance()->grade);
2973 if (count($grademenu) > 0) {
2974 $gradingelement = $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
2975 $mform->setType('grade', PARAM_INT);
2976 if ($gradingdisabled) {
2977 $gradingelement->freeze();
2983 $gradinginfo = grade_get_grades($this->get_course()->id,
2986 $this->get_instance()->id,
2988 if (!empty($CFG->enableoutcomes)) {
2989 foreach($gradinginfo->outcomes as $index=>$outcome) {
2990 $options = make_grades_menu(-$outcome->scaleid);
2991 if ($outcome->grades[$userid]->locked) {
2992 $options[0] = get_string('nooutcome', 'grades');
2993 $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
2994 $options[$outcome->grades[$userid]->grade]);
2996 $options[''] = get_string('nooutcome', 'grades');
2997 $attributes = array('id' => 'menuoutcome_'.$index );
2998 $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
2999 $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
3000 $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
3005 if (has_all_capabilities(array('gradereport/grader:view', 'moodle/grade:viewall'), $this->get_course_context())) {
3006 $gradestring = $this->output->action_link(new moodle_url('/grade/report/grader/index.php',
3007 array('id'=>$this->get_course()->id)),
3008 $gradinginfo->items[0]->grades[$userid]->str_grade);
3010 $gradestring = $gradinginfo->items[0]->grades[$userid]->str_grade;
3012 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assign').':', $gradestring);
3015 $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
3017 // Let feedback plugins add elements to the grading form.
3018 $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
3021 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3022 $mform->setType('id', PARAM_INT);
3023 $mform->addElement('hidden', 'rownum', $rownum);
3024 $mform->setType('rownum', PARAM_INT);
3025 $mform->setConstant('rownum', $rownum);
3026 $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
3027 $mform->setType('useridlist', PARAM_TEXT);
3028 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
3029 $mform->setType('ajax', PARAM_INT);
3031 $mform->addElement('hidden', 'action', 'submitgrade');
3032 $mform->setType('action', PARAM_ALPHA);
3035 $buttonarray=array();
3036 $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
3038 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
3040 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
3041 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
3042 $mform->closeHeaderBefore('buttonar');
3043 $buttonarray=array();
3046 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
3050 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
3052 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
3057 * add elements in submission plugin form
3059 * @param mixed $submission stdClass|null
3060 * @param MoodleQuickForm $mform
3061 * @param stdClass $data
3062 * @param int $userid The current userid (same as $USER->id)
3065 private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data, $userid) {
3066 foreach ($this->submissionplugins as $plugin) {
3067 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3068 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
3069 if (!$plugin->get_form_elements_for_user($submission, $mform, $data, $userid)) {
3070 $mform->removeElement('header_' . $plugin->get_type());
3077 * check if feedback plugins installed are enabled
3081 public function is_any_feedback_plugin_enabled() {
3082 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
3083 $this->cache['any_feedback_plugin_enabled'] = false;
3084 foreach ($this->feedbackplugins as $plugin) {
3085 if ($plugin->is_enabled() && $plugin->is_visible()) {
3086 $this->cache['any_feedback_plugin_enabled'] = true;
3092 return $this->cache['any_feedback_plugin_enabled'];
3097 * check if submission plugins installed are enabled
3101 public function is_any_submission_plugin_enabled() {
3102 if (!isset($this->cache['any_submission_plugin_enabled'])) {
3103 $this->cache['any_submission_plugin_enabled'] = false;
3104 foreach ($this->submissionplugins as $plugin) {
3105 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
3106 $this->cache['any_submission_plugin_enabled'] = true;
3112 return $this->cache['any_submission_plugin_enabled'];
3117 * add elements to submission form
3118 * @param MoodleQuickForm $mform
3119 * @param stdClass $data
3122 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
3125 // online text submissions
3127 $submission = $this->get_user_submission($USER->id, false);
3129 $this->add_plugin_submission_elements($submission, $mform, $data, $USER->id);
3132 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3133 $mform->setType('id', PARAM_INT);
3135 $mform->addElement('hidden', 'action', 'savesubmission');
3136 $mform->setType('action', PARAM_TEXT);
3143 * Uses url parameter userid
3145 * @param int $userid
3148 private function process_revert_to_draft($userid = 0) {
3151 // Need grade permission
3152 require_capability('mod/assign:grade', $this->context);
3156 $userid = required_param('userid', PARAM_INT);
3159 $submission = $this->get_user_submission($userid, false);
3163 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3164 $this->update_submission($submission, false);
3166 // update the modified time on the grade (grader modified)
3167 $grade = $this->get_user_grade($userid, true);
3168 $this->update_grade($grade);
3170 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3172 $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3178 * Uses url parameter userid
3179 * @param int $userid
3182 private function process_lock($userid = 0) {
3185 // Need grade permission
3186 require_capability('mod/assign:grade', $this->context);
3190 $userid = required_param('userid', PARAM_INT);
3193 $grade = $this->get_user_grade($userid, true);
3195 $grade->grader = $USER->id;
3196 $this->update_grade($grade);
3198 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3200 $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3204 * unlock the process
3206 * @param int $userid
3209 private function process_unlock($userid = 0) {
3212 // Need grade permission
3213 require_capability('mod/assign:grade', $this->context);
3217 $userid = required_param('userid', PARAM_INT);
3220 $grade = $this->get_user_grade($userid, true);
3222 $grade->grader = $USER->id;
3223 $this->update_grade($grade);
3225 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3227 $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3231 * save outcomes submitted from grading form
3233 * @param int $userid
3234 * @param stdClass $formdata
3236 private function process_outcomes($userid, $formdata) {
3239 if (empty($CFG->enableoutcomes)) {
3242 if ($this->grading_disabled($userid)) {
3246 require_once($CFG->libdir.'/gradelib.php');
3249 $gradinginfo = grade_get_grades($this->get_course()->id,
3252 $this->get_instance()->id,
3255 if (!empty($gradinginfo->outcomes)) {
3256 foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3257 $name = 'outcome_'.$index;
3258 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3259 $data[$index] = $formdata->{$name}[$userid];
3263 if (count($data) > 0) {
3264 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3273 * @param moodleform $mform
3274 * @return bool - was the grade saved
3276 private function process_save_grade(&$mform) {
3277 global $USER, $DB, $CFG;
3278 // Include grade form
3279 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3281 // Need submit permission to submit an assignment
3282 require_capability('mod/assign:grade', $this->context);
3285 $rownum = required_param('rownum', PARAM_INT);
3286 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3288 $useridlist = explode(',', $useridlist);
3290 $useridlist = $this->get_grading_userid_list();
3293 $userid = $useridlist[$rownum];
3294 if ($rownum == count($useridlist) - 1) {
3298 $data = new stdClass();
3299 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3301 if ($formdata = $mform->get_data()) {
3302 $grade = $this->get_user_grade($userid, true);
3303 $gradingdisabled = $this->grading_disabled($userid);
3304 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
3305 if (!$gradingdisabled) {
3306 if ($gradinginstance) {
3307 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3309 // handle the case when grade is set to No Grade
3310 if (isset($formdata->grade)) {
3311 $grade->grade = grade_floatval(unformat_float($formdata->grade));
3315 $grade->grader= $USER->id;
3317 $adminconfig = $this->get_admin_config();
3318 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
3320 // call save in plugins
3321 foreach ($this->feedbackplugins as $plugin) {
3322 if ($plugin->is_enabled() && $plugin->is_visible()) {
3323 if (!$plugin->save($grade, $formdata)) {
3325 print_error($plugin->get_error());
3327 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3328 // this is the feedback plugin chose to push comments to the gradebook