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_NEW', 'new');
31 define('ASSIGN_SUBMISSION_STATUS_REOPENED', 'reopened');
32 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
33 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
35 // Search filters for grading page.
36 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
37 define('ASSIGN_FILTER_NOT_SUBMITTED', 'notsubmitted');
38 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
39 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
40 define('ASSIGN_FILTER_GRANTED_EXTENSION', 'granted_extension');
42 // Marker filter for grading page.
43 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
45 // Reopen attempt methods.
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
47 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
48 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
50 // Special value means allow unlimited attempts.
51 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
53 // Special value means no grade has been set.
54 define('ASSIGN_GRADE_NOT_SET', -1);
57 define('ASSIGN_GRADING_STATUS_GRADED', 'graded');
58 define('ASSIGN_GRADING_STATUS_NOT_GRADED', 'notgraded');
60 // Marking workflow states.
61 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
62 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
63 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
64 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
65 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
66 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
68 /** ASSIGN_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
69 define("ASSIGN_MAX_EVENT_LENGTH", "432000");
71 // Name of file area for intro attachments.
72 define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
75 define('ASSIGN_EVENT_TYPE_DUE', 'due');
76 define('ASSIGN_EVENT_TYPE_GRADINGDUE', 'gradingdue');
77 define('ASSIGN_EVENT_TYPE_OPEN', 'open');
78 define('ASSIGN_EVENT_TYPE_CLOSE', 'close');
80 require_once($CFG->libdir . '/accesslib.php');
81 require_once($CFG->libdir . '/formslib.php');
82 require_once($CFG->dirroot . '/repository/lib.php');
83 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
84 require_once($CFG->libdir . '/gradelib.php');
85 require_once($CFG->dirroot . '/grade/grading/lib.php');
86 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
87 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
88 require_once($CFG->dirroot . '/mod/assign/renderable.php');
89 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
90 require_once($CFG->libdir . '/eventslib.php');
91 require_once($CFG->libdir . '/portfolio/caller.php');
93 use \mod_assign\output\grading_app;
96 * Standard base class for mod_assign (assignment types).
99 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
104 /** @var stdClass the assignment record that contains the global settings for this assign instance */
107 /** @var grade_item the grade_item record for this assign instance's primary grade item. */
110 /** @var context the context of the course module for this assign instance
111 * (or just the course if we are creating a new one)
115 /** @var stdClass the course this assign instance belongs to */
118 /** @var stdClass the admin config for all assign instances */
119 private $adminconfig;
121 /** @var assign_renderer the custom renderer for this module */
124 /** @var cm_info the course module for this assign instance */
125 private $coursemodule;
127 /** @var array cache for things like the coursemodule name or the scale menu -
128 * only lives for a single request.
132 /** @var array list of the installed submission plugins */
133 private $submissionplugins;
135 /** @var array list of the installed feedback plugins */
136 private $feedbackplugins;
138 /** @var string action to be used to return to this page
139 * (without repeating any form submissions etc).
141 private $returnaction = 'view';
143 /** @var array params to be used to return to this page */
144 private $returnparams = array();
146 /** @var string modulename prevents excessive calls to get_string */
147 private static $modulename = null;
149 /** @var string modulenameplural prevents excessive calls to get_string */
150 private static $modulenameplural = null;
152 /** @var array of marking workflow states for the current user */
153 private $markingworkflowstates = null;
155 /** @var bool whether to exclude users with inactive enrolment */
156 private $showonlyactiveenrol = null;
158 /** @var string A key used to identify userlists created by this object. */
159 private $useridlistid = null;
161 /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
162 private $participants = array();
164 /** @var array cached list of user groups when team submissions are enabled. The cache key will be the user. */
165 private $usersubmissiongroups = array();
167 /** @var array cached list of user groups. The cache key will be the user. */
168 private $usergroups = array();
170 /** @var array cached list of IDs of users who share group membership with the user. The cache key will be the user. */
171 private $sharedgroupmembers = array();
174 * @var stdClass The most recent team submission. Used to determine additional attempt numbers and whether
175 * to update the gradebook.
177 private $mostrecentteamsubmission = null;
180 * Constructor for the base assign class.
182 * Note: For $coursemodule you can supply a stdclass if you like, but it
183 * will be more efficient to supply a cm_info object.
185 * @param mixed $coursemodulecontext context|null the course module context
186 * (or the course context if the coursemodule has not been
188 * @param mixed $coursemodule the current course module if it was already loaded,
189 * otherwise this class will load one from the context as required.
190 * @param mixed $course the current course if it was already loaded,
191 * otherwise this class will load one from the context as required.
193 public function __construct($coursemodulecontext, $coursemodule, $course) {
196 $this->context = $coursemodulecontext;
197 $this->course = $course;
199 // Ensure that $this->coursemodule is a cm_info object (or null).
200 $this->coursemodule = cm_info::create($coursemodule);
202 // Temporary cache only lives for a single request - used to reduce db lookups.
203 $this->cache = array();
205 $this->submissionplugins = $this->load_plugins('assignsubmission');
206 $this->feedbackplugins = $this->load_plugins('assignfeedback');
208 // Extra entropy is required for uniqid() to work on cygwin.
209 $this->useridlistid = clean_param(uniqid('', true), PARAM_ALPHANUM);
211 if (!isset($SESSION->mod_assign_useridlist)) {
212 $SESSION->mod_assign_useridlist = [];
217 * Set the action and parameters that can be used to return to the current page.
219 * @param string $action The action for the current page
220 * @param array $params An array of name value pairs which form the parameters
221 * to return to the current page.
224 public function register_return_link($action, $params) {
226 $params['action'] = $action;
227 $cm = $this->get_course_module();
229 $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $cm->id));
231 $currenturl = new moodle_url('/mod/assign/index.php', array('id' => $this->get_course()->id));
234 $currenturl->params($params);
235 $PAGE->set_url($currenturl);
239 * Return an action that can be used to get back to the current page.
241 * @return string action
243 public function get_return_action() {
246 // Web services don't set a URL, we should avoid debugging when ussing the url object.
248 $params = $PAGE->url->params();
251 if (!empty($params['action'])) {
252 return $params['action'];
258 * Based on the current assignment settings should we display the intro.
260 * @return bool showintro
262 public function show_intro() {
263 if ($this->get_instance()->alwaysshowdescription ||
264 time() > $this->get_instance()->allowsubmissionsfromdate) {
271 * Return a list of parameters that can be used to get back to the current page.
273 * @return array params
275 public function get_return_params() {
278 $params = $PAGE->url->params();
279 unset($params['id']);
280 unset($params['action']);
285 * Set the submitted form data.
287 * @param stdClass $data The form data (instance)
289 public function set_instance(stdClass $data) {
290 $this->instance = $data;
296 * @param context $context The new context
298 public function set_context(context $context) {
299 $this->context = $context;
303 * Set the course data.
305 * @param stdClass $course The course data
307 public function set_course(stdClass $course) {
308 $this->course = $course;
312 * Get list of feedback plugins installed.
316 public function get_feedback_plugins() {
317 return $this->feedbackplugins;
321 * Get list of submission plugins installed.
325 public function get_submission_plugins() {
326 return $this->submissionplugins;
330 * Is blind marking enabled and reveal identities not set yet?
334 public function is_blind_marking() {
335 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
339 * Does an assignment have submission(s) or grade(s) already?
343 public function has_submissions_or_grades() {
344 $allgrades = $this->count_grades();
345 $allsubmissions = $this->count_submissions();
346 if (($allgrades == 0) && ($allsubmissions == 0)) {
353 * Get a specific submission plugin by its type.
355 * @param string $subtype assignsubmission | assignfeedback
356 * @param string $type
357 * @return mixed assign_plugin|null
359 public function get_plugin_by_type($subtype, $type) {
360 $shortsubtype = substr($subtype, strlen('assign'));
361 $name = $shortsubtype . 'plugins';
362 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
365 $pluginlist = $this->$name;
366 foreach ($pluginlist as $plugin) {
367 if ($plugin->get_type() == $type) {
375 * Get a feedback plugin by type.
377 * @param string $type - The type of plugin e.g comments
378 * @return mixed assign_feedback_plugin|null
380 public function get_feedback_plugin_by_type($type) {
381 return $this->get_plugin_by_type('assignfeedback', $type);
385 * Get a submission plugin by type.
387 * @param string $type - The type of plugin e.g comments
388 * @return mixed assign_submission_plugin|null
390 public function get_submission_plugin_by_type($type) {
391 return $this->get_plugin_by_type('assignsubmission', $type);
395 * Load the plugins from the sub folders under subtype.
397 * @param string $subtype - either submission or feedback
398 * @return array - The sorted list of plugins
400 public function load_plugins($subtype) {
404 $names = core_component::get_plugin_list($subtype);
406 foreach ($names as $name => $path) {
407 if (file_exists($path . '/locallib.php')) {
408 require_once($path . '/locallib.php');
410 $shortsubtype = substr($subtype, strlen('assign'));
411 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
413 $plugin = new $pluginclass($this, $name);
415 if ($plugin instanceof assign_plugin) {
416 $idx = $plugin->get_sort_order();
417 while (array_key_exists($idx, $result)) {
420 $result[$idx] = $plugin;
429 * Display the assignment, used by view.php
431 * The assignment is displayed differently depending on your role,
432 * the settings for the assignment and the status of the assignment.
434 * @param string $action The current action if any.
435 * @param array $args Optional arguments to pass to the view (instead of getting them from GET and POST).
436 * @return string - The page output.
438 public function view($action='', $args = array()) {
444 $nextpageparams = array();
446 if (!empty($this->get_course_module()->id)) {
447 $nextpageparams['id'] = $this->get_course_module()->id;
450 // Handle form submissions first.
451 if ($action == 'savesubmission') {
452 $action = 'editsubmission';
453 if ($this->process_save_submission($mform, $notices)) {
454 $action = 'redirect';
455 $nextpageparams['action'] = 'view';
457 } else if ($action == 'editprevioussubmission') {
458 $action = 'editsubmission';
459 if ($this->process_copy_previous_attempt($notices)) {
460 $action = 'redirect';
461 $nextpageparams['action'] = 'editsubmission';
463 } else if ($action == 'lock') {
464 $this->process_lock_submission();
465 $action = 'redirect';
466 $nextpageparams['action'] = 'grading';
467 } else if ($action == 'addattempt') {
468 $this->process_add_attempt(required_param('userid', PARAM_INT));
469 $action = 'redirect';
470 $nextpageparams['action'] = 'grading';
471 } else if ($action == 'reverttodraft') {
472 $this->process_revert_to_draft();
473 $action = 'redirect';
474 $nextpageparams['action'] = 'grading';
475 } else if ($action == 'unlock') {
476 $this->process_unlock_submission();
477 $action = 'redirect';
478 $nextpageparams['action'] = 'grading';
479 } else if ($action == 'setbatchmarkingworkflowstate') {
480 $this->process_set_batch_marking_workflow_state();
481 $action = 'redirect';
482 $nextpageparams['action'] = 'grading';
483 } else if ($action == 'setbatchmarkingallocation') {
484 $this->process_set_batch_marking_allocation();
485 $action = 'redirect';
486 $nextpageparams['action'] = 'grading';
487 } else if ($action == 'confirmsubmit') {
489 if ($this->process_submit_for_grading($mform, $notices)) {
490 $action = 'redirect';
491 $nextpageparams['action'] = 'view';
492 } else if ($notices) {
493 $action = 'viewsubmitforgradingerror';
495 } else if ($action == 'submitotherforgrading') {
496 if ($this->process_submit_other_for_grading($mform, $notices)) {
497 $action = 'redirect';
498 $nextpageparams['action'] = 'grading';
500 $action = 'viewsubmitforgradingerror';
502 } else if ($action == 'gradingbatchoperation') {
503 $action = $this->process_grading_batch_operation($mform);
504 if ($action == 'grading') {
505 $action = 'redirect';
506 $nextpageparams['action'] = 'grading';
508 } else if ($action == 'submitgrade') {
509 if (optional_param('saveandshownext', null, PARAM_RAW)) {
510 // Save and show next.
512 if ($this->process_save_grade($mform)) {
513 $action = 'redirect';
514 $nextpageparams['action'] = 'grade';
515 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
516 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
518 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
519 $action = 'redirect';
520 $nextpageparams['action'] = 'grade';
521 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
522 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
523 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
524 $action = 'redirect';
525 $nextpageparams['action'] = 'grade';
526 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
527 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
528 } else if (optional_param('savegrade', null, PARAM_RAW)) {
529 // Save changes button.
531 if ($this->process_save_grade($mform)) {
532 $action = 'redirect';
533 $nextpageparams['action'] = 'savegradingresult';
537 $action = 'redirect';
538 $nextpageparams['action'] = 'grading';
540 } else if ($action == 'quickgrade') {
541 $message = $this->process_save_quick_grades();
542 $action = 'quickgradingresult';
543 } else if ($action == 'saveoptions') {
544 $this->process_save_grading_options();
545 $action = 'redirect';
546 $nextpageparams['action'] = 'grading';
547 } else if ($action == 'saveextension') {
548 $action = 'grantextension';
549 if ($this->process_save_extension($mform)) {
550 $action = 'redirect';
551 $nextpageparams['action'] = 'grading';
553 } else if ($action == 'revealidentitiesconfirm') {
554 $this->process_reveal_identities();
555 $action = 'redirect';
556 $nextpageparams['action'] = 'grading';
559 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
560 'useridlistid' => optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM));
561 $this->register_return_link($action, $returnparams);
563 // Include any page action as part of the body tag CSS id.
564 if (!empty($action)) {
565 $PAGE->set_pagetype('mod-assign-' . $action);
567 // Now show the right view page.
568 if ($action == 'redirect') {
569 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
570 redirect($nextpageurl);
572 } else if ($action == 'savegradingresult') {
573 $message = get_string('gradingchangessaved', 'assign');
574 $o .= $this->view_savegrading_result($message);
575 } else if ($action == 'quickgradingresult') {
577 $o .= $this->view_quickgrading_result($message);
578 } else if ($action == 'gradingpanel') {
579 $o .= $this->view_single_grading_panel($args);
580 } else if ($action == 'grade') {
581 $o .= $this->view_single_grade_page($mform);
582 } else if ($action == 'viewpluginassignfeedback') {
583 $o .= $this->view_plugin_content('assignfeedback');
584 } else if ($action == 'viewpluginassignsubmission') {
585 $o .= $this->view_plugin_content('assignsubmission');
586 } else if ($action == 'editsubmission') {
587 $o .= $this->view_edit_submission_page($mform, $notices);
588 } else if ($action == 'grader') {
589 $o .= $this->view_grader();
590 } else if ($action == 'grading') {
591 $o .= $this->view_grading_page();
592 } else if ($action == 'downloadall') {
593 $o .= $this->download_submissions();
594 } else if ($action == 'submit') {
595 $o .= $this->check_submit_for_grading($mform);
596 } else if ($action == 'grantextension') {
597 $o .= $this->view_grant_extension($mform);
598 } else if ($action == 'revealidentities') {
599 $o .= $this->view_reveal_identities_confirm($mform);
600 } else if ($action == 'plugingradingbatchoperation') {
601 $o .= $this->view_plugin_grading_batch_operation($mform);
602 } else if ($action == 'viewpluginpage') {
603 $o .= $this->view_plugin_page();
604 } else if ($action == 'viewcourseindex') {
605 $o .= $this->view_course_index();
606 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
607 $o .= $this->view_batch_set_workflow_state($mform);
608 } else if ($action == 'viewbatchmarkingallocation') {
609 $o .= $this->view_batch_markingallocation($mform);
610 } else if ($action == 'viewsubmitforgradingerror') {
611 $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
612 } else if ($action == 'fixrescalednullgrades') {
613 $o .= $this->view_fix_rescaled_null_grades();
615 $o .= $this->view_submission_page();
622 * Add this instance to the database.
624 * @param stdClass $formdata The data submitted from the form
625 * @param bool $callplugins This is used to skip the plugin code
626 * when upgrading an old assignment to a new one (the plugins get called manually)
627 * @return mixed false if an error occurs or the int id of the new instance
629 public function add_instance(stdClass $formdata, $callplugins) {
631 $adminconfig = $this->get_admin_config();
635 // Add the database record.
636 $update = new stdClass();
637 $update->name = $formdata->name;
638 $update->timemodified = time();
639 $update->timecreated = time();
640 $update->course = $formdata->course;
641 $update->courseid = $formdata->course;
642 $update->intro = $formdata->intro;
643 $update->introformat = $formdata->introformat;
644 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
645 $update->submissiondrafts = $formdata->submissiondrafts;
646 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
647 $update->sendnotifications = $formdata->sendnotifications;
648 $update->sendlatenotifications = $formdata->sendlatenotifications;
649 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
650 if (isset($formdata->sendstudentnotifications)) {
651 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
653 $update->duedate = $formdata->duedate;
654 $update->cutoffdate = $formdata->cutoffdate;
655 $update->gradingduedate = $formdata->gradingduedate;
656 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
657 $update->grade = $formdata->grade;
658 $update->completionsubmit = !empty($formdata->completionsubmit);
659 $update->teamsubmission = $formdata->teamsubmission;
660 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
661 if (isset($formdata->teamsubmissiongroupingid)) {
662 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
664 $update->blindmarking = $formdata->blindmarking;
665 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
666 if (!empty($formdata->attemptreopenmethod)) {
667 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
669 if (!empty($formdata->maxattempts)) {
670 $update->maxattempts = $formdata->maxattempts;
672 if (isset($formdata->preventsubmissionnotingroup)) {
673 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
675 $update->markingworkflow = $formdata->markingworkflow;
676 $update->markingallocation = $formdata->markingallocation;
677 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
678 $update->markingallocation = 0;
681 $returnid = $DB->insert_record('assign', $update);
682 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
683 // Cache the course record.
684 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
686 $this->save_intro_draft_files($formdata);
689 // Call save_settings hook for submission plugins.
690 foreach ($this->submissionplugins as $plugin) {
691 if (!$this->update_plugin_instance($plugin, $formdata)) {
692 print_error($plugin->get_error());
696 foreach ($this->feedbackplugins as $plugin) {
697 if (!$this->update_plugin_instance($plugin, $formdata)) {
698 print_error($plugin->get_error());
703 // In the case of upgrades the coursemodule has not been set,
704 // so we need to wait before calling these two.
705 $this->update_calendar($formdata->coursemodule);
706 if (!empty($formdata->completionexpected)) {
707 \core_completion\api::update_completion_date_event($formdata->coursemodule, 'assign', $this->instance,
708 $formdata->completionexpected);
710 $this->update_gradebook(false, $formdata->coursemodule);
714 $update = new stdClass();
715 $update->id = $this->get_instance()->id;
716 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
717 $DB->update_record('assign', $update);
723 * Delete all grades from the gradebook for this assignment.
727 protected function delete_grades() {
730 $result = grade_update('mod/assign',
731 $this->get_course()->id,
734 $this->get_instance()->id,
737 array('deleted'=>1));
738 return $result == GRADE_UPDATE_OK;
742 * Delete this instance from the database.
744 * @return bool false if an error occurs
746 public function delete_instance() {
750 foreach ($this->submissionplugins as $plugin) {
751 if (!$plugin->delete_instance()) {
752 print_error($plugin->get_error());
756 foreach ($this->feedbackplugins as $plugin) {
757 if (!$plugin->delete_instance()) {
758 print_error($plugin->get_error());
763 // Delete files associated with this assignment.
764 $fs = get_file_storage();
765 if (! $fs->delete_area_files($this->context->id) ) {
769 $this->delete_all_overrides();
771 // Delete_records will throw an exception if it fails - so no need for error checking here.
772 $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id));
773 $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id));
774 $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id));
775 $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id));
776 $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id));
778 // Delete items from the gradebook.
779 if (! $this->delete_grades()) {
783 // Delete the instance.
784 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
790 * Deletes a assign override from the database and clears any corresponding calendar events
792 * @param int $overrideid The id of the override being deleted
793 * @return bool true on success
795 public function delete_override($overrideid) {
798 require_once($CFG->dirroot . '/calendar/lib.php');
800 $cm = $this->get_course_module();
802 $instance = $this->get_instance();
803 $cm = get_coursemodule_from_instance('assign', $instance->id, $instance->course);
806 $override = $DB->get_record('assign_overrides', array('id' => $overrideid), '*', MUST_EXIST);
808 // Delete the events.
809 $conds = array('modulename' => 'assign', 'instance' => $this->get_instance()->id);
810 if (isset($override->userid)) {
811 $conds['userid'] = $override->userid;
813 $conds['groupid'] = $override->groupid;
815 $events = $DB->get_records('event', $conds);
816 foreach ($events as $event) {
817 $eventold = calendar_event::load($event);
821 $DB->delete_records('assign_overrides', array('id' => $overrideid));
823 // Set the common parameters for one of the events we will be triggering.
825 'objectid' => $override->id,
826 'context' => context_module::instance($cm->id),
828 'assignid' => $override->assignid
831 // Determine which override deleted event to fire.
832 if (!empty($override->userid)) {
833 $params['relateduserid'] = $override->userid;
834 $event = \mod_assign\event\user_override_deleted::create($params);
836 $params['other']['groupid'] = $override->groupid;
837 $event = \mod_assign\event\group_override_deleted::create($params);
840 // Trigger the override deleted event.
841 $event->add_record_snapshot('assign_overrides', $override);
848 * Deletes all assign overrides from the database and clears any corresponding calendar events
850 public function delete_all_overrides() {
853 $overrides = $DB->get_records('assign_overrides', array('assignid' => $this->get_instance()->id), 'id');
854 foreach ($overrides as $override) {
855 $this->delete_override($override->id);
860 * Updates the assign properties with override information for a user.
862 * Algorithm: For each assign setting, if there is a matching user-specific override,
863 * then use that otherwise, if there are group-specific overrides, return the most
864 * lenient combination of them. If neither applies, leave the assign setting unchanged.
866 * @param int $userid The userid.
868 public function update_effective_access($userid) {
870 $override = $this->override_exists($userid);
872 // Merge with assign defaults.
873 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
874 foreach ($keys as $key) {
875 if (isset($override->{$key})) {
876 $this->get_instance()->{$key} = $override->{$key};
883 * Returns whether an assign has any overrides.
885 * @return true if any, false if not
887 public function has_overrides() {
890 $override = $DB->record_exists('assign_overrides', array('assignid' => $this->get_instance()->id));
900 * Returns user override
902 * Algorithm: For each assign setting, if there is a matching user-specific override,
903 * then use that otherwise, if there are group-specific overrides, use the one with the
904 * lowest sort order. If neither applies, leave the assign setting unchanged.
906 * @param int $userid The userid.
907 * @return stdClass The override
909 public function override_exists($userid) {
912 // Gets an assoc array containing the keys for defined user overrides only.
913 $getuseroverride = function($userid) use ($DB) {
914 $useroverride = $DB->get_record('assign_overrides', ['assignid' => $this->get_instance()->id, 'userid' => $userid]);
915 return $useroverride ? get_object_vars($useroverride) : [];
918 // Gets an assoc array containing the keys for defined group overrides only.
919 $getgroupoverride = function($userid) use ($DB) {
920 $groupings = groups_get_user_groups($this->get_instance()->course, $userid);
922 if (empty($groupings[0])) {
926 // Select all overrides that apply to the User's groups.
927 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
928 $sql = "SELECT * FROM {assign_overrides}
929 WHERE groupid $extra AND assignid = ? ORDER BY sortorder ASC";
930 $params[] = $this->get_instance()->id;
931 $groupoverride = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
933 return $groupoverride ? get_object_vars($groupoverride) : [];
936 // Later arguments clobber earlier ones with array_merge. The two helper functions
937 // return arrays containing keys for only the defined overrides. So we get the
938 // desired behaviour as per the algorithm.
939 return (object)array_merge(
940 ['duedate' => null, 'cutoffdate' => null, 'allowsubmissionsfromdate' => null],
941 $getgroupoverride($userid),
942 $getuseroverride($userid)
947 * Check if the given calendar_event is either a user or group override
952 public function is_override_calendar_event(\calendar_event $event) {
955 if (!isset($event->modulename)) {
959 if ($event->modulename != 'assign') {
963 if (!isset($event->instance)) {
967 if (!isset($event->userid) && !isset($event->groupid)) {
972 'assignid' => $event->instance
975 if (isset($event->groupid)) {
976 $overrideparams['groupid'] = $event->groupid;
977 } else if (isset($event->userid)) {
978 $overrideparams['userid'] = $event->userid;
981 if ($DB->get_record('assign_overrides', $overrideparams)) {
989 * This function calculates the minimum and maximum cutoff values for the timestart of
992 * It will return an array with two values, the first being the minimum cutoff value and
993 * the second being the maximum cutoff value. Either or both values can be null, which
994 * indicates there is no minimum or maximum, respectively.
996 * If a cutoff is required then the function must return an array containing the cutoff
997 * timestamp and error string to display to the user if the cutoff value is violated.
999 * A minimum and maximum cutoff return value will look like:
1001 * [1505704373, 'The due date must be after the sbumission start date'],
1002 * [1506741172, 'The due date must be before the cutoff date']
1005 * If the event does not have a valid timestart range then [false, false] will
1008 * @param calendar_event $event The calendar event to get the time range for
1011 function get_valid_calendar_event_timestart_range(\calendar_event $event) {
1012 $instance = $this->get_instance();
1013 $submissionsfromdate = $instance->allowsubmissionsfromdate;
1014 $cutoffdate = $instance->cutoffdate;
1015 $duedate = $instance->duedate;
1016 $gradingduedate = $instance->gradingduedate;
1020 if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
1021 // This check is in here because due date events are currently
1022 // the only events that can be overridden, so we can save a DB
1023 // query if we don't bother checking other events.
1024 if ($this->is_override_calendar_event($event)) {
1025 // This is an override event so there is no valid timestart
1026 // range to set it to.
1027 return [false, false];
1030 if ($submissionsfromdate) {
1032 $submissionsfromdate,
1033 get_string('duedatevalidation', 'assign'),
1040 get_string('cutoffdatevalidation', 'assign'),
1044 if ($gradingduedate) {
1045 // If we don't have a cutoff date or we've got a grading due date
1046 // that is earlier than the cutoff then we should use that as the
1047 // upper limit for the due date.
1048 if (!$cutoffdate || $gradingduedate < $cutoffdate) {
1051 get_string('gradingdueduedatevalidation', 'assign'),
1055 } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1059 get_string('gradingdueduedatevalidation', 'assign'),
1061 } else if ($submissionsfromdate) {
1063 $submissionsfromdate,
1064 get_string('gradingduefromdatevalidation', 'assign'),
1069 return [$mindate, $maxdate];
1073 * Actual implementation of the reset course functionality, delete all the
1074 * assignment submissions for course $data->courseid.
1076 * @param stdClass $data the data submitted from the reset course.
1077 * @return array status array
1079 public function reset_userdata($data) {
1082 $componentstr = get_string('modulenameplural', 'assign');
1085 $fs = get_file_storage();
1086 if (!empty($data->reset_assign_submissions)) {
1087 // Delete files associated with this assignment.
1088 foreach ($this->submissionplugins as $plugin) {
1089 $fileareas = array();
1090 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
1091 $fileareas = $plugin->get_file_areas();
1092 foreach ($fileareas as $filearea => $notused) {
1093 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
1096 if (!$plugin->delete_instance()) {
1097 $status[] = array('component'=>$componentstr,
1098 'item'=>get_string('deleteallsubmissions', 'assign'),
1099 'error'=>$plugin->get_error());
1103 foreach ($this->feedbackplugins as $plugin) {
1104 $fileareas = array();
1105 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
1106 $fileareas = $plugin->get_file_areas();
1107 foreach ($fileareas as $filearea => $notused) {
1108 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
1111 if (!$plugin->delete_instance()) {
1112 $status[] = array('component'=>$componentstr,
1113 'item'=>get_string('deleteallsubmissions', 'assign'),
1114 'error'=>$plugin->get_error());
1118 $assignids = $DB->get_records('assign', array('course' => $data->courseid), '', 'id');
1119 list($sql, $params) = $DB->get_in_or_equal(array_keys($assignids));
1121 $DB->delete_records_select('assign_submission', "assignment $sql", $params);
1122 $DB->delete_records_select('assign_user_flags', "assignment $sql", $params);
1124 $status[] = array('component'=>$componentstr,
1125 'item'=>get_string('deleteallsubmissions', 'assign'),
1128 if (!empty($data->reset_gradebook_grades)) {
1129 $DB->delete_records_select('assign_grades', "assignment $sql", $params);
1130 // Remove all grades from gradebook.
1131 require_once($CFG->dirroot.'/mod/assign/lib.php');
1132 assign_reset_gradebook($data->courseid);
1135 // Reset revealidentities for assign if blindmarking is enabled.
1136 if ($this->get_instance()->blindmarking) {
1137 $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id));
1141 // Remove user overrides.
1142 if (!empty($data->reset_assign_user_overrides)) {
1143 $DB->delete_records_select('assign_overrides',
1144 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1146 'component' => $componentstr,
1147 'item' => get_string('useroverridesdeleted', 'assign'),
1150 // Remove group overrides.
1151 if (!empty($data->reset_assign_group_overrides)) {
1152 $DB->delete_records_select('assign_overrides',
1153 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1155 'component' => $componentstr,
1156 'item' => get_string('groupoverridesdeleted', 'assign'),
1160 // Updating dates - shift may be negative too.
1161 if ($data->timeshift) {
1162 $DB->execute("UPDATE {assign_overrides}
1163 SET allowsubmissionsfromdate = allowsubmissionsfromdate + ?
1164 WHERE assignid = ? AND allowsubmissionsfromdate <> 0",
1165 array($data->timeshift, $this->get_instance()->id));
1166 $DB->execute("UPDATE {assign_overrides}
1167 SET duedate = duedate + ?
1168 WHERE assignid = ? AND duedate <> 0",
1169 array($data->timeshift, $this->get_instance()->id));
1170 $DB->execute("UPDATE {assign_overrides}
1171 SET cutoffdate = cutoffdate + ?
1172 WHERE assignid =? AND cutoffdate <> 0",
1173 array($data->timeshift, $this->get_instance()->id));
1175 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1177 shift_course_mod_dates('assign',
1178 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
1180 $data->courseid, $this->get_instance()->id);
1181 $status[] = array('component'=>$componentstr,
1182 'item'=>get_string('datechanged'),
1190 * Update the settings for a single plugin.
1192 * @param assign_plugin $plugin The plugin to update
1193 * @param stdClass $formdata The form data
1194 * @return bool false if an error occurs
1196 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
1197 if ($plugin->is_visible()) {
1198 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1199 if (!empty($formdata->$enabledname)) {
1201 if (!$plugin->save_settings($formdata)) {
1202 print_error($plugin->get_error());
1213 * Update the gradebook information for this assignment.
1215 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
1216 * @param int $coursemoduleid This is required because it might not exist in the database yet
1219 public function update_gradebook($reset, $coursemoduleid) {
1222 require_once($CFG->dirroot.'/mod/assign/lib.php');
1223 $assign = clone $this->get_instance();
1224 $assign->cmidnumber = $coursemoduleid;
1226 // Set assign gradebook feedback plugin status (enabled and visible).
1227 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
1234 return assign_grade_item_update($assign, $param);
1238 * Get the marking table page size
1242 public function get_assign_perpage() {
1243 $perpage = (int) get_user_preferences('assign_perpage', 10);
1244 $adminconfig = $this->get_admin_config();
1246 if (isset($adminconfig->maxperpage)) {
1247 $maxperpage = $adminconfig->maxperpage;
1249 if (isset($maxperpage) &&
1250 $maxperpage != -1 &&
1251 ($perpage == -1 || $perpage > $maxperpage)) {
1252 $perpage = $maxperpage;
1258 * Load and cache the admin config for this module.
1260 * @return stdClass the plugin config
1262 public function get_admin_config() {
1263 if ($this->adminconfig) {
1264 return $this->adminconfig;
1266 $this->adminconfig = get_config('assign');
1267 return $this->adminconfig;
1271 * Update the calendar entries for this assignment.
1273 * @param int $coursemoduleid - Required to pass this in because it might
1274 * not exist in the database yet.
1277 public function update_calendar($coursemoduleid) {
1279 require_once($CFG->dirroot.'/calendar/lib.php');
1281 // Special case for add_instance as the coursemodule has not been set yet.
1282 $instance = $this->get_instance();
1284 // Start with creating the event.
1285 $event = new stdClass();
1286 $event->modulename = 'assign';
1287 $event->courseid = $instance->course;
1288 $event->groupid = 0;
1290 $event->instance = $instance->id;
1291 $event->type = CALENDAR_EVENT_TYPE_ACTION;
1293 // Convert the links to pluginfile. It is a bit hacky but at this stage the files
1294 // might not have been saved in the module area yet.
1295 $intro = $instance->intro;
1296 if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
1297 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
1300 // We need to remove the links to files as the calendar is not ready
1301 // to support module events with file areas.
1302 $intro = strip_pluginfile_content($intro);
1303 if ($this->show_intro()) {
1304 $event->description = array(
1306 'format' => $instance->introformat
1309 $event->description = array(
1311 'format' => $instance->introformat
1315 $eventtype = ASSIGN_EVENT_TYPE_DUE;
1316 if ($instance->duedate) {
1317 $event->name = get_string('calendardue', 'assign', $instance->name);
1318 $event->eventtype = $eventtype;
1319 $event->timestart = $instance->duedate;
1320 $event->timesort = $instance->duedate;
1321 $select = "modulename = :modulename
1322 AND instance = :instance
1323 AND eventtype = :eventtype
1326 $params = array('modulename' => 'assign', 'instance' => $instance->id, 'eventtype' => $eventtype);
1327 $event->id = $DB->get_field_select('event', 'id', $select, $params);
1329 // Now process the event.
1331 $calendarevent = calendar_event::load($event->id);
1332 $calendarevent->update($event);
1334 calendar_event::create($event);
1337 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1338 'eventtype' => $eventtype));
1341 $eventtype = ASSIGN_EVENT_TYPE_GRADINGDUE;
1342 if ($instance->gradingduedate) {
1343 $event->name = get_string('calendargradingdue', 'assign', $instance->name);
1344 $event->eventtype = $eventtype;
1345 $event->timestart = $instance->gradingduedate;
1346 $event->timesort = $instance->gradingduedate;
1347 $event->id = $DB->get_field('event', 'id', array('modulename' => 'assign',
1348 'instance' => $instance->id, 'eventtype' => $event->eventtype));
1350 // Now process the event.
1352 $calendarevent = calendar_event::load($event->id);
1353 $calendarevent->update($event);
1355 calendar_event::create($event);
1358 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1359 'eventtype' => $eventtype));
1366 * Update this instance in the database.
1368 * @param stdClass $formdata - the data submitted from the form
1369 * @return bool false if an error occurs
1371 public function update_instance($formdata) {
1373 $adminconfig = $this->get_admin_config();
1375 $update = new stdClass();
1376 $update->id = $formdata->instance;
1377 $update->name = $formdata->name;
1378 $update->timemodified = time();
1379 $update->course = $formdata->course;
1380 $update->intro = $formdata->intro;
1381 $update->introformat = $formdata->introformat;
1382 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
1383 $update->submissiondrafts = $formdata->submissiondrafts;
1384 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
1385 $update->sendnotifications = $formdata->sendnotifications;
1386 $update->sendlatenotifications = $formdata->sendlatenotifications;
1387 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
1388 if (isset($formdata->sendstudentnotifications)) {
1389 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
1391 $update->duedate = $formdata->duedate;
1392 $update->cutoffdate = $formdata->cutoffdate;
1393 $update->gradingduedate = $formdata->gradingduedate;
1394 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
1395 $update->grade = $formdata->grade;
1396 if (!empty($formdata->completionunlocked)) {
1397 $update->completionsubmit = !empty($formdata->completionsubmit);
1399 $update->teamsubmission = $formdata->teamsubmission;
1400 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
1401 if (isset($formdata->teamsubmissiongroupingid)) {
1402 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
1404 $update->blindmarking = $formdata->blindmarking;
1405 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
1406 if (!empty($formdata->attemptreopenmethod)) {
1407 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
1409 if (!empty($formdata->maxattempts)) {
1410 $update->maxattempts = $formdata->maxattempts;
1412 if (isset($formdata->preventsubmissionnotingroup)) {
1413 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
1415 $update->markingworkflow = $formdata->markingworkflow;
1416 $update->markingallocation = $formdata->markingallocation;
1417 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
1418 $update->markingallocation = 0;
1421 $result = $DB->update_record('assign', $update);
1422 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
1424 $this->save_intro_draft_files($formdata);
1426 // Load the assignment so the plugins have access to it.
1428 // Call save_settings hook for submission plugins.
1429 foreach ($this->submissionplugins as $plugin) {
1430 if (!$this->update_plugin_instance($plugin, $formdata)) {
1431 print_error($plugin->get_error());
1435 foreach ($this->feedbackplugins as $plugin) {
1436 if (!$this->update_plugin_instance($plugin, $formdata)) {
1437 print_error($plugin->get_error());
1442 $this->update_calendar($this->get_course_module()->id);
1443 $completionexpected = (!empty($formdata->completionexpected)) ? $formdata->completionexpected : null;
1444 \core_completion\api::update_completion_date_event($this->get_course_module()->id, 'assign', $this->instance,
1445 $completionexpected);
1446 $this->update_gradebook(false, $this->get_course_module()->id);
1448 $update = new stdClass();
1449 $update->id = $this->get_instance()->id;
1450 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
1451 $DB->update_record('assign', $update);
1457 * Save the attachments in the draft areas.
1459 * @param stdClass $formdata
1461 protected function save_intro_draft_files($formdata) {
1462 if (isset($formdata->introattachments)) {
1463 file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1464 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1469 * Add elements in grading plugin form.
1471 * @param mixed $grade stdClass|null
1472 * @param MoodleQuickForm $mform
1473 * @param stdClass $data
1474 * @param int $userid - The userid we are grading
1477 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
1478 foreach ($this->feedbackplugins as $plugin) {
1479 if ($plugin->is_enabled() && $plugin->is_visible()) {
1480 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1488 * Add one plugins settings to edit plugin form.
1490 * @param assign_plugin $plugin The plugin to add the settings from
1491 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1492 * This form is modified directly (not returned).
1493 * @param array $pluginsenabled A list of form elements to be added to a group.
1494 * The new element is added to this array by this function.
1497 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1499 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1500 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1501 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1502 $mform->setType($name, PARAM_BOOL);
1503 $plugin->get_settings($mform);
1504 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1505 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1506 $label = $plugin->get_name();
1507 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1508 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1510 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1511 if ($plugin->get_config('enabled') !== false) {
1512 $default = $plugin->is_enabled();
1514 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1516 $plugin->get_settings($mform);
1522 * Add settings to edit plugin form.
1524 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1525 * This form is modified directly (not returned).
1528 public function add_all_plugin_settings(MoodleQuickForm $mform) {
1529 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1531 $submissionpluginsenabled = array();
1532 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1533 foreach ($this->submissionplugins as $plugin) {
1534 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1536 $group->setElements($submissionpluginsenabled);
1538 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1539 $feedbackpluginsenabled = array();
1540 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1541 foreach ($this->feedbackplugins as $plugin) {
1542 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1544 $group->setElements($feedbackpluginsenabled);
1545 $mform->setExpanded('submissiontypes');
1549 * Allow each plugin an opportunity to update the defaultvalues
1550 * passed in to the settings form (needed to set up draft areas for
1551 * editor and filemanager elements)
1553 * @param array $defaultvalues
1555 public function plugin_data_preprocessing(&$defaultvalues) {
1556 foreach ($this->submissionplugins as $plugin) {
1557 if ($plugin->is_visible()) {
1558 $plugin->data_preprocessing($defaultvalues);
1561 foreach ($this->feedbackplugins as $plugin) {
1562 if ($plugin->is_visible()) {
1563 $plugin->data_preprocessing($defaultvalues);
1569 * Get the name of the current module.
1571 * @return string the module name (Assignment)
1573 protected function get_module_name() {
1574 if (isset(self::$modulename)) {
1575 return self::$modulename;
1577 self::$modulename = get_string('modulename', 'assign');
1578 return self::$modulename;
1582 * Get the plural name of the current module.
1584 * @return string the module name plural (Assignments)
1586 protected function get_module_name_plural() {
1587 if (isset(self::$modulenameplural)) {
1588 return self::$modulenameplural;
1590 self::$modulenameplural = get_string('modulenameplural', 'assign');
1591 return self::$modulenameplural;
1595 * Has this assignment been constructed from an instance?
1599 public function has_instance() {
1600 return $this->instance || $this->get_course_module();
1604 * Get the settings for the current instance of this assignment
1606 * @return stdClass The settings
1608 public function get_instance() {
1610 if ($this->instance) {
1611 return $this->instance;
1613 if ($this->get_course_module()) {
1614 $params = array('id' => $this->get_course_module()->instance);
1615 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1617 if (!$this->instance) {
1618 throw new coding_exception('Improper use of the assignment class. ' .
1619 'Cannot load the assignment record.');
1621 return $this->instance;
1625 * Get the primary grade item for this assign instance.
1627 * @return grade_item The grade_item record
1629 public function get_grade_item() {
1630 if ($this->gradeitem) {
1631 return $this->gradeitem;
1633 $instance = $this->get_instance();
1634 $params = array('itemtype' => 'mod',
1635 'itemmodule' => 'assign',
1636 'iteminstance' => $instance->id,
1637 'courseid' => $instance->course,
1639 $this->gradeitem = grade_item::fetch($params);
1640 if (!$this->gradeitem) {
1641 throw new coding_exception('Improper use of the assignment class. ' .
1642 'Cannot load the grade item.');
1644 return $this->gradeitem;
1648 * Get the context of the current course.
1650 * @return mixed context|null The course context
1652 public function get_course_context() {
1653 if (!$this->context && !$this->course) {
1654 throw new coding_exception('Improper use of the assignment class. ' .
1655 'Cannot load the course context.');
1657 if ($this->context) {
1658 return $this->context->get_course_context();
1660 return context_course::instance($this->course->id);
1666 * Get the current course module.
1668 * @return cm_info|null The course module or null if not known
1670 public function get_course_module() {
1671 if ($this->coursemodule) {
1672 return $this->coursemodule;
1674 if (!$this->context) {
1678 if ($this->context->contextlevel == CONTEXT_MODULE) {
1679 $modinfo = get_fast_modinfo($this->get_course());
1680 $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
1681 return $this->coursemodule;
1687 * Get context module.
1691 public function get_context() {
1692 return $this->context;
1696 * Get the current course.
1698 * @return mixed stdClass|null The course
1700 public function get_course() {
1703 if ($this->course) {
1704 return $this->course;
1707 if (!$this->context) {
1710 $params = array('id' => $this->get_course_context()->instanceid);
1711 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1713 return $this->course;
1717 * Count the number of intro attachments.
1721 protected function count_attachments() {
1723 $fs = get_file_storage();
1724 $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1727 return count($files);
1731 * Are there any intro attachments to display?
1735 protected function has_visible_attachments() {
1736 return ($this->count_attachments() > 0);
1740 * Return a grade in user-friendly form, whether it's a scale or not.
1742 * @param mixed $grade int|null
1743 * @param boolean $editing Are we allowing changes to this grade?
1744 * @param int $userid The user id the grade belongs to
1745 * @param int $modified Timestamp from when the grade was last modified
1746 * @return string User-friendly representation of grade
1748 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1751 static $scalegrades = array();
1755 if ($this->get_instance()->grade >= 0) {
1757 if ($editing && $this->get_instance()->grade > 0) {
1761 $displaygrade = format_float($grade, $this->get_grade_item()->get_decimals());
1763 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1764 get_string('usergrade', 'assign') .
1766 $o .= '<input type="text"
1767 id="quickgrade_' . $userid . '"
1768 name="quickgrade_' . $userid . '"
1769 value="' . $displaygrade . '"
1772 class="quickgrade"/>';
1773 $o .= ' / ' . format_float($this->get_instance()->grade, $this->get_grade_item()->get_decimals());
1776 if ($grade == -1 || $grade === null) {
1779 $item = $this->get_grade_item();
1780 $o .= grade_format_gradevalue($grade, $item);
1781 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1782 // If displaying the raw grade, also display the total value.
1783 $o .= ' / ' . format_float($this->get_instance()->grade, $item->get_decimals());
1791 if (empty($this->cache['scale'])) {
1792 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1793 $this->cache['scale'] = make_menu_from_list($scale->scale);
1800 $o .= '<label class="accesshide"
1801 for="quickgrade_' . $userid . '">' .
1802 get_string('usergrade', 'assign') .
1804 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1805 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1806 foreach ($this->cache['scale'] as $optionid => $option) {
1808 if ($grade == $optionid) {
1809 $selected = 'selected="selected"';
1811 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1816 $scaleid = (int)$grade;
1817 if (isset($this->cache['scale'][$scaleid])) {
1818 $o .= $this->cache['scale'][$scaleid];
1828 * Get the submission status/grading status for all submissions in this assignment for the
1829 * given paticipants.
1831 * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1832 * If this is a group assignment, group info is also returned.
1834 * @param array $participants an associative array where the key is the participant id and
1835 * the value is the participant record.
1836 * @return array an associative array where the key is the participant id and the value is
1837 * the participant record.
1839 private function get_submission_info_for_participants($participants) {
1842 if (empty($participants)) {
1843 return $participants;
1846 list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1848 $assignid = $this->get_instance()->id;
1849 $params['assignmentid1'] = $assignid;
1850 $params['assignmentid2'] = $assignid;
1851 $params['assignmentid3'] = $assignid;
1853 $fields = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade, uf.extensionduedate';
1854 $from = ' FROM {user} u
1855 LEFT JOIN {assign_submission} s
1857 AND s.assignment = :assignmentid1
1859 LEFT JOIN {assign_grades} g
1861 AND g.assignment = :assignmentid2
1862 AND g.attemptnumber = s.attemptnumber
1863 LEFT JOIN {assign_user_flags} uf
1865 AND uf.assignment = :assignmentid3
1867 $where = ' WHERE u.id ' . $insql;
1869 if (!empty($this->get_instance()->blindmarking)) {
1870 $from .= 'LEFT JOIN {assign_user_mapping} um
1872 AND um.assignment = :assignmentid4 ';
1873 $params['assignmentid4'] = $assignid;
1874 $fields .= ', um.id as recordid ';
1877 $sql = "$fields $from $where";
1879 $records = $DB->get_records_sql($sql, $params);
1881 if ($this->get_instance()->teamsubmission) {
1883 $allgroups = groups_get_all_groups($this->get_course()->id,
1884 array_keys($participants),
1885 $this->get_instance()->teamsubmissiongroupingid,
1886 'DISTINCT g.id, g.name');
1889 foreach ($participants as $userid => $participant) {
1890 $participants[$userid]->fullname = $this->fullname($participant);
1891 $participants[$userid]->submitted = false;
1892 $participants[$userid]->requiregrading = false;
1893 $participants[$userid]->grantedextension = false;
1896 foreach ($records as $userid => $submissioninfo) {
1897 // These filters are 100% the same as the ones in the grading table SQL.
1899 $requiregrading = false;
1900 $grantedextension = false;
1902 if (!empty($submissioninfo->stime) && $submissioninfo->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1906 if ($submitted && ($submissioninfo->stime >= $submissioninfo->gtime ||
1907 empty($submissioninfo->gtime) ||
1908 $submissioninfo->grade === null)) {
1909 $requiregrading = true;
1912 if (!empty($submissioninfo->extensionduedate)) {
1913 $grantedextension = true;
1916 $participants[$userid]->submitted = $submitted;
1917 $participants[$userid]->requiregrading = $requiregrading;
1918 $participants[$userid]->grantedextension = $grantedextension;
1919 if ($this->get_instance()->teamsubmission) {
1920 $group = $this->get_submission_group($userid);
1922 $participants[$userid]->groupid = $group->id;
1923 $participants[$userid]->groupname = $group->name;
1927 return $participants;
1931 * Get the submission status/grading status for all submissions in this assignment.
1932 * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1933 * If this is a group assignment, group info is also returned.
1935 * @param int $currentgroup
1936 * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'grantedextension',
1937 * 'groupid', 'groupname'
1939 public function list_participants_with_filter_status_and_group($currentgroup) {
1940 $participants = $this->list_participants($currentgroup, false);
1942 if (empty($participants)) {
1943 return $participants;
1945 return $this->get_submission_info_for_participants($participants);
1950 * Load a list of users enrolled in the current course with the specified permission and group.
1953 * @param int $currentgroup
1954 * @param bool $idsonly
1955 * @return array List of user records
1957 public function list_participants($currentgroup, $idsonly) {
1960 if (empty($currentgroup)) {
1964 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1965 if (!isset($this->participants[$key])) {
1966 list($esql, $params) = get_enrolled_sql($this->context, 'mod/assign:submit', $currentgroup,
1967 $this->show_only_active_users());
1970 $orderby = 'u.lastname, u.firstname, u.id';
1971 $additionaljoins = '';
1972 $additionalfilters = '';
1973 $instance = $this->get_instance();
1974 if (!empty($instance->blindmarking)) {
1975 $additionaljoins .= " LEFT JOIN {assign_user_mapping} um
1977 AND um.assignment = :assignmentid1
1978 LEFT JOIN {assign_submission} s
1980 AND s.assignment = :assignmentid2
1983 $params['assignmentid1'] = (int) $instance->id;
1984 $params['assignmentid2'] = (int) $instance->id;
1985 $fields .= ', um.id as recordid ';
1987 // Sort by submission time first, then by um.id to sort reliably by the blind marking id.
1988 // Note, different DBs have different ordering of NULL values.
1989 // Therefore we coalesce the current time into the timecreated field, and the max possible integer into
1991 $orderby = "COALESCE(s.timecreated, " . time() . ") ASC, COALESCE(s.id, " . PHP_INT_MAX . ") ASC, um.id ASC";
1994 if ($instance->markingworkflow &&
1995 $instance->markingallocation &&
1996 !has_capability('mod/assign:manageallocations', $this->get_context()) &&
1997 has_capability('mod/assign:grade', $this->get_context())) {
1999 $additionaljoins .= ' LEFT JOIN {assign_user_flags} uf
2001 AND uf.assignment = :assignmentid3';
2003 $params['assignmentid3'] = (int) $instance->id;
2005 $additionalfilters .= ' AND uf.allocatedmarker = :markerid';
2006 $params['markerid'] = $USER->id;
2009 $sql = "SELECT $fields
2011 JOIN ($esql) je ON je.id = u.id
2017 $users = $DB->get_records_sql($sql, $params);
2019 $cm = $this->get_course_module();
2020 $info = new \core_availability\info_module($cm);
2021 $users = $info->filter_user_list($users);
2023 $this->participants[$key] = $users;
2028 foreach ($this->participants[$key] as $id => $user) {
2029 $idslist[$id] = new stdClass();
2030 $idslist[$id]->id = $id;
2034 return $this->participants[$key];
2038 * Load a user if they are enrolled in the current course. Populated with submission
2039 * status for this assignment.
2041 * @param int $userid
2042 * @return null|stdClass user record
2044 public function get_participant($userid) {
2047 if ($userid == $USER->id) {
2048 $participant = clone ($USER);
2050 $participant = $DB->get_record('user', array('id' => $userid));
2052 if (!$participant) {
2056 if (!is_enrolled($this->context, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
2060 $result = $this->get_submission_info_for_participants(array($participant->id => $participant));
2061 return $result[$participant->id];
2065 * Load a count of valid teams for this assignment.
2067 * @param int $activitygroup Activity active group
2068 * @return int number of valid teams
2070 public function count_teams($activitygroup = 0) {
2074 $participants = $this->list_participants($activitygroup, true);
2076 // If a team submission grouping id is provided all good as all returned groups
2077 // are the submission teams, but if no team submission grouping was specified
2078 // $groups will contain all participants groups.
2079 if ($this->get_instance()->teamsubmissiongroupingid) {
2081 // We restrict the users to the selected group ones.
2082 $groups = groups_get_all_groups($this->get_course()->id,
2083 array_keys($participants),
2084 $this->get_instance()->teamsubmissiongroupingid,
2085 'DISTINCT g.id, g.name');
2087 $count = count($groups);
2089 // When a specific group is selected we don't count the default group users.
2090 if ($activitygroup == 0) {
2091 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
2092 // See if there are any users in the default group.
2093 $defaultusers = $this->get_submission_group_members(0, true);
2094 if (count($defaultusers) > 0) {
2098 } else if ($activitygroup != 0 && empty($groups)) {
2099 // Set count to 1 if $groups returns empty.
2100 // It means the group is not part of $this->get_instance()->teamsubmissiongroupingid.
2104 // It is faster to loop around participants if no grouping was specified.
2106 foreach ($participants as $participant) {
2107 if ($group = $this->get_submission_group($participant->id)) {
2108 $groups[$group->id] = true;
2109 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
2114 $count = count($groups);
2121 * Load a count of active users enrolled in the current course with the specified permission and group.
2124 * @param int $currentgroup
2125 * @return int number of matching users
2127 public function count_participants($currentgroup) {
2128 return count($this->list_participants($currentgroup, true));
2132 * Load a count of active users submissions in the current module that require grading
2133 * This means the submission modification time is more recent than the
2134 * grading modification time and the status is SUBMITTED.
2136 * @param mixed $currentgroup int|null the group for counting (if null the function will determine it)
2137 * @return int number of matching submissions
2139 public function count_submissions_need_grading($currentgroup = null) {
2142 if ($this->get_instance()->teamsubmission) {
2143 // This does not make sense for group assignment because the submission is shared.
2147 if ($currentgroup === null) {
2148 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2150 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2152 $params['assignid'] = $this->get_instance()->id;
2153 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2154 $sqlscalegrade = $this->get_instance()->grade < 0 ? ' OR g.grade = -1' : '';
2156 $sql = 'SELECT COUNT(s.userid)
2157 FROM {assign_submission} s
2158 LEFT JOIN {assign_grades} g ON
2159 s.assignment = g.assignment AND
2160 s.userid = g.userid AND
2161 g.attemptnumber = s.attemptnumber
2162 JOIN(' . $esql . ') e ON e.id = s.userid
2165 s.assignment = :assignid AND
2166 s.timemodified IS NOT NULL AND
2167 s.status = :submitted AND
2168 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL '
2169 . $sqlscalegrade . ')';
2171 return $DB->count_records_sql($sql, $params);
2175 * Load a count of grades.
2177 * @return int number of grades
2179 public function count_grades() {
2182 if (!$this->has_instance()) {
2186 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2187 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2189 $params['assignid'] = $this->get_instance()->id;
2191 $sql = 'SELECT COUNT(g.userid)
2192 FROM {assign_grades} g
2193 JOIN(' . $esql . ') e ON e.id = g.userid
2194 WHERE g.assignment = :assignid';
2196 return $DB->count_records_sql($sql, $params);
2200 * Load a count of submissions.
2202 * @param bool $includenew When true, also counts the submissions with status 'new'.
2203 * @return int number of submissions
2205 public function count_submissions($includenew = false) {
2208 if (!$this->has_instance()) {
2216 $sqlnew = ' AND s.status <> :status ';
2217 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
2220 if ($this->get_instance()->teamsubmission) {
2221 // We cannot join on the enrolment tables for group submissions (no userid).
2222 $sql = 'SELECT COUNT(DISTINCT s.groupid)
2223 FROM {assign_submission} s
2225 s.assignment = :assignid AND
2226 s.timemodified IS NOT NULL AND
2227 s.userid = :groupuserid' .
2230 $params['assignid'] = $this->get_instance()->id;
2231 $params['groupuserid'] = 0;
2233 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2234 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2236 $params = array_merge($params, $enrolparams);
2237 $params['assignid'] = $this->get_instance()->id;
2239 $sql = 'SELECT COUNT(DISTINCT s.userid)
2240 FROM {assign_submission} s
2241 JOIN(' . $esql . ') e ON e.id = s.userid
2243 s.assignment = :assignid AND
2244 s.timemodified IS NOT NULL ' .
2249 return $DB->count_records_sql($sql, $params);
2253 * Load a count of submissions with a specified status.
2255 * @param string $status The submission status - should match one of the constants
2256 * @param mixed $currentgroup int|null the group for counting (if null the function will determine it)
2257 * @return int number of matching submissions
2259 public function count_submissions_with_status($status, $currentgroup = null) {
2262 if ($currentgroup === null) {
2263 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2265 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2267 $params['assignid'] = $this->get_instance()->id;
2268 $params['assignid2'] = $this->get_instance()->id;
2269 $params['submissionstatus'] = $status;
2271 if ($this->get_instance()->teamsubmission) {
2274 if ($currentgroup != 0) {
2275 // If there is an active group we should only display the current group users groups.
2276 $participants = $this->list_participants($currentgroup, true);
2277 $groups = groups_get_all_groups($this->get_course()->id,
2278 array_keys($participants),
2279 $this->get_instance()->teamsubmissiongroupingid,
2280 'DISTINCT g.id, g.name');
2281 if (empty($groups)) {
2282 // If $groups is empty it means it is not part of $this->get_instance()->teamsubmissiongroupingid.
2283 // All submissions from students that do not belong to any of teamsubmissiongroupingid groups
2284 // count towards groupid = 0. Setting to true as only '0' key matters.
2287 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
2288 $groupsstr = 's.groupid ' . $groupssql . ' AND';
2289 $params = $params + $groupsparams;
2291 $sql = 'SELECT COUNT(s.groupid)
2292 FROM {assign_submission} s
2295 s.assignment = :assignid AND
2296 s.timemodified IS NOT NULL AND
2297 s.userid = :groupuserid AND '
2299 s.status = :submissionstatus';
2300 $params['groupuserid'] = 0;
2302 $sql = 'SELECT COUNT(s.userid)
2303 FROM {assign_submission} s
2304 JOIN(' . $esql . ') e ON e.id = s.userid
2307 s.assignment = :assignid AND
2308 s.timemodified IS NOT NULL AND
2309 s.status = :submissionstatus';
2313 return $DB->count_records_sql($sql, $params);
2317 * Utility function to get the userid for every row in the grading table
2318 * so the order can be frozen while we iterate it.
2320 * @return array An array of userids
2322 protected function get_grading_userid_list() {
2323 $filter = get_user_preferences('assign_filter', '');
2324 $table = new assign_grading_table($this, 0, $filter, 0, false);
2326 $useridlist = $table->get_column_data('userid');
2332 * Generate zip file from array of given files.
2334 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
2335 * This array is indexed by the final file name and each
2336 * element in the array is an instance of a stored_file object.
2337 * @return path of temp file - note this returned file does
2338 * not have a .zip extension - it is a temp file.
2340 protected function pack_files($filesforzipping) {
2342 // Create path for new zip file.
2343 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
2345 $zipper = new zip_packer();
2346 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
2353 * Finds all assignment notifications that have yet to be mailed out, and mails them.
2355 * Cron function to be run periodically according to the moodle cron.
2359 public static function cron() {
2362 // Only ever send a max of one days worth of updates.
2363 $yesterday = time() - (24 * 3600);
2365 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
2367 // Collect all submissions that require mailing.
2368 // Submissions are included if all are true:
2369 // - The assignment is visible in the gradebook.
2370 // - No previous notification has been sent.
2371 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
2372 // if marking workflow is enabled, the workflow state is at 'released'.
2373 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
2374 g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
2376 JOIN {assign_grades} g ON g.assignment = a.id
2377 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
2378 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
2379 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
2380 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
2381 LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
2382 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
2383 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
2384 uf.mailed = 0 AND gri.hidden = 0
2385 ORDER BY a.course, cm.id";
2388 'yesterday' => $yesterday,
2389 'today' => $timenow,
2390 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
2392 $submissions = $DB->get_records_sql($sql, $params);
2394 if (!empty($submissions)) {
2396 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
2398 // Preload courses we are going to need those.
2399 $courseids = array();
2400 foreach ($submissions as $submission) {
2401 $courseids[] = $submission->course;
2404 // Filter out duplicates.
2405 $courseids = array_unique($courseids);
2406 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2407 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
2408 $sql = 'SELECT c.*, ' . $ctxselect .
2410 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
2411 WHERE c.id ' . $courseidsql;
2413 $params['contextlevel'] = CONTEXT_COURSE;
2414 $courses = $DB->get_records_sql($sql, $params);
2416 // Clean up... this could go on for a while.
2419 unset($courseidsql);
2422 // Message students about new feedback.
2423 foreach ($submissions as $submission) {
2425 mtrace("Processing assignment submission $submission->id ...");
2427 // Do not cache user lookups - could be too many.
2428 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
2429 mtrace('Could not find user ' . $submission->userid);
2433 // Use a cache to prevent the same DB queries happening over and over.
2434 if (!array_key_exists($submission->course, $courses)) {
2435 mtrace('Could not find course ' . $submission->course);
2438 $course = $courses[$submission->course];
2439 if (isset($course->ctxid)) {
2440 // Context has not yet been preloaded. Do so now.
2441 context_helper::preload_from_record($course);
2444 // Override the language and timezone of the "current" user, so that
2445 // mail is customised for the receiver.
2446 cron_setup_user($user, $course);
2448 // Context lookups are already cached.
2449 $coursecontext = context_course::instance($course->id);
2450 if (!is_enrolled($coursecontext, $user->id)) {
2451 $courseshortname = format_string($course->shortname,
2453 array('context' => $coursecontext));
2454 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
2458 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
2459 mtrace('Could not find grader ' . $submission->grader);
2463 $modinfo = get_fast_modinfo($course, $user->id);
2464 $cm = $modinfo->get_cm($submission->cmid);
2465 // Context lookups are already cached.
2466 $contextmodule = context_module::instance($cm->id);
2468 if (!$cm->uservisible) {
2469 // Hold mail notification for assignments the user cannot access until later.
2473 // Need to send this to the student.
2474 $messagetype = 'feedbackavailable';
2475 $eventtype = 'assign_notification';
2476 $updatetime = $submission->lastmodified;
2477 $modulename = get_string('modulename', 'assign');
2480 if ($submission->blindmarking && !$submission->revealidentities) {
2481 if (empty($submission->recordid)) {
2482 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $grader->id);
2484 $uniqueid = $submission->recordid;
2487 $showusers = $submission->blindmarking && !$submission->revealidentities;
2488 self::send_assignment_notification($grader,
2501 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
2504 $DB->update_record('assign_user_flags', $flags);
2506 $flags = new stdClass();
2507 $flags->userid = $user->id;
2508 $flags->assignment = $submission->assignment;
2510 $DB->insert_record('assign_user_flags', $flags);
2515 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
2519 // Free up memory just to be sure.
2523 // Update calendar events to provide a description.
2527 allowsubmissionsfromdate >= :lastcron AND
2528 allowsubmissionsfromdate <= :timenow AND
2529 alwaysshowdescription = 0';
2530 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2531 $newlyavailable = $DB->get_records_sql($sql, $params);
2532 foreach ($newlyavailable as $record) {
2533 $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
2534 $context = context_module::instance($cm->id);
2536 $assignment = new assign($context, null, null);
2537 $assignment->update_calendar($cm->id);
2544 * Mark in the database that this grade record should have an update notification sent by cron.
2546 * @param stdClass $grade a grade record keyed on id
2547 * @param bool $mailedoverride when true, flag notification to be sent again.
2548 * @return bool true for success
2550 public function notify_grade_modified($grade, $mailedoverride = false) {
2553 $flags = $this->get_user_flags($grade->userid, true);
2554 if ($flags->mailed != 1 || $mailedoverride) {
2558 return $this->update_user_flags($flags);
2562 * Update user flags for this user in this assignment.
2564 * @param stdClass $flags a flags record keyed on id
2565 * @return bool true for success
2567 public function update_user_flags($flags) {
2569 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
2573 $result = $DB->update_record('assign_user_flags', $flags);
2578 * Update a grade in the grade table for the assignment and in the gradebook.
2580 * @param stdClass $grade a grade record keyed on id
2581 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
2582 * @return bool true for success
2584 public function update_grade($grade, $reopenattempt = false) {
2587 $grade->timemodified = time();
2589 if (!empty($grade->workflowstate)) {
2590 $validstates = $this->get_marking_workflow_states_for_current_user();
2591 if (!array_key_exists($grade->workflowstate, $validstates)) {
2596 if ($grade->grade && $grade->grade != -1) {
2597 if ($this->get_instance()->grade > 0) {
2598 if (!is_numeric($grade->grade)) {
2600 } else if ($grade->grade > $this->get_instance()->grade) {
2602 } else if ($grade->grade < 0) {
2607 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
2608 $scaleoptions = make_menu_from_list($scale->scale);
2609 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
2616 if (empty($grade->attemptnumber)) {
2617 // Set it to the default.
2618 $grade->attemptnumber = 0;
2620 $DB->update_record('assign_grades', $grade);
2623 if ($this->get_instance()->teamsubmission) {
2624 if (isset($this->mostrecentteamsubmission)) {
2625 $submission = $this->mostrecentteamsubmission;
2627 $submission = $this->get_group_submission($grade->userid, 0, false);
2630 $submission = $this->get_user_submission($grade->userid, false);
2633 // Only push to gradebook if the update is for the most recent attempt.
2634 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
2638 if ($this->gradebook_item_update(null, $grade)) {
2639 \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
2642 // If the conditions are met, allow another attempt.
2644 $this->reopen_submission_if_required($grade->userid,
2653 * View the grant extension date page.
2655 * Uses url parameters 'userid'
2656 * or from parameter 'selectedusers'
2658 * @param moodleform $mform - Used for validation of the submitted data
2661 protected function view_grant_extension($mform) {
2663 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2667 $data = new stdClass();
2668 $data->id = $this->get_course_module()->id;
2670 $formparams = array(
2671 'instance' => $this->get_instance(),
2675 $users = optional_param('userid', 0, PARAM_INT);
2677 $users = required_param('selectedusers', PARAM_SEQUENCE);
2679 $userlist = explode(',', $users);
2681 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
2682 $maxoverride = array('allowsubmissionsfromdate' => 0, 'duedate' => 0, 'cutoffdate' => 0);
2683 foreach ($userlist as $userid) {
2684 // To validate extension date with users overrides.
2685 $override = $this->override_exists($userid);
2686 foreach ($keys as $key) {
2687 if ($override->{$key}) {
2688 if ($maxoverride[$key] < $override->{$key}) {
2689 $maxoverride[$key] = $override->{$key};
2691 } else if ($maxoverride[$key] < $this->get_instance()->{$key}) {
2692 $maxoverride[$key] = $this->get_instance()->{$key};
2696 foreach ($keys as $key) {
2697 if ($maxoverride[$key]) {
2698 $this->get_instance()->{$key} = $maxoverride[$key];
2702 $formparams['userlist'] = $userlist;
2704 $data->selectedusers = $users;
2707 if (empty($mform)) {
2708 $mform = new mod_assign_extension_form(null, $formparams);
2710 $mform->set_data($data);
2711 $header = new assign_header($this->get_instance(),
2712 $this->get_context(),
2713 $this->show_intro(),
2714 $this->get_course_module()->id,
2715 get_string('grantextension', 'assign'));
2716 $o .= $this->get_renderer()->render($header);
2717 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
2718 $o .= $this->view_footer();
2723 * Get a list of the users in the same group as this user.
2725 * @param int $groupid The id of the group whose members we want or 0 for the default group
2726 * @param bool $onlyids Whether to retrieve only the user id's
2727 * @param bool $excludesuspended Whether to exclude suspended users
2728 * @return array The users (possibly id's only)
2730 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
2732 if ($groupid != 0) {
2733 $allusers = $this->list_participants($groupid, $onlyids);
2734 foreach ($allusers as $user) {
2735 if ($this->get_submission_group($user->id)) {
2740 $allusers = $this->list_participants(null, $onlyids);
2741 foreach ($allusers as $user) {
2742 if ($this->get_submission_group($user->id) == null) {
2747 // Exclude suspended users, if user can't see them.
2748 if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2749 foreach ($members as $key => $member) {
2750 if (!$this->is_active_user($member->id)) {
2751 unset($members[$key]);
2760 * Get a list of the users in the same group as this user that have not submitted the assignment.
2762 * @param int $groupid The id of the group whose members we want or 0 for the default group
2763 * @param bool $onlyids Whether to retrieve only the user id's
2764 * @return array The users (possibly id's only)
2766 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2767 $instance = $this->get_instance();
2768 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2771 $members = $this->get_submission_group_members($groupid, $onlyids);
2773 foreach ($members as $id => $member) {
2774 $submission = $this->get_user_submission($member->id, false);
2775 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2776 unset($members[$id]);
2778 if ($this->is_blind_marking()) {
2779 $members[$id]->alias = get_string('hiddenuser', 'assign') .
2780 $this->get_uniqueid_for_user($id);
2788 * Load the group submission object for a particular user, optionally creating it if required.
2790 * @param int $userid The id of the user whose submission we want
2791 * @param int $groupid The id of the group for this user - may be 0 in which
2792 * case it is determined from the userid.
2793 * @param bool $create If set to true a new submission object will be created in the database
2794 * with the status set to "new".
2795 * @param int $attemptnumber - -1 means the latest attempt
2796 * @return stdClass The submission
2798 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2801 if ($groupid == 0) {
2802 $group = $this->get_submission_group($userid);
2804 $groupid = $group->id;
2808 // Now get the group submission.
2809 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2810 if ($attemptnumber >= 0) {
2811 $params['attemptnumber'] = $attemptnumber;
2814 // Only return the row with the highest attemptnumber.
2816 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2818 $submission = reset($submissions);
2825 $submission = new stdClass();
2826 $submission->assignment = $this->get_instance()->id;
2827 $submission->userid = 0;
2828 $submission->groupid = $groupid;
2829 $submission->timecreated = time();
2830 $submission->timemodified = $submission->timecreated;
2831 if ($attemptnumber >= 0) {
2832 $submission->attemptnumber = $attemptnumber;
2834 $submission->attemptnumber = 0;
2836 // Work out if this is the latest submission.
2837 $submission->latest = 0;
2838 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2839 if ($attemptnumber == -1) {
2840 // This is a new submission so it must be the latest.
2841 $submission->latest = 1;
2843 // We need to work this out.
2844 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2846 $latestsubmission = reset($result);
2848 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2849 $submission->latest = 1;
2852 if ($submission->latest) {
2853 // This is the case when we need to set latest to 0 for all the other attempts.
2854 $DB->set_field('assign_submission', 'latest', 0, $params);
2856 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2857 $sid = $DB->insert_record('assign_submission', $submission);
2858 return $DB->get_record('assign_submission', array('id' => $sid));
2864 * View a summary listing of all assignments in the current course.
2868 private function view_course_index() {
2873 $course = $this->get_course();
2874 $strplural = get_string('modulenameplural', 'assign');
2876 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2877 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2878 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2882 $strsectionname = '';
2883 $usesections = course_format_uses_sections($course->format);
2884 $modinfo = get_fast_modinfo($course);
2887 $strsectionname = get_string('sectionname', 'format_'.$course->format);
2888 $sections = $modinfo->get_section_info_all();
2890 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2894 $currentsection = '';
2895 foreach ($modinfo->instances['assign'] as $cm) {
2896 if (!$cm->uservisible) {
2900 $timedue = $cms[$cm->id]->duedate;
2903 if ($usesections && $cm->sectionnum) {
2904 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2908 $context = context_module::instance($cm->id);
2910 $assignment = new assign($context, $cm, $course);
2913 $assignment->update_effective_access($USER->id);
2914 $timedue = $assignment->get_instance()->duedate;
2916 if (has_capability('mod/assign:grade', $context)) {
2917 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2919 } else if (has_capability('mod/assign:submit', $context)) {
2920 $usersubmission = $assignment->get_user_submission($USER->id, false);
2922 if (!empty($usersubmission->status)) {
2923 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2925 $submitted = get_string('submissionstatus_', 'assign');
2928 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2929 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2930 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2931 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2936 $courseindexsummary->add_assign_info($cm->id, $cm->get_formatted_name(), $sectionname, $timedue, $submitted, $grade);
2940 $o .= $this->get_renderer()->render($courseindexsummary);
2941 $o .= $this->view_footer();
2947 * View a page rendered by a plugin.
2949 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2953 protected function view_plugin_page() {
2958 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2959 $plugintype = required_param('plugin', PARAM_PLUGIN);
2960 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2962 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2964 print_error('invalidformdata', '');
2968 $o .= $plugin->view_page($pluginaction);
2975 * This is used for team assignments to get the group for the specified user.
2976 * If the user is a member of multiple or no groups this will return false
2978 * @param int $userid The id of the user whose submission we want
2979 * @return mixed The group or false
2981 public function get_submission_group($userid) {
2983 if (isset($this->usersubmissiongroups[$userid])) {
2984 return $this->usersubmissiongroups[$userid];
2987 $groups = $this->get_all_groups($userid);
2988 if (count($groups) != 1) {
2991 $return = array_pop($groups);
2994 // Cache the user submission group.
2995 $this->usersubmissiongroups[$userid] = $return;
3001 * Gets all groups the user is a member of.
3003 * @param int $userid Teh id of the user who's groups we are checking
3004 * @return array The group objects
3006 public function get_all_groups($userid) {
3007 if (isset($this->usergroups[$userid])) {
3008 return $this->usergroups[$userid];
3011 $grouping = $this->get_instance()->teamsubmissiongroupingid;
3012 $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
3014 $this->usergroups[$userid] = $return;
3021 * Display the submission that is used by a plugin.
3023 * Uses url parameters 'sid', 'gid' and 'plugin'.
3025 * @param string $pluginsubtype
3028 protected function view_plugin_content($pluginsubtype) {
3031 $submissionid = optional_param('sid', 0, PARAM_INT);
3032 $gradeid = optional_param('gid', 0, PARAM_INT);
3033 $plugintype = required_param('plugin', PARAM_PLUGIN);
3035 if ($pluginsubtype == 'assignsubmission') {
3036 $plugin = $this->get_submission_plugin_by_type($plugintype);
3037 if ($submissionid <= 0) {
3038 throw new coding_exception('Submission id should not be 0');
3040 $item = $this->get_submission($submissionid);
3042 // Check permissions.
3043 if (empty($item->userid)) {
3044 // Group submission.
3045 $this->require_view_group_submission($item->groupid);
3047 $this->require_view_submission($item->userid);
3049 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3050 $this->get_context(),
3051 $this->show_intro(),
3052 $this->get_course_module()->id,
3053 $plugin->get_name()));
3054 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
3056 assign_submission_plugin_submission::FULL,
3057 $this->get_course_module()->id,
3058 $this->get_return_action(),
3059 $this->get_return_params()));
3061 // Trigger event for viewing a submission.
3062 \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
3065 $plugin = $this->get_feedback_plugin_by_type($plugintype);
3066 if ($gradeid <= 0) {
3067 throw new coding_exception('Grade id should not be 0');
3069 $item = $this->get_grade($gradeid);
3070 // Check permissions.
3071 $this->require_view_submission($item->userid);
3072 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3073 $this->get_context(),
3074 $this->show_intro(),
3075 $this->get_course_module()->id,
3076 $plugin->get_name()));
3077 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
3079 assign_feedback_plugin_feedback::FULL,
3080 $this->get_course_module()->id,
3081 $this->get_return_action(),
3082 $this->get_return_params()));
3084 // Trigger event for viewing feedback.
3085 \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
3088 $o .= $this->view_return_links();
3090 $o .= $this->view_footer();
3096 * Rewrite plugin file urls so they resolve correctly in an exported zip.
3098 * @param string $text - The replacement text
3099 * @param stdClass $user - The user record
3100 * @param assign_plugin $plugin - The assignment plugin
3102 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
3103 // The groupname prefix for the urls doesn't depend on the group mode of the assignment instance.
3104 // Rather, it should be determined by checking the group submission settings of the instance,
3105 // which is what download_submission() does when generating the file name prefixes.
3107 if ($this->get_instance()->teamsubmission) {
3108 $submissiongroup = $this->get_submission_group($user->id);
3109 if ($submissiongroup) {
3110 $groupname = $submissiongroup->name . '-';
3112 $groupname = get_string('defaultteam', 'assign') . '-';
3116 if ($this->is_blind_marking()) {
3117 $prefix = $groupname . get_string('participant', 'assign');
3118 $prefix = str_replace('_', ' ', $prefix);
3119 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
3121 $prefix = $groupname . fullname($user);
3122 $prefix = str_replace('_', ' ', $prefix);
3123 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
3126 // Only prefix files if downloadasfolders user preference is NOT set.
3127 if (!get_user_preferences('assign_downloadasfolders', 1)) {
3128 $subtype = $plugin->get_subtype();
3129 $type = $plugin->get_type();
3130 $prefix = $prefix . $subtype . '_' . $type . '_';
3134 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
3140 * Render the content in editor that is often used by plugin.
3142 * @param string $filearea
3143 * @param int $submissionid
3144 * @param string $plugintype
3145 * @param string $editor
3146 * @param string $component
3147 * @param bool $shortentext Whether to shorten the text content.
3150 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component, $shortentext = false) {
3155 $plugin = $this->get_submission_plugin_by_type($plugintype);
3157 $text = $plugin->get_editor_text($editor, $submissionid);
3159 $text = shorten_text($text, 140);
3161 $format = $plugin->get_editor_format($editor, $submissionid);
3163 $finaltext = file_rewrite_pluginfile_urls($text,
3165 $this->get_context()->id,
3169 $params = array('overflowdiv' => true, 'context' => $this->get_context());
3170 $result .= format_text($finaltext, $format, $params);
3172 if ($CFG->enableportfolios && has_capability('mod/assign:exportownsubmission', $this->context)) {
3173 require_once($CFG->libdir . '/portfoliolib.php');
3175 $button = new portfolio_add_button();
3176 $portfolioparams = array('cmid' => $this->get_course_module()->id,
3177 'sid' => $submissionid,
3178 'plugin' => $plugintype,
3179 'editor' => $editor,
3181 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
3182 $fs = get_file_storage();
3184 if ($files = $fs->get_area_files($this->context->id,
3190 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3192 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3194 $result .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3200 * Display a continue page after grading.
3202 * @param string $message - The message to display.
3205 protected function view_savegrading_result($message) {
3207 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3208 $this->get_context(),
3209 $this->show_intro(),
3210 $this->get_course_module()->id,
3211 get_string('savegradingresult', 'assign')));
3212 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
3214 $this->get_course_module()->id);
3215 $o .= $this->get_renderer()->render($gradingresult);
3216 $o .= $this->view_footer();
3220 * Display a continue page after quickgrading.
3222 * @param string $message - The message to display.
3225 protected function view_quickgrading_result($message) {
3227 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3228 $this->get_context(),
3229 $this->show_intro(),
3230 $this->get_course_module()->id,
3231 get_string('quickgradingresult', 'assign')));
3232 $lastpage = optional_param('lastpage', null, PARAM_INT);
3233 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
3235 $this->get_course_module()->id,
3238 $o .= $this->get_renderer()->render($gradingresult);
3239 $o .= $this->view_footer();
3244 * Display the page footer.
3248 protected function view_footer() {
3249 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
3250 if (!PHPUNIT_TEST) {
3251 return $this->get_renderer()->render_footer();
3258 * Throw an error if the permissions to view this users' group submission are missing.
3260 * @param int $groupid Group id.
3261 * @throws required_capability_exception
3263 public function require_view_group_submission($groupid) {
3264 if (!$this->can_view_group_submission($groupid)) {
3265 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3270 * Throw an error if the permissions to view this users submission are missing.
3272 * @throws required_capability_exception
3275 public function require_view_submission($userid) {
3276 if (!$this->can_view_submission($userid)) {
3277 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3282 * Throw an error if the permissions to view grades in this assignment are missing.
3284 * @throws required_capability_exception
3287 public function require_view_grades() {
3288 if (!$this->can_view_grades()) {
3289 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3294 * Does this user have view grade or grade permission for this assignment?
3296 * @param mixed $groupid int|null when is set to a value, use this group instead calculating it
3299 public function can_view_grades($groupid = null) {
3300 // Permissions check.
3301 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
3304 // Checks for the edge case when user belongs to no groups and groupmode is sep.
3305 if ($this->get_course_module()->effectivegroupmode == SEPARATEGROUPS) {
3306 if ($groupid === null) {
3307 $groupid = groups_get_activity_allowed_groups($this->get_course_module());
3309 $groupflag = has_capability('moodle/site:accessallgroups', $this->get_context());
3310 $groupflag = $groupflag || !empty($groupid);
3311 return (bool)$groupflag;