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');
43 * File areas for assignment portfolio if enabled
45 define('ASSIGN_FILEAREA_PORTFOLIO_FILES', 'portfolio_files');
48 /** Include accesslib.php */
49 require_once($CFG->libdir.'/accesslib.php');
50 /** Include formslib.php */
51 require_once($CFG->libdir.'/formslib.php');
52 /** Include repository/lib.php */
53 require_once($CFG->dirroot . '/repository/lib.php');
54 /** Include local mod_form.php */
55 require_once($CFG->dirroot.'/mod/assign/mod_form.php');
56 /** Include portfoliolib.php */
57 require_once($CFG->libdir . '/portfoliolib.php');
59 require_once($CFG->libdir.'/gradelib.php');
60 /** grading lib.php */
61 require_once($CFG->dirroot.'/grade/grading/lib.php');
62 /** Include feedbackplugin.php */
63 require_once($CFG->dirroot.'/mod/assign/feedbackplugin.php');
64 /** Include submissionplugin.php */
65 require_once($CFG->dirroot.'/mod/assign/submissionplugin.php');
66 /** Include renderable.php */
67 require_once($CFG->dirroot.'/mod/assign/renderable.php');
68 /** Include gradingtable.php */
69 require_once($CFG->dirroot.'/mod/assign/gradingtable.php');
70 /** Include eventslib.php */
71 require_once($CFG->libdir.'/eventslib.php');
75 * Standard base class for mod_assign (assignment types).
78 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
79 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
84 /** @var stdClass the assignment record that contains the global settings for this assign instance */
87 /** @var context the context of the course module for this assign instance (or just the course if we are
88 creating a new one) */
91 /** @var stdClass the course this assign instance belongs to */
94 /** @var stdClass the admin config for all assign instances */
98 /** @var assign_renderer the custom renderer for this module */
101 /** @var stdClass the course module for this assign instance */
102 private $coursemodule;
104 /** @var array cache for things like the coursemodule name or the scale menu - only lives for a single
108 /** @var array list of the installed submission plugins */
109 private $submissionplugins;
111 /** @var array list of the installed feedback plugins */
112 private $feedbackplugins;
114 /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
115 private $returnaction = 'view';
117 /** @var array params to be used to return to this page */
118 private $returnparams = array();
120 /** @var string modulename prevents excessive calls to get_string */
121 private static $modulename = null;
123 /** @var string modulenameplural prevents excessive calls to get_string */
124 private static $modulenameplural = null;
127 * Constructor for the base assign class
129 * @param mixed $coursemodulecontext context|null the course module context (or the course context if the coursemodule has not been created yet)
130 * @param mixed $coursemodule the current course module if it was already loaded - otherwise this class will load one from the context as required
131 * @param mixed $course the current course if it was already loaded - otherwise this class will load one from the context as required
133 public function __construct($coursemodulecontext, $coursemodule, $course) {
136 $this->context = $coursemodulecontext;
137 $this->coursemodule = $coursemodule;
138 $this->course = $course;
139 $this->cache = array(); // temporary cache only lives for a single request - used to reduce db lookups
141 $this->submissionplugins = $this->load_plugins('assignsubmission');
142 $this->feedbackplugins = $this->load_plugins('assignfeedback');
143 $this->output = $PAGE->get_renderer('mod_assign');
147 * Set the action and parameters that can be used to return to the current page
149 * @param string $action The action for the current page
150 * @param array $params An array of name value pairs which form the parameters to return to the current page
153 public function register_return_link($action, $params) {
154 $this->returnaction = $action;
155 $this->returnparams = $params;
159 * Return an action that can be used to get back to the current page
160 * @return string action
162 public function get_return_action() {
163 return $this->returnaction;
167 * Based on the current assignment settings should we display the intro
168 * @return bool showintro
170 private function show_intro() {
171 if ($this->get_instance()->alwaysshowdescription ||
172 time() > $this->get_instance()->allowsubmissionsfromdate) {
179 * Return a list of parameters that can be used to get back to the current page
180 * @return array params
182 public function get_return_params() {
183 return $this->returnparams;
187 * Set the submitted form data
188 * @param stdClass $data The form data (instance)
190 public function set_instance(stdClass $data) {
191 $this->instance = $data;
196 * @param context $context The new context
198 public function set_context(context $context) {
199 $this->context = $context;
203 * Set the course data
204 * @param stdClass $course The course data
206 public function set_course(stdClass $course) {
207 $this->course = $course;
211 * get list of feedback plugins installed
214 public function get_feedback_plugins() {
215 return $this->feedbackplugins;
219 * get list of submission plugins installed
222 public function get_submission_plugins() {
223 return $this->submissionplugins;
228 * get a specific submission plugin by its type
229 * @param string $subtype assignsubmission | assignfeedback
230 * @param string $type
231 * @return mixed assign_plugin|null
233 private function get_plugin_by_type($subtype, $type) {
234 $shortsubtype = substr($subtype, strlen('assign'));
235 $name = $shortsubtype . 'plugins';
236 $pluginlist = $this->$name;
237 foreach ($pluginlist as $plugin) {
238 if ($plugin->get_type() == $type) {
246 * Get a feedback plugin by type
247 * @param string $type - The type of plugin e.g comments
248 * @return mixed assign_feedback_plugin|null
250 public function get_feedback_plugin_by_type($type) {
251 return $this->get_plugin_by_type('assignfeedback', $type);
255 * Get a submission plugin by type
256 * @param string $type - The type of plugin e.g comments
257 * @return mixed assign_submission_plugin|null
259 public function get_submission_plugin_by_type($type) {
260 return $this->get_plugin_by_type('assignsubmission', $type);
264 * Load the plugins from the sub folders under subtype
265 * @param string $subtype - either submission or feedback
266 * @return array - The sorted list of plugins
268 private function load_plugins($subtype) {
272 $names = get_plugin_list($subtype);
274 foreach ($names as $name => $path) {
275 if (file_exists($path . '/locallib.php')) {
276 require_once($path . '/locallib.php');
278 $shortsubtype = substr($subtype, strlen('assign'));
279 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
281 $plugin = new $pluginclass($this, $name);
283 if ($plugin instanceof assign_plugin) {
284 $idx = $plugin->get_sort_order();
285 while (array_key_exists($idx, $result)) $idx +=1;
286 $result[$idx] = $plugin;
296 * Display the assignment, used by view.php
298 * The assignment is displayed differently depending on your role,
299 * the settings for the assignment and the status of the assignment.
300 * @param string $action The current action if any.
303 public function view($action='') {
308 // handle form submissions first
309 if ($action == 'savesubmission') {
310 $action = 'editsubmission';
311 if ($this->process_save_submission($mform)) {
314 } else if ($action == 'lock') {
315 $this->process_lock();
317 } else if ($action == 'reverttodraft') {
318 $this->process_revert_to_draft();
320 } else if ($action == 'unlock') {
321 $this->process_unlock();
323 } else if ($action == 'confirmsubmit') {
324 $this->process_submit_for_grading();
325 // save and show next button
326 } else if ($action == 'batchgradingoperation') {
327 $this->process_batch_grading_operation();
329 } else if ($action == 'submitgrade') {
330 if (optional_param('saveandshownext', null, PARAM_ALPHA)) {
333 if ($this->process_save_grade($mform)) {
334 $action = 'nextgrade';
336 } else if (optional_param('nosaveandprevious', null, PARAM_ALPHA)) {
337 $action = 'previousgrade';
338 } else if (optional_param('nosaveandnext', null, PARAM_ALPHA)) {
340 $action = 'nextgrade';
341 } else if (optional_param('savegrade', null, PARAM_ALPHA)) {
342 //save changes button
344 if ($this->process_save_grade($mform)) {
351 }else if ($action == 'quickgrade') {
352 $message = $this->process_save_quick_grades();
353 $action = 'quickgradingresult';
354 }else if ($action == 'saveoptions') {
355 $this->process_save_grading_options();
359 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
360 $this->register_return_link($action, $returnparams);
362 // now show the right view page
363 if ($action == 'previousgrade') {
365 $o .= $this->view_single_grade_page($mform, -1);
366 } else if ($action == 'quickgradingresult') {
368 $o .= $this->view_quickgrading_result($message);
369 } else if ($action == 'nextgrade') {
371 $o .= $this->view_single_grade_page($mform, 1);
372 } else if ($action == 'redirect') {
373 redirect(required_param('url', PARAM_TEXT));
374 } else if ($action == 'grade') {
375 $o .= $this->view_single_grade_page($mform);
376 } else if ($action == 'viewpluginassignfeedback') {
377 $o .= $this->view_plugin_content('assignfeedback');
378 } else if ($action == 'viewpluginassignsubmission') {
379 $o .= $this->view_plugin_content('assignsubmission');
380 } else if ($action == 'editsubmission') {
381 $o .= $this->view_edit_submission_page($mform);
382 } else if ($action == 'grading') {
383 $o .= $this->view_grading_page();
384 } else if ($action == 'downloadall') {
385 $o .= $this->download_submissions();
386 } else if ($action == 'submit') {
387 $o .= $this->check_submit_for_grading();
389 $o .= $this->view_submission_page();
397 * Add this instance to the database
399 * @param stdClass $formdata The data submitted from the form
400 * @param bool $callplugins This is used to skip the plugin code
401 * when upgrading an old assignment to a new one (the plugins get called manually)
402 * @return mixed false if an error occurs or the int id of the new instance
404 public function add_instance(stdClass $formdata, $callplugins) {
409 // add the database record
410 $update = new stdClass();
411 $update->name = $formdata->name;
412 $update->timemodified = time();
413 $update->timecreated = time();
414 $update->course = $formdata->course;
415 $update->courseid = $formdata->course;
416 $update->intro = $formdata->intro;
417 $update->introformat = $formdata->introformat;
418 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
419 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
420 $update->submissiondrafts = $formdata->submissiondrafts;
421 $update->sendnotifications = $formdata->sendnotifications;
422 $update->sendlatenotifications = $formdata->sendlatenotifications;
423 $update->duedate = $formdata->duedate;
424 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
425 $update->grade = $formdata->grade;
426 $returnid = $DB->insert_record('assign', $update);
427 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
428 // cache the course record
429 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
432 // call save_settings hook for submission plugins
433 foreach ($this->submissionplugins as $plugin) {
434 if (!$this->update_plugin_instance($plugin, $formdata)) {
435 print_error($plugin->get_error());
439 foreach ($this->feedbackplugins as $plugin) {
440 if (!$this->update_plugin_instance($plugin, $formdata)) {
441 print_error($plugin->get_error());
446 // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
447 // TODO: add event to the calendar
448 $this->update_calendar($formdata->coursemodule);
449 // TODO: add the item in the gradebook
450 $this->update_gradebook(false, $formdata->coursemodule);
454 $update = new stdClass();
455 $update->id = $this->get_instance()->id;
456 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
457 $DB->update_record('assign', $update);
463 * Delete all grades from the gradebook for this assignment
467 private function delete_grades() {
470 return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
474 * Delete this instance from the database
476 * @return bool false if an error occurs
478 public function delete_instance() {
482 foreach ($this->submissionplugins as $plugin) {
483 if (!$plugin->delete_instance()) {
484 print_error($plugin->get_error());
488 foreach ($this->feedbackplugins as $plugin) {
489 if (!$plugin->delete_instance()) {
490 print_error($plugin->get_error());
495 // delete files associated with this assignment
496 $fs = get_file_storage();
497 if (! $fs->delete_area_files($this->context->id) ) {
501 // delete_records will throw an exception if it fails - so no need for error checking here
503 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
504 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
505 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
507 // delete items from the gradebook
508 if (! $this->delete_grades()) {
512 // delete the instance
513 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
519 * Update the settings for a single plugin
521 * @param assign_plugin $plugin The plugin to update
522 * @param stdClass $formdata The form data
523 * @return bool false if an error occurs
525 private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
526 if ($plugin->is_visible()) {
527 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
528 if ($formdata->$enabledname) {
530 if (!$plugin->save_settings($formdata)) {
531 print_error($plugin->get_error());
542 * Update the gradebook information for this assignment
544 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
545 * @param int $coursemoduleid This is required because it might not exist in the database yet
548 public function update_gradebook($reset, $coursemoduleid) {
550 /** Include lib.php */
551 require_once($CFG->dirroot.'/mod/assign/lib.php');
552 $assign = clone $this->get_instance();
553 $assign->cmidnumber = $coursemoduleid;
559 return assign_grade_item_update($assign, $param);
562 /** Load and cache the admin config for this module
564 * @return stdClass the plugin config
566 public function get_admin_config() {
567 if ($this->adminconfig) {
568 return $this->adminconfig;
570 $this->adminconfig = get_config('assign');
571 return $this->adminconfig;
576 * Update the calendar entries for this assignment
578 * @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
581 public function update_calendar($coursemoduleid) {
583 require_once($CFG->dirroot.'/calendar/lib.php');
585 // special case for add_instance as the coursemodule has not been set yet.
587 if ($this->get_instance()->duedate) {
588 $event = new stdClass();
590 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {
592 $event->name = $this->get_instance()->name;
594 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
595 $event->timestart = $this->get_instance()->duedate;
597 $calendarevent = calendar_event::load($event->id);
598 $calendarevent->update($event);
600 $event = new stdClass();
601 $event->name = $this->get_instance()->name;
602 $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
603 $event->courseid = $this->get_instance()->course;
606 $event->modulename = 'assign';
607 $event->instance = $this->get_instance()->id;
608 $event->eventtype = 'due';
609 $event->timestart = $this->get_instance()->duedate;
610 $event->timeduration = 0;
612 calendar_event::create($event);
615 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
621 * Update this instance in the database
623 * @param stdClass $formdata - the data submitted from the form
624 * @return bool false if an error occurs
626 public function update_instance($formdata) {
629 $update = new stdClass();
630 $update->id = $formdata->instance;
631 $update->name = $formdata->name;
632 $update->timemodified = time();
633 $update->course = $formdata->course;
634 $update->intro = $formdata->intro;
635 $update->introformat = $formdata->introformat;
636 $update->alwaysshowdescription = $formdata->alwaysshowdescription;
637 $update->preventlatesubmissions = $formdata->preventlatesubmissions;
638 $update->submissiondrafts = $formdata->submissiondrafts;
639 $update->sendnotifications = $formdata->sendnotifications;
640 $update->sendlatenotifications = $formdata->sendlatenotifications;
641 $update->duedate = $formdata->duedate;
642 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
643 $update->grade = $formdata->grade;
645 $result = $DB->update_record('assign', $update);
646 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
648 // load the assignment so the plugins have access to it
650 // call save_settings hook for submission plugins
651 foreach ($this->submissionplugins as $plugin) {
652 if (!$this->update_plugin_instance($plugin, $formdata)) {
653 print_error($plugin->get_error());
657 foreach ($this->feedbackplugins as $plugin) {
658 if (!$this->update_plugin_instance($plugin, $formdata)) {
659 print_error($plugin->get_error());
665 // update the database record
668 // update all the calendar events
669 $this->update_calendar($this->get_course_module()->id);
671 $this->update_gradebook(false, $this->get_course_module()->id);
673 $update = new stdClass();
674 $update->id = $this->get_instance()->id;
675 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
676 $DB->update_record('assign', $update);
686 * add elements in grading plugin form
688 * @param mixed $grade stdClass|null
689 * @param MoodleQuickForm $mform
690 * @param stdClass $data
693 private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data) {
694 foreach ($this->feedbackplugins as $plugin) {
695 if ($plugin->is_enabled() && $plugin->is_visible()) {
696 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
697 if (!$plugin->get_form_elements($grade, $mform, $data)) {
698 $mform->removeElement('header_' . $plugin->get_type());
707 * Add one plugins settings to edit plugin form
709 * @param assign_plugin $plugin The plugin to add the settings from
710 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
713 private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
715 if ($plugin->is_visible()) {
717 //tied disableIf rule to this select element
718 $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
719 $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
722 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
723 if ($plugin->get_config('enabled') !== false) {
724 $default = $plugin->is_enabled();
726 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
728 $plugin->get_settings($mform);
736 * Add settings to edit plugin form
738 * @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
741 public function add_all_plugin_settings(MoodleQuickForm $mform) {
742 $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));
744 foreach ($this->submissionplugins as $plugin) {
745 $this->add_plugin_settings($plugin, $mform);
748 $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
749 foreach ($this->feedbackplugins as $plugin) {
750 $this->add_plugin_settings($plugin, $mform);
755 * Allow each plugin an opportunity to update the defaultvalues
756 * passed in to the settings form (needed to set up draft areas for
757 * editor and filemanager elements)
758 * @param array $defaultvalues
760 public function plugin_data_preprocessing(&$defaultvalues) {
761 foreach ($this->submissionplugins as $plugin) {
762 if ($plugin->is_visible()) {
763 $plugin->data_preprocessing($defaultvalues);
766 foreach ($this->feedbackplugins as $plugin) {
767 if ($plugin->is_visible()) {
768 $plugin->data_preprocessing($defaultvalues);
774 * Get the name of the current module.
776 * @return string the module name (Assignment)
778 protected function get_module_name() {
779 if (isset(self::$modulename)) {
780 return self::$modulename;
782 self::$modulename = get_string('modulename', 'assign');
783 return self::$modulename;
787 * Get the plural name of the current module.
789 * @return string the module name plural (Assignments)
791 protected function get_module_name_plural() {
792 if (isset(self::$modulenameplural)) {
793 return self::$modulenameplural;
795 self::$modulenameplural = get_string('modulenameplural', 'assign');
796 return self::$modulenameplural;
800 * Has this assignment been constructed from an instance?
804 public function has_instance() {
805 return $this->instance || $this->get_course_module();
809 * Get the settings for the current instance of this assignment
811 * @return stdClass The settings
813 public function get_instance() {
815 if ($this->instance) {
816 return $this->instance;
818 if ($this->get_course_module()) {
819 $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
821 if (!$this->instance) {
822 throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
824 return $this->instance;
828 * Get the context of the current course
829 * @return mixed context|null The course context
831 public function get_course_context() {
832 if (!$this->context && !$this->course) {
833 throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
835 if ($this->context) {
836 return $this->context->get_course_context();
838 return context_course::instance($this->course->id);
844 * Get the current course module
846 * @return mixed stdClass|null The course module
848 public function get_course_module() {
849 if ($this->coursemodule) {
850 return $this->coursemodule;
852 if (!$this->context) {
856 if ($this->context->contextlevel == CONTEXT_MODULE) {
857 $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
858 return $this->coursemodule;
868 public function get_context() {
869 return $this->context;
873 * Get the current course
874 * @return mixed stdClass|null The course
876 public function get_course() {
879 return $this->course;
882 if (!$this->context) {
885 $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
886 return $this->course;
890 * Return a grade in user-friendly form, whether it's a scale or not
892 * @param mixed $grade int|null
893 * @param boolean $editing Are we allowing changes to this grade?
894 * @param int $userid The user id the grade belongs to
895 * @param int $modified Timestamp from when the grade was last modified
896 * @return string User-friendly representation of grade
898 public function display_grade($grade, $editing, $userid=0, $modified=0) {
901 static $scalegrades = array();
903 if ($this->get_instance()->grade >= 0) {
906 $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $grade . '" size="6" maxlength="10" class="quickgrade"/>';
907 $o .= ' / ' . format_float($this->get_instance()->grade,2);
908 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
910 } else if ($grade == -1 || $grade === null) {
913 return format_float(($grade),2) .' / '. format_float($this->get_instance()->grade,2);
918 if (empty($this->cache['scale'])) {
919 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
920 $this->cache['scale'] = make_menu_from_list($scale->scale);
926 $o = '<select name="quickgrade_' . $userid . '" class="quickgrade">';
927 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
928 foreach ($this->cache['scale'] as $optionid => $option) {
930 if ($grade == $optionid) {
931 $selected = 'selected="selected"';
933 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
936 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
939 $scaleid = (int)$grade;
940 if (isset($this->cache['scale'][$scaleid])) {
941 return $this->cache['scale'][$scaleid];
949 * Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
951 * @param int $currentgroup
952 * @param bool $idsonly
953 * @return array List of user records
955 public function list_participants($currentgroup, $idsonly) {
957 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
959 return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
964 * Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
966 * @param int $currentgroup
967 * @return int number of matching users
969 public function count_participants($currentgroup) {
970 return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
974 * Load a count of users enrolled in the current course with the specified permission and group (optional)
976 * @param string $status The submission status - should match one of the constants
977 * @return int number of matching submissions
979 public function count_submissions_with_status($status) {
981 return $DB->count_records_sql("SELECT COUNT('x')
982 FROM {assign_submission}
983 WHERE assignment = ? AND
984 status = ?", array($this->get_course_module()->instance, $status));
988 * Utility function to get the userid for every row in the grading table
989 * so the order can be frozen while we iterate it
991 * @return array An array of userids
993 private function get_grading_userid_list(){
994 $filter = get_user_preferences('assign_filter', '');
995 $table = new assign_grading_table($this, 0, $filter, 0, false);
997 $useridlist = $table->get_column_data('userid');
1004 * Utility function get the userid based on the row number of the grading table.
1005 * This takes into account any active filters on the table.
1007 * @param int $num The row number of the user
1008 * @param bool $last This is set to true if this is the last user in the table
1009 * @return mixed The user id of the matching user or false if there was an error
1011 private function get_userid_for_row($num, $last){
1012 if (!array_key_exists('userid_for_row', $this->cache)) {
1013 $this->cache['userid_for_row'] = array();
1015 if (array_key_exists($num, $this->cache['userid_for_row'])) {
1016 list($userid, $last) = $this->cache['userid_for_row'][$num];
1020 $filter = get_user_preferences('assign_filter', '');
1021 $table = new assign_grading_table($this, 0, $filter, 0, false);
1023 $userid = $table->get_cell_data($num, 'userid', $last);
1025 $this->cache['userid_for_row'][$num] = array($userid, $last);
1030 * Return all assignment submissions by ENROLLED students (even empty)
1032 * @param string $sort optional field names for the ORDER BY in the sql query
1033 * @param string $dir optional specifying the sort direction, defaults to DESC
1034 * @return array The submission objects indexed by id
1036 private function get_all_submissions( $sort="", $dir="DESC") {
1039 if ($sort == "lastname" or $sort == "firstname") {
1040 $sort = "u.$sort $dir";
1041 } else if (empty($sort)) {
1042 $sort = "a.timemodified DESC";
1044 $sort = "a.$sort $dir";
1047 return $DB->get_records_sql("SELECT a.*
1048 FROM {assign_submission} a, {user} u
1049 WHERE u.id = a.userid
1050 AND a.assignment = ?
1051 ORDER BY $sort", array($this->get_instance()->id));
1056 * Generate zip file from array of given files
1058 * @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
1059 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
1061 private function pack_files($filesforzipping) {
1063 //create path for new zip file.
1064 $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
1066 $zipper = new zip_packer();
1067 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1074 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1076 * Cron function to be run periodically according to the moodle cron
1080 static function cron() {
1083 // only ever send a max of one days worth of updates
1084 $yesterday = time() - (24 * 3600);
1087 // Collect all submissions from the past 24 hours that require mailing.
1088 $sql = "SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1090 JOIN {assign_grades} g ON g.assignment = a.id
1091 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1092 WHERE g.timemodified >= :yesterday AND
1093 g.timemodified <= :today AND
1095 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1096 $submissions = $DB->get_records_sql($sql, $params);
1098 if (empty($submissions)) {
1103 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1105 // Preload courses we are going to need those.
1106 $courseids = array();
1107 foreach ($submissions as $submission) {
1108 $courseids[] = $submission->course;
1110 // Filter out duplicates
1111 $courseids = array_unique($courseids);
1112 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1113 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1114 $sql = "SELECT c.*, {$ctxselect}
1116 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1117 WHERE c.id {$courseidsql}";
1118 $params['contextlevel'] = CONTEXT_COURSE;
1119 $courses = $DB->get_records_sql($sql, $params);
1120 // Clean up... this could go on for a while.
1123 unset($courseidsql);
1126 // Simple array we'll use for caching modules.
1127 $modcache = array();
1129 // Message students about new feedback
1130 foreach ($submissions as $submission) {
1132 mtrace("Processing assignment submission $submission->id ...");
1134 // do not cache user lookups - could be too many
1135 if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
1136 mtrace("Could not find user $submission->userid");
1140 // use a cache to prevent the same DB queries happening over and over
1141 if (!array_key_exists($submission->course, $courses)) {
1142 mtrace("Could not find course $submission->course");
1145 $course = $courses[$submission->course];
1146 if (isset($course->ctxid)) {
1147 // Context has not yet been preloaded. Do so now.
1148 context_helper::preload_from_record($course);
1151 // Override the language and timezone of the "current" user, so that
1152 // mail is customised for the receiver.
1153 cron_setup_user($user, $course);
1155 // context lookups are already cached
1156 $coursecontext = context_course::instance($course->id);
1157 if (!is_enrolled($coursecontext, $user->id)) {
1158 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1159 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1163 if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1164 mtrace("Could not find grader $submission->grader");
1168 if (!array_key_exists($submission->assignment, $modcache)) {
1169 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1170 mtrace("Could not find course module for assignment id $submission->assignment");
1173 $modcache[$submission->assignment] = $mod;
1175 $mod = $modcache[$submission->assignment];
1177 // context lookups are already cached
1178 $contextmodule = context_module::instance($mod->id);
1180 if (!$mod->visible) {
1181 // Hold mail notification for hidden assignments until later
1185 // need to send this to the student
1186 $messagetype = 'feedbackavailable';
1187 $eventtype = 'assign_student_notification';
1188 $updatetime = $submission->lastmodified;
1189 $modulename = get_string('modulename', 'assign');
1190 self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $mod, $contextmodule, $course, $modulename, $submission->name);
1192 $grade = new stdClass();
1193 $grade->id = $submission->gradeid;
1195 $DB->update_record('assign_grades', $grade);
1199 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1203 // Free up memory just to be sure
1211 * Update a grade in the grade table for the assignment and in the gradebook
1213 * @param stdClass $grade a grade record keyed on id
1214 * @return bool true for success
1216 private function update_grade($grade) {
1219 $grade->timemodified = time();
1221 if ($grade->grade && $grade->grade != -1) {
1222 if ($this->get_instance()->grade > 0) {
1223 if (!is_numeric($grade->grade)) {
1225 } else if ($grade->grade > $this->get_instance()->grade) {
1227 } else if ($grade->grade < 0) {
1232 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1233 $scaleoptions = make_menu_from_list($scale->scale);
1234 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1241 $result = $DB->update_record('assign_grades', $grade);
1243 $this->gradebook_item_update(null, $grade);
1249 * display the submission that is used by a plugin
1250 * Uses url parameters 'sid', 'gid' and 'plugin'
1251 * @param string $pluginsubtype
1254 private function view_plugin_content($pluginsubtype) {
1259 $submissionid = optional_param('sid', 0, PARAM_INT);
1260 $gradeid = optional_param('gid', 0, PARAM_INT);
1261 $plugintype = required_param('plugin', PARAM_TEXT);
1263 if ($pluginsubtype == 'assignsubmission') {
1264 $plugin = $this->get_submission_plugin_by_type($plugintype);
1265 if ($submissionid <= 0) {
1266 throw new coding_exception('Submission id should not be 0');
1268 $item = $this->get_submission($submissionid);
1271 if ($item->userid != $USER->id) {
1272 require_capability('mod/assign:grade', $this->context);
1274 $o .= $this->output->render(new assign_header($this->get_instance(),
1275 $this->get_context(),
1276 $this->show_intro(),
1277 $this->get_course_module()->id,
1278 $plugin->get_name()));
1279 $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1281 assign_submission_plugin_submission::FULL,
1282 $this->get_course_module()->id,
1283 $this->get_return_action(),
1284 $this->get_return_params()));
1286 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1288 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1289 if ($gradeid <= 0) {
1290 throw new coding_exception('Grade id should not be 0');
1292 $item = $this->get_grade($gradeid);
1294 if ($item->userid != $USER->id) {
1295 require_capability('mod/assign:grade', $this->context);
1297 $o .= $this->output->render(new assign_header($this->get_instance(),
1298 $this->get_context(),
1299 $this->show_intro(),
1300 $this->get_course_module()->id,
1301 $plugin->get_name()));
1302 $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1304 assign_feedback_plugin_feedback::FULL,
1305 $this->get_course_module()->id,
1306 $this->get_return_action(),
1307 $this->get_return_params()));
1308 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1312 $o .= $this->view_return_links();
1314 $o .= $this->view_footer();
1319 * render the content in editor that is often used by plugin
1321 * @param string $filearea
1322 * @param int $submissionid
1323 * @param string $plugintype
1324 * @param string $editor
1325 * @param string $component
1328 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1333 $plugin = $this->get_submission_plugin_by_type($plugintype);
1335 $text = $plugin->get_editor_text($editor, $submissionid);
1336 $format = $plugin->get_editor_format($editor, $submissionid);
1338 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1339 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1343 if ($CFG->enableportfolios) {
1344 require_once($CFG->libdir . '/portfoliolib.php');
1346 $button = new portfolio_add_button();
1347 $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');
1348 $fs = get_file_storage();
1350 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1351 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1353 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1355 $result .= $button->to_html();
1361 * Display a grading error
1363 * @param string $message - The description of the result
1366 private function view_quickgrading_result($message) {
1368 $o .= $this->output->render(new assign_header($this->get_instance(),
1369 $this->get_context(),
1370 $this->show_intro(),
1371 $this->get_course_module()->id,
1372 get_string('quickgradingresult', 'assign')));
1373 $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1374 $o .= $this->view_footer();
1379 * Display the page footer
1383 private function view_footer() {
1384 return $this->output->render_footer();
1388 * Does this user have grade permission for this assignment
1392 private function can_grade() {
1393 // Permissions check
1394 if (!has_capability('mod/assign:grade', $this->context)) {
1402 * Download a zip file of all assignment submissions
1406 private function download_submissions() {
1409 // more efficient to load this here
1410 require_once($CFG->libdir.'/filelib.php');
1412 // load all submissions
1413 $submissions = $this->get_all_submissions('','');
1415 if (empty($submissions)) {
1416 print_error('errornosubmissions', 'assign');
1420 // build a list of files to zip
1421 $filesforzipping = array();
1422 $fs = get_file_storage();
1424 $groupmode = groups_get_activity_groupmode($this->get_course_module());
1425 $groupid = 0; // All users
1428 $groupid = groups_get_activity_group($this->get_course_module(), true);
1429 $groupname = groups_get_group_name($groupid).'-';
1432 // construct the zip file name
1433 $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.
1435 // get all the files for each submission
1436 foreach ($submissions as $submission) {
1437 $userid = $submission->userid; //get userid
1438 if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1439 // get the plugins to add their own files to the zip
1441 $user = $DB->get_record("user", array("id"=>$userid),'id,username,firstname,lastname', MUST_EXIST);
1443 $prefix = clean_filename(fullname($user) . "_" .$userid . "_");
1445 foreach ($this->submissionplugins as $plugin) {
1446 if ($plugin->is_enabled() && $plugin->is_visible()) {
1447 $pluginfiles = $plugin->get_files($submission);
1450 foreach ($pluginfiles as $zipfilename => $file) {
1451 $filesforzipping[$prefix . $zipfilename] = $file;
1457 } // end of foreach loop
1458 if ($zipfile = $this->pack_files($filesforzipping)) {
1459 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1460 send_temp_file($zipfile, $filename); //send file and delete after sending.
1465 * Util function to add a message to the log
1467 * @param string $action The current action
1468 * @param string $info A detailed description of the change. But no more than 255 characters.
1469 * @param string $url The url to the assign module instance.
1472 public function add_to_log($action = '', $info = '', $url='') {
1475 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1477 $fullurl .= '&' . $url;
1480 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1484 * Load the submission object for a particular user, optionally creating it if required
1486 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1487 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1488 * @return stdClass The submission
1490 private function get_user_submission($userid, $create) {
1494 $userid = $USER->id;
1496 // if the userid is not null then use userid
1497 $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1503 $submission = new stdClass();
1504 $submission->assignment = $this->get_instance()->id;
1505 $submission->userid = $userid;
1506 $submission->timecreated = time();
1507 $submission->timemodified = $submission->timecreated;
1509 if ($this->get_instance()->submissiondrafts) {
1510 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1512 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1514 $sid = $DB->insert_record('assign_submission', $submission);
1515 $submission->id = $sid;
1522 * Load the submission object from it's id
1524 * @param int $submissionid The id of the submission we want
1525 * @return stdClass The submission
1527 private function get_submission($submissionid) {
1530 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1534 * This will retrieve a grade object from the db, optionally creating it if required
1536 * @param int $userid The user we are grading
1537 * @param bool $create If true the grade will be created if it does not exist
1538 * @return stdClass The grade record
1540 private function get_user_grade($userid, $create) {
1544 $userid = $USER->id;
1547 // if the userid is not null then use userid
1548 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1554 $grade = new stdClass();
1555 $grade->assignment = $this->get_instance()->id;
1556 $grade->userid = $userid;
1557 $grade->timecreated = time();
1558 $grade->timemodified = $grade->timecreated;
1561 $grade->grader = $USER->id;
1562 $gid = $DB->insert_record('assign_grades', $grade);
1570 * This will retrieve a grade object from the db
1572 * @param int $gradeid The id of the grade
1573 * @return stdClass The grade record
1575 private function get_grade($gradeid) {
1578 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1582 * Print the grading page for a single user submission
1584 * @param moodleform $mform
1585 * @param int $offset
1588 private function view_single_grade_page($mform, $offset=0) {
1593 // Include grade form
1594 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1596 // Need submit permission to submit an assignment
1597 require_capability('mod/assign:grade', $this->context);
1599 $o .= $this->output->render(new assign_header($this->get_instance(),
1600 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1602 $rownum = required_param('rownum', PARAM_INT) + $offset;
1603 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1605 $useridlist = explode(',', $useridlist);
1607 $useridlist = $this->get_grading_userid_list();
1610 $userid = $useridlist[$rownum];
1611 if ($rownum == count($useridlist) - 1) {
1614 // the placement of this is important so can pass the list of userids above
1619 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1621 $user = $DB->get_record('user', array('id' => $userid));
1623 $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1625 $submission = $this->get_user_submission($userid, false);
1626 // get the current grade
1627 $grade = $this->get_user_grade($userid, false);
1628 if ($this->can_view_submission($userid)) {
1629 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1630 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1631 $this->get_instance()->alwaysshowdescription,
1633 $this->is_any_submission_plugin_enabled(),
1635 $this->is_graded($userid),
1636 $this->get_instance()->duedate,
1637 $this->get_submission_plugins(),
1638 $this->get_return_action(),
1639 $this->get_return_params(),
1640 $this->get_course_module()->id,
1641 assign_submission_status::GRADER_VIEW,
1646 $data = new stdClass();
1647 if ($grade->grade >= 0) {
1648 $data->grade = format_float($grade->grade,2);
1651 $data = new stdClass();
1655 // now show the grading form
1657 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1659 $o .= $this->output->render(new assign_form('gradingform',$mform));
1661 $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1663 $o .= $this->view_footer();
1670 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1674 private function view_return_links() {
1676 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1677 $returnparams = optional_param('returnparams','', PARAM_TEXT);
1680 parse_str($returnparams, $params);
1681 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1683 return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1688 * View the grading table of all submissions for this assignment
1692 private function view_grading_table() {
1694 // Include grading options form
1695 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
1696 require_once($CFG->dirroot . '/mod/assign/gradingactionsform.php');
1697 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
1698 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1702 $selecturl = (string)(new moodle_url('/mod/assign/view.php',
1703 array('action'=>'grading', 'id'=>$this->get_course_module()->id)));
1704 $links[$selecturl] = get_string('selectlink', 'assign');
1705 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1706 has_capability('moodle/grade:viewall', $this->get_course_context())) {
1707 $gradebookurl = (string) (new moodle_url('/grade/report/grader/index.php',
1708 array('id' => $this->get_course()->id)));
1709 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1711 if ($this->is_any_submission_plugin_enabled()) {
1712 $downloadurl = (string) (new moodle_url('/mod/assign/view.php',
1713 array('id' => $this->get_course_module()->id,
1714 'action' => 'downloadall')));
1715 $links[$downloadurl] = get_string('downloadall', 'assign');
1717 $gradingactionsform = new mod_assign_grading_actions_form(null,
1718 array('links'=>$links,
1719 'cm'=>$this->get_course_module()->id),
1721 array('class'=>'gradingactionsform'));
1723 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1725 $perpage = get_user_preferences('assign_perpage', 10);
1726 $filter = get_user_preferences('assign_filter', '');
1727 $controller = $gradingmanager->get_active_controller();
1728 $showquickgrading = empty($controller);
1729 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1730 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1731 set_user_preference('assign_quickgrading', $quickgrading);
1733 $quickgrading = get_user_preferences('assign_quickgrading', false);
1735 // print options for changing the filter and changing the number of results per page
1736 $gradingoptionsform = new mod_assign_grading_options_form(null,
1737 array('cm'=>$this->get_course_module()->id,
1738 'contextid'=>$this->context->id,
1739 'userid'=>$USER->id,
1740 'showquickgrading'=>$showquickgrading,
1741 'quickgrading'=>$quickgrading),
1743 array('class'=>'gradingoptionsform'));
1745 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1746 array('cm'=>$this->get_course_module()->id,
1747 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1749 array('class'=>'gradingbatchoperationsform'));
1751 $gradingoptionsdata = new stdClass();
1752 $gradingoptionsdata->perpage = $perpage;
1753 $gradingoptionsdata->filter = $filter;
1754 $gradingoptionsform->set_data($gradingoptionsdata);
1756 // plagiarism update status apearring in the grading book
1757 if (!empty($CFG->enableplagiarism)) {
1758 /** Include plagiarismlib.php */
1759 require_once($CFG->libdir . '/plagiarismlib.php');
1760 plagiarism_update_status($this->get_course(), $this->get_course_module());
1763 $o .= $this->output->render(new assign_form('gradingactionsform', $gradingactionsform));
1764 $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
1766 // load and print the table of submissions
1767 if ($showquickgrading && $quickgrading) {
1768 $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1769 $quickgradingform = new mod_assign_quick_grading_form(null,
1770 array('cm'=>$this->get_course_module()->id,
1771 'gradingtable'=>$table));
1772 $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1774 $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1777 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1778 $users = array_keys($this->list_participants($currentgroup, true));
1779 if (count($users) != 0) {
1780 // if no enrolled user in a course then don't display the batch operations feature
1781 $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1787 * View entire grading page.
1791 private function view_grading_page() {
1795 // Need submit permission to submit an assignment
1796 require_capability('mod/assign:grade', $this->context);
1797 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1799 // only load this if it is
1801 $o .= $this->output->render(new assign_header($this->get_instance(),
1802 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign')));
1803 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1806 $o .= $this->view_grading_table();
1808 $o .= $this->view_footer();
1809 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1814 * Capture the output of the plagiarism plugins disclosures and return it as a string
1818 private function plagiarism_print_disclosure() {
1822 if (!empty($CFG->enableplagiarism)) {
1823 /** Include plagiarismlib.php */
1824 require_once($CFG->libdir . '/plagiarismlib.php');
1827 plagiarism_print_disclosure($this->get_course_module()->id);
1828 $o = ob_get_contents();
1836 * message for students when assignment submissions have been closed
1840 private function view_student_error_message() {
1844 // Need submit permission to submit an assignment
1845 require_capability('mod/assign:submit', $this->context);
1847 $o .= $this->output->render(new assign_header($this->get_instance(),
1848 $this->get_context(),
1849 $this->show_intro(),
1850 $this->get_course_module()->id,
1851 get_string('editsubmission', 'assign')));
1853 $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
1855 $o .= $this->view_footer();
1862 * View edit submissions page.
1864 * @param moodleform $mform
1867 private function view_edit_submission_page($mform) {
1871 // Include submission form
1872 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1873 // Need submit permission to submit an assignment
1874 require_capability('mod/assign:submit', $this->context);
1876 if (!$this->submissions_open()) {
1877 return $this->view_student_error_message();
1879 $o .= $this->output->render(new assign_header($this->get_instance(),
1880 $this->get_context(),
1881 $this->show_intro(),
1882 $this->get_course_module()->id,
1883 get_string('editsubmission', 'assign')));
1884 $o .= $this->plagiarism_print_disclosure();
1885 $data = new stdClass();
1888 $mform = new mod_assign_submission_form(null, array($this, $data));
1891 $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1893 $o .= $this->view_footer();
1894 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1900 * See if this assignment has a grade yet
1902 * @param int $userid
1905 private function is_graded($userid) {
1906 $grade = $this->get_user_grade($userid, false);
1908 return ($grade->grade != '');
1915 * Perform an access check to see if the current $USER can view this users submission
1917 * @param int $userid
1920 public function can_view_submission($userid) {
1923 if (!is_enrolled($this->get_course_context(), $userid)) {
1926 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
1929 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
1936 * Ask the user to confirm they want to perform this batch operation
1939 private function process_batch_grading_operation() {
1941 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1944 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1945 array('cm'=>$this->get_course_module()->id,
1946 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1948 array('class'=>'gradingbatchoperationsform'));
1950 if ($data = $gradingbatchoperationsform->get_data()) {
1951 // get the list of users
1952 $users = $data->selectedusers;
1953 $userlist = explode(',', $users);
1955 foreach ($userlist as $userid) {
1956 if ($data->operation == 'lock') {
1957 $this->process_lock($userid);
1958 } else if ($data->operation == 'unlock') {
1959 $this->process_unlock($userid);
1960 } else if ($data->operation == 'reverttodraft') {
1961 $this->process_revert_to_draft($userid);
1970 * Ask the user to confirm they want to submit their work for grading
1973 private function check_submit_for_grading() {
1975 // Check that all of the submission plugins are ready for this submission
1976 $notifications = array();
1977 $submission = $this->get_user_submission($USER->id, false);
1978 $plugins = $this->get_submission_plugins();
1979 foreach ($plugins as $plugin) {
1980 if ($plugin->is_enabled() && $plugin->is_visible()) {
1981 $check = $plugin->precheck_submission($submission);
1982 if ($check !== true) {
1983 $notifications[] = $check;
1989 $o .= $this->output->header();
1990 $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
1991 $o .= $this->view_footer();
1996 * Print 2 tables of information with no action links -
1997 * the submission summary and the grading summary
1999 * @param stdClass $user the user to print the report for
2000 * @param bool $showlinks - Return plain text or links to the profile
2001 * @return string - the html summary
2003 public function view_student_summary($user, $showlinks) {
2004 global $CFG, $DB, $PAGE;
2006 $grade = $this->get_user_grade($user->id, false);
2007 $submission = $this->get_user_submission($user->id, false);
2010 if ($this->can_view_submission($user->id)) {
2011 $showedit = has_capability('mod/assign:submit', $this->context) &&
2012 $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
2013 $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
2014 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
2016 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
2017 $this->get_instance()->alwaysshowdescription,
2019 $this->is_any_submission_plugin_enabled(),
2021 $this->is_graded($user->id),
2022 $this->get_instance()->duedate,
2023 $this->get_submission_plugins(),
2024 $this->get_return_action(),
2025 $this->get_return_params(),
2026 $this->get_course_module()->id,
2027 assign_submission_status::STUDENT_VIEW,
2030 require_once($CFG->libdir.'/gradelib.php');
2031 require_once($CFG->dirroot.'/grade/grading/lib.php');
2033 $gradinginfo = grade_get_grades($this->get_course()->id,
2036 $this->get_instance()->id,
2039 $gradingitem = $gradinginfo->items[0];
2040 $gradebookgrade = $gradingitem->grades[$user->id];
2042 // check to see if all feedback plugins are empty
2043 $emptyplugins = true;
2045 foreach ($this->get_feedback_plugins() as $plugin) {
2046 if ($plugin->is_visible() && $plugin->is_enabled()) {
2047 if (!$plugin->is_empty($grade)) {
2048 $emptyplugins = false;
2055 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2057 $gradefordisplay = '';
2058 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2060 if ($controller = $gradingmanager->get_active_controller()) {
2061 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2062 $gradefordisplay = $controller->render_grade($PAGE,
2065 $gradebookgrade->str_long_grade,
2066 has_capability('mod/assign:grade', $this->get_context()));
2068 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2071 $gradeddate = $gradebookgrade->dategraded;
2072 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2074 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2077 $this->get_feedback_plugins(),
2079 $this->get_course_module()->id,
2080 $this->get_return_action(),
2081 $this->get_return_params());
2083 $o .= $this->output->render($feedbackstatus);
2091 * View submissions page (contains details of current submission).
2095 private function view_submission_page() {
2096 global $CFG, $DB, $USER, $PAGE;
2099 $o .= $this->output->render(new assign_header($this->get_instance(),
2100 $this->get_context(),
2101 $this->show_intro(),
2102 $this->get_course_module()->id));
2104 if ($this->can_grade()) {
2105 $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2106 $this->get_instance()->submissiondrafts,
2107 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2108 $this->is_any_submission_plugin_enabled(),
2109 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2110 $this->get_instance()->duedate,
2111 $this->get_course_module()->id
2114 $grade = $this->get_user_grade($USER->id, false);
2115 $submission = $this->get_user_submission($USER->id, false);
2117 if ($this->can_view_submission($USER->id)) {
2118 $o .= $this->view_student_summary($USER, true);
2122 $o .= $this->view_footer();
2123 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2128 * convert the final raw grade(s) in the grading table for the gradebook
2130 * @param stdClass $grade
2133 private function convert_grade_for_gradebook(stdClass $grade) {
2134 $gradebookgrade = array();
2135 // trying to match those array keys in grade update function in gradelib.php
2136 // with keys in th database table assign_grades
2137 // starting around line 262
2138 $gradebookgrade['rawgrade'] = $grade->grade;
2139 $gradebookgrade['userid'] = $grade->userid;
2140 $gradebookgrade['usermodified'] = $grade->grader;
2141 $gradebookgrade['datesubmitted'] = NULL;
2142 $gradebookgrade['dategraded'] = $grade->timemodified;
2143 if (isset($grade->feedbackformat)) {
2144 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2146 if (isset($grade->feedbacktext)) {
2147 $gradebookgrade['feedback'] = $grade->feedbacktext;
2150 return $gradebookgrade;
2154 * convert submission details for the gradebook
2156 * @param stdClass $submission
2159 private function convert_submission_for_gradebook(stdClass $submission) {
2160 $gradebookgrade = array();
2163 $gradebookgrade['userid'] = $submission->userid;
2164 $gradebookgrade['usermodified'] = $submission->userid;
2165 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2167 return $gradebookgrade;
2171 * update grades in the gradebook
2173 * @param mixed $submission stdClass|null
2174 * @param mixed $grade stdClass|null
2177 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2179 if($submission != NULL){
2181 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2187 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2189 $assign = clone $this->get_instance();
2190 $assign->cmidnumber = $this->get_course_module()->id;
2192 return assign_grade_item_update($assign, $gradebookgrade);
2196 * update grades in the gradebook based on submission time
2198 * @param stdClass $submission
2199 * @param bool $updatetime
2202 private function update_submission(stdClass $submission, $updatetime=true) {
2206 $submission->timemodified = time();
2208 $result= $DB->update_record('assign_submission', $submission);
2210 $this->gradebook_item_update($submission);
2216 * Is this assignment open for submissions?
2218 * Check the due date,
2219 * prevent late submissions,
2220 * has this person already submitted,
2221 * is the assignment locked?
2225 private function submissions_open() {
2230 if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2231 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2233 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2240 // now check if this user has already submitted etc.
2241 if (!is_enrolled($this->get_course_context(), $USER)) {
2244 if ($submission = $this->get_user_submission($USER->id, false)) {
2245 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2246 // drafts are tracked and the student has submitted the assignment
2250 if ($grade = $this->get_user_grade($USER->id, false)) {
2251 if ($grade->locked) {
2256 if ($this->grading_disabled($USER->id)) {
2264 * render the files in file area
2265 * @param string $component
2266 * @param string $area
2267 * @param int $submissionid
2270 public function render_area_files($component, $area, $submissionid) {
2273 if (!$submissionid) {
2274 $submission = $this->get_user_submission($USER->id,false);
2275 $submissionid = $submission->id;
2280 $fs = get_file_storage();
2281 $browser = get_file_browser();
2282 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2283 return $this->output->assign_files($this->context, $submissionid, $area, $component);
2288 * Returns a list of teachers that should be grading given submission
2290 * @param int $userid
2293 private function get_graders($userid) {
2295 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
2298 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
2299 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
2300 foreach ($groups as $group) {
2301 foreach ($potentialgraders as $grader) {
2302 if ($grader->id == $userid) {
2303 continue; // do not send self
2305 if (groups_is_member($group->id, $grader->id)) {
2306 $graders[$grader->id] = $grader;
2311 // user not in group, try to find graders without group
2312 foreach ($potentialgraders as $grader) {
2313 if ($grader->id == $userid) {
2314 continue; // do not send self
2316 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2317 $graders[$grader->id] = $grader;
2322 foreach ($potentialgraders as $grader) {
2323 if ($grader->id == $userid) {
2324 continue; // do not send self
2327 if (is_enrolled($this->get_course_context(), $grader->id)) {
2328 $graders[$grader->id] = $grader;
2336 * Format a notification for plain text
2338 * @param string $messagetype
2339 * @param stdClass $info
2340 * @param stdClass $course
2341 * @param stdClass $context
2342 * @param string $modulename
2343 * @param string $assignmentname
2345 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2346 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2348 format_string($assignmentname, true, array('context' => $context))."\n";
2349 $posttext .= '---------------------------------------------------------------------'."\n";
2350 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
2351 $posttext .= "\n---------------------------------------------------------------------\n";
2356 * Format a notification for HTML
2358 * @param string $messagetype
2359 * @param stdClass $info
2360 * @param stdClass $course
2361 * @param stdClass $context
2362 * @param string $modulename
2363 * @param stdClass $coursemodule
2364 * @param string $assignmentname
2365 * @param stdClass $info
2367 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
2369 $posthtml = '<p><font face="sans-serif">'.
2370 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
2371 '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2372 '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
2373 $posthtml .= '<hr /><font face="sans-serif">';
2374 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
2375 $posthtml .= '</font><hr />';
2380 * Message someone about something (static so it can be called from cron)
2382 * @param stdClass $userfrom
2383 * @param stdClass $userto
2384 * @param string $messagetype
2385 * @param string $eventtype
2386 * @param int $updatetime
2387 * @param stdClass $coursemodule
2388 * @param stdClass $context
2389 * @param stdClass $course
2390 * @param string $modulename
2391 * @param string $assignmentname
2394 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2395 $updatetime, $coursemodule, $context, $course,
2396 $modulename, $assignmentname) {
2399 $info = new stdClass();
2400 $info->username = fullname($userfrom, true);
2401 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2402 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2403 $info->timeupdated = strftime('%c',$updatetime);
2405 $postsubject = get_string($messagetype . 'small', 'assign', $info);
2406 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2407 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2409 $eventdata = new stdClass();
2410 $eventdata->modulename = 'assign';
2411 $eventdata->userfrom = $userfrom;
2412 $eventdata->userto = $userto;
2413 $eventdata->subject = $postsubject;
2414 $eventdata->fullmessage = $posttext;
2415 $eventdata->fullmessageformat = FORMAT_PLAIN;
2416 $eventdata->fullmessagehtml = $posthtml;
2417 $eventdata->smallmessage = $postsubject;
2419 $eventdata->name = $eventtype;
2420 $eventdata->component = 'mod_assign';
2421 $eventdata->notification = 1;
2422 $eventdata->contexturl = $info->url;
2423 $eventdata->contexturlname = $info->assignment;
2425 message_send($eventdata);
2429 * Message someone about something
2431 * @param stdClass $userfrom
2432 * @param stdClass $userto
2433 * @param string $messagetype
2434 * @param string $eventtype
2435 * @param int $updatetime
2438 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2439 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);
2443 * Notify student upon successful submission
2445 * @global moodle_database $DB
2446 * @param stdClass $submission
2449 private function notify_student_submission_receipt(stdClass $submission) {
2452 $adminconfig = $this->get_admin_config();
2453 if (!$adminconfig->submissionreceipts) {
2454 // No need to do anything
2457 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2458 $this->send_notification($user, $user, 'submissionreceipt', 'assign_student_notification', $submission->timemodified);
2462 * Send notifications to graders upon student submissions
2464 * @global moodle_database $DB
2465 * @param stdClass $submission
2468 private function notify_graders(stdClass $submission) {
2471 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
2473 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
2477 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2478 if ($teachers = $this->get_graders($user->id)) {
2479 foreach ($teachers as $teacher) {
2480 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_grader_notification', $submission->timemodified);
2486 * assignment submission is processed before grading
2490 private function process_submit_for_grading() {
2493 // Need submit permission to submit an assignment
2494 require_capability('mod/assign:submit', $this->context);
2497 $submission = $this->get_user_submission($USER->id,true);
2498 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2499 // Give each submission plugin a chance to process the submission
2500 $plugins = $this->get_submission_plugins();
2501 foreach ($plugins as $plugin) {
2502 $plugin->submit_for_grading();
2505 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2506 $this->update_submission($submission);
2507 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
2508 $this->notify_graders($submission);
2509 $this->notify_student_submission_receipt($submission);
2516 * @global moodle_database $DB
2517 * @return string The result of the save operation
2519 private function process_save_quick_grades() {
2520 global $USER, $DB, $CFG;
2522 // Need grade permission
2523 require_capability('mod/assign:grade', $this->context);
2525 // make sure advanced grading is disabled
2526 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2527 $controller = $gradingmanager->get_active_controller();
2528 if (!empty($controller)) {
2529 return get_string('errorquickgradingvsadvancedgrading', 'assign');
2533 // first check all the last modified values
2534 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2535 $participants = $this->list_participants($currentgroup, true);
2537 // gets a list of possible users and look for values based upon that.
2538 foreach ($participants as $userid => $unused) {
2539 $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
2540 if ($modified >= 0) {
2541 // gather the userid, updated grade and last modified value
2542 $record = new stdClass();
2543 $record->userid = $userid;
2544 $record->grade = required_param('quickgrade_' . $userid, PARAM_INT);
2545 $record->lastmodified = $modified;
2546 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2547 $users[$userid] = $record;
2550 if (empty($users)) {
2551 // Quick check to see whether we have any users to update and we don't
2552 return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2555 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2556 $params['assignment'] = $this->get_instance()->id;
2557 // check them all for currency
2558 $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2560 LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2561 WHERE u.id ' . $userids;
2562 $currentgrades = $DB->get_recordset_sql($sql, $params);
2564 $modifiedusers = array();
2565 foreach ($currentgrades as $current) {
2566 $modified = $users[(int)$current->userid];
2567 $grade = $this->get_user_grade($userid, false);
2569 // check to see if the outcomes were modified
2570 if ($CFG->enableoutcomes) {
2571 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2572 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2573 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2574 if ($oldoutcome != $newoutcome) {
2575 // can't check modified time for outcomes because it is not reported
2576 $modifiedusers[$modified->userid] = $modified;
2582 // let plugins participate
2583 foreach ($this->feedbackplugins as $plugin) {
2584 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2585 if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
2586 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2587 return get_string('errorrecordmodified', 'assign');
2589 $modifiedusers[$modified->userid] = $modified;
2597 if (($current->grade < 0 || $current->grade === NULL) &&
2598 ($modified->grade < 0 || $modified->grade === NULL)) {
2599 // different ways to indicate no grade
2602 if ($current->grade != $modified->grade) {
2604 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2605 // error - record has been modified since viewing the page
2606 return get_string('errorrecordmodified', 'assign');
2608 $modifiedusers[$modified->userid] = $modified;
2613 $currentgrades->close();
2615 // ok - ready to process the updates
2616 foreach ($modifiedusers as $userid => $modified) {
2617 $grade = $this->get_user_grade($userid, true);
2618 $grade->grade= grade_floatval($modified->grade);
2619 $grade->grader= $USER->id;
2621 $this->update_grade($grade);
2623 // save plugins data
2624 foreach ($this->feedbackplugins as $plugin) {
2625 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
2626 $plugin->save_quickgrading_changes($userid, $grade);
2631 if ($CFG->enableoutcomes) {
2633 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2634 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2635 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2636 if ($oldoutcome != $newoutcome) {
2637 $data[$outcomeid] = $newoutcome;
2640 if (count($data) > 0) {
2641 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2645 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2648 return get_string('quickgradingchangessaved', 'assign');
2652 * save grading options
2656 private function process_save_grading_options() {
2659 // Include grading options form
2660 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2662 // Need submit permission to submit an assignment
2663 require_capability('mod/assign:grade', $this->context);
2665 $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id, 'contextid'=>$this->context->id, 'userid'=>$USER->id, 'showquickgrading'=>false));
2666 if ($formdata = $mform->get_data()) {
2667 set_user_preference('assign_perpage', $formdata->perpage);
2668 set_user_preference('assign_filter', $formdata->filter);
2673 * Take a grade object and print a short summary for the log file.
2674 * The size limit for the log file is 255 characters, so be careful not
2675 * to include too much information.
2677 * @param stdClass $grade
2680 private function format_grade_for_log(stdClass $grade) {
2683 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2685 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2686 if ($grade->grade != '') {
2687 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
2689 $info .= get_string('nograde', 'assign');
2691 if ($grade->locked) {
2692 $info .= get_string('submissionslocked', 'assign') . '. ';
2698 * Take a submission object and print a short summary for the log file.
2699 * The size limit for the log file is 255 characters, so be careful not
2700 * to include too much information.
2702 * @param stdClass $submission
2705 private function format_submission_for_log(stdClass $submission) {
2707 $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2708 // format_for_log here iterating every single log INFO from either submission or grade in every assignment plugin
2710 foreach ($this->submissionplugins as $plugin) {
2711 if ($plugin->is_enabled() && $plugin->is_visible()) {
2714 $info .= "<br>" . $plugin->format_for_log($submission);
2723 * save assignment submission
2725 * @param moodleform $mform
2728 private function process_save_submission(&$mform) {
2731 // Include submission form
2732 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2734 // Need submit permission to submit an assignment
2735 require_capability('mod/assign:submit', $this->context);
2738 $data = new stdClass();
2739 $mform = new mod_assign_submission_form(null, array($this, $data));
2740 if ($mform->is_cancelled()) {
2743 if ($data = $mform->get_data()) {
2744 $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2745 $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2746 if ($grade && $grade->locked) {
2747 print_error('submissionslocked', 'assign');
2752 foreach ($this->submissionplugins as $plugin) {
2753 if ($plugin->is_enabled()) {
2754 if (!$plugin->save($submission, $data)) {
2755 print_error($plugin->get_error());
2760 $this->update_submission($submission);
2763 $this->add_to_log('submit', $this->format_submission_for_log($submission));
2765 if (!$this->get_instance()->submissiondrafts) {
2766 $this->notify_student_submission_receipt($submission);
2767 $this->notify_graders($submission);
2776 * Determine if this users grade is locked or overridden
2778 * @param int $userid - The student userid
2779 * @return bool $gradingdisabled
2781 private function grading_disabled($userid) {
2784 $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2785 if (!$gradinginfo) {
2789 if (!isset($gradinginfo->items[0]->grades[$userid])) {
2792 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2793 return $gradingdisabled;
2798 * Get an instance of a grading form if advanced grading is enabled
2799 * This is specific to the assignment, marker and student
2801 * @param int $userid - The student userid
2802 * @param bool $gradingdisabled
2803 * @return mixed gradingform_instance|null $gradinginstance
2805 private function get_grading_instance($userid, $gradingdisabled) {
2808 $grade = $this->get_user_grade($userid, false);
2809 $grademenu = make_grades_menu($this->get_instance()->grade);
2811 $advancedgradingwarning = false;
2812 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2813 $gradinginstance = null;
2814 if ($gradingmethod = $gradingmanager->get_active_method()) {
2815 $controller = $gradingmanager->get_controller($gradingmethod);
2816 if ($controller->is_form_available()) {
2819 $itemid = $grade->id;
2821 if ($gradingdisabled && $itemid) {
2822 $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2823 } else if (!$gradingdisabled) {
2824 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2825 $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2828 $advancedgradingwarning = $controller->form_unavailable_notification();
2831 if ($gradinginstance) {
2832 $gradinginstance->get_controller()->set_grade_range($grademenu);
2834 return $gradinginstance;
2838 * add elements to grade form
2840 * @param MoodleQuickForm $mform
2841 * @param stdClass $data
2842 * @param array $params
2845 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2847 $settings = $this->get_instance();
2849 $rownum = $params['rownum'];
2850 $last = $params['last'];
2851 $useridlist = $params['useridlist'];
2852 $userid = $useridlist[$rownum];
2853 $grade = $this->get_user_grade($userid, false);
2855 // add advanced grading
2856 $gradingdisabled = $this->grading_disabled($userid);
2857 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2859 if ($gradinginstance) {
2860 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2861 if ($gradingdisabled) {
2862 $gradingelement->freeze();
2864 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2867 // use simple direct grading
2868 if ($this->get_instance()->grade > 0) {
2869 $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
2870 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2871 $mform->setType('grade', PARAM_TEXT);
2873 $grademenu = make_grades_menu($this->get_instance()->grade);
2874 if (count($grademenu) > 0) {
2875 $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
2876 $mform->setType('grade', PARAM_INT);
2881 $gradinginfo = grade_get_grades($this->get_course()->id,
2884 $this->get_instance()->id,
2886 if (!empty($CFG->enableoutcomes)) {
2887 foreach($gradinginfo->outcomes as $index=>$outcome) {
2888 $options = make_grades_menu(-$outcome->scaleid);
2889 if ($outcome->grades[$userid]->locked) {
2890 $options[0] = get_string('nooutcome', 'grades');
2891 $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
2892 $options[$outcome->grades[$userid]->grade]);
2894 $options[''] = get_string('nooutcome', 'grades');
2895 $attributes = array('id' => 'menuoutcome_'.$index );
2896 $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
2897 $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
2898 $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
2903 $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
2906 $this->add_plugin_grade_elements($grade, $mform, $data);
2909 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
2910 $mform->setType('id', PARAM_INT);
2911 $mform->addElement('hidden', 'rownum', $rownum);
2912 $mform->setType('rownum', PARAM_INT);
2913 $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
2914 $mform->setType('useridlist', PARAM_TEXT);
2915 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
2916 $mform->setType('ajax', PARAM_INT);
2918 $mform->addElement('hidden', 'action', 'submitgrade');
2919 $mform->setType('action', PARAM_ALPHA);
2922 $buttonarray=array();
2923 $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
2925 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
2927 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
2928 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
2929 $mform->closeHeaderBefore('buttonar');
2930 $buttonarray=array();
2933 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
2937 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
2939 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
2944 * add elements in submission plugin form
2946 * @param mixed $submission stdClass|null
2947 * @param MoodleQuickForm $mform
2948 * @param stdClass $data
2951 private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data) {
2952 foreach ($this->submissionplugins as $plugin) {
2953 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2954 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
2955 if (!$plugin->get_form_elements($submission, $mform, $data)) {
2956 $mform->removeElement('header_' . $plugin->get_type());
2963 * check if feedback plugins installed are enabled
2967 public function is_any_feedback_plugin_enabled() {
2968 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
2969 $this->cache['any_feedback_plugin_enabled'] = false;
2970 foreach ($this->feedbackplugins as $plugin) {
2971 if ($plugin->is_enabled() && $plugin->is_visible()) {
2972 $this->cache['any_feedback_plugin_enabled'] = true;
2978 return $this->cache['any_feedback_plugin_enabled'];
2983 * check if submission plugins installed are enabled
2987 public function is_any_submission_plugin_enabled() {
2988 if (!isset($this->cache['any_submission_plugin_enabled'])) {
2989 $this->cache['any_submission_plugin_enabled'] = false;
2990 foreach ($this->submissionplugins as $plugin) {
2991 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2992 $this->cache['any_submission_plugin_enabled'] = true;
2998 return $this->cache['any_submission_plugin_enabled'];
3003 * add elements to submission form
3004 * @param MoodleQuickForm $mform
3005 * @param stdClass $data
3008 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
3011 // online text submissions
3013 $submission = $this->get_user_submission($USER->id, false);
3015 $this->add_plugin_submission_elements($submission, $mform, $data);
3018 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
3019 $mform->setType('id', PARAM_INT);
3021 $mform->addElement('hidden', 'action', 'savesubmission');
3022 $mform->setType('action', PARAM_TEXT);
3029 * Uses url parameter userid
3031 * @param int $userid
3034 private function process_revert_to_draft($userid = 0) {
3037 // Need grade permission
3038 require_capability('mod/assign:grade', $this->context);
3042 $userid = required_param('userid', PARAM_INT);
3045 $submission = $this->get_user_submission($userid, false);
3049 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
3050 $this->update_submission($submission, false);
3052 // update the modified time on the grade (grader modified)
3053 $grade = $this->get_user_grade($userid, true);
3054 $this->update_grade($grade);
3056 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3058 $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3064 * Uses url parameter userid
3065 * @param int $userid
3068 private function process_lock($userid = 0) {
3071 // Need grade permission
3072 require_capability('mod/assign:grade', $this->context);
3076 $userid = required_param('userid', PARAM_INT);
3079 $grade = $this->get_user_grade($userid, true);
3081 $grade->grader = $USER->id;
3082 $this->update_grade($grade);
3084 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3086 $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3090 * unlock the process
3092 * @param int $userid
3095 private function process_unlock($userid = 0) {
3098 // Need grade permission
3099 require_capability('mod/assign:grade', $this->context);
3103 $userid = required_param('userid', PARAM_INT);
3106 $grade = $this->get_user_grade($userid, true);
3108 $grade->grader = $USER->id;
3109 $this->update_grade($grade);
3111 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3113 $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3117 * save outcomes submitted from grading form
3119 * @param int $userid
3120 * @param stdClass $formdata
3122 private function process_outcomes($userid, $formdata) {
3125 if (empty($CFG->enableoutcomes)) {
3129 require_once($CFG->libdir.'/gradelib.php');
3132 $gradinginfo = grade_get_grades($this->get_course()->id,
3135 $this->get_instance()->id,
3138 if (!empty($gradinginfo->outcomes)) {
3139 foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3140 $name = 'outcome_'.$index;
3141 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3142 $data[$index] = $formdata->{$name}[$userid];
3146 if (count($data) > 0) {
3147 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3156 * @param moodleform $mform
3157 * @return bool - was the grade saved
3159 private function process_save_grade(&$mform) {
3160 global $USER, $DB, $CFG;
3161 // Include grade form
3162 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3164 // Need submit permission to submit an assignment
3165 require_capability('mod/assign:grade', $this->context);
3168 $rownum = required_param('rownum', PARAM_INT);
3169 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3171 $useridlist = explode(',', $useridlist);
3173 $useridlist = $this->get_grading_userid_list();
3176 $userid = $useridlist[$rownum];
3177 if ($rownum == count($useridlist) - 1) {
3181 $data = new stdClass();
3182 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3184 if ($formdata = $mform->get_data()) {
3185 $grade = $this->get_user_grade($userid, true);
3186 $gradingdisabled = $this->grading_disabled($userid);
3187 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
3188 if ($gradinginstance) {
3189 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3191 // handle the case when grade is set to No Grade
3192 if (isset($formdata->grade)) {
3193 $grade->grade= grade_floatval($formdata->grade);
3196 $grade->grader= $USER->id;
3198 $adminconfig = $this->get_admin_config();
3199 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
3201 // call save in plugins
3202 foreach ($this->feedbackplugins as $plugin) {
3203 if ($plugin->is_enabled() && $plugin->is_visible()) {
3204 if (!$plugin->save($grade, $formdata)) {
3206 print_error($plugin->get_error());
3208 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3209 // this is the feedback plugin chose to push comments to the gradebook
3210 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
3211 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
3215 $this->process_outcomes($userid, $formdata);
3219 $this->update_grade($grade);
3221 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3223 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
3233 * This function is a static wrapper around can_upgrade
3235 * @param string $type The plugin type
3236 * @param int $version The plugin version
3239 public static function can_upgrade_assignment($type, $version) {
3240 $assignment = new assign(null, null, null);
3241 return $assignment->can_upgrade($type, $version);
3245 * This function returns true if it can upgrade an assignment from the 2.2
3247 * @param string $type The plugin type
3248 * @param int $version The plugin version
3251 public function can_upgrade($type, $version) {
3252 if ($type == 'offline' && $version >= 2011112900) {
3255 foreach ($this->submissionplugins as $plugin) {
3256 if ($plugin->can_upgrade($type, $version)) {
3260 foreach ($this->feedbackplugins as $plugin) {
3261 if ($plugin->can_upgrade($type, $version)) {
3269 * Copy all the files from the old assignment files area to the new one.
3270 * This is used by the plugin upgrade code.
3272 * @param int $oldcontextid The old assignment context id
3273 * @param int $oldcomponent The old assignment component ('assignment')
3274 * @param int $oldfilearea The old assignment filearea ('submissions')
3275 * @param int $olditemid The old submissionid (can be null e.g. intro)
3276 * @param int $newcontextid The new assignment context id
3277 * @param int $newcomponent The new assignment component ('assignment')
3278 * @param int $newfilearea The new assignment filearea ('submissions')
3279 * @param int $newitemid The new submissionid (can be null e.g. intro)
3280 * @return int The number of files copied
3282 public function copy_area_files_for_upgrade($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, $newcontextid, $newcomponent, $newfilearea, $newitemid) {
3283 // Note, this code is based on some code in filestorage - but that code
3284 // deleted the old files (which we don't want)
3287 $fs = get_file_storage();
3289 $oldfiles = $fs->get_area_files($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, 'id', false);
3290 foreach ($oldfiles as $oldfile) {
3291 $filerecord = new stdClass();
3292 $filerecord->contextid = $newcontextid;
3293 $filerecord->component = $newcomponent;
3294 $filerecord->filearea = $newfilearea;
3295 $filerecord->itemid = $newitemid;
3296 $fs->create_file_from_storedfile($filerecord, $oldfile);
3304 * Get an upto date list of user grades and feedback for the gradebook
3306 * @param int $userid int or 0 for all users
3307 * @return array of grade data formated for the gradebook api
3308 * The data required by the gradebook api is userid,
3316 public function get_user_grades_for_gradebook($userid) {
3319 $assignmentid = $this->get_instance()->id;
3321 $adminconfig = $this->get_admin_config();
3322 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook;
3323 $gradebookplugin = null;
3325 // find the gradebook plugin
3326 foreach ($this->feedbackplugins as $plugin) {
3327 if ($plugin->is_enabled() && $plugin->is_visible()) {
3328 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
3329 $gradebookplugin = $plugin;
3334 $where = ' WHERE u.id = ? ';
3336 $where = ' WHERE u.id != ? ';
3339 $graderesults = $DB->get_recordset_sql('SELECT u.id as userid, s.timemodified as datesubmitted, g.grade as rawgrade, g.timemodified as dategraded, g.grader as usermodified
3341 LEFT JOIN {assign_submission} s ON u.id = s.userid and s.assignment = ?
3342 LEFT JOIN {assign_grades} g ON u.id = g.userid and g.assignment = ?
3343 ' . $where, array($assignmentid, $assignmentid, $userid));