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 = '';
123 /** @var string modulenameplural prevents excessive calls to get_string */
124 private static $modulenameplural = '';
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 * Cron function to be run periodically according to the moodle cron
1075 * Finds all assignment notifications that have yet to be mailed out, and mails them
1079 static function cron() {
1082 // used to cache DB lookups
1083 $croncache = array();
1085 // only ever send a max of one days worth of updates
1086 $yesterday = time() - (24 * 3600);
1089 // email students about new feedback
1090 $submissions = $DB->get_records_sql("SELECT s.*, a.course, a.name, g.*, g.id as gradeid, g.timemodified as lastmodified
1092 JOIN {assign_grades} g ON g.assignment = a.id
1093 LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
1094 WHERE g.timemodified >= :yesterday
1095 AND g.timemodified <= :today
1096 AND g.mailed = 0", array('yesterday'=>$yesterday, 'today'=>$timenow));
1098 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1100 foreach ($submissions as $submission) {
1102 mtrace("Processing assignment submission $submission->id ...");
1104 // do not cache user lookups - could be too many
1105 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
1106 mtrace("Could not find user $submission->userid");
1110 // use a cache to prevent the same DB queries happening over and over
1111 if (! $course = array_search('course_' . $submission->course, $croncache)) {
1112 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
1113 mtrace("Could not find course $submission->course");
1116 $croncache['course_' . $submission->course] = $course;
1119 /// Override the language and timezone of the "current" user, so that
1120 /// mail is customised for the receiver.
1121 cron_setup_user($user, $course);
1123 // context lookups are already cached
1124 $coursecontext = context_course::instance($submission->course);
1125 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
1126 if (!is_enrolled($coursecontext, $user->id)) {
1127 mtrace(fullname($user)." not an active participant in " . $courseshortname);
1131 if (! $grader = $DB->get_record("user", array("id"=>$submission->grader))) {
1132 mtrace("Could not find grader $submission->grader");
1137 if (! $mod = array_search('mod_' . $submission->assignment, $croncache)) {
1138 if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
1139 mtrace("Could not find course module for assignment id $submission->assignment");
1142 $croncache['mod_' . $submission->assignment] = $mod;
1145 // context lookups are already cached
1146 $contextmodule = context_module::instance($mod->id);
1148 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
1152 // need to send this to the student
1153 self::send_assignment_notification($grader, $user, 'feedbackavailable', 'assign_student_notification', $submission->lastmodified, $mod, $contextmodule, $course, get_string('modulename', 'assign'), $submission->name);
1155 $grade = new stdClass();
1156 $grade->id = $submission->gradeid;
1158 $DB->update_record('assign_grades', $grade);
1162 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1172 * Update a grade in the grade table for the assignment and in the gradebook
1174 * @param stdClass $grade a grade record keyed on id
1175 * @return bool true for success
1177 private function update_grade($grade) {
1180 $grade->timemodified = time();
1182 if ($grade->grade && $grade->grade != -1) {
1183 if ($this->get_instance()->grade > 0) {
1184 if (!is_numeric($grade->grade)) {
1186 } else if ($grade->grade > $this->get_instance()->grade) {
1188 } else if ($grade->grade < 0) {
1193 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1194 $scaleoptions = make_menu_from_list($scale->scale);
1195 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1202 $result = $DB->update_record('assign_grades', $grade);
1204 $this->gradebook_item_update(null, $grade);
1210 * display the submission that is used by a plugin
1211 * Uses url parameters 'sid', 'gid' and 'plugin'
1212 * @param string $pluginsubtype
1215 private function view_plugin_content($pluginsubtype) {
1220 $submissionid = optional_param('sid', 0, PARAM_INT);
1221 $gradeid = optional_param('gid', 0, PARAM_INT);
1222 $plugintype = required_param('plugin', PARAM_TEXT);
1224 if ($pluginsubtype == 'assignsubmission') {
1225 $plugin = $this->get_submission_plugin_by_type($plugintype);
1226 if ($submissionid <= 0) {
1227 throw new coding_exception('Submission id should not be 0');
1229 $item = $this->get_submission($submissionid);
1232 if ($item->userid != $USER->id) {
1233 require_capability('mod/assign:grade', $this->context);
1235 $o .= $this->output->render(new assign_header($this->get_instance(),
1236 $this->get_context(),
1237 $this->show_intro(),
1238 $this->get_course_module()->id,
1239 $plugin->get_name()));
1240 $o .= $this->output->render(new assign_submission_plugin_submission($plugin,
1242 assign_submission_plugin_submission::FULL,
1243 $this->get_course_module()->id,
1244 $this->get_return_action(),
1245 $this->get_return_params()));
1247 $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
1249 $plugin = $this->get_feedback_plugin_by_type($plugintype);
1250 if ($gradeid <= 0) {
1251 throw new coding_exception('Grade id should not be 0');
1253 $item = $this->get_grade($gradeid);
1255 if ($item->userid != $USER->id) {
1256 require_capability('mod/assign:grade', $this->context);
1258 $o .= $this->output->render(new assign_header($this->get_instance(),
1259 $this->get_context(),
1260 $this->show_intro(),
1261 $this->get_course_module()->id,
1262 $plugin->get_name()));
1263 $o .= $this->output->render(new assign_feedback_plugin_feedback($plugin,
1265 assign_feedback_plugin_feedback::FULL,
1266 $this->get_course_module()->id,
1267 $this->get_return_action(),
1268 $this->get_return_params()));
1269 $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
1273 $o .= $this->view_return_links();
1275 $o .= $this->view_footer();
1280 * render the content in editor that is often used by plugin
1282 * @param string $filearea
1283 * @param int $submissionid
1284 * @param string $plugintype
1285 * @param string $editor
1286 * @param string $component
1289 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
1294 $plugin = $this->get_submission_plugin_by_type($plugintype);
1296 $text = $plugin->get_editor_text($editor, $submissionid);
1297 $format = $plugin->get_editor_format($editor, $submissionid);
1299 $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
1300 $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));
1304 if ($CFG->enableportfolios) {
1305 require_once($CFG->libdir . '/portfoliolib.php');
1307 $button = new portfolio_add_button();
1308 $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');
1309 $fs = get_file_storage();
1311 if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
1312 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1314 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1316 $result .= $button->to_html();
1322 * Display a grading error
1324 * @param string $message - The description of the result
1327 private function view_quickgrading_result($message) {
1329 $o .= $this->output->render(new assign_header($this->get_instance(),
1330 $this->get_context(),
1331 $this->show_intro(),
1332 $this->get_course_module()->id,
1333 get_string('quickgradingresult', 'assign')));
1334 $o .= $this->output->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
1335 $o .= $this->view_footer();
1340 * Display the page footer
1344 private function view_footer() {
1345 return $this->output->render_footer();
1349 * Does this user have grade permission for this assignment
1353 private function can_grade() {
1354 // Permissions check
1355 if (!has_capability('mod/assign:grade', $this->context)) {
1363 * Download a zip file of all assignment submissions
1367 private function download_submissions() {
1370 // more efficient to load this here
1371 require_once($CFG->libdir.'/filelib.php');
1373 // load all submissions
1374 $submissions = $this->get_all_submissions('','');
1376 if (empty($submissions)) {
1377 print_error('errornosubmissions', 'assign');
1381 // build a list of files to zip
1382 $filesforzipping = array();
1383 $fs = get_file_storage();
1385 $groupmode = groups_get_activity_groupmode($this->get_course_module());
1386 $groupid = 0; // All users
1389 $groupid = groups_get_activity_group($this->get_course_module(), true);
1390 $groupname = groups_get_group_name($groupid).'-';
1393 // construct the zip file name
1394 $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.
1396 // get all the files for each submission
1397 foreach ($submissions as $submission) {
1398 $userid = $submission->userid; //get userid
1399 if ((groups_is_member($groupid,$userid) or !$groupmode or !$groupid)) {
1400 // get the plugins to add their own files to the zip
1402 $user = $DB->get_record("user", array("id"=>$userid),'id,username,firstname,lastname', MUST_EXIST);
1404 $prefix = clean_filename(fullname($user) . "_" .$userid . "_");
1406 foreach ($this->submissionplugins as $plugin) {
1407 if ($plugin->is_enabled() && $plugin->is_visible()) {
1408 $pluginfiles = $plugin->get_files($submission);
1411 foreach ($pluginfiles as $zipfilename => $file) {
1412 $filesforzipping[$prefix . $zipfilename] = $file;
1418 } // end of foreach loop
1419 if ($zipfile = $this->pack_files($filesforzipping)) {
1420 $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
1421 send_temp_file($zipfile, $filename); //send file and delete after sending.
1426 * Util function to add a message to the log
1428 * @param string $action The current action
1429 * @param string $info A detailed description of the change. But no more than 255 characters.
1430 * @param string $url The url to the assign module instance.
1433 public function add_to_log($action = '', $info = '', $url='') {
1436 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
1438 $fullurl .= '&' . $url;
1441 add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
1445 * Load the submission object for a particular user, optionally creating it if required
1447 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
1448 * @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
1449 * @return stdClass The submission
1451 private function get_user_submission($userid, $create) {
1455 $userid = $USER->id;
1457 // if the userid is not null then use userid
1458 $submission = $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1464 $submission = new stdClass();
1465 $submission->assignment = $this->get_instance()->id;
1466 $submission->userid = $userid;
1467 $submission->timecreated = time();
1468 $submission->timemodified = $submission->timecreated;
1470 if ($this->get_instance()->submissiondrafts) {
1471 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1473 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1475 $sid = $DB->insert_record('assign_submission', $submission);
1476 $submission->id = $sid;
1483 * Load the submission object from it's id
1485 * @param int $submissionid The id of the submission we want
1486 * @return stdClass The submission
1488 private function get_submission($submissionid) {
1491 return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
1495 * This will retrieve a grade object from the db, optionally creating it if required
1497 * @param int $userid The user we are grading
1498 * @param bool $create If true the grade will be created if it does not exist
1499 * @return stdClass The grade record
1501 private function get_user_grade($userid, $create) {
1505 $userid = $USER->id;
1508 // if the userid is not null then use userid
1509 $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));
1515 $grade = new stdClass();
1516 $grade->assignment = $this->get_instance()->id;
1517 $grade->userid = $userid;
1518 $grade->timecreated = time();
1519 $grade->timemodified = $grade->timecreated;
1522 $grade->grader = $USER->id;
1523 $gid = $DB->insert_record('assign_grades', $grade);
1531 * This will retrieve a grade object from the db
1533 * @param int $gradeid The id of the grade
1534 * @return stdClass The grade record
1536 private function get_grade($gradeid) {
1539 return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
1543 * Print the grading page for a single user submission
1545 * @param moodleform $mform
1546 * @param int $offset
1549 private function view_single_grade_page($mform, $offset=0) {
1554 // Include grade form
1555 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1557 // Need submit permission to submit an assignment
1558 require_capability('mod/assign:grade', $this->context);
1560 $o .= $this->output->render(new assign_header($this->get_instance(),
1561 $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));
1563 $rownum = required_param('rownum', PARAM_INT) + $offset;
1564 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
1566 $useridlist = explode(',', $useridlist);
1568 $useridlist = $this->get_grading_userid_list();
1571 $userid = $useridlist[$rownum];
1572 if ($rownum == count($useridlist) - 1) {
1575 // the placement of this is important so can pass the list of userids above
1580 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
1582 $user = $DB->get_record('user', array('id' => $userid));
1584 $o .= $this->output->render(new assign_user_summary($user, $this->get_course()->id, has_capability('moodle/site:viewfullnames', $this->get_course_context())));
1586 $submission = $this->get_user_submission($userid, false);
1587 // get the current grade
1588 $grade = $this->get_user_grade($userid, false);
1589 if ($this->can_view_submission($userid)) {
1590 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
1591 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1592 $this->get_instance()->alwaysshowdescription,
1594 $this->is_any_submission_plugin_enabled(),
1596 $this->is_graded($userid),
1597 $this->get_instance()->duedate,
1598 $this->get_submission_plugins(),
1599 $this->get_return_action(),
1600 $this->get_return_params(),
1601 $this->get_course_module()->id,
1602 assign_submission_status::GRADER_VIEW,
1607 $data = new stdClass();
1608 if ($grade->grade >= 0) {
1609 $data->grade = format_float($grade->grade,2);
1612 $data = new stdClass();
1616 // now show the grading form
1618 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last)), 'post', '', array('class'=>'gradeform'));
1620 $o .= $this->output->render(new assign_form('gradingform',$mform));
1622 $this->add_to_log('view grading form', get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
1624 $o .= $this->view_footer();
1631 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
1635 private function view_return_links() {
1637 $returnaction = optional_param('returnaction','', PARAM_ALPHA);
1638 $returnparams = optional_param('returnparams','', PARAM_TEXT);
1641 parse_str($returnparams, $params);
1642 $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);
1644 return $this->output->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');
1649 * View the grading table of all submissions for this assignment
1653 private function view_grading_table() {
1655 // Include grading options form
1656 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
1657 require_once($CFG->dirroot . '/mod/assign/gradingactionsform.php');
1658 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
1659 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1663 $selecturl = (string)(new moodle_url('/mod/assign/view.php',
1664 array('action'=>'grading', 'id'=>$this->get_course_module()->id)));
1665 $links[$selecturl] = get_string('selectlink', 'assign');
1666 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
1667 has_capability('moodle/grade:viewall', $this->get_course_context())) {
1668 $gradebookurl = (string) (new moodle_url('/grade/report/grader/index.php',
1669 array('id' => $this->get_course()->id)));
1670 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
1672 if ($this->is_any_submission_plugin_enabled()) {
1673 $downloadurl = (string) (new moodle_url('/mod/assign/view.php',
1674 array('id' => $this->get_course_module()->id,
1675 'action' => 'downloadall')));
1676 $links[$downloadurl] = get_string('downloadall', 'assign');
1678 $gradingactionsform = new mod_assign_grading_actions_form(null,
1679 array('links'=>$links,
1680 'cm'=>$this->get_course_module()->id),
1682 array('class'=>'gradingactionsform'));
1684 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
1686 $perpage = get_user_preferences('assign_perpage', 10);
1687 $filter = get_user_preferences('assign_filter', '');
1688 $controller = $gradingmanager->get_active_controller();
1689 $showquickgrading = empty($controller);
1690 if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
1691 $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
1692 set_user_preference('assign_quickgrading', $quickgrading);
1694 $quickgrading = get_user_preferences('assign_quickgrading', false);
1696 // print options for changing the filter and changing the number of results per page
1697 $gradingoptionsform = new mod_assign_grading_options_form(null,
1698 array('cm'=>$this->get_course_module()->id,
1699 'contextid'=>$this->context->id,
1700 'userid'=>$USER->id,
1701 'showquickgrading'=>$showquickgrading,
1702 'quickgrading'=>$quickgrading),
1704 array('class'=>'gradingoptionsform'));
1706 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1707 array('cm'=>$this->get_course_module()->id,
1708 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1710 array('class'=>'gradingbatchoperationsform'));
1712 $gradingoptionsdata = new stdClass();
1713 $gradingoptionsdata->perpage = $perpage;
1714 $gradingoptionsdata->filter = $filter;
1715 $gradingoptionsform->set_data($gradingoptionsdata);
1717 // plagiarism update status apearring in the grading book
1718 if (!empty($CFG->enableplagiarism)) {
1719 /** Include plagiarismlib.php */
1720 require_once($CFG->libdir . '/plagiarismlib.php');
1721 plagiarism_update_status($this->get_course(), $this->get_course_module());
1724 $o .= $this->output->render(new assign_form('gradingactionsform', $gradingactionsform));
1725 $o .= $this->output->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
1727 // load and print the table of submissions
1728 if ($showquickgrading && $quickgrading) {
1729 $table = $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, true));
1730 $quickgradingform = new mod_assign_quick_grading_form(null,
1731 array('cm'=>$this->get_course_module()->id,
1732 'gradingtable'=>$table));
1733 $o .= $this->output->render(new assign_form('quickgradingform', $quickgradingform));
1735 $o .= $this->output->render(new assign_grading_table($this, $perpage, $filter, 0, false));
1738 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1739 $users = array_keys($this->list_participants($currentgroup, true));
1740 if (count($users) != 0) {
1741 // if no enrolled user in a course then don't display the batch operations feature
1742 $o .= $this->output->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
1748 * View entire grading page.
1752 private function view_grading_page() {
1756 // Need submit permission to submit an assignment
1757 require_capability('mod/assign:grade', $this->context);
1758 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1760 // only load this if it is
1762 $o .= $this->output->render(new assign_header($this->get_instance(),
1763 $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign')));
1764 $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);
1767 $o .= $this->view_grading_table();
1769 $o .= $this->view_footer();
1770 $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
1775 * Capture the output of the plagiarism plugins disclosures and return it as a string
1779 private function plagiarism_print_disclosure() {
1783 if (!empty($CFG->enableplagiarism)) {
1784 /** Include plagiarismlib.php */
1785 require_once($CFG->libdir . '/plagiarismlib.php');
1788 plagiarism_print_disclosure($this->get_course_module()->id);
1789 $o = ob_get_contents();
1797 * message for students when assignment submissions have been closed
1801 private function view_student_error_message() {
1805 // Need submit permission to submit an assignment
1806 require_capability('mod/assign:submit', $this->context);
1808 $o .= $this->output->render(new assign_header($this->get_instance(),
1809 $this->get_context(),
1810 $this->show_intro(),
1811 $this->get_course_module()->id,
1812 get_string('editsubmission', 'assign')));
1814 $o .= $this->output->notification(get_string('submissionsclosed', 'assign'));
1816 $o .= $this->view_footer();
1823 * View edit submissions page.
1825 * @param moodleform $mform
1828 private function view_edit_submission_page($mform) {
1832 // Include submission form
1833 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
1834 // Need submit permission to submit an assignment
1835 require_capability('mod/assign:submit', $this->context);
1837 if (!$this->submissions_open()) {
1838 return $this->view_student_error_message();
1840 $o .= $this->output->render(new assign_header($this->get_instance(),
1841 $this->get_context(),
1842 $this->show_intro(),
1843 $this->get_course_module()->id,
1844 get_string('editsubmission', 'assign')));
1845 $o .= $this->plagiarism_print_disclosure();
1846 $data = new stdClass();
1849 $mform = new mod_assign_submission_form(null, array($this, $data));
1852 $o .= $this->output->render(new assign_form('editsubmissionform',$mform));
1854 $o .= $this->view_footer();
1855 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
1861 * See if this assignment has a grade yet
1863 * @param int $userid
1866 private function is_graded($userid) {
1867 $grade = $this->get_user_grade($userid, false);
1869 return ($grade->grade != '');
1876 * Perform an access check to see if the current $USER can view this users submission
1878 * @param int $userid
1881 public function can_view_submission($userid) {
1884 if (!is_enrolled($this->get_course_context(), $userid)) {
1887 if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
1890 if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
1897 * Ask the user to confirm they want to perform this batch operation
1900 private function process_batch_grading_operation() {
1902 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
1905 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
1906 array('cm'=>$this->get_course_module()->id,
1907 'submissiondrafts'=>$this->get_instance()->submissiondrafts),
1909 array('class'=>'gradingbatchoperationsform'));
1911 if ($data = $gradingbatchoperationsform->get_data()) {
1912 // get the list of users
1913 $users = $data->selectedusers;
1914 $userlist = explode(',', $users);
1916 foreach ($userlist as $userid) {
1917 if ($data->operation == 'lock') {
1918 $this->process_lock($userid);
1919 } else if ($data->operation == 'unlock') {
1920 $this->process_unlock($userid);
1921 } else if ($data->operation == 'reverttodraft') {
1922 $this->process_revert_to_draft($userid);
1931 * Ask the user to confirm they want to submit their work for grading
1934 private function check_submit_for_grading() {
1936 // Check that all of the submission plugins are ready for this submission
1937 $notifications = array();
1938 $submission = $this->get_user_submission($USER->id, false);
1939 $plugins = $this->get_submission_plugins();
1940 foreach ($plugins as $plugin) {
1941 if ($plugin->is_enabled() && $plugin->is_visible()) {
1942 $check = $plugin->precheck_submission($submission);
1943 if ($check !== true) {
1944 $notifications[] = $check;
1950 $o .= $this->output->header();
1951 $o .= $this->output->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id));
1952 $o .= $this->view_footer();
1957 * Print 2 tables of information with no action links -
1958 * the submission summary and the grading summary
1960 * @param stdClass $user the user to print the report for
1961 * @param bool $showlinks - Return plain text or links to the profile
1962 * @return string - the html summary
1964 public function view_student_summary($user, $showlinks) {
1965 global $CFG, $DB, $PAGE;
1967 $grade = $this->get_user_grade($user->id, false);
1968 $submission = $this->get_user_submission($user->id, false);
1971 if ($this->can_view_submission($user->id)) {
1972 $showedit = has_capability('mod/assign:submit', $this->context) &&
1973 $this->submissions_open() && ($this->is_any_submission_plugin_enabled()) && $showlinks;
1974 $showsubmit = $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT) && $showlinks;
1975 $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
1977 $o .= $this->output->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
1978 $this->get_instance()->alwaysshowdescription,
1980 $this->is_any_submission_plugin_enabled(),
1982 $this->is_graded($user->id),
1983 $this->get_instance()->duedate,
1984 $this->get_submission_plugins(),
1985 $this->get_return_action(),
1986 $this->get_return_params(),
1987 $this->get_course_module()->id,
1988 assign_submission_status::STUDENT_VIEW,
1991 require_once($CFG->libdir.'/gradelib.php');
1992 require_once($CFG->dirroot.'/grade/grading/lib.php');
1994 $gradinginfo = grade_get_grades($this->get_course()->id,
1997 $this->get_instance()->id,
2000 $gradingitem = $gradinginfo->items[0];
2001 $gradebookgrade = $gradingitem->grades[$user->id];
2003 // check to see if all feedback plugins are empty
2004 $emptyplugins = true;
2006 foreach ($this->get_feedback_plugins() as $plugin) {
2007 if ($plugin->is_visible() && $plugin->is_enabled()) {
2008 if (!$plugin->is_empty($grade)) {
2009 $emptyplugins = false;
2016 if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {
2018 $gradefordisplay = '';
2019 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2021 if ($controller = $gradingmanager->get_active_controller()) {
2022 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
2023 $gradefordisplay = $controller->render_grade($PAGE,
2026 $gradebookgrade->str_long_grade,
2027 has_capability('mod/assign:grade', $this->get_context()));
2029 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
2032 $gradeddate = $gradebookgrade->dategraded;
2033 $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));
2035 $feedbackstatus = new assign_feedback_status($gradefordisplay,
2038 $this->get_feedback_plugins(),
2040 $this->get_course_module()->id,
2041 $this->get_return_action(),
2042 $this->get_return_params());
2044 $o .= $this->output->render($feedbackstatus);
2052 * View submissions page (contains details of current submission).
2056 private function view_submission_page() {
2057 global $CFG, $DB, $USER, $PAGE;
2060 $o .= $this->output->render(new assign_header($this->get_instance(),
2061 $this->get_context(),
2062 $this->show_intro(),
2063 $this->get_course_module()->id));
2065 if ($this->can_grade()) {
2066 $o .= $this->output->render(new assign_grading_summary($this->count_participants(0),
2067 $this->get_instance()->submissiondrafts,
2068 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
2069 $this->is_any_submission_plugin_enabled(),
2070 $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
2071 $this->get_instance()->duedate,
2072 $this->get_course_module()->id
2075 $grade = $this->get_user_grade($USER->id, false);
2076 $submission = $this->get_user_submission($USER->id, false);
2078 if ($this->can_view_submission($USER->id)) {
2079 $o .= $this->view_student_summary($USER, true);
2083 $o .= $this->view_footer();
2084 $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
2089 * convert the final raw grade(s) in the grading table for the gradebook
2091 * @param stdClass $grade
2094 private function convert_grade_for_gradebook(stdClass $grade) {
2095 $gradebookgrade = array();
2096 // trying to match those array keys in grade update function in gradelib.php
2097 // with keys in th database table assign_grades
2098 // starting around line 262
2099 $gradebookgrade['rawgrade'] = $grade->grade;
2100 $gradebookgrade['userid'] = $grade->userid;
2101 $gradebookgrade['usermodified'] = $grade->grader;
2102 $gradebookgrade['datesubmitted'] = NULL;
2103 $gradebookgrade['dategraded'] = $grade->timemodified;
2104 if (isset($grade->feedbackformat)) {
2105 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
2107 if (isset($grade->feedbacktext)) {
2108 $gradebookgrade['feedback'] = $grade->feedbacktext;
2111 return $gradebookgrade;
2115 * convert submission details for the gradebook
2117 * @param stdClass $submission
2120 private function convert_submission_for_gradebook(stdClass $submission) {
2121 $gradebookgrade = array();
2124 $gradebookgrade['userid'] = $submission->userid;
2125 $gradebookgrade['usermodified'] = $submission->userid;
2126 $gradebookgrade['datesubmitted'] = $submission->timemodified;
2128 return $gradebookgrade;
2132 * update grades in the gradebook
2134 * @param mixed $submission stdClass|null
2135 * @param mixed $grade stdClass|null
2138 private function gradebook_item_update($submission=NULL, $grade=NULL) {
2140 if($submission != NULL){
2142 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
2148 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
2150 $assign = clone $this->get_instance();
2151 $assign->cmidnumber = $this->get_course_module()->id;
2153 return assign_grade_item_update($assign, $gradebookgrade);
2157 * update grades in the gradebook based on submission time
2159 * @param stdClass $submission
2160 * @param bool $updatetime
2163 private function update_submission(stdClass $submission, $updatetime=true) {
2167 $submission->timemodified = time();
2169 $result= $DB->update_record('assign_submission', $submission);
2171 $this->gradebook_item_update($submission);
2177 * Is this assignment open for submissions?
2179 * Check the due date,
2180 * prevent late submissions,
2181 * has this person already submitted,
2182 * is the assignment locked?
2186 private function submissions_open() {
2191 if ($this->get_instance()->preventlatesubmissions && $this->get_instance()->duedate) {
2192 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $this->get_instance()->duedate);
2194 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
2201 // now check if this user has already submitted etc.
2202 if (!is_enrolled($this->get_course_context(), $USER)) {
2205 if ($submission = $this->get_user_submission($USER->id, false)) {
2206 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2207 // drafts are tracked and the student has submitted the assignment
2211 if ($grade = $this->get_user_grade($USER->id, false)) {
2212 if ($grade->locked) {
2217 if ($this->grading_disabled($USER->id)) {
2225 * render the files in file area
2226 * @param string $component
2227 * @param string $area
2228 * @param int $submissionid
2231 public function render_area_files($component, $area, $submissionid) {
2234 if (!$submissionid) {
2235 $submission = $this->get_user_submission($USER->id,false);
2236 $submissionid = $submission->id;
2241 $fs = get_file_storage();
2242 $browser = get_file_browser();
2243 $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
2244 return $this->output->assign_files($this->context, $submissionid, $area, $component);
2249 * Returns a list of teachers that should be grading given submission
2251 * @param int $userid
2254 private function get_graders($userid) {
2256 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");
2259 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
2260 if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
2261 foreach ($groups as $group) {
2262 foreach ($potentialgraders as $grader) {
2263 if ($grader->id == $userid) {
2264 continue; // do not send self
2266 if (groups_is_member($group->id, $grader->id)) {
2267 $graders[$grader->id] = $grader;
2272 // user not in group, try to find graders without group
2273 foreach ($potentialgraders as $grader) {
2274 if ($grader->id == $userid) {
2275 continue; // do not send self
2277 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
2278 $graders[$grader->id] = $grader;
2283 foreach ($potentialgraders as $grader) {
2284 if ($grader->id == $userid) {
2285 continue; // do not send self
2288 if (is_enrolled($this->get_course_context(), $grader->id)) {
2289 $graders[$grader->id] = $grader;
2297 * Format a notification based on it's type
2299 * @param string $messagetype
2300 * @param stdClass $info
2301 * @param stdClass $course
2302 * @param stdClass $context
2303 * @param string $modulename
2304 * @param string $assignmentname
2306 private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
2307 $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
2309 format_string($assignmentname, true, array('context' => $context))."\n";
2310 $posttext .= '---------------------------------------------------------------------'."\n";
2311 $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
2312 $posttext .= "\n---------------------------------------------------------------------\n";
2317 * Format a notification based on it's type
2319 * @param string $messagetype
2320 * @param stdClass $info
2322 private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
2324 $posthtml = '<p><font face="sans-serif">'.
2325 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
2326 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
2327 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
2328 $posthtml .= '<hr /><font face="sans-serif">';
2329 $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
2330 $posthtml .= '</font><hr />';
2335 * email someone about something (static so it can be called from cron)
2337 * @global stdClass $CFG
2338 * @global moodle_database $DB
2339 * @param stdClass $userfrom
2340 * @param stdClass $userto
2341 * @param string $messagetype
2342 * @param string $eventtype
2343 * @param int $updatetime
2344 * @param stdClass $coursemodule
2345 * @param stdClass $context
2346 * @param stdClass $course
2347 * @param string $modulename
2348 * @param string $moduleplural
2349 * @param string $assignmentname
2352 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
2353 $updatetime, $coursemodule, $context, $course,
2354 $modulename, $assignmentname) {
2357 $strnotification = get_string('notification', 'assign');
2359 $info = new stdClass();
2360 $info->username = fullname($userfrom, true);
2361 $info->assignment = format_string($assignmentname,true, array('context'=>$context));
2362 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
2363 $info->timeupdated = strftime('%c',$updatetime);
2365 $postsubject = get_string($messagetype . 'small', 'assign', $info);
2366 $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
2367 $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';
2369 $eventdata = new stdClass();
2370 $eventdata->modulename = 'assign';
2371 $eventdata->userfrom = $userfrom;
2372 $eventdata->userto = $userto;
2373 $eventdata->subject = $postsubject;
2374 $eventdata->fullmessage = $posttext;
2375 $eventdata->fullmessageformat = FORMAT_PLAIN;
2376 $eventdata->fullmessagehtml = $posthtml;
2377 $eventdata->smallmessage = $postsubject;
2379 $eventdata->name = $eventtype;
2380 $eventdata->component = 'mod_assign';
2381 $eventdata->notification = 1;
2382 $eventdata->contexturl = $info->url;
2383 $eventdata->contexturlname = $info->assignment;
2385 message_send($eventdata);
2390 * email someone about something
2392 * @global stdClass $CFG
2393 * @global moodle_database $DB
2394 * @param stdClass $submission
2397 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
2398 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);
2402 * email student upon successful submission
2404 * @global stdClass $CFG
2405 * @global moodle_database $DB
2406 * @param stdClass $submission
2409 private function email_student_submission_receipt(stdClass $submission) {
2412 $adminconfig = $this->get_admin_config();
2413 if (!$adminconfig->submissionreceipts) { // No need to do anything
2417 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2419 $this->send_notification($user, $user, 'submissionreceipt', 'assign_student_notification', $submission->timemodified);
2423 * email graders upon student submissions
2425 * @global stdClass $CFG
2426 * @global moodle_database $DB
2427 * @param stdClass $submission
2430 private function email_graders(stdClass $submission) {
2433 $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());
2435 if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
2439 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
2441 if ($teachers = $this->get_graders($user->id)) {
2443 $strassignments = $this->get_module_name_plural();
2444 $strassignment = $this->get_module_name();
2445 $strsubmitted = get_string('submitted', 'assign');
2447 foreach ($teachers as $teacher) {
2448 $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_grader_notification', $submission->timemodified);
2454 * assignment submission is processed before grading
2458 private function process_submit_for_grading() {
2461 // Need submit permission to submit an assignment
2462 require_capability('mod/assign:submit', $this->context);
2465 $submission = $this->get_user_submission($USER->id,true);
2466 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2467 // Give each submission plugin a chance to process the submission
2468 $plugins = $this->get_submission_plugins();
2469 foreach ($plugins as $plugin) {
2470 $plugin->submit_for_grading();
2473 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2474 $this->update_submission($submission);
2475 $this->add_to_log('submit for grading', $this->format_submission_for_log($submission));
2476 $this->email_graders($submission);
2477 $this->email_student_submission_receipt($submission);
2484 * @global moodle_database $DB
2485 * @return string The result of the save operation
2487 private function process_save_quick_grades() {
2488 global $USER, $DB, $CFG;
2490 // Need grade permission
2491 require_capability('mod/assign:grade', $this->context);
2493 // make sure advanced grading is disabled
2494 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2495 $controller = $gradingmanager->get_active_controller();
2496 if (!empty($controller)) {
2497 return get_string('errorquickgradingvsadvancedgrading', 'assign');
2501 // first check all the last modified values
2502 // Using POST is really unfortunate. A better solution needs to be found here. As we are looking for grades students we could
2503 // gets a list of possible users and look for values based upon that.
2504 foreach ($_POST as $key => $value) {
2505 if (preg_match('#^grademodified_(\d+)$#', $key, $matches)) {
2506 // gather the userid, updated grade and last modified value
2507 $record = new stdClass();
2508 $record->userid = (int)$matches[1];
2509 $record->grade = required_param('quickgrade_' . $record->userid, PARAM_INT);
2510 $record->lastmodified = clean_param($value, PARAM_INT);
2511 $record->gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($record->userid));
2512 $users[$record->userid] = $record;
2515 if (empty($users)) {
2516 // Quick check to see whether we have any users to update and we don't
2517 return get_string('quickgradingchangessaved', 'assign'); // Technical lie
2520 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
2521 $params['assignment'] = $this->get_instance()->id;
2522 // check them all for currency
2523 $sql = 'SELECT u.id as userid, g.grade as grade, g.timemodified as lastmodified
2525 LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignment
2526 WHERE u.id ' . $userids;
2527 $currentgrades = $DB->get_recordset_sql($sql, $params);
2529 $modifiedusers = array();
2530 foreach ($currentgrades as $current) {
2531 $modified = $users[(int)$current->userid];
2533 // check to see if the outcomes were modified
2534 if ($CFG->enableoutcomes) {
2535 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2536 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2537 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2538 if ($oldoutcome != $newoutcome) {
2539 // can't check modified time for outcomes because it is not reported
2540 $modifiedusers[$modified->userid] = $modified;
2547 if (($current->grade < 0 || $current->grade === NULL) &&
2548 ($modified->grade < 0 || $modified->grade === NULL)) {
2549 // different ways to indicate no grade
2552 if ($current->grade != $modified->grade) {
2554 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
2555 // error - record has been modified since viewing the page
2556 return get_string('errorrecordmodified', 'assign');
2558 $modifiedusers[$modified->userid] = $modified;
2563 $currentgrades->close();
2565 // ok - ready to process the updates
2566 foreach ($modifiedusers as $userid => $modified) {
2567 $grade = $this->get_user_grade($userid, true);
2568 $grade->grade= grade_floatval($modified->grade);
2569 $grade->grader= $USER->id;
2571 $this->update_grade($grade);
2574 if ($CFG->enableoutcomes) {
2576 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
2577 $oldoutcome = $outcome->grades[$modified->userid]->grade;
2578 $newoutcome = optional_param('outcome_' . $outcomeid . '_' . $modified->userid, -1, PARAM_INT);
2579 if ($oldoutcome != $newoutcome) {
2580 $data[$outcomeid] = $newoutcome;
2583 if (count($data) > 0) {
2584 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
2588 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
2591 return get_string('quickgradingchangessaved', 'assign');
2595 * save grading options
2599 private function process_save_grading_options() {
2602 // Include grading options form
2603 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2605 // Need submit permission to submit an assignment
2606 require_capability('mod/assign:grade', $this->context);
2608 $mform = new mod_assign_grading_options_form(null, array('cm'=>$this->get_course_module()->id, 'contextid'=>$this->context->id, 'userid'=>$USER->id, 'showquickgrading'=>false));
2609 if ($formdata = $mform->get_data()) {
2610 set_user_preference('assign_perpage', $formdata->perpage);
2611 set_user_preference('assign_filter', $formdata->filter);
2616 * Take a grade object and print a short summary for the log file.
2617 * The size limit for the log file is 255 characters, so be careful not
2618 * to include too much information.
2620 * @param stdClass $grade
2623 private function format_grade_for_log(stdClass $grade) {
2626 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
2628 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
2629 if ($grade->grade != '') {
2630 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
2632 $info .= get_string('nograde', 'assign');
2634 if ($grade->locked) {
2635 $info .= get_string('submissionslocked', 'assign') . '. ';
2641 * Take a submission object and print a short summary for the log file.
2642 * The size limit for the log file is 255 characters, so be careful not
2643 * to include too much information.
2645 * @param stdClass $submission
2648 private function format_submission_for_log(stdClass $submission) {
2650 $info .= get_string('submissionstatus', 'assign') . ': ' . get_string('submissionstatus_' . $submission->status, 'assign') . '. <br>';
2651 // format_for_log here iterating every single log INFO from either submission or grade in every assignment plugin
2653 foreach ($this->submissionplugins as $plugin) {
2654 if ($plugin->is_enabled() && $plugin->is_visible()) {
2657 $info .= "<br>" . $plugin->format_for_log($submission);
2666 * save assignment submission
2668 * @param moodleform $mform
2671 private function process_save_submission(&$mform) {
2674 // Include submission form
2675 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
2677 // Need submit permission to submit an assignment
2678 require_capability('mod/assign:submit', $this->context);
2681 $data = new stdClass();
2682 $mform = new mod_assign_submission_form(null, array($this, $data));
2683 if ($mform->is_cancelled()) {
2686 if ($data = $mform->get_data()) {
2687 $submission = $this->get_user_submission($USER->id, true); //create the submission if needed & its id
2688 $grade = $this->get_user_grade($USER->id, false); // get the grade to check if it is locked
2689 if ($grade && $grade->locked) {
2690 print_error('submissionslocked', 'assign');
2695 foreach ($this->submissionplugins as $plugin) {
2696 if ($plugin->is_enabled()) {
2697 if (!$plugin->save($submission, $data)) {
2698 print_error($plugin->get_error());
2703 $this->update_submission($submission);
2706 $this->add_to_log('submit', $this->format_submission_for_log($submission));
2708 if (!$this->get_instance()->submissiondrafts) {
2709 $this->email_student_submission_receipt($submission);
2710 $this->email_graders($submission);
2719 * Determine if this users grade is locked or overridden
2721 * @param int $userid - The student userid
2722 * @return bool $gradingdisabled
2724 private function grading_disabled($userid) {
2727 $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, array($userid));
2728 if (!$gradinginfo) {
2732 if (!isset($gradinginfo->items[0]->grades[$userid])) {
2735 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
2736 return $gradingdisabled;
2741 * Get an instance of a grading form if advanced grading is enabled
2742 * This is specific to the assignment, marker and student
2744 * @param int $userid - The student userid
2745 * @param bool $gradingdisabled
2746 * @return mixed gradingform_instance|null $gradinginstance
2748 private function get_grading_instance($userid, $gradingdisabled) {
2751 $grade = $this->get_user_grade($userid, false);
2752 $grademenu = make_grades_menu($this->get_instance()->grade);
2754 $advancedgradingwarning = false;
2755 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
2756 $gradinginstance = null;
2757 if ($gradingmethod = $gradingmanager->get_active_method()) {
2758 $controller = $gradingmanager->get_controller($gradingmethod);
2759 if ($controller->is_form_available()) {
2762 $itemid = $grade->id;
2764 if ($gradingdisabled && $itemid) {
2765 $gradinginstance = ($controller->get_current_instance($USER->id, $itemid));
2766 } else if (!$gradingdisabled) {
2767 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
2768 $gradinginstance = ($controller->get_or_create_instance($instanceid, $USER->id, $itemid));
2771 $advancedgradingwarning = $controller->form_unavailable_notification();
2774 if ($gradinginstance) {
2775 $gradinginstance->get_controller()->set_grade_range($grademenu);
2777 return $gradinginstance;
2781 * add elements to grade form
2783 * @param MoodleQuickForm $mform
2784 * @param stdClass $data
2785 * @param array $params
2788 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
2790 $settings = $this->get_instance();
2792 $rownum = $params['rownum'];
2793 $last = $params['last'];
2794 $useridlist = $params['useridlist'];
2795 $userid = $useridlist[$rownum];
2796 $grade = $this->get_user_grade($userid, false);
2798 // add advanced grading
2799 $gradingdisabled = $this->grading_disabled($userid);
2800 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
2802 if ($gradinginstance) {
2803 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2804 if ($gradingdisabled) {
2805 $gradingelement->freeze();
2807 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2810 // use simple direct grading
2811 if ($this->get_instance()->grade > 0) {
2812 $mform->addElement('text', 'grade', get_string('gradeoutof', 'assign',$this->get_instance()->grade));
2813 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
2814 $mform->setType('grade', PARAM_TEXT);
2816 $grademenu = make_grades_menu($this->get_instance()->grade);
2817 if (count($grademenu) > 0) {
2818 $mform->addElement('select', 'grade', get_string('grade').':', $grademenu);
2819 $mform->setType('grade', PARAM_INT);
2824 $gradinginfo = grade_get_grades($this->get_course()->id,
2827 $this->get_instance()->id,
2829 if (!empty($CFG->enableoutcomes)) {
2830 foreach($gradinginfo->outcomes as $index=>$outcome) {
2831 $options = make_grades_menu(-$outcome->scaleid);
2832 if ($outcome->grades[$userid]->locked) {
2833 $options[0] = get_string('nooutcome', 'grades');
2834 $mform->addElement('static', 'outcome_'.$index.'['.$userid.']', $outcome->name.':',
2835 $options[$outcome->grades[$userid]->grade]);
2837 $options[''] = get_string('nooutcome', 'grades');
2838 $attributes = array('id' => 'menuoutcome_'.$index );
2839 $mform->addElement('select', 'outcome_'.$index.'['.$userid.']', $outcome->name.':', $options, $attributes );
2840 $mform->setType('outcome_'.$index.'['.$userid.']', PARAM_INT);
2841 $mform->setDefault('outcome_'.$index.'['.$userid.']', $outcome->grades[$userid]->grade );
2846 $mform->addElement('static', 'progress', '', get_string('gradingstudentprogress', 'assign', array('index'=>$rownum+1, 'count'=>count($useridlist))));
2849 $this->add_plugin_grade_elements($grade, $mform, $data);
2852 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
2853 $mform->setType('id', PARAM_INT);
2854 $mform->addElement('hidden', 'rownum', $rownum);
2855 $mform->setType('rownum', PARAM_INT);
2856 $mform->addElement('hidden', 'useridlist', implode(',', $useridlist));
2857 $mform->setType('useridlist', PARAM_TEXT);
2858 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
2859 $mform->setType('ajax', PARAM_INT);
2861 $mform->addElement('hidden', 'action', 'submitgrade');
2862 $mform->setType('action', PARAM_ALPHA);
2865 $buttonarray=array();
2866 $buttonarray[] = $mform->createElement('submit', 'savegrade', get_string('savechanges', 'assign'));
2868 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', get_string('savenext','assign'));
2870 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
2871 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
2872 $mform->closeHeaderBefore('buttonar');
2873 $buttonarray=array();
2876 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', get_string('previous','assign'));
2880 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', get_string('nosavebutnext', 'assign'));
2882 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
2887 * add elements in submission plugin form
2889 * @param mixed $submission stdClass|null
2890 * @param MoodleQuickForm $mform
2891 * @param stdClass $data
2894 private function add_plugin_submission_elements($submission, MoodleQuickForm $mform, stdClass $data) {
2895 foreach ($this->submissionplugins as $plugin) {
2896 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2897 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
2898 if (!$plugin->get_form_elements($submission, $mform, $data)) {
2899 $mform->removeElement('header_' . $plugin->get_type());
2906 * check if feedback plugins installed are enabled
2910 public function is_any_feedback_plugin_enabled() {
2911 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
2912 $this->cache['any_feedback_plugin_enabled'] = false;
2913 foreach ($this->feedbackplugins as $plugin) {
2914 if ($plugin->is_enabled() && $plugin->is_visible()) {
2915 $this->cache['any_feedback_plugin_enabled'] = true;
2921 return $this->cache['any_feedback_plugin_enabled'];
2926 * check if submission plugins installed are enabled
2930 public function is_any_submission_plugin_enabled() {
2931 if (!isset($this->cache['any_submission_plugin_enabled'])) {
2932 $this->cache['any_submission_plugin_enabled'] = false;
2933 foreach ($this->submissionplugins as $plugin) {
2934 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
2935 $this->cache['any_submission_plugin_enabled'] = true;
2941 return $this->cache['any_submission_plugin_enabled'];
2946 * add elements to submission form
2947 * @param MoodleQuickForm $mform
2948 * @param stdClass $data
2951 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
2954 // online text submissions
2956 $submission = $this->get_user_submission($USER->id, false);
2958 $this->add_plugin_submission_elements($submission, $mform, $data);
2961 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
2962 $mform->setType('id', PARAM_INT);
2964 $mform->addElement('hidden', 'action', 'savesubmission');
2965 $mform->setType('action', PARAM_TEXT);
2972 * Uses url parameter userid
2974 * @param int $userid
2977 private function process_revert_to_draft($userid = 0) {
2980 // Need grade permission
2981 require_capability('mod/assign:grade', $this->context);
2985 $userid = required_param('userid', PARAM_INT);
2988 $submission = $this->get_user_submission($userid, false);
2992 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2993 $this->update_submission($submission, false);
2995 // update the modified time on the grade (grader modified)
2996 $grade = $this->get_user_grade($userid, true);
2997 $this->update_grade($grade);
2999 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3001 $this->add_to_log('revert submission to draft', get_string('reverttodraftforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3007 * Uses url parameter userid
3008 * @param int $userid
3011 private function process_lock($userid = 0) {
3014 // Need grade permission
3015 require_capability('mod/assign:grade', $this->context);
3019 $userid = required_param('userid', PARAM_INT);
3022 $grade = $this->get_user_grade($userid, true);
3024 $grade->grader = $USER->id;
3025 $this->update_grade($grade);
3027 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3029 $this->add_to_log('lock submission', get_string('locksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3033 * unlock the process
3035 * @param int $userid
3038 private function process_unlock($userid = 0) {
3041 // Need grade permission
3042 require_capability('mod/assign:grade', $this->context);
3046 $userid = required_param('userid', PARAM_INT);
3049 $grade = $this->get_user_grade($userid, true);
3051 $grade->grader = $USER->id;
3052 $this->update_grade($grade);
3054 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3056 $this->add_to_log('unlock submission', get_string('unlocksubmissionforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user))));
3060 * save outcomes submitted from grading form
3062 * @param int $userid
3063 * @param stdClass $formdata
3065 private function process_outcomes($userid, $formdata) {
3068 if (empty($CFG->enableoutcomes)) {
3072 require_once($CFG->libdir.'/gradelib.php');
3075 $gradinginfo = grade_get_grades($this->get_course()->id,
3078 $this->get_instance()->id,
3081 if (!empty($gradinginfo->outcomes)) {
3082 foreach($gradinginfo->outcomes as $index=>$oldoutcome) {
3083 $name = 'outcome_'.$index;
3084 if (isset($formdata->{$name}[$userid]) and $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$userid]) {
3085 $data[$index] = $formdata->{$name}[$userid];
3089 if (count($data) > 0) {
3090 grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
3099 * @param moodleform $mform
3100 * @return bool - was the grade saved
3102 private function process_save_grade(&$mform) {
3103 global $USER, $DB, $CFG;
3104 // Include grade form
3105 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3107 // Need submit permission to submit an assignment
3108 require_capability('mod/assign:grade', $this->context);
3111 $rownum = required_param('rownum', PARAM_INT);
3112 $useridlist = optional_param('useridlist', '', PARAM_TEXT);
3114 $useridlist = explode(',', $useridlist);
3116 $useridlist = $this->get_grading_userid_list();
3119 $userid = $useridlist[$rownum];
3120 if ($rownum == count($useridlist) - 1) {
3124 $data = new stdClass();
3125 $mform = new mod_assign_grade_form(null, array($this, $data, array('rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>false)), 'post', '', array('class'=>'gradeform'));
3127 if ($formdata = $mform->get_data()) {
3128 $grade = $this->get_user_grade($userid, true);
3129 $gradingdisabled = $this->grading_disabled($userid);
3130 $gradinginstance = $this->get_grading_instance($userid, $gradingdisabled);
3131 if ($gradinginstance) {
3132 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading, $grade->id);
3134 // handle the case when grade is set to No Grade
3135 if (isset($formdata->grade)) {
3136 $grade->grade= grade_floatval($formdata->grade);
3139 $grade->grader= $USER->id;
3141 $adminconfig = $this->get_admin_config();
3142 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
3144 // call save in plugins
3145 foreach ($this->feedbackplugins as $plugin) {
3146 if ($plugin->is_enabled() && $plugin->is_visible()) {
3147 if (!$plugin->save($grade, $formdata)) {
3149 print_error($plugin->get_error());
3151 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
3152 // this is the feedback plugin chose to push comments to the gradebook
3153 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
3154 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
3158 $this->process_outcomes($userid, $formdata);
3162 $this->update_grade($grade);
3164 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
3166 $this->add_to_log('grade submission', $this->format_grade_for_log($grade));
3176 * This function is a static wrapper around can_upgrade
3178 * @param string $type The plugin type
3179 * @param int $version The plugin version
3182 public static function can_upgrade_assignment($type, $version) {
3183 $assignment = new assign(null, null, null);
3184 return $assignment->can_upgrade($type, $version);
3188 * This function returns true if it can upgrade an assignment from the 2.2
3190 * @param string $type The plugin type
3191 * @param int $version The plugin version
3194 public function can_upgrade($type, $version) {
3195 if ($type == 'offline' && $version >= 2011112900) {
3198 foreach ($this->submissionplugins as $plugin) {
3199 if ($plugin->can_upgrade($type, $version)) {
3203 foreach ($this->feedbackplugins as $plugin) {
3204 if ($plugin->can_upgrade($type, $version)) {
3212 * Copy all the files from the old assignment files area to the new one.
3213 * This is used by the plugin upgrade code.
3215 * @param int $oldcontextid The old assignment context id
3216 * @param int $oldcomponent The old assignment component ('assignment')
3217 * @param int $oldfilearea The old assignment filearea ('submissions')
3218 * @param int $olditemid The old submissionid (can be null e.g. intro)
3219 * @param int $newcontextid The new assignment context id
3220 * @param int $newcomponent The new assignment component ('assignment')
3221 * @param int $newfilearea The new assignment filearea ('submissions')
3222 * @param int $newitemid The new submissionid (can be null e.g. intro)
3223 * @return int The number of files copied
3225 public function copy_area_files_for_upgrade($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, $newcontextid, $newcomponent, $newfilearea, $newitemid) {
3226 // Note, this code is based on some code in filestorage - but that code
3227 // deleted the old files (which we don't want)
3230 $fs = get_file_storage();
3232 $oldfiles = $fs->get_area_files($oldcontextid, $oldcomponent, $oldfilearea, $olditemid, 'id', false);
3233 foreach ($oldfiles as $oldfile) {
3234 $filerecord = new stdClass();
3235 $filerecord->contextid = $newcontextid;
3236 $filerecord->component = $newcomponent;
3237 $filerecord->filearea = $newfilearea;
3238 $filerecord->itemid = $newitemid;
3239 $fs->create_file_from_storedfile($filerecord, $oldfile);
3247 * Get an upto date list of user grades and feedback for the gradebook
3249 * @param int $userid int or 0 for all users
3250 * @return array of grade data formated for the gradebook api
3251 * The data required by the gradebook api is userid,
3259 public function get_user_grades_for_gradebook($userid) {
3262 $assignmentid = $this->get_instance()->id;
3264 $adminconfig = $this->get_admin_config();
3265 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook;
3266 $gradebookplugin = null;
3268 // find the gradebook plugin
3269 foreach ($this->feedbackplugins as $plugin) {
3270 if ($plugin->is_enabled() && $plugin->is_visible()) {
3271 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
3272 $gradebookplugin = $plugin;
3277 $where = ' WHERE u.id = ? ';
3279 $where = ' WHERE u.id != ? ';
3282 $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
3284 LEFT JOIN {assign_submission} s ON u.id = s.userid and s.assignment = ?
3285 LEFT JOIN {assign_grades} g ON u.id = g.userid and g.assignment = ?
3286 ' . $where, array($assignmentid, $assignmentid, $userid));
3289 foreach ($graderesults as $result) {
3290 $gradebookgrade = clone $result;
3291 // now get the feedback
3292 if ($gradebookplugin) {
3293 $grade = $this->get_user_grade($result->userid, false);
3294 $gradebookgrade->feedbacktext = $gradebookplugin->text_for_gradebook($grade);
3295 $gradebookgrade->feedbackformat = $gradebookplugin->format_for_gradebook($grade);
3297 $grades[$gradebookgrade->userid] = $gradebookgrade;
3300 $graderesults->close();