2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains the definition for the class assignment
20 * This class provides all the functionality for the new assign module.
23 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 // Assignment submission statuses.
30 define('ASSIGN_SUBMISSION_STATUS_REOPENED', 'reopened');
31 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
32 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
34 // Search filters for grading page.
35 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
36 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
37 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
39 // Reopen attempt methods.
40 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
41 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
42 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
44 // Special value means allow unlimited attempts.
45 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
47 // Marking workflow states.
48 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
49 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
50 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
51 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
52 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
53 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
55 require_once($CFG->libdir . '/accesslib.php');
56 require_once($CFG->libdir . '/formslib.php');
57 require_once($CFG->dirroot . '/repository/lib.php');
58 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
59 require_once($CFG->libdir . '/gradelib.php');
60 require_once($CFG->dirroot . '/grade/grading/lib.php');
61 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
62 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
63 require_once($CFG->dirroot . '/mod/assign/renderable.php');
64 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
65 require_once($CFG->libdir . '/eventslib.php');
66 require_once($CFG->libdir . '/portfolio/caller.php');
69 * Standard base class for mod_assign (assignment types).
72 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
77 /** @var stdClass the assignment record that contains the global settings for this assign instance */
80 /** @var stdClass the grade_item record for this assign instance's primary grade item. */
83 /** @var context the context of the course module for this assign instance
84 * (or just the course if we are creating a new one)
88 /** @var stdClass the course this assign instance belongs to */
91 /** @var stdClass the admin config for all assign instances */
94 /** @var assign_renderer the custom renderer for this module */
97 /** @var stdClass the course module for this assign instance */
98 private $coursemodule;
100 /** @var array cache for things like the coursemodule name or the scale menu -
101 * only lives for a single request.
105 /** @var array list of the installed submission plugins */
106 private $submissionplugins;
108 /** @var array list of the installed feedback plugins */
109 private $feedbackplugins;
111 /** @var string action to be used to return to this page
112 * (without repeating any form submissions etc).
114 private $returnaction = 'view';
116 /** @var array params to be used to return to this page */
117 private $returnparams = array();
119 /** @var string modulename prevents excessive calls to get_string */
120 private static $modulename = null;
122 /** @var string modulenameplural prevents excessive calls to get_string */
123 private static $modulenameplural = null;
125 /** @var array of marking workflow states for the current user */
126 private $markingworkflowstates = null;
128 /** @var bool whether to exclude users with inactive enrolment */
129 private $showonlyactiveenrol = null;
131 /** @var array list of suspended user IDs in form of ([id1] => id1) */
132 public $susers = null;
135 * Constructor for the base assign class.
137 * @param mixed $coursemodulecontext context|null the course module context
138 * (or the course context if the coursemodule has not been
140 * @param mixed $coursemodule the current course module if it was already loaded,
141 * otherwise this class will load one from the context as required.
142 * @param mixed $course the current course if it was already loaded,
143 * otherwise this class will load one from the context as required.
145 public function __construct($coursemodulecontext, $coursemodule, $course) {
146 $this->context = $coursemodulecontext;
147 $this->coursemodule = $coursemodule;
148 $this->course = $course;
150 // Temporary cache only lives for a single request - used to reduce db lookups.
151 $this->cache = array();
153 $this->submissionplugins = $this->load_plugins('assignsubmission');
154 $this->feedbackplugins = $this->load_plugins('assignfeedback');
158 * Set the action and parameters that can be used to return to the current page.
160 * @param string $action The action for the current page
161 * @param array $params An array of name value pairs which form the parameters
162 * to return to the current page.
165 public function register_return_link($action, $params) {
167 $params['action'] = $action;
168 $currenturl = $PAGE->url;
170 $currenturl->params($params);
171 $PAGE->set_url($currenturl);
175 * Return an action that can be used to get back to the current page.
177 * @return string action
179 public function get_return_action() {
182 $params = $PAGE->url->params();
184 if (!empty($params['action'])) {
185 return $params['action'];
191 * Based on the current assignment settings should we display the intro.
193 * @return bool showintro
195 protected function show_intro() {
196 if ($this->get_instance()->alwaysshowdescription ||
197 time() > $this->get_instance()->allowsubmissionsfromdate) {
204 * Return a list of parameters that can be used to get back to the current page.
206 * @return array params
208 public function get_return_params() {
211 $params = $PAGE->url->params();
212 unset($params['id']);
213 unset($params['action']);
218 * Set the submitted form data.
220 * @param stdClass $data The form data (instance)
222 public function set_instance(stdClass $data) {
223 $this->instance = $data;
229 * @param context $context The new context
231 public function set_context(context $context) {
232 $this->context = $context;
236 * Set the course data.
238 * @param stdClass $course The course data
240 public function set_course(stdClass $course) {
241 $this->course = $course;
245 * Get list of feedback plugins installed.
249 public function get_feedback_plugins() {
250 return $this->feedbackplugins;
254 * Get list of submission plugins installed.
258 public function get_submission_plugins() {
259 return $this->submissionplugins;
263 * Is blind marking enabled and reveal identities not set yet?
267 public function is_blind_marking() {
268 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
272 * Does an assignment have submission(s) or grade(s) already?
276 public function has_submissions_or_grades() {
277 $allgrades = $this->count_grades();
278 $allsubmissions = $this->count_submissions();
279 if (($allgrades == 0) && ($allsubmissions == 0)) {
286 * Get a specific submission plugin by its type.
288 * @param string $subtype assignsubmission | assignfeedback
289 * @param string $type
290 * @return mixed assign_plugin|null
292 public function get_plugin_by_type($subtype, $type) {
293 $shortsubtype = substr($subtype, strlen('assign'));
294 $name = $shortsubtype . 'plugins';
295 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
298 $pluginlist = $this->$name;
299 foreach ($pluginlist as $plugin) {
300 if ($plugin->get_type() == $type) {
308 * Get a feedback plugin by type.
310 * @param string $type - The type of plugin e.g comments
311 * @return mixed assign_feedback_plugin|null
313 public function get_feedback_plugin_by_type($type) {
314 return $this->get_plugin_by_type('assignfeedback', $type);
318 * Get a submission plugin by type.
320 * @param string $type - The type of plugin e.g comments
321 * @return mixed assign_submission_plugin|null
323 public function get_submission_plugin_by_type($type) {
324 return $this->get_plugin_by_type('assignsubmission', $type);
328 * Load the plugins from the sub folders under subtype.
330 * @param string $subtype - either submission or feedback
331 * @return array - The sorted list of plugins
333 protected function load_plugins($subtype) {
337 $names = core_component::get_plugin_list($subtype);
339 foreach ($names as $name => $path) {
340 if (file_exists($path . '/locallib.php')) {
341 require_once($path . '/locallib.php');
343 $shortsubtype = substr($subtype, strlen('assign'));
344 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
346 $plugin = new $pluginclass($this, $name);
348 if ($plugin instanceof assign_plugin) {
349 $idx = $plugin->get_sort_order();
350 while (array_key_exists($idx, $result)) {
353 $result[$idx] = $plugin;
362 * Display the assignment, used by view.php
364 * The assignment is displayed differently depending on your role,
365 * the settings for the assignment and the status of the assignment.
367 * @param string $action The current action if any.
368 * @return string - The page output.
370 public function view($action='') {
375 $nextpageparams = array();
377 if (!empty($this->get_course_module()->id)) {
378 $nextpageparams['id'] = $this->get_course_module()->id;
381 // Handle form submissions first.
382 if ($action == 'savesubmission') {
383 $action = 'editsubmission';
384 if ($this->process_save_submission($mform, $notices)) {
385 $action = 'redirect';
386 $nextpageparams['action'] = 'view';
388 } else if ($action == 'editprevioussubmission') {
389 $action = 'editsubmission';
390 if ($this->process_copy_previous_attempt($notices)) {
391 $action = 'redirect';
392 $nextpageparams['action'] = 'editsubmission';
394 } else if ($action == 'lock') {
395 $this->process_lock_submission();
396 $action = 'redirect';
397 $nextpageparams['action'] = 'grading';
398 } else if ($action == 'addattempt') {
399 $this->process_add_attempt(required_param('userid', PARAM_INT));
400 $action = 'redirect';
401 $nextpageparams['action'] = 'grading';
402 } else if ($action == 'reverttodraft') {
403 $this->process_revert_to_draft();
404 $action = 'redirect';
405 $nextpageparams['action'] = 'grading';
406 } else if ($action == 'unlock') {
407 $this->process_unlock_submission();
408 $action = 'redirect';
409 $nextpageparams['action'] = 'grading';
410 } else if ($action == 'setbatchmarkingworkflowstate') {
411 $this->process_set_batch_marking_workflow_state();
412 $action = 'redirect';
413 $nextpageparams['action'] = 'grading';
414 } else if ($action == 'setbatchmarkingallocation') {
415 $this->process_set_batch_marking_allocation();
416 $action = 'redirect';
417 $nextpageparams['action'] = 'grading';
418 } else if ($action == 'confirmsubmit') {
420 if ($this->process_submit_for_grading($mform)) {
421 $action = 'redirect';
422 $nextpageparams['action'] = 'view';
424 } else if ($action == 'gradingbatchoperation') {
425 $action = $this->process_grading_batch_operation($mform);
426 if ($action == 'grading') {
427 $action = 'redirect';
428 $nextpageparams['action'] = 'grading';
430 } else if ($action == 'submitgrade') {
431 if (optional_param('saveandshownext', null, PARAM_RAW)) {
432 // Save and show next.
434 if ($this->process_save_grade($mform)) {
435 $action = 'redirect';
436 $nextpageparams['action'] = 'grade';
437 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
438 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
440 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
441 $action = 'redirect';
442 $nextpageparams['action'] = 'grade';
443 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
444 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
445 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
446 $action = 'redirect';
447 $nextpageparams['action'] = 'grade';
448 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
449 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
450 } else if (optional_param('savegrade', null, PARAM_RAW)) {
451 // Save changes button.
453 if ($this->process_save_grade($mform)) {
454 $message = get_string('gradingchangessaved', 'assign');
455 $action = 'savegradingresult';
459 $action = 'redirect';
460 $nextpageparams['action'] = 'grading';
462 } else if ($action == 'quickgrade') {
463 $message = $this->process_save_quick_grades();
464 $action = 'quickgradingresult';
465 } else if ($action == 'saveoptions') {
466 $this->process_save_grading_options();
467 $action = 'redirect';
468 $nextpageparams['action'] = 'grading';
469 } else if ($action == 'saveextension') {
470 $action = 'grantextension';
471 if ($this->process_save_extension($mform)) {
472 $action = 'redirect';
473 $nextpageparams['action'] = 'grading';
475 } else if ($action == 'revealidentitiesconfirm') {
476 $this->process_reveal_identities();
477 $action = 'redirect';
478 $nextpageparams['action'] = 'grading';
481 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
482 'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
483 $this->register_return_link($action, $returnparams);
485 // Now show the right view page.
486 if ($action == 'redirect') {
487 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
488 redirect($nextpageurl);
490 } else if ($action == 'savegradingresult') {
491 $o .= $this->view_savegrading_result($message);
492 } else if ($action == 'quickgradingresult') {
494 $o .= $this->view_quickgrading_result($message);
495 } else if ($action == 'grade') {
496 $o .= $this->view_single_grade_page($mform);
497 } else if ($action == 'viewpluginassignfeedback') {
498 $o .= $this->view_plugin_content('assignfeedback');
499 } else if ($action == 'viewpluginassignsubmission') {
500 $o .= $this->view_plugin_content('assignsubmission');
501 } else if ($action == 'editsubmission') {
502 $o .= $this->view_edit_submission_page($mform, $notices);
503 } else if ($action == 'grading') {
504 $o .= $this->view_grading_page();
505 } else if ($action == 'downloadall') {
506 $o .= $this->download_submissions();
507 } else if ($action == 'submit') {
508 $o .= $this->check_submit_for_grading($mform);
509 } else if ($action == 'grantextension') {
510 $o .= $this->view_grant_extension($mform);
511 } else if ($action == 'revealidentities') {
512 $o .= $this->view_reveal_identities_confirm($mform);
513 } else if ($action == 'plugingradingbatchoperation') {
514 $o .= $this->view_plugin_grading_batch_operation($mform);
515 } else if ($action == 'viewpluginpage') {
516 $o .= $this->view_plugin_page();
517 } else if ($action == 'viewcourseindex') {
518 $o .= $this->view_course_index();
519 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
520 $o .= $this->view_batch_set_workflow_state($mform);
521 } else if ($action == 'viewbatchmarkingallocation') {
522 $o .= $this->view_batch_markingallocation($mform);
524 $o .= $this->view_submission_page();
531 * Add this instance to the database.
533 * @param stdClass $formdata The data submitted from the form
534 * @param bool $callplugins This is used to skip the plugin code
535 * when upgrading an old assignment to a new one (the plugins get called manually)
536 * @return mixed false if an error occurs or the int id of the new instance
538 public function add_instance(stdClass $formdata, $callplugins) {
543 // Add the database record.
544 $update = new stdClass();
545 $update->name = $formdata->name;
546 $update->timemodified = time();
547 $update->timecreated = time();
548 $update->course = $formdata->course;
549 $update->courseid = $formdata->course;
550 $update->intro = $formdata->intro;
551 $update->introformat = $formdata->introformat;
552 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
553 $update->submissiondrafts = $formdata->submissiondrafts;
554 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
555 $update->sendnotifications = $formdata->sendnotifications;
556 $update->sendlatenotifications = $formdata->sendlatenotifications;
557 $update->duedate = $formdata->duedate;
558 $update->cutoffdate = $formdata->cutoffdate;
559 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
560 $update->grade = $formdata->grade;
561 $update->completionsubmit = !empty($formdata->completionsubmit);
562 $update->teamsubmission = $formdata->teamsubmission;
563 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
564 if (isset($formdata->teamsubmissiongroupingid)) {
565 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
567 $update->blindmarking = $formdata->blindmarking;
568 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
569 if (!empty($formdata->attemptreopenmethod)) {
570 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
572 if (!empty($formdata->maxattempts)) {
573 $update->maxattempts = $formdata->maxattempts;
575 $update->markingworkflow = $formdata->markingworkflow;
576 $update->markingallocation = $formdata->markingallocation;
578 $returnid = $DB->insert_record('assign', $update);
579 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
580 // Cache the course record.
581 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
584 // Call save_settings hook for submission plugins.
585 foreach ($this->submissionplugins as $plugin) {
586 if (!$this->update_plugin_instance($plugin, $formdata)) {
587 print_error($plugin->get_error());
591 foreach ($this->feedbackplugins as $plugin) {
592 if (!$this->update_plugin_instance($plugin, $formdata)) {
593 print_error($plugin->get_error());
598 // In the case of upgrades the coursemodule has not been set,
599 // so we need to wait before calling these two.
600 $this->update_calendar($formdata->coursemodule);
601 $this->update_gradebook(false, $formdata->coursemodule);
605 $update = new stdClass();
606 $update->id = $this->get_instance()->id;
607 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
608 $DB->update_record('assign', $update);
614 * Delete all grades from the gradebook for this assignment.
618 protected function delete_grades() {
621 $result = grade_update('mod/assign',
622 $this->get_course()->id,
625 $this->get_instance()->id,
628 array('deleted'=>1));
629 return $result == GRADE_UPDATE_OK;
633 * Delete this instance from the database.
635 * @return bool false if an error occurs
637 public function delete_instance() {
641 foreach ($this->submissionplugins as $plugin) {
642 if (!$plugin->delete_instance()) {
643 print_error($plugin->get_error());
647 foreach ($this->feedbackplugins as $plugin) {
648 if (!$plugin->delete_instance()) {
649 print_error($plugin->get_error());
654 // Delete files associated with this assignment.
655 $fs = get_file_storage();
656 if (! $fs->delete_area_files($this->context->id) ) {
660 // Delete_records will throw an exception if it fails - so no need for error checking here.
661 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
662 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
663 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
665 // Delete items from the gradebook.
666 if (! $this->delete_grades()) {
670 // Delete the instance.
671 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
677 * Actual implementation of the reset course functionality, delete all the
678 * assignment submissions for course $data->courseid.
680 * @param stdClass $data the data submitted from the reset course.
681 * @return array status array
683 public function reset_userdata($data) {
686 $componentstr = get_string('modulenameplural', 'assign');
689 $fs = get_file_storage();
690 if (!empty($data->reset_assign_submissions)) {
691 // Delete files associated with this assignment.
692 foreach ($this->submissionplugins as $plugin) {
693 $fileareas = array();
694 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
695 $fileareas = $plugin->get_file_areas();
696 foreach ($fileareas as $filearea) {
697 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
700 if (!$plugin->delete_instance()) {
701 $status[] = array('component'=>$componentstr,
702 'item'=>get_string('deleteallsubmissions', 'assign'),
703 'error'=>$plugin->get_error());
707 foreach ($this->feedbackplugins as $plugin) {
708 $fileareas = array();
709 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
710 $fileareas = $plugin->get_file_areas();
711 foreach ($fileareas as $filearea) {
712 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
715 if (!$plugin->delete_instance()) {
716 $status[] = array('component'=>$componentstr,
717 'item'=>get_string('deleteallsubmissions', 'assign'),
718 'error'=>$plugin->get_error());
722 $assignssql = 'SELECT a.id
724 WHERE a.course=:course';
725 $params = array('course'=>$data->courseid);
727 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
729 $status[] = array('component'=>$componentstr,
730 'item'=>get_string('deleteallsubmissions', 'assign'),
733 if (!empty($data->reset_gradebook_grades)) {
734 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
735 // Remove all grades from gradebook.
736 require_once($CFG->dirroot.'/mod/assign/lib.php');
737 assign_reset_gradebook($data->courseid);
740 // Updating dates - shift may be negative too.
741 if ($data->timeshift) {
742 shift_course_mod_dates('assign',
743 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
746 $status[] = array('component'=>$componentstr,
747 'item'=>get_string('datechanged'),
755 * Update the settings for a single plugin.
757 * @param assign_plugin $plugin The plugin to update
758 * @param stdClass $formdata The form data
759 * @return bool false if an error occurs
761 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
762 if ($plugin->is_visible()) {
763 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
764 if (!empty($formdata->$enabledname)) {
766 if (!$plugin->save_settings($formdata)) {
767 print_error($plugin->get_error());
778 * Update the gradebook information for this assignment.
780 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
781 * @param int $coursemoduleid This is required because it might not exist in the database yet
784 public function update_gradebook($reset, $coursemoduleid) {
787 require_once($CFG->dirroot.'/mod/assign/lib.php');
788 $assign = clone $this->get_instance();
789 $assign->cmidnumber = $coursemoduleid;
795 return assign_grade_item_update($assign, $param);
799 * Load and cache the admin config for this module.
801 * @return stdClass the plugin config
803 public function get_admin_config() {
804 if ($this->adminconfig) {
805 return $this->adminconfig;
807 $this->adminconfig = get_config('assign');
808 return $this->adminconfig;
812 * Update the calendar entries for this assignment.
814 * @param int $coursemoduleid - Required to pass this in because it might
815 * not exist in the database yet.
818 public function update_calendar($coursemoduleid) {
820 require_once($CFG->dirroot.'/calendar/lib.php');
822 // Special case for add_instance as the coursemodule has not been set yet.
823 $instance = $this->get_instance();
825 if ($instance->duedate) {
826 $event = new stdClass();
828 $params = array('modulename'=>'assign', 'instance'=>$instance->id);
829 $event->id = $DB->get_field('event',
834 $event->name = $instance->name;
835 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
836 $event->timestart = $instance->duedate;
838 $calendarevent = calendar_event::load($event->id);
839 $calendarevent->update($event);
841 $event = new stdClass();
842 $event->name = $instance->name;
843 $event->description = format_module_intro('assign', $instance, $coursemoduleid);
844 $event->courseid = $instance->course;
847 $event->modulename = 'assign';
848 $event->instance = $instance->id;
849 $event->eventtype = 'due';
850 $event->timestart = $instance->duedate;
851 $event->timeduration = 0;
853 calendar_event::create($event);
856 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
862 * Update this instance in the database.
864 * @param stdClass $formdata - the data submitted from the form
865 * @return bool false if an error occurs
867 public function update_instance($formdata) {
870 $update = new stdClass();
871 $update->id = $formdata->instance;
872 $update->name = $formdata->name;
873 $update->timemodified = time();
874 $update->course = $formdata->course;
875 $update->intro = $formdata->intro;
876 $update->introformat = $formdata->introformat;
877 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
878 $update->submissiondrafts = $formdata->submissiondrafts;
879 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
880 $update->sendnotifications = $formdata->sendnotifications;
881 $update->sendlatenotifications = $formdata->sendlatenotifications;
882 $update->duedate = $formdata->duedate;
883 $update->cutoffdate = $formdata->cutoffdate;
884 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
885 $update->grade = $formdata->grade;
886 if (!empty($formdata->completionunlocked)) {
887 $update->completionsubmit = !empty($formdata->completionsubmit);
889 $update->teamsubmission = $formdata->teamsubmission;
890 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
891 if (isset($formdata->teamsubmissiongroupingid)) {
892 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
894 $update->blindmarking = $formdata->blindmarking;
895 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
896 if (!empty($formdata->attemptreopenmethod)) {
897 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
899 if (!empty($formdata->maxattempts)) {
900 $update->maxattempts = $formdata->maxattempts;
902 $update->markingworkflow = $formdata->markingworkflow;
903 $update->markingallocation = $formdata->markingallocation;
905 $result = $DB->update_record('assign', $update);
906 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
908 // Load the assignment so the plugins have access to it.
910 // Call save_settings hook for submission plugins.
911 foreach ($this->submissionplugins as $plugin) {
912 if (!$this->update_plugin_instance($plugin, $formdata)) {
913 print_error($plugin->get_error());
917 foreach ($this->feedbackplugins as $plugin) {
918 if (!$this->update_plugin_instance($plugin, $formdata)) {
919 print_error($plugin->get_error());
924 $this->update_calendar($this->get_course_module()->id);
925 $this->update_gradebook(false, $this->get_course_module()->id);
927 $update = new stdClass();
928 $update->id = $this->get_instance()->id;
929 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
930 $DB->update_record('assign', $update);
936 * Add elements in grading plugin form.
938 * @param mixed $grade stdClass|null
939 * @param MoodleQuickForm $mform
940 * @param stdClass $data
941 * @param int $userid - The userid we are grading
944 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
945 foreach ($this->feedbackplugins as $plugin) {
946 if ($plugin->is_enabled() && $plugin->is_visible()) {
947 $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
948 $mform->setExpanded('header_' . $plugin->get_type());
949 if (!$plugin->get_form_elements_for_user($grade, $mform, $data, $userid)) {
950 $mform->removeElement('header_' . $plugin->get_type());
959 * Add one plugins settings to edit plugin form.
961 * @param assign_plugin $plugin The plugin to add the settings from
962 * @param MoodleQuickForm $mform The form to add the configuration settings to.
963 * This form is modified directly (not returned).
964 * @param array $pluginsenabled A list of form elements to be added to a group.
965 * The new element is added to this array by this function.
968 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
970 if ($plugin->is_visible()) {
972 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
973 $label = $plugin->get_name();
974 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
975 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
977 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
978 if ($plugin->get_config('enabled') !== false) {
979 $default = $plugin->is_enabled();
981 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
983 $plugin->get_settings($mform);
989 * Add settings to edit plugin form.
991 * @param MoodleQuickForm $mform The form to add the configuration settings to.
992 * This form is modified directly (not returned).
995 public function add_all_plugin_settings(MoodleQuickForm $mform) {
996 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
998 $submissionpluginsenabled = array();
999 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1000 foreach ($this->submissionplugins as $plugin) {
1001 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1003 $group->setElements($submissionpluginsenabled);
1005 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1006 $feedbackpluginsenabled = array();
1007 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1008 foreach ($this->feedbackplugins as $plugin) {
1009 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1011 $group->setElements($feedbackpluginsenabled);
1012 $mform->setExpanded('submissiontypes');
1016 * Allow each plugin an opportunity to update the defaultvalues
1017 * passed in to the settings form (needed to set up draft areas for
1018 * editor and filemanager elements)
1020 * @param array $defaultvalues
1022 public function plugin_data_preprocessing(&$defaultvalues) {
1023 foreach ($this->submissionplugins as $plugin) {
1024 if ($plugin->is_visible()) {
1025 $plugin->data_preprocessing($defaultvalues);
1028 foreach ($this->feedbackplugins as $plugin) {
1029 if ($plugin->is_visible()) {
1030 $plugin->data_preprocessing($defaultvalues);
1036 * Get the name of the current module.
1038 * @return string the module name (Assignment)
1040 protected function get_module_name() {
1041 if (isset(self::$modulename)) {
1042 return self::$modulename;
1044 self::$modulename = get_string('modulename', 'assign');
1045 return self::$modulename;
1049 * Get the plural name of the current module.
1051 * @return string the module name plural (Assignments)
1053 protected function get_module_name_plural() {
1054 if (isset(self::$modulenameplural)) {
1055 return self::$modulenameplural;
1057 self::$modulenameplural = get_string('modulenameplural', 'assign');
1058 return self::$modulenameplural;
1062 * Has this assignment been constructed from an instance?
1066 public function has_instance() {
1067 return $this->instance || $this->get_course_module();
1071 * Get the settings for the current instance of this assignment
1073 * @return stdClass The settings
1075 public function get_instance() {
1077 if ($this->instance) {
1078 return $this->instance;
1080 if ($this->get_course_module()) {
1081 $params = array('id' => $this->get_course_module()->instance);
1082 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1084 if (!$this->instance) {
1085 throw new coding_exception('Improper use of the assignment class. ' .
1086 'Cannot load the assignment record.');
1088 return $this->instance;
1092 * Get the primary grade item for this assign instance.
1094 * @return stdClass The grade_item record
1096 public function get_grade_item() {
1097 if ($this->gradeitem) {
1098 return $this->gradeitem;
1100 $instance = $this->get_instance();
1101 $params = array('itemtype' => 'mod',
1102 'itemmodule' => 'assign',
1103 'iteminstance' => $instance->id,
1104 'courseid' => $instance->course,
1106 $this->gradeitem = grade_item::fetch($params);
1107 if (!$this->gradeitem) {
1108 throw new coding_exception('Improper use of the assignment class. ' .
1109 'Cannot load the grade item.');
1111 return $this->gradeitem;
1115 * Get the context of the current course.
1117 * @return mixed context|null The course context
1119 public function get_course_context() {
1120 if (!$this->context && !$this->course) {
1121 throw new coding_exception('Improper use of the assignment class. ' .
1122 'Cannot load the course context.');
1124 if ($this->context) {
1125 return $this->context->get_course_context();
1127 return context_course::instance($this->course->id);
1133 * Get the current course module.
1135 * @return mixed stdClass|null The course module
1137 public function get_course_module() {
1138 if ($this->coursemodule) {
1139 return $this->coursemodule;
1141 if (!$this->context) {
1145 if ($this->context->contextlevel == CONTEXT_MODULE) {
1146 $this->coursemodule = get_coursemodule_from_id('assign',
1147 $this->context->instanceid,
1151 return $this->coursemodule;
1157 * Get context module.
1161 public function get_context() {
1162 return $this->context;
1166 * Get the current course.
1168 * @return mixed stdClass|null The course
1170 public function get_course() {
1173 if ($this->course) {
1174 return $this->course;
1177 if (!$this->context) {
1180 $params = array('id' => $this->get_course_context()->instanceid);
1181 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1183 return $this->course;
1187 * Return a grade in user-friendly form, whether it's a scale or not.
1189 * @param mixed $grade int|null
1190 * @param boolean $editing Are we allowing changes to this grade?
1191 * @param int $userid The user id the grade belongs to
1192 * @param int $modified Timestamp from when the grade was last modified
1193 * @return string User-friendly representation of grade
1195 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1198 static $scalegrades = array();
1202 if ($this->get_instance()->grade >= 0) {
1204 if ($editing && $this->get_instance()->grade > 0) {
1208 $displaygrade = format_float($grade, 2);
1210 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1211 get_string('usergrade', 'assign') .
1213 $o .= '<input type="text"
1214 id="quickgrade_' . $userid . '"
1215 name="quickgrade_' . $userid . '"
1216 value="' . $displaygrade . '"
1219 class="quickgrade"/>';
1220 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1221 $o .= '<input type="hidden"
1222 name="grademodified_' . $userid . '"
1223 value="' . $modified . '"/>';
1226 $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
1227 if ($grade == -1 || $grade === null) {
1230 $item = $this->get_grade_item();
1231 $o .= grade_format_gradevalue($grade, $item);
1232 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1233 // If displaying the raw grade, also display the total value.
1234 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1242 if (empty($this->cache['scale'])) {
1243 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1244 $this->cache['scale'] = make_menu_from_list($scale->scale);
1251 $o .= '<label class="accesshide"
1252 for="quickgrade_' . $userid . '">' .
1253 get_string('usergrade', 'assign') .
1255 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1256 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1257 foreach ($this->cache['scale'] as $optionid => $option) {
1259 if ($grade == $optionid) {
1260 $selected = 'selected="selected"';
1262 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1265 $o .= '<input type="hidden" ' .
1266 'name="grademodified_' . $userid . '" ' .
1267 'value="' . $modified . '"/>';
1270 $scaleid = (int)$grade;
1271 if (isset($this->cache['scale'][$scaleid])) {
1272 $o .= $this->cache['scale'][$scaleid];
1282 * Load a list of users enrolled in the current course with the specified permission and group.
1285 * @param int $currentgroup
1286 * @param bool $idsonly
1287 * @return array List of user records
1289 public function list_participants($currentgroup, $idsonly) {
1291 $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.id', null, null, null,
1292 $this->show_only_active_users());
1294 $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1295 $this->show_only_active_users());
1298 $cm = $this->get_course_module();
1299 foreach ($users as $userid => $user) {
1300 if (!groups_course_module_visible($cm, $userid)) {
1301 unset($users[$userid]);
1309 * Load a count of valid teams for this assignment.
1311 * @return int number of valid teams
1313 public function count_teams() {
1315 $groups = groups_get_all_groups($this->get_course()->id,
1317 $this->get_instance()->teamsubmissiongroupingid,
1319 $count = count($groups);
1321 // See if there are any users in the default group.
1322 $defaultusers = $this->get_submission_group_members(0, true);
1323 if (count($defaultusers) > 0) {
1330 * Load a count of active users enrolled in the current course with the specified permission and group.
1333 * @param int $currentgroup
1334 * @return int number of matching users
1336 public function count_participants($currentgroup) {
1337 return count($this->list_participants($currentgroup, true));
1341 * Load a count of active users submissions in the current module that require grading
1342 * This means the submission modification time is more recent than the
1343 * grading modification time and the status is SUBMITTED.
1345 * @return int number of matching submissions
1347 public function count_submissions_need_grading() {
1350 if ($this->get_instance()->teamsubmission) {
1351 // This does not make sense for group assignment because the submission is shared.
1355 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1356 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1358 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1359 FROM {assign_submission} mxs
1360 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1361 $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1362 FROM {assign_grades} mxg
1363 WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1365 $params['assignid'] = $this->get_instance()->id;
1366 $params['assignid2'] = $this->get_instance()->id;
1367 $params['assignid3'] = $this->get_instance()->id;
1368 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1370 $sql = 'SELECT COUNT(s.userid)
1371 FROM {assign_submission} s
1372 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1373 LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1374 LEFT JOIN {assign_grades} g ON
1375 s.assignment = g.assignment AND
1376 s.userid = g.userid AND
1377 g.attemptnumber = gmx.maxattempt
1378 JOIN(' . $esql . ') e ON e.id = s.userid
1380 s.attemptnumber = smx.maxattempt AND
1381 s.assignment = :assignid AND
1382 s.timemodified IS NOT NULL AND
1383 s.status = :submitted AND
1384 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1386 return $DB->count_records_sql($sql, $params);
1390 * Load a count of grades.
1392 * @return int number of grades
1394 public function count_grades() {
1397 if (!$this->has_instance()) {
1401 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1402 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1404 $params['assignid'] = $this->get_instance()->id;
1406 $sql = 'SELECT COUNT(g.userid)
1407 FROM {assign_grades} g
1408 JOIN(' . $esql . ') e ON e.id = g.userid
1409 WHERE g.assignment = :assignid';
1411 return $DB->count_records_sql($sql, $params);
1415 * Load a count of submissions.
1417 * @return int number of submissions
1419 public function count_submissions() {
1422 if (!$this->has_instance()) {
1428 if ($this->get_instance()->teamsubmission) {
1429 // We cannot join on the enrolment tables for group submissions (no userid).
1430 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1431 FROM {assign_submission} s
1433 s.assignment = :assignid AND
1434 s.timemodified IS NOT NULL AND
1435 s.userid = :groupuserid';
1437 $params['assignid'] = $this->get_instance()->id;
1438 $params['groupuserid'] = 0;
1440 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1441 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1443 $params['assignid'] = $this->get_instance()->id;
1445 $sql = 'SELECT COUNT(DISTINCT s.userid)
1446 FROM {assign_submission} s
1447 JOIN(' . $esql . ') e ON e.id = s.userid
1449 s.assignment = :assignid AND
1450 s.timemodified IS NOT NULL';
1454 return $DB->count_records_sql($sql, $params);
1458 * Load a count of submissions with a specified status.
1460 * @param string $status The submission status - should match one of the constants
1461 * @return int number of matching submissions
1463 public function count_submissions_with_status($status) {
1466 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1467 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1469 $params['assignid'] = $this->get_instance()->id;
1470 $params['assignid2'] = $this->get_instance()->id;
1471 $params['submissionstatus'] = $status;
1473 if ($this->get_instance()->teamsubmission) {
1474 $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1475 FROM {assign_submission} mxs
1476 WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1478 $sql = 'SELECT COUNT(s.groupid)
1479 FROM {assign_submission} s
1480 JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1482 s.attemptnumber = smx.maxattempt AND
1483 s.assignment = :assignid AND
1484 s.timemodified IS NOT NULL AND
1485 s.userid = :groupuserid AND
1486 s.status = :submissionstatus';
1487 $params['groupuserid'] = 0;
1489 $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1490 FROM {assign_submission} mxs
1491 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1493 $sql = 'SELECT COUNT(s.userid)
1494 FROM {assign_submission} s
1495 JOIN(' . $esql . ') e ON e.id = s.userid
1496 JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1498 s.attemptnumber = smx.maxattempt AND
1499 s.assignment = :assignid AND
1500 s.timemodified IS NOT NULL AND
1501 s.status = :submissionstatus';
1505 return $DB->count_records_sql($sql, $params);
1509 * Utility function to get the userid for every row in the grading table
1510 * so the order can be frozen while we iterate it.
1512 * @return array An array of userids
1514 protected function get_grading_userid_list() {
1515 $filter = get_user_preferences('assign_filter', '');
1516 $table = new assign_grading_table($this, 0, $filter, 0, false);
1518 $useridlist = $table->get_column_data('userid');
1524 * Generate zip file from array of given files.
1526 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1527 * This array is indexed by the final file name and each
1528 * element in the array is an instance of a stored_file object.
1529 * @return path of temp file - note this returned file does
1530 * not have a .zip extension - it is a temp file.
1532 protected function pack_files($filesforzipping) {
1534 // Create path for new zip file.
1535 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1537 $zipper = new zip_packer();
1538 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1545 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1547 * Cron function to be run periodically according to the moodle cron.
1551 public static function cron() {
1554 // Only ever send a max of one days worth of updates.
1555 $yesterday = time() - (24 * 3600);
1558 // Collect all submissions from the past 24 hours that require mailing.
1559 $sql = 'SELECT a.course, a.name, a.blindmarking, a.revealidentities,
1560 g.*, g.id as gradeid, g.timemodified as lastmodified
1562 JOIN {assign_grades} g ON g.assignment = a.id
1563 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1564 WHERE g.timemodified >= :yesterday AND
1565 g.timemodified <= :today AND
1568 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1569 $submissions = $DB->get_records_sql($sql, $params);
1571 if (empty($submissions)) {
1575 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1577 // Preload courses we are going to need those.
1578 $courseids = array();
1579 foreach ($submissions as $submission) {
1580 $courseids[] = $submission->course;
1583 // Filter out duplicates.
1584 $courseids = array_unique($courseids);
1585 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1586 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1587 $sql = 'SELECT c.*, ' . $ctxselect .
1589 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1590 WHERE c.id ' . $courseidsql;
1592 $params['contextlevel'] = CONTEXT_COURSE;
1593 $courses = $DB->get_records_sql($sql, $params);
1595 // Clean up... this could go on for a while.
1598 unset($courseidsql);
1601 // Simple array we'll use for caching modules.
1602 $modcache = array();
1604 // Message students about new feedback.
1605 foreach ($submissions as $submission) {
1607 mtrace("Processing assignment submission $submission->id ...");
1609 // Do not cache user lookups - could be too many.
1610 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1611 mtrace('Could not find user ' . $submission->userid);
1615 // Use a cache to prevent the same DB queries happening over and over.
1616 if (!array_key_exists($submission->course, $courses)) {
1617 mtrace('Could not find course ' . $submission->course);
1620 $course = $courses[$submission->course];
1621 if (isset($course->ctxid)) {
1622 // Context has not yet been preloaded. Do so now.
1623 context_helper::preload_from_record($course);
1626 // Override the language and timezone of the "current" user, so that
1627 // mail is customised for the receiver.
1628 cron_setup_user($user, $course);
1630 // Context lookups are already cached.
1631 $coursecontext = context_course::instance($course->id);
1632 if (!is_enrolled($coursecontext, $user->id)) {
1633 $courseshortname = format_string($course->shortname,
1635 array('context' => $coursecontext));
1636 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1640 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1641 mtrace('Could not find grader ' . $submission->grader);
1645 if (!array_key_exists($submission->assignment, $modcache)) {
1646 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1648 mtrace('Could not find course module for assignment id ' . $submission->assignment);
1651 $modcache[$submission->assignment] = $mod;
1653 $mod = $modcache[$submission->assignment];
1655 // Context lookups are already cached.
1656 $contextmodule = context_module::instance($mod->id);
1658 if (!$mod->visible) {
1659 // Hold mail notification for hidden assignments until later.
1663 // Need to send this to the student.
1664 $messagetype = 'feedbackavailable';
1665 $eventtype = 'assign_notification';
1666 $updatetime = $submission->lastmodified;
1667 $modulename = get_string('modulename', 'assign');
1670 if ($submission->blindmarking && !$submission->revealidentities) {
1671 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1673 $showusers = $submission->blindmarking && !$submission->revealidentities;
1674 self::send_assignment_notification($grader,
1687 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1690 $DB->update_record('assign_user_flags', $flags);
1692 $flags = new stdClass();
1693 $flags->userid = $user->id;
1694 $flags->assignment = $submission->assignment;
1696 $DB->insert_record('assign_user_flags', $flags);
1701 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1705 // Free up memory just to be sure.
1713 * Mark in the database that this grade record should have an update notification sent by cron.
1715 * @param stdClass $grade a grade record keyed on id
1716 * @return bool true for success
1718 public function notify_grade_modified($grade) {
1721 $flags = $this->get_user_flags($grade->userid, true);
1722 if ($flags->mailed != 1) {
1726 return $this->update_user_flags($flags);
1730 * Update user flags for this user in this assignment.
1732 * @param stdClass $flags a flags record keyed on id
1733 * @return bool true for success
1735 public function update_user_flags($flags) {
1737 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1741 $result = $DB->update_record('assign_user_flags', $flags);
1746 * Update a grade in the grade table for the assignment and in the gradebook.
1748 * @param stdClass $grade a grade record keyed on id
1749 * @return bool true for success
1751 public function update_grade($grade) {
1754 $grade->timemodified = time();
1756 if (!empty($grade->workflowstate)) {
1757 $validstates = $this->get_marking_workflow_states_for_current_user();
1758 if (!array_key_exists($grade->workflowstate, $validstates)) {
1763 if ($grade->grade && $grade->grade != -1) {
1764 if ($this->get_instance()->grade > 0) {
1765 if (!is_numeric($grade->grade)) {
1767 } else if ($grade->grade > $this->get_instance()->grade) {
1769 } else if ($grade->grade < 0) {
1774 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1775 $scaleoptions = make_menu_from_list($scale->scale);
1776 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1783 if (empty($grade->attemptnumber)) {
1784 // Set it to the default.
1785 $grade->attemptnumber = 0;
1787 $result = $DB->update_record('assign_grades', $grade);
1789 // Only push to gradebook if the update is for the latest attempt.
1791 if ($this->get_instance()->teamsubmission) {
1792 $submission = $this->get_group_submission($grade->userid, 0, false);
1794 $submission = $this->get_user_submission($grade->userid, false);
1796 // Not the latest attempt.
1797 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1802 $this->gradebook_item_update(null, $grade);
1808 * View the grant extension date page.
1810 * Uses url parameters 'userid'
1811 * or from parameter 'selectedusers'
1813 * @param moodleform $mform - Used for validation of the submitted data
1816 protected function view_grant_extension($mform) {
1818 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1821 $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1822 $data = new stdClass();
1823 $data->extensionduedate = null;
1826 $userid = required_param('userid', PARAM_INT);
1828 $grade = $this->get_user_grade($userid, false);
1830 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1833 $data->extensionduedate = $grade->extensionduedate;
1835 $data->userid = $userid;
1837 $data->batchusers = $batchusers;
1839 $header = new assign_header($this->get_instance(),
1840 $this->get_context(),
1841 $this->show_intro(),
1842 $this->get_course_module()->id,
1843 get_string('grantextension', 'assign'));
1844 $o .= $this->get_renderer()->render($header);
1847 $formparams = array($this->get_course_module()->id,
1850 $this->get_instance(),
1852 $mform = new mod_assign_extension_form(null, $formparams);
1854 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1855 $o .= $this->view_footer();
1860 * Get a list of the users in the same group as this user.
1862 * @param int $groupid The id of the group whose members we want or 0 for the default group
1863 * @param bool $onlyids Whether to retrieve only the user id's
1864 * @return array The users (possibly id's only)
1866 public function get_submission_group_members($groupid, $onlyids) {
1868 if ($groupid != 0) {
1870 $allusers = groups_get_members($groupid, 'u.id');
1872 $allusers = groups_get_members($groupid);
1874 foreach ($allusers as $user) {
1875 if ($this->get_submission_group($user->id)) {
1880 $allusers = $this->list_participants(null, $onlyids);
1881 foreach ($allusers as $user) {
1882 if ($this->get_submission_group($user->id) == null) {
1887 // Exclude suspended users, if user can't see them.
1888 if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1889 foreach ($members as $key => $member) {
1890 if (!$this->is_active_user($member->id)) {
1891 unset($members[$key]);
1899 * Get a list of the users in the same group as this user that have not submitted the assignment.
1901 * @param int $groupid The id of the group whose members we want or 0 for the default group
1902 * @param bool $onlyids Whether to retrieve only the user id's
1903 * @return array The users (possibly id's only)
1905 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1906 $instance = $this->get_instance();
1907 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1910 $members = $this->get_submission_group_members($groupid, $onlyids);
1912 foreach ($members as $id => $member) {
1913 $submission = $this->get_user_submission($member->id, false);
1914 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1915 unset($members[$id]);
1917 if ($this->is_blind_marking()) {
1918 $members[$id]->alias = get_string('hiddenuser', 'assign') .
1919 $this->get_uniqueid_for_user($id);
1927 * Load the group submission object for a particular user, optionally creating it if required.
1929 * @param int $userid The id of the user whose submission we want
1930 * @param int $groupid The id of the group for this user - may be 0 in which
1931 * case it is determined from the userid.
1932 * @param bool $create If set to true a new submission object will be created in the database
1933 * @param int $attemptnumber - -1 means the latest attempt
1934 * @return stdClass The submission
1936 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1939 if ($groupid == 0) {
1940 $group = $this->get_submission_group($userid);
1942 $groupid = $group->id;
1946 // Now get the group submission.
1947 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1948 if ($attemptnumber >= 0) {
1949 $params['attemptnumber'] = $attemptnumber;
1952 // Only return the row with the highest attemptnumber.
1954 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1956 $submission = reset($submissions);
1963 $submission = new stdClass();
1964 $submission->assignment = $this->get_instance()->id;
1965 $submission->userid = 0;
1966 $submission->groupid = $groupid;
1967 $submission->timecreated = time();
1968 $submission->timemodified = $submission->timecreated;
1969 if ($attemptnumber >= 0) {
1970 $submission->attemptnumber = $attemptnumber;
1972 $submission->attemptnumber = 0;
1975 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
1976 $sid = $DB->insert_record('assign_submission', $submission);
1977 $submission->id = $sid;
1984 * View a summary listing of all assignments in the current course.
1988 private function view_course_index() {
1993 $course = $this->get_course();
1994 $strplural = get_string('modulenameplural', 'assign');
1996 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
1997 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
1998 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2002 $strsectionname = get_string('sectionname', 'format_'.$course->format);
2003 $usesections = course_format_uses_sections($course->format);
2004 $modinfo = get_fast_modinfo($course);
2007 $sections = $modinfo->get_section_info_all();
2009 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2013 $currentsection = '';
2014 foreach ($modinfo->instances['assign'] as $cm) {
2015 if (!$cm->uservisible) {
2019 $timedue = $cms[$cm->id]->duedate;
2022 if ($usesections && $cm->sectionnum) {
2023 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2027 $context = context_module::instance($cm->id);
2029 $assignment = new assign($context, $cm, $course);
2031 if (has_capability('mod/assign:grade', $context)) {
2032 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2034 } else if (has_capability('mod/assign:submit', $context)) {
2035 $usersubmission = $assignment->get_user_submission($USER->id, false);
2037 if (!empty($usersubmission->status)) {
2038 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2040 $submitted = get_string('submissionstatus_', 'assign');
2043 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2044 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2045 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2046 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2051 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2055 $o .= $this->get_renderer()->render($courseindexsummary);
2056 $o .= $this->view_footer();
2062 * View a page rendered by a plugin.
2064 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2068 protected function view_plugin_page() {
2073 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2074 $plugintype = required_param('plugin', PARAM_TEXT);
2075 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2077 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2079 print_error('invalidformdata', '');
2083 $o .= $plugin->view_page($pluginaction);
2090 * This is used for team assignments to get the group for the specified user.
2091 * If the user is a member of multiple or no groups this will return false
2093 * @param int $userid The id of the user whose submission we want
2094 * @return mixed The group or false
2096 public function get_submission_group($userid) {
2097 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2098 $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2099 if (count($groups) != 1) {
2102 return array_pop($groups);
2107 * Display the submission that is used by a plugin.
2109 * Uses url parameters 'sid', 'gid' and 'plugin'.
2111 * @param string $pluginsubtype
2114 protected function view_plugin_content($pluginsubtype) {
2119 $submissionid = optional_param('sid', 0, PARAM_INT);
2120 $gradeid = optional_param('gid', 0, PARAM_INT);
2121 $plugintype = required_param('plugin', PARAM_TEXT);
2123 if ($pluginsubtype == 'assignsubmission') {
2124 $plugin = $this->get_submission_plugin_by_type($plugintype);
2125 if ($submissionid <= 0) {
2126 throw new coding_exception('Submission id should not be 0');
2128 $item = $this->get_submission($submissionid);
2130 // Check permissions.
2131 if ($item->userid != $USER->id) {
2132 require_capability('mod/assign:grade', $this->context);
2134 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2135 $this->get_context(),
2136 $this->show_intro(),
2137 $this->get_course_module()->id,
2138 $plugin->get_name()));
2139 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2141 assign_submission_plugin_submission::FULL,
2142 $this->get_course_module()->id,
2143 $this->get_return_action(),
2144 $this->get_return_params()));
2146 $logmessage = get_string('viewsubmissionforuser', 'assign', $item->userid);
2147 $this->add_to_log('view submission', $logmessage);
2149 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2150 if ($gradeid <= 0) {
2151 throw new coding_exception('Grade id should not be 0');
2153 $item = $this->get_grade($gradeid);
2154 // Check permissions.
2155 if ($item->userid != $USER->id) {
2156 require_capability('mod/assign:grade', $this->context);
2158 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2159 $this->get_context(),
2160 $this->show_intro(),
2161 $this->get_course_module()->id,
2162 $plugin->get_name()));
2163 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2165 assign_feedback_plugin_feedback::FULL,
2166 $this->get_course_module()->id,
2167 $this->get_return_action(),
2168 $this->get_return_params()));
2169 $logmessage = get_string('viewfeedbackforuser', 'assign', $item->userid);
2170 $this->add_to_log('view feedback', $logmessage);
2173 $o .= $this->view_return_links();
2175 $o .= $this->view_footer();
2180 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2182 * @param string $text - The replacement text
2183 * @param stdClass $user - The user record
2184 * @param assign_plugin $plugin - The assignment plugin
2186 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2187 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2190 $groupid = groups_get_activity_group($this->get_course_module(), true);
2191 $groupname = groups_get_group_name($groupid).'-';
2194 if ($this->is_blind_marking()) {
2195 $prefix = $groupname . get_string('participant', 'assign');
2196 $prefix = str_replace('_', ' ', $prefix);
2197 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2199 $prefix = $groupname . fullname($user);
2200 $prefix = str_replace('_', ' ', $prefix);
2201 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2204 $subtype = $plugin->get_subtype();
2205 $type = $plugin->get_type();
2206 $prefix = $prefix . $subtype . '_' . $type . '_';
2208 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2214 * Render the content in editor that is often used by plugin.
2216 * @param string $filearea
2217 * @param int $submissionid
2218 * @param string $plugintype
2219 * @param string $editor
2220 * @param string $component
2223 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2228 $plugin = $this->get_submission_plugin_by_type($plugintype);
2230 $text = $plugin->get_editor_text($editor, $submissionid);
2231 $format = $plugin->get_editor_format($editor, $submissionid);
2233 $finaltext = file_rewrite_pluginfile_urls($text,
2235 $this->get_context()->id,
2239 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2240 $result .= format_text($finaltext, $format, $params);
2242 if ($CFG->enableportfolios) {
2243 require_once($CFG->libdir . '/portfoliolib.php');
2245 $button = new portfolio_add_button();
2246 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2247 'sid' => $submissionid,
2248 'plugin' => $plugintype,
2249 'editor' => $editor,
2251 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2252 $fs = get_file_storage();
2254 if ($files = $fs->get_area_files($this->context->id,
2260 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2262 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2264 $result .= $button->to_html();
2270 * Display a continue page.
2272 * @param string $message - The message to display
2275 protected function view_savegrading_result($message) {
2277 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2278 $this->get_context(),
2279 $this->show_intro(),
2280 $this->get_course_module()->id,
2281 get_string('savegradingresult', 'assign')));
2282 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2284 $this->get_course_module()->id);
2285 $o .= $this->get_renderer()->render($gradingresult);
2286 $o .= $this->view_footer();
2290 * Display a grading error.
2292 * @param string $message - The description of the result
2295 protected function view_quickgrading_result($message) {
2297 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2298 $this->get_context(),
2299 $this->show_intro(),
2300 $this->get_course_module()->id,
2301 get_string('quickgradingresult', 'assign')));
2302 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2304 $this->get_course_module()->id);
2305 $o .= $this->get_renderer()->render($gradingresult);
2306 $o .= $this->view_footer();
2311 * Display the page footer.
2315 protected function view_footer() {
2316 return $this->get_renderer()->render_footer();
2320 * Does this user have grade permission for this assignment?
2324 public function can_grade() {
2325 // Permissions check.
2326 if (!has_capability('mod/assign:grade', $this->context)) {
2334 * Download a zip file of all assignment submissions.
2336 * @return string - If an error occurs, this will contain the error page.
2338 protected function download_submissions() {
2341 // More efficient to load this here.
2342 require_once($CFG->libdir.'/filelib.php');
2344 require_capability('mod/assign:grade', $this->context);
2346 // Load all users with submit.
2347 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2348 $this->show_only_active_users());
2350 // Build a list of files to zip.
2351 $filesforzipping = array();
2352 $fs = get_file_storage();
2354 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2359 $groupid = groups_get_activity_group($this->get_course_module(), true);
2360 $groupname = groups_get_group_name($groupid).'-';
2363 // Construct the zip file name.
2364 $filename = clean_filename($this->get_course()->shortname . '-' .
2365 $this->get_instance()->name . '-' .
2366 $groupname.$this->get_course_module()->id . '.zip');
2368 // Get all the files for each student.
2369 foreach ($students as $student) {
2370 $userid = $student->id;
2372 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2373 // Get the plugins to add their own files to the zip.
2375 $submissiongroup = false;
2377 if ($this->get_instance()->teamsubmission) {
2378 $submission = $this->get_group_submission($userid, 0, false);
2379 $submissiongroup = $this->get_submission_group($userid);
2380 if ($submissiongroup) {
2381 $groupname = $submissiongroup->name . '-';
2383 $groupname = get_string('defaultteam', 'assign') . '-';
2386 $submission = $this->get_user_submission($userid, false);
2389 if ($this->is_blind_marking()) {
2390 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2391 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2393 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2394 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2398 foreach ($this->submissionplugins as $plugin) {
2399 if ($plugin->is_enabled() && $plugin->is_visible()) {
2400 $pluginfiles = $plugin->get_files($submission, $student);
2401 foreach ($pluginfiles as $zipfilename => $file) {
2402 $subtype = $plugin->get_subtype();
2403 $type = $plugin->get_type();
2404 $prefixedfilename = clean_filename($prefix .
2410 $filesforzipping[$prefixedfilename] = $file;
2418 if (count($filesforzipping) == 0) {
2419 $header = new assign_header($this->get_instance(),
2420 $this->get_context(),
2422 $this->get_course_module()->id,
2423 get_string('downloadall', 'assign'));
2424 $result .= $this->get_renderer()->render($header);
2425 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2426 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2427 'action'=>'grading'));
2428 $result .= $this->get_renderer()->continue_button($url);
2429 $result .= $this->view_footer();
2430 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2431 $addtolog = $this->add_to_log('download all submissions', get_string('downloadall', 'assign'), '', true);
2433 'context' => $this->context,
2434 'objectid' => $this->get_instance()->id
2436 $event = \mod_assign\event\all_submissions_downloaded::create($params);
2437 $event->set_legacy_logdata($addtolog);
2439 // Send file and delete after sending.
2440 send_temp_file($zipfile, $filename);
2441 // We will not get here - send_temp_file calls exit.
2447 * Util function to add a message to the log.
2449 * @param string $action The current action
2450 * @param string $info A detailed description of the change. But no more than 255 characters.
2451 * @param string $url The url to the assign module instance.
2452 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2453 * retrieve the arguments to use them with the new event system (Event 2).
2454 * @return void|array
2456 public function add_to_log($action = '', $info = '', $url='', $return = false) {
2459 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2461 $fullurl .= '&' . $url;
2465 $this->get_course()->id,
2470 $this->get_course_module()->id,
2477 call_user_func_array('add_to_log', $args);
2481 * Lazy load the page renderer and expose the renderer to plugins.
2483 * @return assign_renderer
2485 public function get_renderer() {
2487 if ($this->output) {
2488 return $this->output;
2490 $this->output = $PAGE->get_renderer('mod_assign');
2491 return $this->output;
2495 * Load the submission object for a particular user, optionally creating it if required.
2497 * For team assignments there are 2 submissions - the student submission and the team submission
2498 * All files are associated with the team submission but the status of the students contribution is
2499 * recorded separately.
2501 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2502 * @param bool $create optional - defaults to false. If set to true a new submission object
2503 * will be created in the database.
2504 * @param int $attemptnumber - -1 means the latest attempt
2505 * @return stdClass The submission
2507 public function get_user_submission($userid, $create, $attemptnumber=-1) {
2511 $userid = $USER->id;
2513 // If the userid is not null then use userid.
2514 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2515 if ($attemptnumber >= 0) {
2516 $params['attemptnumber'] = $attemptnumber;
2519 // Only return the row with the highest attemptnumber.
2521 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2523 $submission = reset($submissions);
2530 $submission = new stdClass();
2531 $submission->assignment = $this->get_instance()->id;
2532 $submission->userid = $userid;
2533 $submission->timecreated = time();
2534 $submission->timemodified = $submission->timecreated;
2535 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2536 if ($attemptnumber >= 0) {
2537 $submission->attemptnumber = $attemptnumber;
2539 $submission->attemptnumber = 0;
2541 $sid = $DB->insert_record('assign_submission', $submission);
2542 $submission->id = $sid;
2549 * Load the submission object from it's id.
2551 * @param int $submissionid The id of the submission we want
2552 * @return stdClass The submission
2554 protected function get_submission($submissionid) {
2557 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2558 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2562 * This will retrieve a user flags object from the db optionally creating it if required.
2563 * The user flags was split from the user_grades table in 2.5.
2565 * @param int $userid The user we are getting the flags for.
2566 * @param bool $create If true the flags record will be created if it does not exist
2567 * @return stdClass The flags record
2569 public function get_user_flags($userid, $create) {
2572 // If the userid is not null then use userid.
2574 $userid = $USER->id;
2577 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2579 $flags = $DB->get_record('assign_user_flags', $params);
2585 $flags = new stdClass();
2586 $flags->assignment = $this->get_instance()->id;
2587 $flags->userid = $userid;
2589 $flags->extensionduedate = 0;
2590 $flags->workflowstate = '';
2591 $flags->allocatedmarker = 0;
2593 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2594 // This is because students only want to be notified about certain types of update (grades and feedback).
2597 $fid = $DB->insert_record('assign_user_flags', $flags);
2605 * This will retrieve a grade object from the db, optionally creating it if required.
2607 * @param int $userid The user we are grading
2608 * @param bool $create If true the grade will be created if it does not exist
2609 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2610 * @return stdClass The grade record
2612 public function get_user_grade($userid, $create, $attemptnumber=-1) {
2615 // If the userid is not null then use userid.
2617 $userid = $USER->id;
2620 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2621 if ($attemptnumber < 0) {
2622 // Make sure this grade matches the latest submission attempt.
2623 if ($this->get_instance()->teamsubmission) {
2624 $submission = $this->get_group_submission($userid, 0, false);
2626 $submission = $this->get_user_submission($userid, false);
2629 $attemptnumber = $submission->attemptnumber;
2633 if ($attemptnumber >= 0) {
2634 $params['attemptnumber'] = $attemptnumber;
2637 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2640 return reset($grades);
2643 $grade = new stdClass();
2644 $grade->assignment = $this->get_instance()->id;
2645 $grade->userid = $userid;
2646 $grade->timecreated = time();
2647 $grade->timemodified = $grade->timecreated;
2649 $grade->grader = $USER->id;
2650 if ($attemptnumber >= 0) {
2651 $grade->attemptnumber = $attemptnumber;
2654 $gid = $DB->insert_record('assign_grades', $grade);
2662 * This will retrieve a grade object from the db.
2664 * @param int $gradeid The id of the grade
2665 * @return stdClass The grade record
2667 protected function get_grade($gradeid) {
2670 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2671 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2675 * Print the grading page for a single user submission.
2677 * @param moodleform $mform
2680 protected function view_single_grade_page($mform) {
2684 $instance = $this->get_instance();
2686 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2688 // Need submit permission to submit an assignment.
2689 require_capability('mod/assign:grade', $this->context);
2691 $header = new assign_header($instance,
2692 $this->get_context(),
2694 $this->get_course_module()->id,
2695 get_string('grading', 'assign'));
2696 $o .= $this->get_renderer()->render($header);
2698 // If userid is passed - we are only grading a single student.
2699 $rownum = required_param('rownum', PARAM_INT);
2700 $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2701 $userid = optional_param('userid', 0, PARAM_INT);
2702 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2704 $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2706 if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2707 $useridlist = $this->get_grading_userid_list();
2709 $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2712 $useridlist = array($userid);
2715 if ($rownum < 0 || $rownum > count($useridlist)) {
2716 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2720 $userid = $useridlist[$rownum];
2721 if ($rownum == count($useridlist) - 1) {
2724 $user = $DB->get_record('user', array('id' => $userid));
2726 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2727 $usersummary = new assign_user_summary($user,
2728 $this->get_course()->id,
2730 $this->is_blind_marking(),
2731 $this->get_uniqueid_for_user($user->id),
2732 get_extra_user_fields($this->get_context()),
2733 !$this->is_active_user($userid));
2734 $o .= $this->get_renderer()->render($usersummary);
2736 $submission = $this->get_user_submission($userid, false, $attemptnumber);
2737 $submissiongroup = null;
2738 $teamsubmission = null;
2739 $notsubmitted = array();
2740 if ($instance->teamsubmission) {
2741 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2742 $submissiongroup = $this->get_submission_group($userid);
2744 if ($submissiongroup) {
2745 $groupid = $submissiongroup->id;
2747 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2751 // Get the requested grade.
2752 $grade = $this->get_user_grade($userid, false, $attemptnumber);
2753 $flags = $this->get_user_flags($userid, false);
2754 if ($this->can_view_submission($userid)) {
2755 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2756 $extensionduedate = null;
2758 $extensionduedate = $flags->extensionduedate;
2760 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2762 if ($teamsubmission) {
2763 $showsubmit = $showedit &&
2765 ($teamsubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) &&
2766 !$this->submission_empty($teamsubmission);
2768 $showsubmit = $showedit &&
2770 ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) &&
2771 !$this->submission_empty($submission);
2773 if (!$this->get_instance()->submissiondrafts) {
2774 $showsubmit = false;
2776 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2778 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2779 $instance->alwaysshowdescription,
2781 $instance->teamsubmission,
2785 $this->is_any_submission_plugin_enabled(),
2787 $this->is_graded($userid),
2789 $instance->cutoffdate,
2790 $this->get_submission_plugins(),
2791 $this->get_return_action(),
2792 $this->get_return_params(),
2793 $this->get_course_module()->id,
2794 $this->get_course()->id,
2795 assign_submission_status::GRADER_VIEW,
2800 $this->get_context(),
2801 $this->is_blind_marking(),
2803 $instance->attemptreopenmethod,
2804 $instance->maxattempts);
2805 $o .= $this->get_renderer()->render($submissionstatus);
2809 $data = new stdClass();
2810 if ($grade->grade !== null && $grade->grade >= 0) {
2811 $data->grade = format_float($grade->grade, 2);
2813 if (!empty($flags->workflowstate)) {
2814 $data->workflowstate = $flags->workflowstate;
2816 if (!empty($flags->allocatedmarker)) {
2817 $data->allocatedmarker = $flags->allocatedmarker;
2820 $data = new stdClass();
2823 // Warning if required.
2824 $allsubmissions = $this->get_all_submissions($userid);
2826 if ($attemptnumber != -1) {
2827 $params = array('attemptnumber'=>$attemptnumber + 1,
2828 'totalattempts'=>count($allsubmissions));
2829 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2830 $o .= $this->get_renderer()->notification($message);
2833 // Now show the grading form.
2835 $pagination = array('rownum'=>$rownum,
2836 'useridlistid'=>$useridlistid,
2838 'userid'=>optional_param('userid', 0, PARAM_INT),
2839 'attemptnumber'=>$attemptnumber);
2840 $formparams = array($this, $data, $pagination);
2841 $mform = new mod_assign_grade_form(null,
2845 array('class'=>'gradeform'));
2847 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2848 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2850 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2851 $allgrades = $this->get_all_grades($userid);
2852 $history = new assign_attempt_history($allsubmissions,
2854 $this->get_submission_plugins(),
2855 $this->get_feedback_plugins(),
2856 $this->get_course_module()->id,
2857 $this->get_return_action(),
2858 $this->get_return_params(),
2861 $o .= $this->get_renderer()->render($history);
2864 $msg = get_string('viewgradingformforstudent',
2866 array('id'=>$user->id, 'fullname'=>fullname($user)));
2867 $this->add_to_log('view grading form', $msg);
2869 $o .= $this->view_footer();
2874 * Show a confirmation page to make sure they want to release student identities.
2878 protected function view_reveal_identities_confirm() {
2881 require_capability('mod/assign:revealidentities', $this->get_context());
2884 $header = new assign_header($this->get_instance(),
2885 $this->get_context(),
2887 $this->get_course_module()->id);
2888 $o .= $this->get_renderer()->render($header);
2890 $urlparams = array('id'=>$this->get_course_module()->id,
2891 'action'=>'revealidentitiesconfirm',
2892 'sesskey'=>sesskey());
2893 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2895 $urlparams = array('id'=>$this->get_course_module()->id,
2896 'action'=>'grading');
2897 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2899 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2902 $o .= $this->view_footer();
2903 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2908 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
2912 protected function view_return_links() {
2913 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
2914 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
2917 $returnparams = str_replace('&', '&', $returnparams);
2918 parse_str($returnparams, $params);
2919 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
2920 $params = array_merge($newparams, $params);
2922 $url = new moodle_url('/mod/assign/view.php', $params);
2923 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
2927 * View the grading table of all submissions for this assignment.
2931 protected function view_grading_table() {
2934 // Include grading options form.
2935 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
2936 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
2937 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
2939 $cmid = $this->get_course_module()->id;
2942 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
2943 has_capability('moodle/grade:viewall', $this->get_course_context())) {
2944 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
2945 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
2947 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
2948 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
2949 $links[$downloadurl] = get_string('downloadall', 'assign');
2951 if ($this->is_blind_marking() &&
2952 has_capability('mod/assign:revealidentities', $this->get_context())) {
2953 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
2954 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
2956 foreach ($this->get_feedback_plugins() as $plugin) {
2957 if ($plugin->is_enabled() && $plugin->is_visible()) {
2958 foreach ($plugin->get_grading_actions() as $action => $description) {
2959 $url = '/mod/assign/view.php' .
2961 '&plugin=' . $plugin->get_type() .
2962 '&pluginsubtype=assignfeedback' .
2963 '&action=viewpluginpage&pluginaction=' . $action;
2964 $links[$url] = $description;
2969 // Sort links alphabetically based on the link description.
2970 core_collator::asort($links);
2972 $gradingactions = new url_select($links);
2973 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
2975 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
2977 $perpage = get_user_preferences('assign_perpage', 10);
2978 $filter = get_user_preferences('assign_filter', '');
2979 $markerfilter = get_user_preferences('assign_markerfilter', '');
2980 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
2981 $controller = $gradingmanager->get_active_controller();
2982 $showquickgrading = empty($controller);
2983 $quickgrading = get_user_preferences('assign_quickgrading', false);
2984 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
2986 $markingallocation = $this->get_instance()->markingallocation &&
2987 has_capability('mod/assign:manageallocations', $this->context);
2988 // Get markers to use in drop lists.
2989 $markingallocationoptions = array();
2990 if ($markingallocation) {
2991 $markers = get_users_by_capability($this->context, 'mod/assign:grade');
2992 $markingallocationoptions[''] = get_string('filternone', 'assign');
2993 foreach ($markers as $marker) {
2994 $markingallocationoptions[$marker->id] = fullname($marker);
2998 $markingworkflow = $this->get_instance()->markingworkflow;
2999 // Get marking states to show in form.
3000 $markingworkflowoptions = array();
3001 if ($markingworkflow) {
3002 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3003 $markingworkflowoptions[''] = get_string('filternone', 'assign');
3004 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3005 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3008 // Print options for changing the filter and changing the number of results per page.
3009 $gradingoptionsformparams = array('cm'=>$cmid,
3010 'contextid'=>$this->context->id,
3011 'userid'=>$USER->id,
3012 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3013 'showquickgrading'=>$showquickgrading,
3014 'quickgrading'=>$quickgrading,
3015 'markingworkflowopt'=>$markingworkflowoptions,
3016 'markingallocationopt'=>$markingallocationoptions,
3017 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3018 'showonlyactiveenrol'=>$this->show_only_active_users());
3020 $classoptions = array('class'=>'gradingoptionsform');
3021 $gradingoptionsform = new mod_assign_grading_options_form(null,
3022 $gradingoptionsformparams,
3027 $batchformparams = array('cm'=>$cmid,
3028 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3029 'duedate'=>$this->get_instance()->duedate,
3030 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3031 'feedbackplugins'=>$this->get_feedback_plugins(),
3032 'context'=>$this->get_context(),
3033 'markingworkflow'=>$markingworkflow,
3034 'markingallocation'=>$markingallocation);
3035 $classoptions = array('class'=>'gradingbatchoperationsform');
3037 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3043 $gradingoptionsdata = new stdClass();
3044 $gradingoptionsdata->perpage = $perpage;
3045 $gradingoptionsdata->filter = $filter;
3046 $gradingoptionsdata->markerfilter = $markerfilter;
3047 $gradingoptionsdata->workflowfilter = $workflowfilter;
3048 $gradingoptionsform->set_data($gradingoptionsdata);
3050 $actionformtext = $this->get_renderer()->render($gradingactions);
3051 $header = new assign_header($this->get_instance(),
3052 $this->get_context(),
3054 $this->get_course_module()->id,
3055 get_string('grading', 'assign'),
3057 $o .= $this->get_renderer()->render($header);
3059 $currenturl = $CFG->wwwroot .
3060 '/mod/assign/view.php?id=' .
3061 $this->get_course_module()->id .
3064 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3066 // Plagiarism update status apearring in the grading book.
3067 if (!empty($CFG->enableplagiarism)) {
3068 require_once($CFG->libdir . '/plagiarismlib.php');
3069 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3072 // Load and print the table of submissions.
3073 if ($showquickgrading && $quickgrading) {
3074 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3075 $table = $this->get_renderer()->render($gradingtable);
3076 $quickformparams = array('cm'=>$this->get_course_module()->id, 'gradingtable'=>$table);
3077 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3079 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3081 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3082 $o .= $this->get_renderer()->render($gradingtable);
3085 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3086 $users = array_keys($this->list_participants($currentgroup, true));
3087 if (count($users) != 0) {
3088 // If no enrolled user in a course then don't display the batch operations feature.
3089 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3090 $o .= $this->get_renderer()->render($assignform);
3092 $assignform = new assign_form('gradingoptionsform',
3093 $gradingoptionsform,
3094 'M.mod_assign.init_grading_options');
3095 $o .= $this->get_renderer()->render($assignform);
3100 * View entire grading page.
3104 protected function view_grading_page() {
3108 // Need submit permission to submit an assignment.
3109 require_capability('mod/assign:grade', $this->context);
3110 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3112 // Only load this if it is.
3114 $o .= $this->view_grading_table();
3116 $o .= $this->view_footer();
3118 $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3119 $this->add_to_log('view submission grading table', $logmessage);
3124 * Capture the output of the plagiarism plugins disclosures and return it as a string.
3128 protected function plagiarism_print_disclosure() {
3132 if (!empty($CFG->enableplagiarism)) {
3133 require_once($CFG->libdir . '/plagiarismlib.php');
3135 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3142 * Message for students when assignment submissions have been closed.
3146 protected function view_student_error_message() {
3150 // Need submit permission to submit an assignment.
3151 require_capability('mod/assign:submit', $this->context);
3153 $header = new assign_header($this->get_instance(),
3154 $this->get_context(),
3155 $this->show_intro(),
3156 $this->get_course_module()->id,
3157 get_string('editsubmission', 'assign'));
3158 $o .= $this->get_renderer()->render($header);
3160 $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));
3162 $o .= $this->view_footer();
3169 * View edit submissions page.
3171 * @param moodleform $mform
3172 * @param array $notices A list of notices to display at the top of the
3173 * edit submission form (e.g. from plugins).
3174 * @return string The page output.
3176 protected function view_edit_submission_page($mform, $notices) {
3180 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
3181 // Need submit permission to submit an assignment.
3182 require_capability('mod/assign:submit', $this->context);
3184 if (!$this->submissions_open()) {
3185 return $this->view_student_error_message();
3187 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3188 $this->get_context(),
3189 $this->show_intro(),
3190 $this->get_course_module()->id,
3191 get_string('editsubmission', 'assign')));
3192 $o .= $this->plagiarism_print_disclosure();
3193 $data = new stdClass();
3196 $mform = new mod_assign_submission_form(null, array($this, $data));
3199 foreach ($notices as $notice) {
3200 $o .= $this->get_renderer()->notification($notice);
3203 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
3205 $o .= $this->view_footer();
3206 $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));
3212 * See if this assignment has a grade yet.
3214 * @param int $userid
3217 protected function is_graded($userid) {
3218 $grade = $this->get_user_grade($userid, false);
3220 return ($grade->grade !== null && $grade->grade >= 0);
3226 * Perform an access check to see if the current $USER can view this group submission.
3228 * @param int $groupid
3231 public function can_view_group_submission($groupid) {
3234 if (has_capability('mod/assign:grade', $this->context)) {
3237 if (!is_enrolled($this->get_course_context(), $USER->id)) {
3240 $members = $this->get_submission_group_members($groupid, true);
3241 foreach ($members as $member) {
3242 if ($member->id == $USER->id) {
3250 * Perform an access check to see if the current $USER can view this users submission.
3252 * @param int $userid
3255 public function can_view_submission($userid) {
3258 if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
3261 if (has_capability('mod/assign:grade', $this->context)) {