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_NOT_SUBMITTED', 'notsubmitted');
37 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
38 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
40 // Marker filter for grading page.
41 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
43 // Reopen attempt methods.
44 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
45 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
48 // Special value means allow unlimited attempts.
49 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
51 // Marking workflow states.
52 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
53 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
54 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
55 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
56 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
57 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
59 require_once($CFG->libdir . '/accesslib.php');
60 require_once($CFG->libdir . '/formslib.php');
61 require_once($CFG->dirroot . '/repository/lib.php');
62 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
63 require_once($CFG->libdir . '/gradelib.php');
64 require_once($CFG->dirroot . '/grade/grading/lib.php');
65 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
66 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
67 require_once($CFG->dirroot . '/mod/assign/renderable.php');
68 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
69 require_once($CFG->libdir . '/eventslib.php');
70 require_once($CFG->libdir . '/portfolio/caller.php');
73 * Standard base class for mod_assign (assignment types).
76 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
77 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
81 /** @var stdClass the assignment record that contains the global settings for this assign instance */
84 /** @var stdClass the grade_item record for this assign instance's primary grade item. */
87 /** @var context the context of the course module for this assign instance
88 * (or just the course if we are creating a new one)
92 /** @var stdClass the course this assign instance belongs to */
95 /** @var stdClass the admin config for all assign instances */
98 /** @var assign_renderer the custom renderer for this module */
101 /** @var stdClass the course module for this assign instance */
102 private $coursemodule;
104 /** @var array cache for things like the coursemodule name or the scale menu -
105 * only lives for a single request.
109 /** @var array list of the installed submission plugins */
110 private $submissionplugins;
112 /** @var array list of the installed feedback plugins */
113 private $feedbackplugins;
115 /** @var string action to be used to return to this page
116 * (without repeating any form submissions etc).
118 private $returnaction = 'view';
120 /** @var array params to be used to return to this page */
121 private $returnparams = array();
123 /** @var string modulename prevents excessive calls to get_string */
124 private static $modulename = null;
126 /** @var string modulenameplural prevents excessive calls to get_string */
127 private static $modulenameplural = null;
129 /** @var array of marking workflow states for the current user */
130 private $markingworkflowstates = null;
132 /** @var bool whether to exclude users with inactive enrolment */
133 private $showonlyactiveenrol = null;
135 /** @var array list of suspended user IDs in form of ([id1] => id1) */
136 public $susers = null;
138 /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
139 private $participants = array();
142 * Constructor for the base assign class.
144 * @param mixed $coursemodulecontext context|null the course module context
145 * (or the course context if the coursemodule has not been
147 * @param mixed $coursemodule the current course module if it was already loaded,
148 * otherwise this class will load one from the context as required.
149 * @param mixed $course the current course if it was already loaded,
150 * otherwise this class will load one from the context as required.
152 public function __construct($coursemodulecontext, $coursemodule, $course) {
153 $this->context = $coursemodulecontext;
154 $this->coursemodule = $coursemodule;
155 $this->course = $course;
157 // Temporary cache only lives for a single request - used to reduce db lookups.
158 $this->cache = array();
160 $this->submissionplugins = $this->load_plugins('assignsubmission');
161 $this->feedbackplugins = $this->load_plugins('assignfeedback');
165 * Set the action and parameters that can be used to return to the current page.
167 * @param string $action The action for the current page
168 * @param array $params An array of name value pairs which form the parameters
169 * to return to the current page.
172 public function register_return_link($action, $params) {
174 $params['action'] = $action;
175 $currenturl = $PAGE->url;
177 $currenturl->params($params);
178 $PAGE->set_url($currenturl);
182 * Return an action that can be used to get back to the current page.
184 * @return string action
186 public function get_return_action() {
189 $params = $PAGE->url->params();
191 if (!empty($params['action'])) {
192 return $params['action'];
198 * Based on the current assignment settings should we display the intro.
200 * @return bool showintro
202 protected function show_intro() {
203 if ($this->get_instance()->alwaysshowdescription ||
204 time() > $this->get_instance()->allowsubmissionsfromdate) {
211 * Return a list of parameters that can be used to get back to the current page.
213 * @return array params
215 public function get_return_params() {
218 $params = $PAGE->url->params();
219 unset($params['id']);
220 unset($params['action']);
225 * Set the submitted form data.
227 * @param stdClass $data The form data (instance)
229 public function set_instance(stdClass $data) {
230 $this->instance = $data;
236 * @param context $context The new context
238 public function set_context(context $context) {
239 $this->context = $context;
243 * Set the course data.
245 * @param stdClass $course The course data
247 public function set_course(stdClass $course) {
248 $this->course = $course;
252 * Get list of feedback plugins installed.
256 public function get_feedback_plugins() {
257 return $this->feedbackplugins;
261 * Get list of submission plugins installed.
265 public function get_submission_plugins() {
266 return $this->submissionplugins;
270 * Is blind marking enabled and reveal identities not set yet?
274 public function is_blind_marking() {
275 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
279 * Does an assignment have submission(s) or grade(s) already?
283 public function has_submissions_or_grades() {
284 $allgrades = $this->count_grades();
285 $allsubmissions = $this->count_submissions();
286 if (($allgrades == 0) && ($allsubmissions == 0)) {
293 * Get a specific submission plugin by its type.
295 * @param string $subtype assignsubmission | assignfeedback
296 * @param string $type
297 * @return mixed assign_plugin|null
299 public function get_plugin_by_type($subtype, $type) {
300 $shortsubtype = substr($subtype, strlen('assign'));
301 $name = $shortsubtype . 'plugins';
302 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
305 $pluginlist = $this->$name;
306 foreach ($pluginlist as $plugin) {
307 if ($plugin->get_type() == $type) {
315 * Get a feedback plugin by type.
317 * @param string $type - The type of plugin e.g comments
318 * @return mixed assign_feedback_plugin|null
320 public function get_feedback_plugin_by_type($type) {
321 return $this->get_plugin_by_type('assignfeedback', $type);
325 * Get a submission plugin by type.
327 * @param string $type - The type of plugin e.g comments
328 * @return mixed assign_submission_plugin|null
330 public function get_submission_plugin_by_type($type) {
331 return $this->get_plugin_by_type('assignsubmission', $type);
335 * Load the plugins from the sub folders under subtype.
337 * @param string $subtype - either submission or feedback
338 * @return array - The sorted list of plugins
340 protected function load_plugins($subtype) {
344 $names = core_component::get_plugin_list($subtype);
346 foreach ($names as $name => $path) {
347 if (file_exists($path . '/locallib.php')) {
348 require_once($path . '/locallib.php');
350 $shortsubtype = substr($subtype, strlen('assign'));
351 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
353 $plugin = new $pluginclass($this, $name);
355 if ($plugin instanceof assign_plugin) {
356 $idx = $plugin->get_sort_order();
357 while (array_key_exists($idx, $result)) {
360 $result[$idx] = $plugin;
369 * Display the assignment, used by view.php
371 * The assignment is displayed differently depending on your role,
372 * the settings for the assignment and the status of the assignment.
374 * @param string $action The current action if any.
375 * @return string - The page output.
377 public function view($action='') {
382 $nextpageparams = array();
384 if (!empty($this->get_course_module()->id)) {
385 $nextpageparams['id'] = $this->get_course_module()->id;
388 // Handle form submissions first.
389 if ($action == 'savesubmission') {
390 $action = 'editsubmission';
391 if ($this->process_save_submission($mform, $notices)) {
392 $action = 'redirect';
393 $nextpageparams['action'] = 'view';
395 } else if ($action == 'editprevioussubmission') {
396 $action = 'editsubmission';
397 if ($this->process_copy_previous_attempt($notices)) {
398 $action = 'redirect';
399 $nextpageparams['action'] = 'editsubmission';
401 } else if ($action == 'lock') {
402 $this->process_lock_submission();
403 $action = 'redirect';
404 $nextpageparams['action'] = 'grading';
405 } else if ($action == 'addattempt') {
406 $this->process_add_attempt(required_param('userid', PARAM_INT));
407 $action = 'redirect';
408 $nextpageparams['action'] = 'grading';
409 } else if ($action == 'reverttodraft') {
410 $this->process_revert_to_draft();
411 $action = 'redirect';
412 $nextpageparams['action'] = 'grading';
413 } else if ($action == 'unlock') {
414 $this->process_unlock_submission();
415 $action = 'redirect';
416 $nextpageparams['action'] = 'grading';
417 } else if ($action == 'setbatchmarkingworkflowstate') {
418 $this->process_set_batch_marking_workflow_state();
419 $action = 'redirect';
420 $nextpageparams['action'] = 'grading';
421 } else if ($action == 'setbatchmarkingallocation') {
422 $this->process_set_batch_marking_allocation();
423 $action = 'redirect';
424 $nextpageparams['action'] = 'grading';
425 } else if ($action == 'confirmsubmit') {
427 if ($this->process_submit_for_grading($mform, $notices)) {
428 $action = 'redirect';
429 $nextpageparams['action'] = 'view';
430 } else if ($notices) {
431 $action = 'viewsubmitforgradingerror';
433 } else if ($action == 'submitotherforgrading') {
434 if ($this->process_submit_other_for_grading($mform, $notices)) {
435 $action = 'redirect';
436 $nextpageparams['action'] = 'grading';
438 $action = 'viewsubmitforgradingerror';
440 } else if ($action == 'gradingbatchoperation') {
441 $action = $this->process_grading_batch_operation($mform);
442 if ($action == 'grading') {
443 $action = 'redirect';
444 $nextpageparams['action'] = 'grading';
446 } else if ($action == 'submitgrade') {
447 if (optional_param('saveandshownext', null, PARAM_RAW)) {
448 // Save and show next.
450 if ($this->process_save_grade($mform)) {
451 $action = 'redirect';
452 $nextpageparams['action'] = 'grade';
453 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
454 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
456 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
457 $action = 'redirect';
458 $nextpageparams['action'] = 'grade';
459 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
460 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
461 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
462 $action = 'redirect';
463 $nextpageparams['action'] = 'grade';
464 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
465 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
466 } else if (optional_param('savegrade', null, PARAM_RAW)) {
467 // Save changes button.
469 if ($this->process_save_grade($mform)) {
470 $action = 'redirect';
471 $nextpageparams['action'] = 'savegradingresult';
475 $action = 'redirect';
476 $nextpageparams['action'] = 'grading';
478 } else if ($action == 'quickgrade') {
479 $message = $this->process_save_quick_grades();
480 $action = 'quickgradingresult';
481 } else if ($action == 'saveoptions') {
482 $this->process_save_grading_options();
483 $action = 'redirect';
484 $nextpageparams['action'] = 'grading';
485 } else if ($action == 'saveextension') {
486 $action = 'grantextension';
487 if ($this->process_save_extension($mform)) {
488 $action = 'redirect';
489 $nextpageparams['action'] = 'grading';
491 } else if ($action == 'revealidentitiesconfirm') {
492 $this->process_reveal_identities();
493 $action = 'redirect';
494 $nextpageparams['action'] = 'grading';
497 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
498 'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
499 $this->register_return_link($action, $returnparams);
501 // Now show the right view page.
502 if ($action == 'redirect') {
503 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
504 redirect($nextpageurl);
506 } else if ($action == 'savegradingresult') {
507 $message = get_string('gradingchangessaved', 'assign');
508 $o .= $this->view_savegrading_result($message);
509 } else if ($action == 'quickgradingresult') {
511 $o .= $this->view_quickgrading_result($message);
512 } else if ($action == 'grade') {
513 $o .= $this->view_single_grade_page($mform);
514 } else if ($action == 'viewpluginassignfeedback') {
515 $o .= $this->view_plugin_content('assignfeedback');
516 } else if ($action == 'viewpluginassignsubmission') {
517 $o .= $this->view_plugin_content('assignsubmission');
518 } else if ($action == 'editsubmission') {
519 $o .= $this->view_edit_submission_page($mform, $notices);
520 } else if ($action == 'grading') {
521 $o .= $this->view_grading_page();
522 } else if ($action == 'downloadall') {
523 $o .= $this->download_submissions();
524 } else if ($action == 'submit') {
525 $o .= $this->check_submit_for_grading($mform);
526 } else if ($action == 'grantextension') {
527 $o .= $this->view_grant_extension($mform);
528 } else if ($action == 'revealidentities') {
529 $o .= $this->view_reveal_identities_confirm($mform);
530 } else if ($action == 'plugingradingbatchoperation') {
531 $o .= $this->view_plugin_grading_batch_operation($mform);
532 } else if ($action == 'viewpluginpage') {
533 $o .= $this->view_plugin_page();
534 } else if ($action == 'viewcourseindex') {
535 $o .= $this->view_course_index();
536 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
537 $o .= $this->view_batch_set_workflow_state($mform);
538 } else if ($action == 'viewbatchmarkingallocation') {
539 $o .= $this->view_batch_markingallocation($mform);
540 } else if ($action == 'viewsubmitforgradingerror') {
541 $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
543 $o .= $this->view_submission_page();
550 * Add this instance to the database.
552 * @param stdClass $formdata The data submitted from the form
553 * @param bool $callplugins This is used to skip the plugin code
554 * when upgrading an old assignment to a new one (the plugins get called manually)
555 * @return mixed false if an error occurs or the int id of the new instance
557 public function add_instance(stdClass $formdata, $callplugins) {
559 $adminconfig = $this->get_admin_config();
563 // Add the database record.
564 $update = new stdClass();
565 $update->name = $formdata->name;
566 $update->timemodified = time();
567 $update->timecreated = time();
568 $update->course = $formdata->course;
569 $update->courseid = $formdata->course;
570 $update->intro = $formdata->intro;
571 $update->introformat = $formdata->introformat;
572 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
573 $update->submissiondrafts = $formdata->submissiondrafts;
574 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
575 $update->sendnotifications = $formdata->sendnotifications;
576 $update->sendlatenotifications = $formdata->sendlatenotifications;
577 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
578 if (isset($formdata->sendstudentnotifications)) {
579 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
581 $update->duedate = $formdata->duedate;
582 $update->cutoffdate = $formdata->cutoffdate;
583 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
584 $update->grade = $formdata->grade;
585 $update->completionsubmit = !empty($formdata->completionsubmit);
586 $update->teamsubmission = $formdata->teamsubmission;
587 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
588 if (isset($formdata->teamsubmissiongroupingid)) {
589 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
591 $update->blindmarking = $formdata->blindmarking;
592 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
593 if (!empty($formdata->attemptreopenmethod)) {
594 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
596 if (!empty($formdata->maxattempts)) {
597 $update->maxattempts = $formdata->maxattempts;
599 $update->markingworkflow = $formdata->markingworkflow;
600 $update->markingallocation = $formdata->markingallocation;
602 $returnid = $DB->insert_record('assign', $update);
603 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
604 // Cache the course record.
605 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
608 // Call save_settings hook for submission plugins.
609 foreach ($this->submissionplugins as $plugin) {
610 if (!$this->update_plugin_instance($plugin, $formdata)) {
611 print_error($plugin->get_error());
615 foreach ($this->feedbackplugins as $plugin) {
616 if (!$this->update_plugin_instance($plugin, $formdata)) {
617 print_error($plugin->get_error());
622 // In the case of upgrades the coursemodule has not been set,
623 // so we need to wait before calling these two.
624 $this->update_calendar($formdata->coursemodule);
625 $this->update_gradebook(false, $formdata->coursemodule);
629 $update = new stdClass();
630 $update->id = $this->get_instance()->id;
631 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
632 $DB->update_record('assign', $update);
638 * Delete all grades from the gradebook for this assignment.
642 protected function delete_grades() {
645 $result = grade_update('mod/assign',
646 $this->get_course()->id,
649 $this->get_instance()->id,
652 array('deleted'=>1));
653 return $result == GRADE_UPDATE_OK;
657 * Delete this instance from the database.
659 * @return bool false if an error occurs
661 public function delete_instance() {
665 foreach ($this->submissionplugins as $plugin) {
666 if (!$plugin->delete_instance()) {
667 print_error($plugin->get_error());
671 foreach ($this->feedbackplugins as $plugin) {
672 if (!$plugin->delete_instance()) {
673 print_error($plugin->get_error());
678 // Delete files associated with this assignment.
679 $fs = get_file_storage();
680 if (! $fs->delete_area_files($this->context->id) ) {
684 // Delete_records will throw an exception if it fails - so no need for error checking here.
685 $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
686 $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
687 $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));
689 // Delete items from the gradebook.
690 if (! $this->delete_grades()) {
694 // Delete the instance.
695 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
701 * Actual implementation of the reset course functionality, delete all the
702 * assignment submissions for course $data->courseid.
704 * @param stdClass $data the data submitted from the reset course.
705 * @return array status array
707 public function reset_userdata($data) {
710 $componentstr = get_string('modulenameplural', 'assign');
713 $fs = get_file_storage();
714 if (!empty($data->reset_assign_submissions)) {
715 // Delete files associated with this assignment.
716 foreach ($this->submissionplugins as $plugin) {
717 $fileareas = array();
718 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
719 $fileareas = $plugin->get_file_areas();
720 foreach ($fileareas as $filearea) {
721 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
724 if (!$plugin->delete_instance()) {
725 $status[] = array('component'=>$componentstr,
726 'item'=>get_string('deleteallsubmissions', 'assign'),
727 'error'=>$plugin->get_error());
731 foreach ($this->feedbackplugins as $plugin) {
732 $fileareas = array();
733 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
734 $fileareas = $plugin->get_file_areas();
735 foreach ($fileareas as $filearea) {
736 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
739 if (!$plugin->delete_instance()) {
740 $status[] = array('component'=>$componentstr,
741 'item'=>get_string('deleteallsubmissions', 'assign'),
742 'error'=>$plugin->get_error());
746 $assignssql = 'SELECT a.id
748 WHERE a.course=:course';
749 $params = array('course'=>$data->courseid);
751 $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
753 $status[] = array('component'=>$componentstr,
754 'item'=>get_string('deleteallsubmissions', 'assign'),
757 if (!empty($data->reset_gradebook_grades)) {
758 $DB->delete_records_select('assign_grades', "assignment IN ($assignssql)", $params);
759 // Remove all grades from gradebook.
760 require_once($CFG->dirroot.'/mod/assign/lib.php');
761 assign_reset_gradebook($data->courseid);
764 // Updating dates - shift may be negative too.
765 if ($data->timeshift) {
766 shift_course_mod_dates('assign',
767 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
769 $data->courseid, $this->get_instance()->id);
770 $status[] = array('component'=>$componentstr,
771 'item'=>get_string('datechanged'),
779 * Update the settings for a single plugin.
781 * @param assign_plugin $plugin The plugin to update
782 * @param stdClass $formdata The form data
783 * @return bool false if an error occurs
785 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
786 if ($plugin->is_visible()) {
787 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
788 if (!empty($formdata->$enabledname)) {
790 if (!$plugin->save_settings($formdata)) {
791 print_error($plugin->get_error());
802 * Update the gradebook information for this assignment.
804 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
805 * @param int $coursemoduleid This is required because it might not exist in the database yet
808 public function update_gradebook($reset, $coursemoduleid) {
811 require_once($CFG->dirroot.'/mod/assign/lib.php');
812 $assign = clone $this->get_instance();
813 $assign->cmidnumber = $coursemoduleid;
815 // Set assign gradebook feedback plugin status (enabled and visible).
816 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
823 return assign_grade_item_update($assign, $param);
827 * Load and cache the admin config for this module.
829 * @return stdClass the plugin config
831 public function get_admin_config() {
832 if ($this->adminconfig) {
833 return $this->adminconfig;
835 $this->adminconfig = get_config('assign');
836 return $this->adminconfig;
840 * Update the calendar entries for this assignment.
842 * @param int $coursemoduleid - Required to pass this in because it might
843 * not exist in the database yet.
846 public function update_calendar($coursemoduleid) {
848 require_once($CFG->dirroot.'/calendar/lib.php');
850 // Special case for add_instance as the coursemodule has not been set yet.
851 $instance = $this->get_instance();
853 if ($instance->duedate) {
854 $event = new stdClass();
856 $params = array('modulename'=>'assign', 'instance'=>$instance->id);
857 $event->id = $DB->get_field('event', 'id', $params);
858 $event->name = $instance->name;
859 $event->timestart = $instance->duedate;
861 // Convert the links to pluginfile. It is a bit hacky but at this stage the files
862 // might not have been saved in the module area yet.
863 $intro = $instance->intro;
864 if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
865 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
868 // We need to remove the links to files as the calendar is not ready
869 // to support module events with file areas.
870 $intro = strip_pluginfile_content($intro);
871 $event->description = array(
873 'format' => $instance->introformat
877 $calendarevent = calendar_event::load($event->id);
878 $calendarevent->update($event);
881 $event->courseid = $instance->course;
884 $event->modulename = 'assign';
885 $event->instance = $instance->id;
886 $event->eventtype = 'due';
887 $event->timeduration = 0;
888 calendar_event::create($event);
891 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
897 * Update this instance in the database.
899 * @param stdClass $formdata - the data submitted from the form
900 * @return bool false if an error occurs
902 public function update_instance($formdata) {
904 $adminconfig = $this->get_admin_config();
906 $update = new stdClass();
907 $update->id = $formdata->instance;
908 $update->name = $formdata->name;
909 $update->timemodified = time();
910 $update->course = $formdata->course;
911 $update->intro = $formdata->intro;
912 $update->introformat = $formdata->introformat;
913 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
914 $update->submissiondrafts = $formdata->submissiondrafts;
915 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
916 $update->sendnotifications = $formdata->sendnotifications;
917 $update->sendlatenotifications = $formdata->sendlatenotifications;
918 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
919 if (isset($formdata->sendstudentnotifications)) {
920 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
922 $update->duedate = $formdata->duedate;
923 $update->cutoffdate = $formdata->cutoffdate;
924 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
925 $update->grade = $formdata->grade;
926 if (!empty($formdata->completionunlocked)) {
927 $update->completionsubmit = !empty($formdata->completionsubmit);
929 $update->teamsubmission = $formdata->teamsubmission;
930 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
931 if (isset($formdata->teamsubmissiongroupingid)) {
932 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
934 $update->blindmarking = $formdata->blindmarking;
935 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
936 if (!empty($formdata->attemptreopenmethod)) {
937 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
939 if (!empty($formdata->maxattempts)) {
940 $update->maxattempts = $formdata->maxattempts;
942 $update->markingworkflow = $formdata->markingworkflow;
943 $update->markingallocation = $formdata->markingallocation;
945 $result = $DB->update_record('assign', $update);
946 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
948 // Load the assignment so the plugins have access to it.
950 // Call save_settings hook for submission plugins.
951 foreach ($this->submissionplugins as $plugin) {
952 if (!$this->update_plugin_instance($plugin, $formdata)) {
953 print_error($plugin->get_error());
957 foreach ($this->feedbackplugins as $plugin) {
958 if (!$this->update_plugin_instance($plugin, $formdata)) {
959 print_error($plugin->get_error());
964 $this->update_calendar($this->get_course_module()->id);
965 $this->update_gradebook(false, $this->get_course_module()->id);
967 $update = new stdClass();
968 $update->id = $this->get_instance()->id;
969 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
970 $DB->update_record('assign', $update);
976 * Add elements in grading plugin form.
978 * @param mixed $grade stdClass|null
979 * @param MoodleQuickForm $mform
980 * @param stdClass $data
981 * @param int $userid - The userid we are grading
984 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
985 foreach ($this->feedbackplugins as $plugin) {
986 if ($plugin->is_enabled() && $plugin->is_visible()) {
987 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
995 * Add one plugins settings to edit plugin form.
997 * @param assign_plugin $plugin The plugin to add the settings from
998 * @param MoodleQuickForm $mform The form to add the configuration settings to.
999 * This form is modified directly (not returned).
1000 * @param array $pluginsenabled A list of form elements to be added to a group.
1001 * The new element is added to this array by this function.
1004 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1006 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1007 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1008 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1009 $mform->setType($name, PARAM_BOOL);
1010 $plugin->get_settings($mform);
1011 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1012 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1013 $label = $plugin->get_name();
1014 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1015 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1017 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1018 if ($plugin->get_config('enabled') !== false) {
1019 $default = $plugin->is_enabled();
1021 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1023 $plugin->get_settings($mform);
1029 * Add settings to edit plugin form.
1031 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1032 * This form is modified directly (not returned).
1035 public function add_all_plugin_settings(MoodleQuickForm $mform) {
1036 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1038 $submissionpluginsenabled = array();
1039 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1040 foreach ($this->submissionplugins as $plugin) {
1041 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1043 $group->setElements($submissionpluginsenabled);
1045 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1046 $feedbackpluginsenabled = array();
1047 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1048 foreach ($this->feedbackplugins as $plugin) {
1049 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1051 $group->setElements($feedbackpluginsenabled);
1052 $mform->setExpanded('submissiontypes');
1056 * Allow each plugin an opportunity to update the defaultvalues
1057 * passed in to the settings form (needed to set up draft areas for
1058 * editor and filemanager elements)
1060 * @param array $defaultvalues
1062 public function plugin_data_preprocessing(&$defaultvalues) {
1063 foreach ($this->submissionplugins as $plugin) {
1064 if ($plugin->is_visible()) {
1065 $plugin->data_preprocessing($defaultvalues);
1068 foreach ($this->feedbackplugins as $plugin) {
1069 if ($plugin->is_visible()) {
1070 $plugin->data_preprocessing($defaultvalues);
1076 * Get the name of the current module.
1078 * @return string the module name (Assignment)
1080 protected function get_module_name() {
1081 if (isset(self::$modulename)) {
1082 return self::$modulename;
1084 self::$modulename = get_string('modulename', 'assign');
1085 return self::$modulename;
1089 * Get the plural name of the current module.
1091 * @return string the module name plural (Assignments)
1093 protected function get_module_name_plural() {
1094 if (isset(self::$modulenameplural)) {
1095 return self::$modulenameplural;
1097 self::$modulenameplural = get_string('modulenameplural', 'assign');
1098 return self::$modulenameplural;
1102 * Has this assignment been constructed from an instance?
1106 public function has_instance() {
1107 return $this->instance || $this->get_course_module();
1111 * Get the settings for the current instance of this assignment
1113 * @return stdClass The settings
1115 public function get_instance() {
1117 if ($this->instance) {
1118 return $this->instance;
1120 if ($this->get_course_module()) {
1121 $params = array('id' => $this->get_course_module()->instance);
1122 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1124 if (!$this->instance) {
1125 throw new coding_exception('Improper use of the assignment class. ' .
1126 'Cannot load the assignment record.');
1128 return $this->instance;
1132 * Get the primary grade item for this assign instance.
1134 * @return stdClass The grade_item record
1136 public function get_grade_item() {
1137 if ($this->gradeitem) {
1138 return $this->gradeitem;
1140 $instance = $this->get_instance();
1141 $params = array('itemtype' => 'mod',
1142 'itemmodule' => 'assign',
1143 'iteminstance' => $instance->id,
1144 'courseid' => $instance->course,
1146 $this->gradeitem = grade_item::fetch($params);
1147 if (!$this->gradeitem) {
1148 throw new coding_exception('Improper use of the assignment class. ' .
1149 'Cannot load the grade item.');
1151 return $this->gradeitem;
1155 * Get the context of the current course.
1157 * @return mixed context|null The course context
1159 public function get_course_context() {
1160 if (!$this->context && !$this->course) {
1161 throw new coding_exception('Improper use of the assignment class. ' .
1162 'Cannot load the course context.');
1164 if ($this->context) {
1165 return $this->context->get_course_context();
1167 return context_course::instance($this->course->id);
1173 * Get the current course module.
1175 * @return mixed stdClass|null The course module
1177 public function get_course_module() {
1178 if ($this->coursemodule) {
1179 return $this->coursemodule;
1181 if (!$this->context) {
1185 if ($this->context->contextlevel == CONTEXT_MODULE) {
1186 $this->coursemodule = get_coursemodule_from_id('assign',
1187 $this->context->instanceid,
1191 return $this->coursemodule;
1197 * Get context module.
1201 public function get_context() {
1202 return $this->context;
1206 * Get the current course.
1208 * @return mixed stdClass|null The course
1210 public function get_course() {
1213 if ($this->course) {
1214 return $this->course;
1217 if (!$this->context) {
1220 $params = array('id' => $this->get_course_context()->instanceid);
1221 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1223 return $this->course;
1227 * Return a grade in user-friendly form, whether it's a scale or not.
1229 * @param mixed $grade int|null
1230 * @param boolean $editing Are we allowing changes to this grade?
1231 * @param int $userid The user id the grade belongs to
1232 * @param int $modified Timestamp from when the grade was last modified
1233 * @return string User-friendly representation of grade
1235 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1238 static $scalegrades = array();
1242 if ($this->get_instance()->grade >= 0) {
1244 if ($editing && $this->get_instance()->grade > 0) {
1248 $displaygrade = format_float($grade, 2);
1250 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1251 get_string('usergrade', 'assign') .
1253 $o .= '<input type="text"
1254 id="quickgrade_' . $userid . '"
1255 name="quickgrade_' . $userid . '"
1256 value="' . $displaygrade . '"
1259 class="quickgrade"/>';
1260 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1263 if ($grade == -1 || $grade === null) {
1266 $item = $this->get_grade_item();
1267 $o .= grade_format_gradevalue($grade, $item);
1268 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1269 // If displaying the raw grade, also display the total value.
1270 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1278 if (empty($this->cache['scale'])) {
1279 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1280 $this->cache['scale'] = make_menu_from_list($scale->scale);
1287 $o .= '<label class="accesshide"
1288 for="quickgrade_' . $userid . '">' .
1289 get_string('usergrade', 'assign') .
1291 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1292 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1293 foreach ($this->cache['scale'] as $optionid => $option) {
1295 if ($grade == $optionid) {
1296 $selected = 'selected="selected"';
1298 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1303 $scaleid = (int)$grade;
1304 if (isset($this->cache['scale'][$scaleid])) {
1305 $o .= $this->cache['scale'][$scaleid];
1315 * Load a list of users enrolled in the current course with the specified permission and group.
1318 * @param int $currentgroup
1319 * @param bool $idsonly
1320 * @return array List of user records
1322 public function list_participants($currentgroup, $idsonly) {
1323 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1324 if (!isset($this->participants[$key])) {
1325 $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1326 $this->show_only_active_users());
1328 $cm = $this->get_course_module();
1329 $users = groups_filter_users_by_course_module_visible($cm, $users);
1331 $this->participants[$key] = $users;
1336 foreach ($this->participants[$key] as $id => $user) {
1337 $idslist[$id] = new stdClass();
1338 $idslist[$id]->id = $id;
1342 return $this->participants[$key];
1346 * Load a count of valid teams for this assignment.
1348 * @return int number of valid teams
1350 public function count_teams() {
1352 $groups = groups_get_all_groups($this->get_course()->id,
1354 $this->get_instance()->teamsubmissiongroupingid,
1356 $count = count($groups);
1358 // See if there are any users in the default group.
1359 $defaultusers = $this->get_submission_group_members(0, true);
1360 if (count($defaultusers) > 0) {
1367 * Load a count of active users enrolled in the current course with the specified permission and group.
1370 * @param int $currentgroup
1371 * @return int number of matching users
1373 public function count_participants($currentgroup) {
1374 return count($this->list_participants($currentgroup, true));
1378 * Load a count of active users submissions in the current module that require grading
1379 * This means the submission modification time is more recent than the
1380 * grading modification time and the status is SUBMITTED.
1382 * @return int number of matching submissions
1384 public function count_submissions_need_grading() {
1387 if ($this->get_instance()->teamsubmission) {
1388 // This does not make sense for group assignment because the submission is shared.
1392 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1393 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1395 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1396 FROM {assign_submission} mxs
1397 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1398 $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
1399 FROM {assign_grades} mxg
1400 WHERE mxg.assignment = :assignid3 GROUP BY mxg.userid';
1402 $params['assignid'] = $this->get_instance()->id;
1403 $params['assignid2'] = $this->get_instance()->id;
1404 $params['assignid3'] = $this->get_instance()->id;
1405 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1407 $sql = 'SELECT COUNT(s.userid)
1408 FROM {assign_submission} s
1409 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON s.userid = smx.userid
1410 LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON s.userid = gmx.userid
1411 LEFT JOIN {assign_grades} g ON
1412 s.assignment = g.assignment AND
1413 s.userid = g.userid AND
1414 g.attemptnumber = gmx.maxattempt
1415 JOIN(' . $esql . ') e ON e.id = s.userid
1417 s.attemptnumber = smx.maxattempt AND
1418 s.assignment = :assignid AND
1419 s.timemodified IS NOT NULL AND
1420 s.status = :submitted AND
1421 (s.timemodified > g.timemodified OR g.timemodified IS NULL)';
1423 return $DB->count_records_sql($sql, $params);
1427 * Load a count of grades.
1429 * @return int number of grades
1431 public function count_grades() {
1434 if (!$this->has_instance()) {
1438 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1439 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1441 $params['assignid'] = $this->get_instance()->id;
1443 $sql = 'SELECT COUNT(g.userid)
1444 FROM {assign_grades} g
1445 JOIN(' . $esql . ') e ON e.id = g.userid
1446 WHERE g.assignment = :assignid';
1448 return $DB->count_records_sql($sql, $params);
1452 * Load a count of submissions.
1454 * @return int number of submissions
1456 public function count_submissions() {
1459 if (!$this->has_instance()) {
1465 if ($this->get_instance()->teamsubmission) {
1466 // We cannot join on the enrolment tables for group submissions (no userid).
1467 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1468 FROM {assign_submission} s
1470 s.assignment = :assignid AND
1471 s.timemodified IS NOT NULL AND
1472 s.userid = :groupuserid';
1474 $params['assignid'] = $this->get_instance()->id;
1475 $params['groupuserid'] = 0;
1477 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1478 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1480 $params['assignid'] = $this->get_instance()->id;
1482 $sql = 'SELECT COUNT(DISTINCT s.userid)
1483 FROM {assign_submission} s
1484 JOIN(' . $esql . ') e ON e.id = s.userid
1486 s.assignment = :assignid AND
1487 s.timemodified IS NOT NULL';
1491 return $DB->count_records_sql($sql, $params);
1495 * Load a count of submissions with a specified status.
1497 * @param string $status The submission status - should match one of the constants
1498 * @return int number of matching submissions
1500 public function count_submissions_with_status($status) {
1503 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1504 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1506 $params['assignid'] = $this->get_instance()->id;
1507 $params['assignid2'] = $this->get_instance()->id;
1508 $params['submissionstatus'] = $status;
1510 if ($this->get_instance()->teamsubmission) {
1511 $maxattemptsql = 'SELECT mxs.groupid, MAX(mxs.attemptnumber) AS maxattempt
1512 FROM {assign_submission} mxs
1513 WHERE mxs.assignment = :assignid2 GROUP BY mxs.groupid';
1515 $sql = 'SELECT COUNT(s.groupid)
1516 FROM {assign_submission} s
1517 JOIN(' . $maxattemptsql . ') smx ON s.groupid = smx.groupid
1519 s.attemptnumber = smx.maxattempt AND
1520 s.assignment = :assignid AND
1521 s.timemodified IS NOT NULL AND
1522 s.userid = :groupuserid AND
1523 s.status = :submissionstatus';
1524 $params['groupuserid'] = 0;
1526 $maxattemptsql = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
1527 FROM {assign_submission} mxs
1528 WHERE mxs.assignment = :assignid2 GROUP BY mxs.userid';
1530 $sql = 'SELECT COUNT(s.userid)
1531 FROM {assign_submission} s
1532 JOIN(' . $esql . ') e ON e.id = s.userid
1533 JOIN(' . $maxattemptsql . ') smx ON s.userid = smx.userid
1535 s.attemptnumber = smx.maxattempt AND
1536 s.assignment = :assignid AND
1537 s.timemodified IS NOT NULL AND
1538 s.status = :submissionstatus';
1542 return $DB->count_records_sql($sql, $params);
1546 * Utility function to get the userid for every row in the grading table
1547 * so the order can be frozen while we iterate it.
1549 * @return array An array of userids
1551 protected function get_grading_userid_list() {
1552 $filter = get_user_preferences('assign_filter', '');
1553 $table = new assign_grading_table($this, 0, $filter, 0, false);
1555 $useridlist = $table->get_column_data('userid');
1561 * Generate zip file from array of given files.
1563 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1564 * This array is indexed by the final file name and each
1565 * element in the array is an instance of a stored_file object.
1566 * @return path of temp file - note this returned file does
1567 * not have a .zip extension - it is a temp file.
1569 protected function pack_files($filesforzipping) {
1571 // Create path for new zip file.
1572 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1574 $zipper = new zip_packer();
1575 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1582 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1584 * Cron function to be run periodically according to the moodle cron.
1588 public static function cron() {
1591 // Only ever send a max of one days worth of updates.
1592 $yesterday = time() - (24 * 3600);
1595 // Collect all submissions from the past 24 hours that require mailing.
1596 $sql = 'SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1597 g.*, g.timemodified as lastmodified
1599 JOIN {assign_grades} g ON g.assignment = a.id
1600 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1601 WHERE g.timemodified >= :yesterday AND
1602 g.timemodified <= :today AND
1605 $params = array('yesterday' => $yesterday, 'today' => $timenow);
1606 $submissions = $DB->get_records_sql($sql, $params);
1608 if (empty($submissions)) {
1612 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1614 // Preload courses we are going to need those.
1615 $courseids = array();
1616 foreach ($submissions as $submission) {
1617 $courseids[] = $submission->course;
1620 // Filter out duplicates.
1621 $courseids = array_unique($courseids);
1622 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1623 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1624 $sql = 'SELECT c.*, ' . $ctxselect .
1626 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1627 WHERE c.id ' . $courseidsql;
1629 $params['contextlevel'] = CONTEXT_COURSE;
1630 $courses = $DB->get_records_sql($sql, $params);
1632 // Clean up... this could go on for a while.
1635 unset($courseidsql);
1638 // Simple array we'll use for caching modules.
1639 $modcache = array();
1641 // Message students about new feedback.
1642 foreach ($submissions as $submission) {
1644 mtrace("Processing assignment submission $submission->id ...");
1646 // Do not cache user lookups - could be too many.
1647 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1648 mtrace('Could not find user ' . $submission->userid);
1652 // Use a cache to prevent the same DB queries happening over and over.
1653 if (!array_key_exists($submission->course, $courses)) {
1654 mtrace('Could not find course ' . $submission->course);
1657 $course = $courses[$submission->course];
1658 if (isset($course->ctxid)) {
1659 // Context has not yet been preloaded. Do so now.
1660 context_helper::preload_from_record($course);
1663 // Override the language and timezone of the "current" user, so that
1664 // mail is customised for the receiver.
1665 cron_setup_user($user, $course);
1667 // Context lookups are already cached.
1668 $coursecontext = context_course::instance($course->id);
1669 if (!is_enrolled($coursecontext, $user->id)) {
1670 $courseshortname = format_string($course->shortname,
1672 array('context' => $coursecontext));
1673 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1677 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1678 mtrace('Could not find grader ' . $submission->grader);
1682 if (!array_key_exists($submission->assignment, $modcache)) {
1683 $mod = get_coursemodule_from_instance('assign', $submission->assignment, $course->id);
1685 mtrace('Could not find course module for assignment id ' . $submission->assignment);
1688 $modcache[$submission->assignment] = $mod;
1690 $mod = $modcache[$submission->assignment];
1692 // Context lookups are already cached.
1693 $contextmodule = context_module::instance($mod->id);
1695 if (!$mod->visible) {
1696 // Hold mail notification for hidden assignments until later.
1700 // Need to send this to the student.
1701 $messagetype = 'feedbackavailable';
1702 $eventtype = 'assign_notification';
1703 $updatetime = $submission->lastmodified;
1704 $modulename = get_string('modulename', 'assign');
1707 if ($submission->blindmarking && !$submission->revealidentities) {
1708 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1710 $showusers = $submission->blindmarking && !$submission->revealidentities;
1711 self::send_assignment_notification($grader,
1724 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1727 $DB->update_record('assign_user_flags', $flags);
1729 $flags = new stdClass();
1730 $flags->userid = $user->id;
1731 $flags->assignment = $submission->assignment;
1733 $DB->insert_record('assign_user_flags', $flags);
1738 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1742 // Free up memory just to be sure.
1750 * Mark in the database that this grade record should have an update notification sent by cron.
1752 * @param stdClass $grade a grade record keyed on id
1753 * @return bool true for success
1755 public function notify_grade_modified($grade) {
1758 $flags = $this->get_user_flags($grade->userid, true);
1759 if ($flags->mailed != 1) {
1763 return $this->update_user_flags($flags);
1767 * Update user flags for this user in this assignment.
1769 * @param stdClass $flags a flags record keyed on id
1770 * @return bool true for success
1772 public function update_user_flags($flags) {
1774 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1778 $result = $DB->update_record('assign_user_flags', $flags);
1783 * Update a grade in the grade table for the assignment and in the gradebook.
1785 * @param stdClass $grade a grade record keyed on id
1786 * @return bool true for success
1788 public function update_grade($grade) {
1791 $grade->timemodified = time();
1793 if (!empty($grade->workflowstate)) {
1794 $validstates = $this->get_marking_workflow_states_for_current_user();
1795 if (!array_key_exists($grade->workflowstate, $validstates)) {
1800 if ($grade->grade && $grade->grade != -1) {
1801 if ($this->get_instance()->grade > 0) {
1802 if (!is_numeric($grade->grade)) {
1804 } else if ($grade->grade > $this->get_instance()->grade) {
1806 } else if ($grade->grade < 0) {
1811 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1812 $scaleoptions = make_menu_from_list($scale->scale);
1813 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1820 if (empty($grade->attemptnumber)) {
1821 // Set it to the default.
1822 $grade->attemptnumber = 0;
1824 $result = $DB->update_record('assign_grades', $grade);
1826 // Only push to gradebook if the update is for the latest attempt.
1828 if ($this->get_instance()->teamsubmission) {
1829 $submission = $this->get_group_submission($grade->userid, 0, false);
1831 $submission = $this->get_user_submission($grade->userid, false);
1833 // Not the latest attempt.
1834 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1839 $this->gradebook_item_update(null, $grade);
1845 * View the grant extension date page.
1847 * Uses url parameters 'userid'
1848 * or from parameter 'selectedusers'
1850 * @param moodleform $mform - Used for validation of the submitted data
1853 protected function view_grant_extension($mform) {
1855 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
1858 $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
1859 $data = new stdClass();
1860 $data->extensionduedate = null;
1863 $userid = required_param('userid', PARAM_INT);
1865 $grade = $this->get_user_grade($userid, false);
1867 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
1870 $data->extensionduedate = $grade->extensionduedate;
1872 $data->userid = $userid;
1874 $data->batchusers = $batchusers;
1876 $header = new assign_header($this->get_instance(),
1877 $this->get_context(),
1878 $this->show_intro(),
1879 $this->get_course_module()->id,
1880 get_string('grantextension', 'assign'));
1881 $o .= $this->get_renderer()->render($header);
1884 $formparams = array($this->get_course_module()->id,
1887 $this->get_instance(),
1889 $mform = new mod_assign_extension_form(null, $formparams);
1891 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
1892 $o .= $this->view_footer();
1897 * Get a list of the users in the same group as this user.
1899 * @param int $groupid The id of the group whose members we want or 0 for the default group
1900 * @param bool $onlyids Whether to retrieve only the user id's
1901 * @return array The users (possibly id's only)
1903 public function get_submission_group_members($groupid, $onlyids) {
1905 if ($groupid != 0) {
1907 $allusers = groups_get_members($groupid, 'u.id');
1909 $allusers = groups_get_members($groupid);
1911 foreach ($allusers as $user) {
1912 if ($this->get_submission_group($user->id)) {
1917 $allusers = $this->list_participants(null, $onlyids);
1918 foreach ($allusers as $user) {
1919 if ($this->get_submission_group($user->id) == null) {
1924 // Exclude suspended users, if user can't see them.
1925 if (!has_capability('moodle/course:viewsuspendedusers', $this->context)) {
1926 foreach ($members as $key => $member) {
1927 if (!$this->is_active_user($member->id)) {
1928 unset($members[$key]);
1936 * Get a list of the users in the same group as this user that have not submitted the assignment.
1938 * @param int $groupid The id of the group whose members we want or 0 for the default group
1939 * @param bool $onlyids Whether to retrieve only the user id's
1940 * @return array The users (possibly id's only)
1942 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
1943 $instance = $this->get_instance();
1944 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
1947 $members = $this->get_submission_group_members($groupid, $onlyids);
1949 foreach ($members as $id => $member) {
1950 $submission = $this->get_user_submission($member->id, false);
1951 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1952 unset($members[$id]);
1954 if ($this->is_blind_marking()) {
1955 $members[$id]->alias = get_string('hiddenuser', 'assign') .
1956 $this->get_uniqueid_for_user($id);
1964 * Load the group submission object for a particular user, optionally creating it if required.
1966 * @param int $userid The id of the user whose submission we want
1967 * @param int $groupid The id of the group for this user - may be 0 in which
1968 * case it is determined from the userid.
1969 * @param bool $create If set to true a new submission object will be created in the database
1970 * @param int $attemptnumber - -1 means the latest attempt
1971 * @return stdClass The submission
1973 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
1976 if ($groupid == 0) {
1977 $group = $this->get_submission_group($userid);
1979 $groupid = $group->id;
1983 // Now get the group submission.
1984 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
1985 if ($attemptnumber >= 0) {
1986 $params['attemptnumber'] = $attemptnumber;
1989 // Only return the row with the highest attemptnumber.
1991 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
1993 $submission = reset($submissions);
2000 $submission = new stdClass();
2001 $submission->assignment = $this->get_instance()->id;
2002 $submission->userid = 0;
2003 $submission->groupid = $groupid;
2004 $submission->timecreated = time();
2005 $submission->timemodified = $submission->timecreated;
2006 if ($attemptnumber >= 0) {
2007 $submission->attemptnumber = $attemptnumber;
2009 $submission->attemptnumber = 0;
2012 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2013 $sid = $DB->insert_record('assign_submission', $submission);
2014 $submission->id = $sid;
2021 * View a summary listing of all assignments in the current course.
2025 private function view_course_index() {
2030 $course = $this->get_course();
2031 $strplural = get_string('modulenameplural', 'assign');
2033 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2034 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2035 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2039 $strsectionname = '';
2040 $usesections = course_format_uses_sections($course->format);
2041 $modinfo = get_fast_modinfo($course);
2044 $strsectionname = get_string('sectionname', 'format_'.$course->format);
2045 $sections = $modinfo->get_section_info_all();
2047 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2051 $currentsection = '';
2052 foreach ($modinfo->instances['assign'] as $cm) {
2053 if (!$cm->uservisible) {
2057 $timedue = $cms[$cm->id]->duedate;
2060 if ($usesections && $cm->sectionnum) {
2061 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2065 $context = context_module::instance($cm->id);
2067 $assignment = new assign($context, $cm, $course);
2069 if (has_capability('mod/assign:grade', $context)) {
2070 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2072 } else if (has_capability('mod/assign:submit', $context)) {
2073 $usersubmission = $assignment->get_user_submission($USER->id, false);
2075 if (!empty($usersubmission->status)) {
2076 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2078 $submitted = get_string('submissionstatus_', 'assign');
2081 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2082 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2083 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2084 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2089 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2093 $o .= $this->get_renderer()->render($courseindexsummary);
2094 $o .= $this->view_footer();
2100 * View a page rendered by a plugin.
2102 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2106 protected function view_plugin_page() {
2111 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2112 $plugintype = required_param('plugin', PARAM_TEXT);
2113 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2115 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2117 print_error('invalidformdata', '');
2121 $o .= $plugin->view_page($pluginaction);
2128 * This is used for team assignments to get the group for the specified user.
2129 * If the user is a member of multiple or no groups this will return false
2131 * @param int $userid The id of the user whose submission we want
2132 * @return mixed The group or false
2134 public function get_submission_group($userid) {
2135 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2136 $groups = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2137 if (count($groups) != 1) {
2140 return array_pop($groups);
2145 * Display the submission that is used by a plugin.
2147 * Uses url parameters 'sid', 'gid' and 'plugin'.
2149 * @param string $pluginsubtype
2152 protected function view_plugin_content($pluginsubtype) {
2155 $submissionid = optional_param('sid', 0, PARAM_INT);
2156 $gradeid = optional_param('gid', 0, PARAM_INT);
2157 $plugintype = required_param('plugin', PARAM_TEXT);
2159 if ($pluginsubtype == 'assignsubmission') {
2160 $plugin = $this->get_submission_plugin_by_type($plugintype);
2161 if ($submissionid <= 0) {
2162 throw new coding_exception('Submission id should not be 0');
2164 $item = $this->get_submission($submissionid);
2166 // Check permissions.
2167 $this->require_view_submission($item->userid);
2168 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2169 $this->get_context(),
2170 $this->show_intro(),
2171 $this->get_course_module()->id,
2172 $plugin->get_name()));
2173 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2175 assign_submission_plugin_submission::FULL,
2176 $this->get_course_module()->id,
2177 $this->get_return_action(),
2178 $this->get_return_params()));
2180 // Trigger event for viewing a submission.
2181 $logmessage = new lang_string('viewsubmissionforuser', 'assign', $item->userid);
2182 $event = \mod_assign\event\submission_viewed::create(array(
2183 'objectid' => $item->id,
2184 'relateduserid' => $item->userid,
2185 'context' => $this->get_context(),
2187 'assignid' => $this->get_instance()->id
2190 $event->set_legacy_logdata('view submission', $logmessage);
2193 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2194 if ($gradeid <= 0) {
2195 throw new coding_exception('Grade id should not be 0');
2197 $item = $this->get_grade($gradeid);
2198 // Check permissions.
2199 $this->require_view_submission($item->userid);
2200 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2201 $this->get_context(),
2202 $this->show_intro(),
2203 $this->get_course_module()->id,
2204 $plugin->get_name()));
2205 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2207 assign_feedback_plugin_feedback::FULL,
2208 $this->get_course_module()->id,
2209 $this->get_return_action(),
2210 $this->get_return_params()));
2212 // Trigger event for viewing feedback.
2213 $logmessage = new lang_string('viewfeedbackforuser', 'assign', $item->userid);
2214 $event = \mod_assign\event\feedback_viewed::create(array(
2215 'objectid' => $item->id,
2216 'relateduserid' => $item->userid,
2217 'context' => $this->get_context(),
2219 'assignid' => $this->get_instance()->id
2222 $event->set_legacy_logdata('view feedback', $logmessage);
2226 $o .= $this->view_return_links();
2228 $o .= $this->view_footer();
2234 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2236 * @param string $text - The replacement text
2237 * @param stdClass $user - The user record
2238 * @param assign_plugin $plugin - The assignment plugin
2240 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2241 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2244 $groupid = groups_get_activity_group($this->get_course_module(), true);
2245 $groupname = groups_get_group_name($groupid).'-';
2248 if ($this->is_blind_marking()) {
2249 $prefix = $groupname . get_string('participant', 'assign');
2250 $prefix = str_replace('_', ' ', $prefix);
2251 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2253 $prefix = $groupname . fullname($user);
2254 $prefix = str_replace('_', ' ', $prefix);
2255 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2258 $subtype = $plugin->get_subtype();
2259 $type = $plugin->get_type();
2260 $prefix = $prefix . $subtype . '_' . $type . '_';
2262 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2268 * Render the content in editor that is often used by plugin.
2270 * @param string $filearea
2271 * @param int $submissionid
2272 * @param string $plugintype
2273 * @param string $editor
2274 * @param string $component
2277 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2282 $plugin = $this->get_submission_plugin_by_type($plugintype);
2284 $text = $plugin->get_editor_text($editor, $submissionid);
2285 $format = $plugin->get_editor_format($editor, $submissionid);
2287 $finaltext = file_rewrite_pluginfile_urls($text,
2289 $this->get_context()->id,
2293 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2294 $result .= format_text($finaltext, $format, $params);
2296 if ($CFG->enableportfolios) {
2297 require_once($CFG->libdir . '/portfoliolib.php');
2299 $button = new portfolio_add_button();
2300 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2301 'sid' => $submissionid,
2302 'plugin' => $plugintype,
2303 'editor' => $editor,
2305 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2306 $fs = get_file_storage();
2308 if ($files = $fs->get_area_files($this->context->id,
2314 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2316 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2318 $result .= $button->to_html();
2324 * Display a continue page.
2326 * @param string $message - The message to display
2329 protected function view_savegrading_result($message) {
2331 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2332 $this->get_context(),
2333 $this->show_intro(),
2334 $this->get_course_module()->id,
2335 get_string('savegradingresult', 'assign')));
2336 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2338 $this->get_course_module()->id);
2339 $o .= $this->get_renderer()->render($gradingresult);
2340 $o .= $this->view_footer();
2344 * Display a grading error.
2346 * @param string $message - The description of the result
2349 protected function view_quickgrading_result($message) {
2351 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2352 $this->get_context(),
2353 $this->show_intro(),
2354 $this->get_course_module()->id,
2355 get_string('quickgradingresult', 'assign')));
2356 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2358 $this->get_course_module()->id);
2359 $o .= $this->get_renderer()->render($gradingresult);
2360 $o .= $this->view_footer();
2365 * Display the page footer.
2369 protected function view_footer() {
2370 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2371 if (!PHPUNIT_TEST) {
2372 return $this->get_renderer()->render_footer();
2379 * Throw an error if the permissions to view this users submission are missing.
2381 * @throws required_capability_exception
2384 public function require_view_submission($userid) {
2385 if (!$this->can_view_submission($userid)) {
2386 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2391 * Throw an error if the permissions to view grades in this assignment are missing.
2393 * @throws required_capability_exception
2396 public function require_view_grades() {
2397 if (!$this->can_view_grades()) {
2398 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2403 * Does this user have view grade or grade permission for this assignment?
2407 public function can_view_grades() {
2408 // Permissions check.
2409 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2417 * Does this user have grade permission for this assignment?
2421 public function can_grade() {
2422 // Permissions check.
2423 if (!has_capability('mod/assign:grade', $this->context)) {
2431 * Download a zip file of all assignment submissions.
2433 * @return string - If an error occurs, this will contain the error page.
2435 protected function download_submissions() {
2438 // More efficient to load this here.
2439 require_once($CFG->libdir.'/filelib.php');
2441 $this->require_view_grades();
2443 // Load all users with submit.
2444 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2445 $this->show_only_active_users());
2447 // Build a list of files to zip.
2448 $filesforzipping = array();
2449 $fs = get_file_storage();
2451 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2456 $groupid = groups_get_activity_group($this->get_course_module(), true);
2457 $groupname = groups_get_group_name($groupid).'-';
2460 // Construct the zip file name.
2461 $filename = clean_filename($this->get_course()->shortname . '-' .
2462 $this->get_instance()->name . '-' .
2463 $groupname.$this->get_course_module()->id . '.zip');
2465 // Get all the files for each student.
2466 foreach ($students as $student) {
2467 $userid = $student->id;
2469 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2470 // Get the plugins to add their own files to the zip.
2472 $submissiongroup = false;
2474 if ($this->get_instance()->teamsubmission) {
2475 $submission = $this->get_group_submission($userid, 0, false);
2476 $submissiongroup = $this->get_submission_group($userid);
2477 if ($submissiongroup) {
2478 $groupname = $submissiongroup->name . '-';
2480 $groupname = get_string('defaultteam', 'assign') . '-';
2483 $submission = $this->get_user_submission($userid, false);
2486 if ($this->is_blind_marking()) {
2487 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2488 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2490 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2491 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2495 foreach ($this->submissionplugins as $plugin) {
2496 if ($plugin->is_enabled() && $plugin->is_visible()) {
2497 $pluginfiles = $plugin->get_files($submission, $student);
2498 foreach ($pluginfiles as $zipfilename => $file) {
2499 $subtype = $plugin->get_subtype();
2500 $type = $plugin->get_type();
2501 $prefixedfilename = clean_filename($prefix .
2507 $filesforzipping[$prefixedfilename] = $file;
2515 if (count($filesforzipping) == 0) {
2516 $header = new assign_header($this->get_instance(),
2517 $this->get_context(),
2519 $this->get_course_module()->id,
2520 get_string('downloadall', 'assign'));
2521 $result .= $this->get_renderer()->render($header);
2522 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2523 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2524 'action'=>'grading'));
2525 $result .= $this->get_renderer()->continue_button($url);
2526 $result .= $this->view_footer();
2527 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2529 'context' => $this->context,
2530 'objectid' => $this->get_instance()->id
2532 $event = \mod_assign\event\all_submissions_downloaded::create($params);
2533 $event->set_legacy_logdata('download all submissions', new lang_string('downloadall', 'assign'));
2535 // Send file and delete after sending.
2536 send_temp_file($zipfile, $filename);
2537 // We will not get here - send_temp_file calls exit.
2543 * Util function to add a message to the log.
2545 * @deprecated since 2.7 - Use new events system instead.
2546 * (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2548 * @param string $action The current action
2549 * @param string $info A detailed description of the change. But no more than 255 characters.
2550 * @param string $url The url to the assign module instance.
2551 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2552 * retrieve the arguments to use them with the new event system (Event 2).
2553 * @return void|array
2555 public function add_to_log($action = '', $info = '', $url='', $return = false) {
2558 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2560 $fullurl .= '&' . $url;
2564 $this->get_course()->id,
2569 $this->get_course_module()->id
2573 // We only need to call debugging when returning a value. This is because the call to
2574 // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2575 debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2578 call_user_func_array('add_to_log', $args);
2582 * Lazy load the page renderer and expose the renderer to plugins.
2584 * @return assign_renderer
2586 public function get_renderer() {
2588 if ($this->output) {
2589 return $this->output;
2591 $this->output = $PAGE->get_renderer('mod_assign');
2592 return $this->output;
2596 * Load the submission object for a particular user, optionally creating it if required.
2598 * For team assignments there are 2 submissions - the student submission and the team submission
2599 * All files are associated with the team submission but the status of the students contribution is
2600 * recorded separately.
2602 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2603 * @param bool $create optional - defaults to false. If set to true a new submission object
2604 * will be created in the database.
2605 * @param int $attemptnumber - -1 means the latest attempt
2606 * @return stdClass The submission
2608 public function get_user_submission($userid, $create, $attemptnumber=-1) {
2612 $userid = $USER->id;
2614 // If the userid is not null then use userid.
2615 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2616 if ($attemptnumber >= 0) {
2617 $params['attemptnumber'] = $attemptnumber;
2620 // Only return the row with the highest attemptnumber.
2622 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2624 $submission = reset($submissions);
2631 $submission = new stdClass();
2632 $submission->assignment = $this->get_instance()->id;
2633 $submission->userid = $userid;
2634 $submission->timecreated = time();
2635 $submission->timemodified = $submission->timecreated;
2636 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
2637 if ($attemptnumber >= 0) {
2638 $submission->attemptnumber = $attemptnumber;
2640 $submission->attemptnumber = 0;
2642 $sid = $DB->insert_record('assign_submission', $submission);
2643 $submission->id = $sid;
2650 * Load the submission object from it's id.
2652 * @param int $submissionid The id of the submission we want
2653 * @return stdClass The submission
2655 protected function get_submission($submissionid) {
2658 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2659 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2663 * This will retrieve a user flags object from the db optionally creating it if required.
2664 * The user flags was split from the user_grades table in 2.5.
2666 * @param int $userid The user we are getting the flags for.
2667 * @param bool $create If true the flags record will be created if it does not exist
2668 * @return stdClass The flags record
2670 public function get_user_flags($userid, $create) {
2673 // If the userid is not null then use userid.
2675 $userid = $USER->id;
2678 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2680 $flags = $DB->get_record('assign_user_flags', $params);
2686 $flags = new stdClass();
2687 $flags->assignment = $this->get_instance()->id;
2688 $flags->userid = $userid;
2690 $flags->extensionduedate = 0;
2691 $flags->workflowstate = '';
2692 $flags->allocatedmarker = 0;
2694 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2695 // This is because students only want to be notified about certain types of update (grades and feedback).
2698 $fid = $DB->insert_record('assign_user_flags', $flags);
2706 * This will retrieve a grade object from the db, optionally creating it if required.
2708 * @param int $userid The user we are grading
2709 * @param bool $create If true the grade will be created if it does not exist
2710 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2711 * @return stdClass The grade record
2713 public function get_user_grade($userid, $create, $attemptnumber=-1) {
2716 // If the userid is not null then use userid.
2718 $userid = $USER->id;
2721 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2722 if ($attemptnumber < 0) {
2723 // Make sure this grade matches the latest submission attempt.
2724 if ($this->get_instance()->teamsubmission) {
2725 $submission = $this->get_group_submission($userid, 0, false);
2727 $submission = $this->get_user_submission($userid, false);
2730 $attemptnumber = $submission->attemptnumber;
2734 if ($attemptnumber >= 0) {
2735 $params['attemptnumber'] = $attemptnumber;
2738 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2741 return reset($grades);
2744 $grade = new stdClass();
2745 $grade->assignment = $this->get_instance()->id;
2746 $grade->userid = $userid;
2747 $grade->timecreated = time();
2748 $grade->timemodified = $grade->timecreated;
2750 $grade->grader = $USER->id;
2751 if ($attemptnumber >= 0) {
2752 $grade->attemptnumber = $attemptnumber;
2755 $gid = $DB->insert_record('assign_grades', $grade);
2763 * This will retrieve a grade object from the db.
2765 * @param int $gradeid The id of the grade
2766 * @return stdClass The grade record
2768 protected function get_grade($gradeid) {
2771 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2772 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2776 * Print the grading page for a single user submission.
2778 * @param moodleform $mform
2781 protected function view_single_grade_page($mform) {
2785 $instance = $this->get_instance();
2787 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2789 // Need submit permission to submit an assignment.
2790 require_capability('mod/assign:grade', $this->context);
2792 $header = new assign_header($instance,
2793 $this->get_context(),
2795 $this->get_course_module()->id,
2796 get_string('grading', 'assign'));
2797 $o .= $this->get_renderer()->render($header);
2799 // If userid is passed - we are only grading a single student.
2800 $rownum = required_param('rownum', PARAM_INT);
2801 $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
2802 $userid = optional_param('userid', 0, PARAM_INT);
2803 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
2805 $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
2807 if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
2808 $useridlist = $this->get_grading_userid_list();
2810 $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
2813 $useridlist = array($userid);
2816 if ($rownum < 0 || $rownum > count($useridlist)) {
2817 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
2821 $userid = $useridlist[$rownum];
2822 if ($rownum == count($useridlist) - 1) {
2825 $user = $DB->get_record('user', array('id' => $userid));
2827 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2828 $usersummary = new assign_user_summary($user,
2829 $this->get_course()->id,
2831 $this->is_blind_marking(),
2832 $this->get_uniqueid_for_user($user->id),
2833 get_extra_user_fields($this->get_context()),
2834 !$this->is_active_user($userid));
2835 $o .= $this->get_renderer()->render($usersummary);
2837 $submission = $this->get_user_submission($userid, false, $attemptnumber);
2838 $submissiongroup = null;
2839 $teamsubmission = null;
2840 $notsubmitted = array();
2841 if ($instance->teamsubmission) {
2842 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
2843 $submissiongroup = $this->get_submission_group($userid);
2845 if ($submissiongroup) {
2846 $groupid = $submissiongroup->id;
2848 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
2852 // Get the requested grade.
2853 $grade = $this->get_user_grade($userid, false, $attemptnumber);
2854 $flags = $this->get_user_flags($userid, false);
2855 if ($this->can_view_submission($userid)) {
2856 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
2857 $extensionduedate = null;
2859 $extensionduedate = $flags->extensionduedate;
2861 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
2862 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
2864 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
2865 $instance->alwaysshowdescription,
2867 $instance->teamsubmission,
2871 $this->is_any_submission_plugin_enabled(),
2873 $this->is_graded($userid),
2875 $instance->cutoffdate,
2876 $this->get_submission_plugins(),
2877 $this->get_return_action(),
2878 $this->get_return_params(),
2879 $this->get_course_module()->id,
2880 $this->get_course()->id,
2881 assign_submission_status::GRADER_VIEW,
2886 $this->get_context(),
2887 $this->is_blind_marking(),
2889 $instance->attemptreopenmethod,
2890 $instance->maxattempts);
2891 $o .= $this->get_renderer()->render($submissionstatus);
2895 $data = new stdClass();
2896 if ($grade->grade !== null && $grade->grade >= 0) {
2897 $data->grade = format_float($grade->grade, 2);
2899 if (!empty($flags->workflowstate)) {
2900 $data->workflowstate = $flags->workflowstate;
2902 if (!empty($flags->allocatedmarker)) {
2903 $data->allocatedmarker = $flags->allocatedmarker;
2906 $data = new stdClass();
2909 // Warning if required.
2910 $allsubmissions = $this->get_all_submissions($userid);
2912 if ($attemptnumber != -1) {
2913 $params = array('attemptnumber'=>$attemptnumber + 1,
2914 'totalattempts'=>count($allsubmissions));
2915 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
2916 $o .= $this->get_renderer()->notification($message);
2919 // Now show the grading form.
2921 $pagination = array('rownum'=>$rownum,
2922 'useridlistid'=>$useridlistid,
2924 'userid'=>optional_param('userid', 0, PARAM_INT),
2925 'attemptnumber'=>$attemptnumber);
2926 $formparams = array($this, $data, $pagination);
2927 $mform = new mod_assign_grade_form(null,
2931 array('class'=>'gradeform'));
2933 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
2934 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
2936 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
2937 $allgrades = $this->get_all_grades($userid);
2938 $history = new assign_attempt_history($allsubmissions,
2940 $this->get_submission_plugins(),
2941 $this->get_feedback_plugins(),
2942 $this->get_course_module()->id,
2943 $this->get_return_action(),
2944 $this->get_return_params(),
2949 $o .= $this->get_renderer()->render($history);
2952 $msg = get_string('viewgradingformforstudent',
2954 array('id'=>$user->id, 'fullname'=>fullname($user)));
2955 $this->add_to_log('view grading form', $msg);
2957 $o .= $this->view_footer();
2962 * Show a confirmation page to make sure they want to release student identities.
2966 protected function view_reveal_identities_confirm() {
2969 require_capability('mod/assign:revealidentities', $this->get_context());
2972 $header = new assign_header($this->get_instance(),
2973 $this->get_context(),
2975 $this->get_course_module()->id);
2976 $o .= $this->get_renderer()->render($header);
2978 $urlparams = array('id'=>$this->get_course_module()->id,
2979 'action'=>'revealidentitiesconfirm',
2980 'sesskey'=>sesskey());
2981 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
2983 $urlparams = array('id'=>$this->get_course_module()->id,
2984 'action'=>'grading');
2985 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
2987 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
2990 $o .= $this->view_footer();
2991 $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
2996 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3000 protected function view_return_links() {
3001 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
3002 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3005 $returnparams = str_replace('&', '&', $returnparams);
3006 parse_str($returnparams, $params);
3007 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3008 $params = array_merge($newparams, $params);
3010 $url = new moodle_url('/mod/assign/view.php', $params);
3011 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3015 * View the grading table of all submissions for this assignment.
3019 protected function view_grading_table() {
3022 // Include grading options form.
3023 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3024 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3025 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3027 $cmid = $this->get_course_module()->id;
3030 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3031 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3032 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3033 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3035 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3036 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3037 $links[$downloadurl] = get_string('downloadall', 'assign');
3039 if ($this->is_blind_marking() &&
3040 has_capability('mod/assign:revealidentities', $this->get_context())) {
3041 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3042 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3044 foreach ($this->get_feedback_plugins() as $plugin) {
3045 if ($plugin->is_enabled() && $plugin->is_visible()) {
3046 foreach ($plugin->get_grading_actions() as $action => $description) {
3047 $url = '/mod/assign/view.php' .
3049 '&plugin=' . $plugin->get_type() .
3050 '&pluginsubtype=assignfeedback' .
3051 '&action=viewpluginpage&pluginaction=' . $action;
3052 $links[$url] = $description;
3057 // Sort links alphabetically based on the link description.
3058 core_collator::asort($links);
3060 $gradingactions = new url_select($links);
3061 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
3063 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3065 $perpage = get_user_preferences('assign_perpage', 10);
3066 $filter = get_user_preferences('assign_filter', '');
3067 $markerfilter = get_user_preferences('assign_markerfilter', '');
3068 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
3069 $controller = $gradingmanager->get_active_controller();
3070 $showquickgrading = empty($controller) && $this->can_grade();
3071 $quickgrading = get_user_preferences('assign_quickgrading', false);
3072 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
3074 $markingallocation = $this->get_instance()->markingallocation &&
3075 has_capability('mod/assign:manageallocations', $this->context);
3076 // Get markers to use in drop lists.
3077 $markingallocationoptions = array();
3078 if ($markingallocation) {
3079 $markers = get_users_by_capability($this->context, 'mod/assign:grade');
3080 $markingallocationoptions[''] = get_string('filternone', 'assign');
3081 $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
3082 foreach ($markers as $marker) {
3083 $markingallocationoptions[$marker->id] = fullname($marker);
3087 $markingworkflow = $this->get_instance()->markingworkflow;
3088 // Get marking states to show in form.
3089 $markingworkflowoptions = array();
3090 if ($markingworkflow) {
3091 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3092 $markingworkflowoptions[''] = get_string('filternone', 'assign');
3093 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
3094 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3097 // Print options for changing the filter and changing the number of results per page.
3098 $gradingoptionsformparams = array('cm'=>$cmid,
3099 'contextid'=>$this->context->id,
3100 'userid'=>$USER->id,
3101 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3102 'showquickgrading'=>$showquickgrading,
3103 'quickgrading'=>$quickgrading,
3104 'markingworkflowopt'=>$markingworkflowoptions,
3105 'markingallocationopt'=>$markingallocationoptions,
3106 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3107 'showonlyactiveenrol'=>$this->show_only_active_users());
3109 $classoptions = array('class'=>'gradingoptionsform');
3110 $gradingoptionsform = new mod_assign_grading_options_form(null,
3111 $gradingoptionsformparams,
3116 $batchformparams = array('cm'=>$cmid,
3117 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
3118 'duedate'=>$this->get_instance()->duedate,
3119 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
3120 'feedbackplugins'=>$this->get_feedback_plugins(),
3121 'context'=>$this->get_context(),
3122 'markingworkflow'=>$markingworkflow,
3123 'markingallocation'=>$markingallocation);
3124 $classoptions = array('class'=>'gradingbatchoperationsform');
3126 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3132 $gradingoptionsdata = new stdClass();
3133 $gradingoptionsdata->perpage = $perpage;
3134 $gradingoptionsdata->filter = $filter;
3135 $gradingoptionsdata->markerfilter = $markerfilter;
3136 $gradingoptionsdata->workflowfilter = $workflowfilter;
3137 $gradingoptionsform->set_data($gradingoptionsdata);
3139 $actionformtext = $this->get_renderer()->render($gradingactions);
3140 $header = new assign_header($this->get_instance(),
3141 $this->get_context(),
3143 $this->get_course_module()->id,
3144 get_string('grading', 'assign'),
3146 $o .= $this->get_renderer()->render($header);
3148 $currenturl = $CFG->wwwroot .
3149 '/mod/assign/view.php?id=' .
3150 $this->get_course_module()->id .
3153 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3155 // Plagiarism update status apearring in the grading book.
3156 if (!empty($CFG->enableplagiarism)) {
3157 require_once($CFG->libdir . '/plagiarismlib.php');
3158 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3161 // Load and print the table of submissions.
3162 if ($showquickgrading && $quickgrading) {
3163 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3164 $table = $this->get_renderer()->render($gradingtable);
3165 $quickformparams = array('cm'=>$this->get_course_module()->id,
3166 'gradingtable'=>$table,
3167 'sendstudentnotifications'=>$this->get_instance()->sendstudentnotifications);
3168 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3170 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3172 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3173 $o .= $this->get_renderer()->render($gradingtable);
3176 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3177 $users = array_keys($this->list_participants($currentgroup, true));
3178 if (count($users) != 0 && $this->can_grade()) {
3179 // If no enrolled user in a course then don't display the batch operations feature.
3180 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3181 $o .= $this->get_renderer()->render($assignform);
3183 $assignform = new assign_form('gradingoptionsform',
3184 $gradingoptionsform,
3185 'M.mod_assign.init_grading_options');
3186 $o .= $this->get_renderer()->render($assignform);
3191 * View entire grading page.
3195 protected function view_grading_page() {
3199 // Need submit permission to submit an assignment.
3200 $this->require_view_grades();
3201 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3203 // Only load this if it is.
3205 $o .= $this->view_grading_table();
3207 $o .= $this->view_footer();
3209 $logmessage = get_string('viewsubmissiongradingtable', 'assign');
3210 $this->add_to_log('view submission grading table', $logmessage);
3215 * Capture the output of the plagiarism plugins disclosures and return it as a string.
3219 protected function plagiarism_print_disclosure() {
3223 if (!empty($CFG->enableplagiarism)) {
3224 require_once($CFG->libdir . '/plagiarismlib.php');
3226 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
3233 * Message for students when assignment submissions have been closed.
3235 * @param string $title The page title
3236 * @param array $notices The array of notices to show.
3239 protected function view_notices($title, $notices) {
3244 $header = new assign_header($this->get_instance(),
3245 $this->get_context(),
3246 $this->show_intro(),
3247 $this->get_course_module()->id,
3249 $o .= $this->get_renderer()->render($header);
3251 foreach ($notices as $notice) {
3252 $o .= $this->get_renderer()->notification($notice);
3255 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id, 'action'=>'view'));
3256 $o .= $this->get_renderer()->continue_button($url);
3258 $o .= $this->view_footer();