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');
41 // Marker filter for grading page.
42 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
44 // Reopen attempt methods.
45 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
47 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
49 // Special value means allow unlimited attempts.
50 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
53 define('ASSIGN_GRADING_STATUS_GRADED', 'graded');
54 define('ASSIGN_GRADING_STATUS_NOT_GRADED', 'notgraded');
56 // Marking workflow states.
57 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
58 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
59 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
60 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
61 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
62 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
64 // Name of file area for intro attachments.
65 define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
67 require_once($CFG->libdir
. '/accesslib.php');
68 require_once($CFG->libdir
. '/formslib.php');
69 require_once($CFG->dirroot
. '/repository/lib.php');
70 require_once($CFG->dirroot
. '/mod/assign/mod_form.php');
71 require_once($CFG->libdir
. '/gradelib.php');
72 require_once($CFG->dirroot
. '/grade/grading/lib.php');
73 require_once($CFG->dirroot
. '/mod/assign/feedbackplugin.php');
74 require_once($CFG->dirroot
. '/mod/assign/submissionplugin.php');
75 require_once($CFG->dirroot
. '/mod/assign/renderable.php');
76 require_once($CFG->dirroot
. '/mod/assign/gradingtable.php');
77 require_once($CFG->libdir
. '/eventslib.php');
78 require_once($CFG->libdir
. '/portfolio/caller.php');
80 use \mod_assign\output\grading_app
;
83 * Standard base class for mod_assign (assignment types).
86 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
87 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
91 /** @var stdClass the assignment record that contains the global settings for this assign instance */
94 /** @var stdClass the grade_item record for this assign instance's primary grade item. */
97 /** @var context the context of the course module for this assign instance
98 * (or just the course if we are creating a new one)
102 /** @var stdClass the course this assign instance belongs to */
105 /** @var stdClass the admin config for all assign instances */
106 private $adminconfig;
108 /** @var assign_renderer the custom renderer for this module */
111 /** @var cm_info the course module for this assign instance */
112 private $coursemodule;
114 /** @var array cache for things like the coursemodule name or the scale menu -
115 * only lives for a single request.
119 /** @var array list of the installed submission plugins */
120 private $submissionplugins;
122 /** @var array list of the installed feedback plugins */
123 private $feedbackplugins;
125 /** @var string action to be used to return to this page
126 * (without repeating any form submissions etc).
128 private $returnaction = 'view';
130 /** @var array params to be used to return to this page */
131 private $returnparams = array();
133 /** @var string modulename prevents excessive calls to get_string */
134 private static $modulename = null;
136 /** @var string modulenameplural prevents excessive calls to get_string */
137 private static $modulenameplural = null;
139 /** @var array of marking workflow states for the current user */
140 private $markingworkflowstates = null;
142 /** @var bool whether to exclude users with inactive enrolment */
143 private $showonlyactiveenrol = null;
145 /** @var string A key used to identify userlists created by this object. */
146 private $useridlistid = null;
148 /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
149 private $participants = array();
151 /** @var array cached list of user groups when team submissions are enabled. The cache key will be the user. */
152 private $usersubmissiongroups = array();
154 /** @var array cached list of user groups. The cache key will be the user. */
155 private $usergroups = array();
157 /** @var array cached list of IDs of users who share group membership with the user. The cache key will be the user. */
158 private $sharedgroupmembers = array();
161 * Constructor for the base assign class.
163 * Note: For $coursemodule you can supply a stdclass if you like, but it
164 * will be more efficient to supply a cm_info object.
166 * @param mixed $coursemodulecontext context|null the course module context
167 * (or the course context if the coursemodule has not been
169 * @param mixed $coursemodule the current course module if it was already loaded,
170 * otherwise this class will load one from the context as required.
171 * @param mixed $course the current course if it was already loaded,
172 * otherwise this class will load one from the context as required.
174 public function __construct($coursemodulecontext, $coursemodule, $course) {
177 $this->context
= $coursemodulecontext;
178 $this->course
= $course;
180 // Ensure that $this->coursemodule is a cm_info object (or null).
181 $this->coursemodule
= cm_info
::create($coursemodule);
183 // Temporary cache only lives for a single request - used to reduce db lookups.
184 $this->cache
= array();
186 $this->submissionplugins
= $this->load_plugins('assignsubmission');
187 $this->feedbackplugins
= $this->load_plugins('assignfeedback');
189 // Extra entropy is required for uniqid() to work on cygwin.
190 $this->useridlistid
= clean_param(uniqid('', true), PARAM_ALPHANUM
);
192 if (!isset($SESSION->mod_assign_useridlist
)) {
193 $SESSION->mod_assign_useridlist
= [];
198 * Set the action and parameters that can be used to return to the current page.
200 * @param string $action The action for the current page
201 * @param array $params An array of name value pairs which form the parameters
202 * to return to the current page.
205 public function register_return_link($action, $params) {
207 $params['action'] = $action;
208 $cm = $this->get_course_module();
210 $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $cm->id
));
212 $currenturl = new moodle_url('/mod/assign/index.php', array('id' => $this->get_course()->id
));
215 $currenturl->params($params);
216 $PAGE->set_url($currenturl);
220 * Return an action that can be used to get back to the current page.
222 * @return string action
224 public function get_return_action() {
227 // Web services don't set a URL, we should avoid debugging when ussing the url object.
229 $params = $PAGE->url
->params();
232 if (!empty($params['action'])) {
233 return $params['action'];
239 * Based on the current assignment settings should we display the intro.
241 * @return bool showintro
243 public function show_intro() {
244 if ($this->get_instance()->alwaysshowdescription ||
245 time() > $this->get_instance()->allowsubmissionsfromdate
) {
252 * Return a list of parameters that can be used to get back to the current page.
254 * @return array params
256 public function get_return_params() {
259 $params = $PAGE->url
->params();
260 unset($params['id']);
261 unset($params['action']);
266 * Set the submitted form data.
268 * @param stdClass $data The form data (instance)
270 public function set_instance(stdClass
$data) {
271 $this->instance
= $data;
277 * @param context $context The new context
279 public function set_context(context
$context) {
280 $this->context
= $context;
284 * Set the course data.
286 * @param stdClass $course The course data
288 public function set_course(stdClass
$course) {
289 $this->course
= $course;
293 * Get list of feedback plugins installed.
297 public function get_feedback_plugins() {
298 return $this->feedbackplugins
;
302 * Get list of submission plugins installed.
306 public function get_submission_plugins() {
307 return $this->submissionplugins
;
311 * Is blind marking enabled and reveal identities not set yet?
315 public function is_blind_marking() {
316 return $this->get_instance()->blindmarking
&& !$this->get_instance()->revealidentities
;
320 * Does an assignment have submission(s) or grade(s) already?
324 public function has_submissions_or_grades() {
325 $allgrades = $this->count_grades();
326 $allsubmissions = $this->count_submissions();
327 if (($allgrades == 0) && ($allsubmissions == 0)) {
334 * Get a specific submission plugin by its type.
336 * @param string $subtype assignsubmission | assignfeedback
337 * @param string $type
338 * @return mixed assign_plugin|null
340 public function get_plugin_by_type($subtype, $type) {
341 $shortsubtype = substr($subtype, strlen('assign'));
342 $name = $shortsubtype . 'plugins';
343 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
346 $pluginlist = $this->$name;
347 foreach ($pluginlist as $plugin) {
348 if ($plugin->get_type() == $type) {
356 * Get a feedback plugin by type.
358 * @param string $type - The type of plugin e.g comments
359 * @return mixed assign_feedback_plugin|null
361 public function get_feedback_plugin_by_type($type) {
362 return $this->get_plugin_by_type('assignfeedback', $type);
366 * Get a submission plugin by type.
368 * @param string $type - The type of plugin e.g comments
369 * @return mixed assign_submission_plugin|null
371 public function get_submission_plugin_by_type($type) {
372 return $this->get_plugin_by_type('assignsubmission', $type);
376 * Load the plugins from the sub folders under subtype.
378 * @param string $subtype - either submission or feedback
379 * @return array - The sorted list of plugins
381 public function load_plugins($subtype) {
385 $names = core_component
::get_plugin_list($subtype);
387 foreach ($names as $name => $path) {
388 if (file_exists($path . '/locallib.php')) {
389 require_once($path . '/locallib.php');
391 $shortsubtype = substr($subtype, strlen('assign'));
392 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
394 $plugin = new $pluginclass($this, $name);
396 if ($plugin instanceof assign_plugin
) {
397 $idx = $plugin->get_sort_order();
398 while (array_key_exists($idx, $result)) {
401 $result[$idx] = $plugin;
410 * Display the assignment, used by view.php
412 * The assignment is displayed differently depending on your role,
413 * the settings for the assignment and the status of the assignment.
415 * @param string $action The current action if any.
416 * @param array $args Optional arguments to pass to the view (instead of getting them from GET and POST).
417 * @return string - The page output.
419 public function view($action='', $args = array()) {
425 $nextpageparams = array();
427 if (!empty($this->get_course_module()->id
)) {
428 $nextpageparams['id'] = $this->get_course_module()->id
;
431 // Handle form submissions first.
432 if ($action == 'savesubmission') {
433 $action = 'editsubmission';
434 if ($this->process_save_submission($mform, $notices)) {
435 $action = 'redirect';
436 $nextpageparams['action'] = 'view';
438 } else if ($action == 'editprevioussubmission') {
439 $action = 'editsubmission';
440 if ($this->process_copy_previous_attempt($notices)) {
441 $action = 'redirect';
442 $nextpageparams['action'] = 'editsubmission';
444 } else if ($action == 'lock') {
445 $this->process_lock_submission();
446 $action = 'redirect';
447 $nextpageparams['action'] = 'grading';
448 } else if ($action == 'addattempt') {
449 $this->process_add_attempt(required_param('userid', PARAM_INT
));
450 $action = 'redirect';
451 $nextpageparams['action'] = 'grading';
452 } else if ($action == 'reverttodraft') {
453 $this->process_revert_to_draft();
454 $action = 'redirect';
455 $nextpageparams['action'] = 'grading';
456 } else if ($action == 'unlock') {
457 $this->process_unlock_submission();
458 $action = 'redirect';
459 $nextpageparams['action'] = 'grading';
460 } else if ($action == 'setbatchmarkingworkflowstate') {
461 $this->process_set_batch_marking_workflow_state();
462 $action = 'redirect';
463 $nextpageparams['action'] = 'grading';
464 } else if ($action == 'setbatchmarkingallocation') {
465 $this->process_set_batch_marking_allocation();
466 $action = 'redirect';
467 $nextpageparams['action'] = 'grading';
468 } else if ($action == 'confirmsubmit') {
470 if ($this->process_submit_for_grading($mform, $notices)) {
471 $action = 'redirect';
472 $nextpageparams['action'] = 'view';
473 } else if ($notices) {
474 $action = 'viewsubmitforgradingerror';
476 } else if ($action == 'submitotherforgrading') {
477 if ($this->process_submit_other_for_grading($mform, $notices)) {
478 $action = 'redirect';
479 $nextpageparams['action'] = 'grading';
481 $action = 'viewsubmitforgradingerror';
483 } else if ($action == 'gradingbatchoperation') {
484 $action = $this->process_grading_batch_operation($mform);
485 if ($action == 'grading') {
486 $action = 'redirect';
487 $nextpageparams['action'] = 'grading';
489 } else if ($action == 'submitgrade') {
490 if (optional_param('saveandshownext', null, PARAM_RAW
)) {
491 // Save and show next.
493 if ($this->process_save_grade($mform)) {
494 $action = 'redirect';
495 $nextpageparams['action'] = 'grade';
496 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT
) +
1;
497 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM
);
499 } else if (optional_param('nosaveandprevious', null, PARAM_RAW
)) {
500 $action = 'redirect';
501 $nextpageparams['action'] = 'grade';
502 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT
) - 1;
503 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM
);
504 } else if (optional_param('nosaveandnext', null, PARAM_RAW
)) {
505 $action = 'redirect';
506 $nextpageparams['action'] = 'grade';
507 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT
) +
1;
508 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM
);
509 } else if (optional_param('savegrade', null, PARAM_RAW
)) {
510 // Save changes button.
512 if ($this->process_save_grade($mform)) {
513 $action = 'redirect';
514 $nextpageparams['action'] = 'savegradingresult';
518 $action = 'redirect';
519 $nextpageparams['action'] = 'grading';
521 } else if ($action == 'quickgrade') {
522 $message = $this->process_save_quick_grades();
523 $action = 'quickgradingresult';
524 } else if ($action == 'saveoptions') {
525 $this->process_save_grading_options();
526 $action = 'redirect';
527 $nextpageparams['action'] = 'grading';
528 } else if ($action == 'saveextension') {
529 $action = 'grantextension';
530 if ($this->process_save_extension($mform)) {
531 $action = 'redirect';
532 $nextpageparams['action'] = 'grading';
534 } else if ($action == 'revealidentitiesconfirm') {
535 $this->process_reveal_identities();
536 $action = 'redirect';
537 $nextpageparams['action'] = 'grading';
540 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT
),
541 'useridlistid' => optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM
));
542 $this->register_return_link($action, $returnparams);
544 // Include any page action as part of the body tag CSS id.
545 if (!empty($action)) {
546 $PAGE->set_pagetype('mod-assign-' . $action);
548 // Now show the right view page.
549 if ($action == 'redirect') {
550 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
551 redirect($nextpageurl);
553 } else if ($action == 'savegradingresult') {
554 $message = get_string('gradingchangessaved', 'assign');
555 $o .= $this->view_savegrading_result($message);
556 } else if ($action == 'quickgradingresult') {
558 $o .= $this->view_quickgrading_result($message);
559 } else if ($action == 'gradingpanel') {
560 $o .= $this->view_single_grading_panel($args);
561 } else if ($action == 'grade') {
562 $o .= $this->view_single_grade_page($mform);
563 } else if ($action == 'viewpluginassignfeedback') {
564 $o .= $this->view_plugin_content('assignfeedback');
565 } else if ($action == 'viewpluginassignsubmission') {
566 $o .= $this->view_plugin_content('assignsubmission');
567 } else if ($action == 'editsubmission') {
568 $o .= $this->view_edit_submission_page($mform, $notices);
569 } else if ($action == 'grader') {
570 $o .= $this->view_grader();
571 } else if ($action == 'grading') {
572 $o .= $this->view_grading_page();
573 } else if ($action == 'downloadall') {
574 $o .= $this->download_submissions();
575 } else if ($action == 'submit') {
576 $o .= $this->check_submit_for_grading($mform);
577 } else if ($action == 'grantextension') {
578 $o .= $this->view_grant_extension($mform);
579 } else if ($action == 'revealidentities') {
580 $o .= $this->view_reveal_identities_confirm($mform);
581 } else if ($action == 'plugingradingbatchoperation') {
582 $o .= $this->view_plugin_grading_batch_operation($mform);
583 } else if ($action == 'viewpluginpage') {
584 $o .= $this->view_plugin_page();
585 } else if ($action == 'viewcourseindex') {
586 $o .= $this->view_course_index();
587 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
588 $o .= $this->view_batch_set_workflow_state($mform);
589 } else if ($action == 'viewbatchmarkingallocation') {
590 $o .= $this->view_batch_markingallocation($mform);
591 } else if ($action == 'viewsubmitforgradingerror') {
592 $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
594 $o .= $this->view_submission_page();
601 * Add this instance to the database.
603 * @param stdClass $formdata The data submitted from the form
604 * @param bool $callplugins This is used to skip the plugin code
605 * when upgrading an old assignment to a new one (the plugins get called manually)
606 * @return mixed false if an error occurs or the int id of the new instance
608 public function add_instance(stdClass
$formdata, $callplugins) {
610 $adminconfig = $this->get_admin_config();
614 // Add the database record.
615 $update = new stdClass();
616 $update->name
= $formdata->name
;
617 $update->timemodified
= time();
618 $update->timecreated
= time();
619 $update->course
= $formdata->course
;
620 $update->courseid
= $formdata->course
;
621 $update->intro
= $formdata->intro
;
622 $update->introformat
= $formdata->introformat
;
623 $update->alwaysshowdescription
= !empty($formdata->alwaysshowdescription
);
624 $update->submissiondrafts
= $formdata->submissiondrafts
;
625 $update->requiresubmissionstatement
= $formdata->requiresubmissionstatement
;
626 $update->sendnotifications
= $formdata->sendnotifications
;
627 $update->sendlatenotifications
= $formdata->sendlatenotifications
;
628 $update->sendstudentnotifications
= $adminconfig->sendstudentnotifications
;
629 if (isset($formdata->sendstudentnotifications
)) {
630 $update->sendstudentnotifications
= $formdata->sendstudentnotifications
;
632 $update->duedate
= $formdata->duedate
;
633 $update->cutoffdate
= $formdata->cutoffdate
;
634 $update->allowsubmissionsfromdate
= $formdata->allowsubmissionsfromdate
;
635 $update->grade
= $formdata->grade
;
636 $update->completionsubmit
= !empty($formdata->completionsubmit
);
637 $update->teamsubmission
= $formdata->teamsubmission
;
638 $update->requireallteammemberssubmit
= $formdata->requireallteammemberssubmit
;
639 if (isset($formdata->teamsubmissiongroupingid
)) {
640 $update->teamsubmissiongroupingid
= $formdata->teamsubmissiongroupingid
;
642 $update->blindmarking
= $formdata->blindmarking
;
643 $update->attemptreopenmethod
= ASSIGN_ATTEMPT_REOPEN_METHOD_NONE
;
644 if (!empty($formdata->attemptreopenmethod
)) {
645 $update->attemptreopenmethod
= $formdata->attemptreopenmethod
;
647 if (!empty($formdata->maxattempts
)) {
648 $update->maxattempts
= $formdata->maxattempts
;
650 if (isset($formdata->preventsubmissionnotingroup
)) {
651 $update->preventsubmissionnotingroup
= $formdata->preventsubmissionnotingroup
;
653 $update->markingworkflow
= $formdata->markingworkflow
;
654 $update->markingallocation
= $formdata->markingallocation
;
655 if (empty($update->markingworkflow
)) { // If marking workflow is disabled, make sure allocation is disabled.
656 $update->markingallocation
= 0;
659 $returnid = $DB->insert_record('assign', $update);
660 $this->instance
= $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST
);
661 // Cache the course record.
662 $this->course
= $DB->get_record('course', array('id'=>$formdata->course
), '*', MUST_EXIST
);
664 $this->save_intro_draft_files($formdata);
667 // Call save_settings hook for submission plugins.
668 foreach ($this->submissionplugins
as $plugin) {
669 if (!$this->update_plugin_instance($plugin, $formdata)) {
670 print_error($plugin->get_error());
674 foreach ($this->feedbackplugins
as $plugin) {
675 if (!$this->update_plugin_instance($plugin, $formdata)) {
676 print_error($plugin->get_error());
681 // In the case of upgrades the coursemodule has not been set,
682 // so we need to wait before calling these two.
683 $this->update_calendar($formdata->coursemodule
);
684 $this->update_gradebook(false, $formdata->coursemodule
);
688 $update = new stdClass();
689 $update->id
= $this->get_instance()->id
;
690 $update->nosubmissions
= (!$this->is_any_submission_plugin_enabled()) ?
1: 0;
691 $DB->update_record('assign', $update);
697 * Delete all grades from the gradebook for this assignment.
701 protected function delete_grades() {
704 $result = grade_update('mod/assign',
705 $this->get_course()->id
,
708 $this->get_instance()->id
,
711 array('deleted'=>1));
712 return $result == GRADE_UPDATE_OK
;
716 * Delete this instance from the database.
718 * @return bool false if an error occurs
720 public function delete_instance() {
724 foreach ($this->submissionplugins
as $plugin) {
725 if (!$plugin->delete_instance()) {
726 print_error($plugin->get_error());
730 foreach ($this->feedbackplugins
as $plugin) {
731 if (!$plugin->delete_instance()) {
732 print_error($plugin->get_error());
737 // Delete files associated with this assignment.
738 $fs = get_file_storage();
739 if (! $fs->delete_area_files($this->context
->id
) ) {
743 // Delete_records will throw an exception if it fails - so no need for error checking here.
744 $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id
));
745 $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id
));
746 $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id
));
747 $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id
));
748 $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id
));
750 // Delete items from the gradebook.
751 if (! $this->delete_grades()) {
755 // Delete the instance.
756 $DB->delete_records('assign', array('id'=>$this->get_instance()->id
));
762 * Actual implementation of the reset course functionality, delete all the
763 * assignment submissions for course $data->courseid.
765 * @param stdClass $data the data submitted from the reset course.
766 * @return array status array
768 public function reset_userdata($data) {
771 $componentstr = get_string('modulenameplural', 'assign');
774 $fs = get_file_storage();
775 if (!empty($data->reset_assign_submissions
)) {
776 // Delete files associated with this assignment.
777 foreach ($this->submissionplugins
as $plugin) {
778 $fileareas = array();
779 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
780 $fileareas = $plugin->get_file_areas();
781 foreach ($fileareas as $filearea => $notused) {
782 $fs->delete_area_files($this->context
->id
, $plugincomponent, $filearea);
785 if (!$plugin->delete_instance()) {
786 $status[] = array('component'=>$componentstr,
787 'item'=>get_string('deleteallsubmissions', 'assign'),
788 'error'=>$plugin->get_error());
792 foreach ($this->feedbackplugins
as $plugin) {
793 $fileareas = array();
794 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
795 $fileareas = $plugin->get_file_areas();
796 foreach ($fileareas as $filearea => $notused) {
797 $fs->delete_area_files($this->context
->id
, $plugincomponent, $filearea);
800 if (!$plugin->delete_instance()) {
801 $status[] = array('component'=>$componentstr,
802 'item'=>get_string('deleteallsubmissions', 'assign'),
803 'error'=>$plugin->get_error());
807 $assignids = $DB->get_records('assign', array('course' => $data->courseid
), '', 'id');
808 list($sql, $params) = $DB->get_in_or_equal(array_keys($assignids));
810 $DB->delete_records_select('assign_submission', "assignment $sql", $params);
811 $DB->delete_records_select('assign_user_flags', "assignment $sql", $params);
813 $status[] = array('component'=>$componentstr,
814 'item'=>get_string('deleteallsubmissions', 'assign'),
817 if (!empty($data->reset_gradebook_grades
)) {
818 $DB->delete_records_select('assign_grades', "assignment $sql", $params);
819 // Remove all grades from gradebook.
820 require_once($CFG->dirroot
.'/mod/assign/lib.php');
821 assign_reset_gradebook($data->courseid
);
823 // Reset revealidentities if both submissions and grades have been reset.
824 if ($this->get_instance()->blindmarking
&& $this->get_instance()->revealidentities
) {
825 $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id
));
829 // Updating dates - shift may be negative too.
830 if ($data->timeshift
) {
831 shift_course_mod_dates('assign',
832 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
834 $data->courseid
, $this->get_instance()->id
);
835 $status[] = array('component'=>$componentstr,
836 'item'=>get_string('datechanged'),
844 * Update the settings for a single plugin.
846 * @param assign_plugin $plugin The plugin to update
847 * @param stdClass $formdata The form data
848 * @return bool false if an error occurs
850 protected function update_plugin_instance(assign_plugin
$plugin, stdClass
$formdata) {
851 if ($plugin->is_visible()) {
852 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
853 if (!empty($formdata->$enabledname)) {
855 if (!$plugin->save_settings($formdata)) {
856 print_error($plugin->get_error());
867 * Update the gradebook information for this assignment.
869 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
870 * @param int $coursemoduleid This is required because it might not exist in the database yet
873 public function update_gradebook($reset, $coursemoduleid) {
876 require_once($CFG->dirroot
.'/mod/assign/lib.php');
877 $assign = clone $this->get_instance();
878 $assign->cmidnumber
= $coursemoduleid;
880 // Set assign gradebook feedback plugin status (enabled and visible).
881 $assign->gradefeedbackenabled
= $this->is_gradebook_feedback_enabled();
888 return assign_grade_item_update($assign, $param);
892 * Get the marking table page size
896 public function get_assign_perpage() {
897 $perpage = (int) get_user_preferences('assign_perpage', 10);
898 $adminconfig = $this->get_admin_config();
900 if (isset($adminconfig->maxperpage
)) {
901 $maxperpage = $adminconfig->maxperpage
;
903 if (isset($maxperpage) &&
905 ($perpage == -1 ||
$perpage > $maxperpage)) {
906 $perpage = $maxperpage;
912 * Load and cache the admin config for this module.
914 * @return stdClass the plugin config
916 public function get_admin_config() {
917 if ($this->adminconfig
) {
918 return $this->adminconfig
;
920 $this->adminconfig
= get_config('assign');
921 return $this->adminconfig
;
925 * Update the calendar entries for this assignment.
927 * @param int $coursemoduleid - Required to pass this in because it might
928 * not exist in the database yet.
931 public function update_calendar($coursemoduleid) {
933 require_once($CFG->dirroot
.'/calendar/lib.php');
935 // Special case for add_instance as the coursemodule has not been set yet.
936 $instance = $this->get_instance();
940 if ($instance->duedate
) {
941 $event = new stdClass();
943 $params = array('modulename' => 'assign', 'instance' => $instance->id
, 'eventtype' => $eventtype);
944 $event->id
= $DB->get_field('event', 'id', $params);
945 $event->name
= $instance->name
;
946 $event->timestart
= $instance->duedate
;
948 // Convert the links to pluginfile. It is a bit hacky but at this stage the files
949 // might not have been saved in the module area yet.
950 $intro = $instance->intro
;
951 if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
952 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
955 // We need to remove the links to files as the calendar is not ready
956 // to support module events with file areas.
957 $intro = strip_pluginfile_content($intro);
958 if ($this->show_intro()) {
959 $event->description
= array(
961 'format' => $instance->introformat
964 $event->description
= array(
966 'format' => $instance->introformat
971 $calendarevent = calendar_event
::load($event->id
);
972 $calendarevent->update($event);
975 $event->courseid
= $instance->course
;
978 $event->modulename
= 'assign';
979 $event->instance
= $instance->id
;
980 $event->eventtype
= $eventtype;
981 $event->timeduration
= 0;
982 calendar_event
::create($event);
985 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id
, 'eventtype' => $eventtype));
991 * Update this instance in the database.
993 * @param stdClass $formdata - the data submitted from the form
994 * @return bool false if an error occurs
996 public function update_instance($formdata) {
998 $adminconfig = $this->get_admin_config();
1000 $update = new stdClass();
1001 $update->id
= $formdata->instance
;
1002 $update->name
= $formdata->name
;
1003 $update->timemodified
= time();
1004 $update->course
= $formdata->course
;
1005 $update->intro
= $formdata->intro
;
1006 $update->introformat
= $formdata->introformat
;
1007 $update->alwaysshowdescription
= !empty($formdata->alwaysshowdescription
);
1008 $update->submissiondrafts
= $formdata->submissiondrafts
;
1009 $update->requiresubmissionstatement
= $formdata->requiresubmissionstatement
;
1010 $update->sendnotifications
= $formdata->sendnotifications
;
1011 $update->sendlatenotifications
= $formdata->sendlatenotifications
;
1012 $update->sendstudentnotifications
= $adminconfig->sendstudentnotifications
;
1013 if (isset($formdata->sendstudentnotifications
)) {
1014 $update->sendstudentnotifications
= $formdata->sendstudentnotifications
;
1016 $update->duedate
= $formdata->duedate
;
1017 $update->cutoffdate
= $formdata->cutoffdate
;
1018 $update->allowsubmissionsfromdate
= $formdata->allowsubmissionsfromdate
;
1019 $update->grade
= $formdata->grade
;
1020 if (!empty($formdata->completionunlocked
)) {
1021 $update->completionsubmit
= !empty($formdata->completionsubmit
);
1023 $update->teamsubmission
= $formdata->teamsubmission
;
1024 $update->requireallteammemberssubmit
= $formdata->requireallteammemberssubmit
;
1025 if (isset($formdata->teamsubmissiongroupingid
)) {
1026 $update->teamsubmissiongroupingid
= $formdata->teamsubmissiongroupingid
;
1028 $update->blindmarking
= $formdata->blindmarking
;
1029 $update->attemptreopenmethod
= ASSIGN_ATTEMPT_REOPEN_METHOD_NONE
;
1030 if (!empty($formdata->attemptreopenmethod
)) {
1031 $update->attemptreopenmethod
= $formdata->attemptreopenmethod
;
1033 if (!empty($formdata->maxattempts
)) {
1034 $update->maxattempts
= $formdata->maxattempts
;
1036 if (isset($formdata->preventsubmissionnotingroup
)) {
1037 $update->preventsubmissionnotingroup
= $formdata->preventsubmissionnotingroup
;
1039 $update->markingworkflow
= $formdata->markingworkflow
;
1040 $update->markingallocation
= $formdata->markingallocation
;
1041 if (empty($update->markingworkflow
)) { // If marking workflow is disabled, make sure allocation is disabled.
1042 $update->markingallocation
= 0;
1045 $result = $DB->update_record('assign', $update);
1046 $this->instance
= $DB->get_record('assign', array('id'=>$update->id
), '*', MUST_EXIST
);
1048 $this->save_intro_draft_files($formdata);
1050 // Load the assignment so the plugins have access to it.
1052 // Call save_settings hook for submission plugins.
1053 foreach ($this->submissionplugins
as $plugin) {
1054 if (!$this->update_plugin_instance($plugin, $formdata)) {
1055 print_error($plugin->get_error());
1059 foreach ($this->feedbackplugins
as $plugin) {
1060 if (!$this->update_plugin_instance($plugin, $formdata)) {
1061 print_error($plugin->get_error());
1066 $this->update_calendar($this->get_course_module()->id
);
1067 $this->update_gradebook(false, $this->get_course_module()->id
);
1069 $update = new stdClass();
1070 $update->id
= $this->get_instance()->id
;
1071 $update->nosubmissions
= (!$this->is_any_submission_plugin_enabled()) ?
1: 0;
1072 $DB->update_record('assign', $update);
1078 * Save the attachments in the draft areas.
1080 * @param stdClass $formdata
1082 protected function save_intro_draft_files($formdata) {
1083 if (isset($formdata->introattachments
)) {
1084 file_save_draft_area_files($formdata->introattachments
, $this->get_context()->id
,
1085 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA
, 0);
1090 * Add elements in grading plugin form.
1092 * @param mixed $grade stdClass|null
1093 * @param MoodleQuickForm $mform
1094 * @param stdClass $data
1095 * @param int $userid - The userid we are grading
1098 protected function add_plugin_grade_elements($grade, MoodleQuickForm
$mform, stdClass
$data, $userid) {
1099 foreach ($this->feedbackplugins
as $plugin) {
1100 if ($plugin->is_enabled() && $plugin->is_visible()) {
1101 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1109 * Add one plugins settings to edit plugin form.
1111 * @param assign_plugin $plugin The plugin to add the settings from
1112 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1113 * This form is modified directly (not returned).
1114 * @param array $pluginsenabled A list of form elements to be added to a group.
1115 * The new element is added to this array by this function.
1118 protected function add_plugin_settings(assign_plugin
$plugin, MoodleQuickForm
$mform, & $pluginsenabled) {
1120 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1121 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1122 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1123 $mform->setType($name, PARAM_BOOL
);
1124 $plugin->get_settings($mform);
1125 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1126 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1127 $label = $plugin->get_name();
1128 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1129 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1131 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1132 if ($plugin->get_config('enabled') !== false) {
1133 $default = $plugin->is_enabled();
1135 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1137 $plugin->get_settings($mform);
1143 * Add settings to edit plugin form.
1145 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1146 * This form is modified directly (not returned).
1149 public function add_all_plugin_settings(MoodleQuickForm
$mform) {
1150 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1152 $submissionpluginsenabled = array();
1153 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1154 foreach ($this->submissionplugins
as $plugin) {
1155 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1157 $group->setElements($submissionpluginsenabled);
1159 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1160 $feedbackpluginsenabled = array();
1161 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1162 foreach ($this->feedbackplugins
as $plugin) {
1163 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1165 $group->setElements($feedbackpluginsenabled);
1166 $mform->setExpanded('submissiontypes');
1170 * Allow each plugin an opportunity to update the defaultvalues
1171 * passed in to the settings form (needed to set up draft areas for
1172 * editor and filemanager elements)
1174 * @param array $defaultvalues
1176 public function plugin_data_preprocessing(&$defaultvalues) {
1177 foreach ($this->submissionplugins
as $plugin) {
1178 if ($plugin->is_visible()) {
1179 $plugin->data_preprocessing($defaultvalues);
1182 foreach ($this->feedbackplugins
as $plugin) {
1183 if ($plugin->is_visible()) {
1184 $plugin->data_preprocessing($defaultvalues);
1190 * Get the name of the current module.
1192 * @return string the module name (Assignment)
1194 protected function get_module_name() {
1195 if (isset(self
::$modulename)) {
1196 return self
::$modulename;
1198 self
::$modulename = get_string('modulename', 'assign');
1199 return self
::$modulename;
1203 * Get the plural name of the current module.
1205 * @return string the module name plural (Assignments)
1207 protected function get_module_name_plural() {
1208 if (isset(self
::$modulenameplural)) {
1209 return self
::$modulenameplural;
1211 self
::$modulenameplural = get_string('modulenameplural', 'assign');
1212 return self
::$modulenameplural;
1216 * Has this assignment been constructed from an instance?
1220 public function has_instance() {
1221 return $this->instance ||
$this->get_course_module();
1225 * Get the settings for the current instance of this assignment
1227 * @return stdClass The settings
1229 public function get_instance() {
1231 if ($this->instance
) {
1232 return $this->instance
;
1234 if ($this->get_course_module()) {
1235 $params = array('id' => $this->get_course_module()->instance
);
1236 $this->instance
= $DB->get_record('assign', $params, '*', MUST_EXIST
);
1238 if (!$this->instance
) {
1239 throw new coding_exception('Improper use of the assignment class. ' .
1240 'Cannot load the assignment record.');
1242 return $this->instance
;
1246 * Get the primary grade item for this assign instance.
1248 * @return stdClass The grade_item record
1250 public function get_grade_item() {
1251 if ($this->gradeitem
) {
1252 return $this->gradeitem
;
1254 $instance = $this->get_instance();
1255 $params = array('itemtype' => 'mod',
1256 'itemmodule' => 'assign',
1257 'iteminstance' => $instance->id
,
1258 'courseid' => $instance->course
,
1260 $this->gradeitem
= grade_item
::fetch($params);
1261 if (!$this->gradeitem
) {
1262 throw new coding_exception('Improper use of the assignment class. ' .
1263 'Cannot load the grade item.');
1265 return $this->gradeitem
;
1269 * Get the context of the current course.
1271 * @return mixed context|null The course context
1273 public function get_course_context() {
1274 if (!$this->context
&& !$this->course
) {
1275 throw new coding_exception('Improper use of the assignment class. ' .
1276 'Cannot load the course context.');
1278 if ($this->context
) {
1279 return $this->context
->get_course_context();
1281 return context_course
::instance($this->course
->id
);
1287 * Get the current course module.
1289 * @return cm_info|null The course module or null if not known
1291 public function get_course_module() {
1292 if ($this->coursemodule
) {
1293 return $this->coursemodule
;
1295 if (!$this->context
) {
1299 if ($this->context
->contextlevel
== CONTEXT_MODULE
) {
1300 $modinfo = get_fast_modinfo($this->get_course());
1301 $this->coursemodule
= $modinfo->get_cm($this->context
->instanceid
);
1302 return $this->coursemodule
;
1308 * Get context module.
1312 public function get_context() {
1313 return $this->context
;
1317 * Get the current course.
1319 * @return mixed stdClass|null The course
1321 public function get_course() {
1324 if ($this->course
) {
1325 return $this->course
;
1328 if (!$this->context
) {
1331 $params = array('id' => $this->get_course_context()->instanceid
);
1332 $this->course
= $DB->get_record('course', $params, '*', MUST_EXIST
);
1334 return $this->course
;
1338 * Count the number of intro attachments.
1342 protected function count_attachments() {
1344 $fs = get_file_storage();
1345 $files = $fs->get_area_files($this->get_context()->id
, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA
,
1348 return count($files);
1352 * Are there any intro attachments to display?
1356 protected function has_visible_attachments() {
1357 return ($this->count_attachments() > 0);
1361 * Return a grade in user-friendly form, whether it's a scale or not.
1363 * @param mixed $grade int|null
1364 * @param boolean $editing Are we allowing changes to this grade?
1365 * @param int $userid The user id the grade belongs to
1366 * @param int $modified Timestamp from when the grade was last modified
1367 * @return string User-friendly representation of grade
1369 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1372 static $scalegrades = array();
1374 $decimals = $this->get_grade_item()->get_decimals();
1377 if ($this->get_instance()->grade
>= 0) {
1379 if ($editing && $this->get_instance()->grade
> 0) {
1383 $displaygrade = format_float($grade, $decimals);
1385 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1386 get_string('usergrade', 'assign') .
1388 $o .= '<input type="text"
1389 id="quickgrade_' . $userid . '"
1390 name="quickgrade_' . $userid . '"
1391 value="' . $displaygrade . '"
1394 class="quickgrade"/>';
1395 $o .= ' / ' . format_float($this->get_instance()->grade
, $decimals);
1398 if ($grade == -1 ||
$grade === null) {
1401 $item = $this->get_grade_item();
1402 $o .= grade_format_gradevalue($grade, $item);
1403 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL
) {
1404 // If displaying the raw grade, also display the total value.
1405 $o .= ' / ' . format_float($this->get_instance()->grade
, $decimals);
1413 if (empty($this->cache
['scale'])) {
1414 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade
)))) {
1415 $this->cache
['scale'] = make_menu_from_list($scale->scale
);
1422 $o .= '<label class="accesshide"
1423 for="quickgrade_' . $userid . '">' .
1424 get_string('usergrade', 'assign') .
1426 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1427 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1428 foreach ($this->cache
['scale'] as $optionid => $option) {
1430 if ($grade == $optionid) {
1431 $selected = 'selected="selected"';
1433 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1438 $scaleid = (int)$grade;
1439 if (isset($this->cache
['scale'][$scaleid])) {
1440 $o .= $this->cache
['scale'][$scaleid];
1450 * Get the submission status/grading status for all submissions in this assignment for the
1451 * given paticipants.
1453 * These statuses match the available filters (requiregrading, submitted, notsubmitted).
1454 * If this is a group assignment, group info is also returned.
1456 * @param array $participants an associative array where the key is the participant id and
1457 * the value is the participant record.
1458 * @return array an associative array where the key is the participant id and the value is
1459 * the participant record.
1461 private function get_submission_info_for_participants($participants) {
1464 if (empty($participants)) {
1465 return $participants;
1468 list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED
);
1470 $assignid = $this->get_instance()->id
;
1471 $params['assignmentid1'] = $assignid;
1472 $params['assignmentid2'] = $assignid;
1474 $fields = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade';
1475 $from = ' FROM {user} u
1476 LEFT JOIN {assign_submission} s
1478 AND s.assignment = :assignmentid1
1480 LEFT JOIN {assign_grades} g
1482 AND g.assignment = :assignmentid2
1483 AND g.attemptnumber = s.attemptnumber
1485 $where = ' WHERE u.id ' . $insql;
1487 if (!empty($this->get_instance()->blindmarking
)) {
1488 $from .= 'LEFT JOIN {assign_user_mapping} um
1490 AND um.assignment = :assignmentid3 ';
1491 $params['assignmentid3'] = $assignid;
1492 $fields .= ', um.id as recordid ';
1495 $sql = "$fields $from $where";
1497 $records = $DB->get_records_sql($sql, $params);
1499 if ($this->get_instance()->teamsubmission
) {
1501 $allgroups = groups_get_all_groups($this->get_course()->id
,
1502 array_keys($participants),
1503 $this->get_instance()->teamsubmissiongroupingid
,
1504 'DISTINCT g.id, g.name');
1507 foreach ($participants as $userid => $participant) {
1508 $participants[$userid]->fullname
= $this->fullname($participant);
1509 $participants[$userid]->submitted
= false;
1510 $participants[$userid]->requiregrading
= false;
1513 foreach ($records as $userid => $submissioninfo) {
1514 // These filters are 100% the same as the ones in the grading table SQL.
1516 $requiregrading = false;
1518 if (!empty($submissioninfo->stime
) && $submissioninfo->status
== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
1522 if ($submitted && ($submissioninfo->stime
>= $submissioninfo->gtime ||
1523 empty($submissioninfo->gtime
) ||
1524 $submissioninfo->grade
=== null)) {
1525 $requiregrading = true;
1528 $participants[$userid]->submitted
= $submitted;
1529 $participants[$userid]->requiregrading
= $requiregrading;
1530 if ($this->get_instance()->teamsubmission
) {
1531 $group = $this->get_submission_group($userid);
1533 $participants[$userid]->groupid
= $group->id
;
1534 $participants[$userid]->groupname
= $group->name
;
1538 return $participants;
1542 * Get the submission status/grading status for all submissions in this assignment.
1543 * These statuses match the available filters (requiregrading, submitted, notsubmitted).
1544 * If this is a group assignment, group info is also returned.
1546 * @param int $currentgroup
1547 * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'groupid', 'groupname'
1549 public function list_participants_with_filter_status_and_group($currentgroup) {
1550 $participants = $this->list_participants($currentgroup, false);
1552 if (empty($participants)) {
1553 return $participants;
1555 return $this->get_submission_info_for_participants($participants);
1560 * Load a list of users enrolled in the current course with the specified permission and group.
1563 * @param int $currentgroup
1564 * @param bool $idsonly
1565 * @return array List of user records
1567 public function list_participants($currentgroup, $idsonly) {
1570 if (empty($currentgroup)) {
1574 $key = $this->context
->id
. '-' . $currentgroup . '-' . $this->show_only_active_users();
1575 if (!isset($this->participants
[$key])) {
1576 list($esql, $params) = get_enrolled_sql($this->context
, 'mod/assign:submit', $currentgroup,
1577 $this->show_only_active_users());
1580 $orderby = 'u.lastname, u.firstname, u.id';
1581 $additionaljoins = '';
1582 $instance = $this->get_instance();
1583 if (!empty($instance->blindmarking
)) {
1584 $additionaljoins .= " LEFT JOIN {assign_user_mapping} um
1586 AND um.assignment = :assignmentid1
1587 LEFT JOIN {assign_submission} s
1589 AND s.assignment = :assignmentid2
1592 $params['assignmentid1'] = (int) $instance->id
;
1593 $params['assignmentid2'] = (int) $instance->id
;
1594 $fields .= ', um.id as recordid ';
1596 // Sort by submission time first, then by um.id to sort reliably by the blind marking id.
1597 // Note, different DBs have different ordering of NULL values.
1598 // Therefore we coalesce the current time into the timecreated field, and the max possible integer into
1600 $orderby = "COALESCE(s.timecreated, " . time() . ") ASC, COALESCE(s.id, " . PHP_INT_MAX
. ") ASC, um.id ASC";
1603 $sql = "SELECT $fields
1605 JOIN ($esql) je ON je.id = u.id
1610 $users = $DB->get_records_sql($sql, $params);
1612 $cm = $this->get_course_module();
1613 $info = new \core_availability\
info_module($cm);
1614 $users = $info->filter_user_list($users);
1616 $this->participants
[$key] = $users;
1621 foreach ($this->participants
[$key] as $id => $user) {
1622 $idslist[$id] = new stdClass();
1623 $idslist[$id]->id
= $id;
1627 return $this->participants
[$key];
1631 * Load a user if they are enrolled in the current course. Populated with submission
1632 * status for this assignment.
1634 * @param int $userid
1635 * @return null|stdClass user record
1637 public function get_participant($userid) {
1640 $participant = $DB->get_record('user', array('id' => $userid));
1641 if (!$participant) {
1645 if (!is_enrolled($this->context
, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
1649 $result = $this->get_submission_info_for_participants(array($participant->id
=> $participant));
1650 return $result[$participant->id
];
1654 * Load a count of valid teams for this assignment.
1656 * @param int $activitygroup Activity active group
1657 * @return int number of valid teams
1659 public function count_teams($activitygroup = 0) {
1663 $participants = $this->list_participants($activitygroup, true);
1665 // If a team submission grouping id is provided all good as all returned groups
1666 // are the submission teams, but if no team submission grouping was specified
1667 // $groups will contain all participants groups.
1668 if ($this->get_instance()->teamsubmissiongroupingid
) {
1670 // We restrict the users to the selected group ones.
1671 $groups = groups_get_all_groups($this->get_course()->id
,
1672 array_keys($participants),
1673 $this->get_instance()->teamsubmissiongroupingid
,
1674 'DISTINCT g.id, g.name');
1676 $count = count($groups);
1678 // When a specific group is selected we don't count the default group users.
1679 if ($activitygroup == 0) {
1680 if (empty($this->get_instance()->preventsubmissionnotingroup
)) {
1681 // See if there are any users in the default group.
1682 $defaultusers = $this->get_submission_group_members(0, true);
1683 if (count($defaultusers) > 0) {
1689 // It is faster to loop around participants if no grouping was specified.
1691 foreach ($participants as $participant) {
1692 if ($group = $this->get_submission_group($participant->id
)) {
1693 $groups[$group->id
] = true;
1694 } else if (empty($this->get_instance()->preventsubmissionnotingroup
)) {
1699 $count = count($groups);
1706 * Load a count of active users enrolled in the current course with the specified permission and group.
1709 * @param int $currentgroup
1710 * @return int number of matching users
1712 public function count_participants($currentgroup) {
1713 return count($this->list_participants($currentgroup, true));
1717 * Load a count of active users submissions in the current module that require grading
1718 * This means the submission modification time is more recent than the
1719 * grading modification time and the status is SUBMITTED.
1721 * @return int number of matching submissions
1723 public function count_submissions_need_grading() {
1726 if ($this->get_instance()->teamsubmission
) {
1727 // This does not make sense for group assignment because the submission is shared.
1731 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1732 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1734 $params['assignid'] = $this->get_instance()->id
;
1735 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
1737 $sql = 'SELECT COUNT(s.userid)
1738 FROM {assign_submission} s
1739 LEFT JOIN {assign_grades} g ON
1740 s.assignment = g.assignment AND
1741 s.userid = g.userid AND
1742 g.attemptnumber = s.attemptnumber
1743 JOIN(' . $esql . ') e ON e.id = s.userid
1746 s.assignment = :assignid AND
1747 s.timemodified IS NOT NULL AND
1748 s.status = :submitted AND
1749 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL)';
1751 return $DB->count_records_sql($sql, $params);
1755 * Load a count of grades.
1757 * @return int number of grades
1759 public function count_grades() {
1762 if (!$this->has_instance()) {
1766 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1767 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1769 $params['assignid'] = $this->get_instance()->id
;
1771 $sql = 'SELECT COUNT(g.userid)
1772 FROM {assign_grades} g
1773 JOIN(' . $esql . ') e ON e.id = g.userid
1774 WHERE g.assignment = :assignid';
1776 return $DB->count_records_sql($sql, $params);
1780 * Load a count of submissions.
1782 * @param bool $includenew When true, also counts the submissions with status 'new'.
1783 * @return int number of submissions
1785 public function count_submissions($includenew = false) {
1788 if (!$this->has_instance()) {
1796 $sqlnew = ' AND s.status <> :status ';
1797 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW
;
1800 if ($this->get_instance()->teamsubmission
) {
1801 // We cannot join on the enrolment tables for group submissions (no userid).
1802 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1803 FROM {assign_submission} s
1805 s.assignment = :assignid AND
1806 s.timemodified IS NOT NULL AND
1807 s.userid = :groupuserid' .
1810 $params['assignid'] = $this->get_instance()->id
;
1811 $params['groupuserid'] = 0;
1813 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1814 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1816 $params = array_merge($params, $enrolparams);
1817 $params['assignid'] = $this->get_instance()->id
;
1819 $sql = 'SELECT COUNT(DISTINCT s.userid)
1820 FROM {assign_submission} s
1821 JOIN(' . $esql . ') e ON e.id = s.userid
1823 s.assignment = :assignid AND
1824 s.timemodified IS NOT NULL ' .
1829 return $DB->count_records_sql($sql, $params);
1833 * Load a count of submissions with a specified status.
1835 * @param string $status The submission status - should match one of the constants
1836 * @return int number of matching submissions
1838 public function count_submissions_with_status($status) {
1841 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1842 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1844 $params['assignid'] = $this->get_instance()->id
;
1845 $params['assignid2'] = $this->get_instance()->id
;
1846 $params['submissionstatus'] = $status;
1848 if ($this->get_instance()->teamsubmission
) {
1851 if ($currentgroup != 0) {
1852 // If there is an active group we should only display the current group users groups.
1853 $participants = $this->list_participants($currentgroup, true);
1854 $groups = groups_get_all_groups($this->get_course()->id
,
1855 array_keys($participants),
1856 $this->get_instance()->teamsubmissiongroupingid
,
1857 'DISTINCT g.id, g.name');
1858 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED
);
1859 $groupsstr = 's.groupid ' . $groupssql . ' AND';
1860 $params = $params +
$groupsparams;
1862 $sql = 'SELECT COUNT(s.groupid)
1863 FROM {assign_submission} s
1866 s.assignment = :assignid AND
1867 s.timemodified IS NOT NULL AND
1868 s.userid = :groupuserid AND '
1870 s.status = :submissionstatus';
1871 $params['groupuserid'] = 0;
1873 $sql = 'SELECT COUNT(s.userid)
1874 FROM {assign_submission} s
1875 JOIN(' . $esql . ') e ON e.id = s.userid
1878 s.assignment = :assignid AND
1879 s.timemodified IS NOT NULL AND
1880 s.status = :submissionstatus';
1884 return $DB->count_records_sql($sql, $params);
1888 * Utility function to get the userid for every row in the grading table
1889 * so the order can be frozen while we iterate it.
1891 * @return array An array of userids
1893 protected function get_grading_userid_list() {
1894 $filter = get_user_preferences('assign_filter', '');
1895 $table = new assign_grading_table($this, 0, $filter, 0, false);
1897 $useridlist = $table->get_column_data('userid');
1903 * Generate zip file from array of given files.
1905 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1906 * This array is indexed by the final file name and each
1907 * element in the array is an instance of a stored_file object.
1908 * @return path of temp file - note this returned file does
1909 * not have a .zip extension - it is a temp file.
1911 protected function pack_files($filesforzipping) {
1913 // Create path for new zip file.
1914 $tempzip = tempnam($CFG->tempdir
. '/', 'assignment_');
1916 $zipper = new zip_packer();
1917 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1924 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1926 * Cron function to be run periodically according to the moodle cron.
1930 public static function cron() {
1933 // Only ever send a max of one days worth of updates.
1934 $yesterday = time() - (24 * 3600);
1936 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
1938 // Collect all submissions that require mailing.
1939 // Submissions are included if all are true:
1940 // - The assignment is visible in the gradebook.
1941 // - No previous notification has been sent.
1942 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
1943 // if marking workflow is enabled, the workflow state is at 'released'.
1944 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1945 g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
1947 JOIN {assign_grades} g ON g.assignment = a.id
1948 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1949 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
1950 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
1951 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
1952 LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
1953 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
1954 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
1955 uf.mailed = 0 AND gri.hidden = 0
1956 ORDER BY a.course, cm.id";
1959 'yesterday' => $yesterday,
1960 'today' => $timenow,
1961 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
,
1963 $submissions = $DB->get_records_sql($sql, $params);
1965 if (!empty($submissions)) {
1967 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1969 // Preload courses we are going to need those.
1970 $courseids = array();
1971 foreach ($submissions as $submission) {
1972 $courseids[] = $submission->course
;
1975 // Filter out duplicates.
1976 $courseids = array_unique($courseids);
1977 $ctxselect = context_helper
::get_preload_record_columns_sql('ctx');
1978 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
1979 $sql = 'SELECT c.*, ' . $ctxselect .
1981 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1982 WHERE c.id ' . $courseidsql;
1984 $params['contextlevel'] = CONTEXT_COURSE
;
1985 $courses = $DB->get_records_sql($sql, $params);
1987 // Clean up... this could go on for a while.
1990 unset($courseidsql);
1993 // Message students about new feedback.
1994 foreach ($submissions as $submission) {
1996 mtrace("Processing assignment submission $submission->id ...");
1998 // Do not cache user lookups - could be too many.
1999 if (!$user = $DB->get_record('user', array('id'=>$submission->userid
))) {
2000 mtrace('Could not find user ' . $submission->userid
);
2004 // Use a cache to prevent the same DB queries happening over and over.
2005 if (!array_key_exists($submission->course
, $courses)) {
2006 mtrace('Could not find course ' . $submission->course
);
2009 $course = $courses[$submission->course
];
2010 if (isset($course->ctxid
)) {
2011 // Context has not yet been preloaded. Do so now.
2012 context_helper
::preload_from_record($course);
2015 // Override the language and timezone of the "current" user, so that
2016 // mail is customised for the receiver.
2017 cron_setup_user($user, $course);
2019 // Context lookups are already cached.
2020 $coursecontext = context_course
::instance($course->id
);
2021 if (!is_enrolled($coursecontext, $user->id
)) {
2022 $courseshortname = format_string($course->shortname
,
2024 array('context' => $coursecontext));
2025 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
2029 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader
))) {
2030 mtrace('Could not find grader ' . $submission->grader
);
2034 $modinfo = get_fast_modinfo($course, $user->id
);
2035 $cm = $modinfo->get_cm($submission->cmid
);
2036 // Context lookups are already cached.
2037 $contextmodule = context_module
::instance($cm->id
);
2039 if (!$cm->uservisible
) {
2040 // Hold mail notification for assignments the user cannot access until later.
2044 // Need to send this to the student.
2045 $messagetype = 'feedbackavailable';
2046 $eventtype = 'assign_notification';
2047 $updatetime = $submission->lastmodified
;
2048 $modulename = get_string('modulename', 'assign');
2051 if ($submission->blindmarking
&& !$submission->revealidentities
) {
2052 if (empty($submission->recordid
)) {
2053 $uniqueid = self
::get_uniqueid_for_user_static($submission->assignment
, $user->id
);
2055 $uniqueid = $submission->recordid
;
2058 $showusers = $submission->blindmarking
&& !$submission->revealidentities
;
2059 self
::send_assignment_notification($grader,
2072 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id
, 'assignment'=>$submission->assignment
));
2075 $DB->update_record('assign_user_flags', $flags);
2077 $flags = new stdClass();
2078 $flags->userid
= $user->id
;
2079 $flags->assignment
= $submission->assignment
;
2081 $DB->insert_record('assign_user_flags', $flags);
2086 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
2090 // Free up memory just to be sure.
2094 // Update calendar events to provide a description.
2098 allowsubmissionsfromdate >= :lastcron AND
2099 allowsubmissionsfromdate <= :timenow AND
2100 alwaysshowdescription = 0';
2101 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2102 $newlyavailable = $DB->get_records_sql($sql, $params);
2103 foreach ($newlyavailable as $record) {
2104 $cm = get_coursemodule_from_instance('assign', $record->id
, 0, false, MUST_EXIST
);
2105 $context = context_module
::instance($cm->id
);
2107 $assignment = new assign($context, null, null);
2108 $assignment->update_calendar($cm->id
);
2115 * Mark in the database that this grade record should have an update notification sent by cron.
2117 * @param stdClass $grade a grade record keyed on id
2118 * @param bool $mailedoverride when true, flag notification to be sent again.
2119 * @return bool true for success
2121 public function notify_grade_modified($grade, $mailedoverride = false) {
2124 $flags = $this->get_user_flags($grade->userid
, true);
2125 if ($flags->mailed
!= 1 ||
$mailedoverride) {
2129 return $this->update_user_flags($flags);
2133 * Update user flags for this user in this assignment.
2135 * @param stdClass $flags a flags record keyed on id
2136 * @return bool true for success
2138 public function update_user_flags($flags) {
2140 if ($flags->userid
<= 0 ||
$flags->assignment
<= 0 ||
$flags->id
<= 0) {
2144 $result = $DB->update_record('assign_user_flags', $flags);
2149 * Update a grade in the grade table for the assignment and in the gradebook.
2151 * @param stdClass $grade a grade record keyed on id
2152 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
2153 * @return bool true for success
2155 public function update_grade($grade, $reopenattempt = false) {
2158 $grade->timemodified
= time();
2160 if (!empty($grade->workflowstate
)) {
2161 $validstates = $this->get_marking_workflow_states_for_current_user();
2162 if (!array_key_exists($grade->workflowstate
, $validstates)) {
2167 if ($grade->grade
&& $grade->grade
!= -1) {
2168 if ($this->get_instance()->grade
> 0) {
2169 if (!is_numeric($grade->grade
)) {
2171 } else if ($grade->grade
> $this->get_instance()->grade
) {
2173 } else if ($grade->grade
< 0) {
2178 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade
)))) {
2179 $scaleoptions = make_menu_from_list($scale->scale
);
2180 if (!array_key_exists((int) $grade->grade
, $scaleoptions)) {
2187 if (empty($grade->attemptnumber
)) {
2188 // Set it to the default.
2189 $grade->attemptnumber
= 0;
2191 $DB->update_record('assign_grades', $grade);
2194 if ($this->get_instance()->teamsubmission
) {
2195 $submission = $this->get_group_submission($grade->userid
, 0, false);
2197 $submission = $this->get_user_submission($grade->userid
, false);
2200 // Only push to gradebook if the update is for the latest attempt.
2201 // Not the latest attempt.
2202 if ($submission && $submission->attemptnumber
!= $grade->attemptnumber
) {
2206 if ($this->gradebook_item_update(null, $grade)) {
2207 \mod_assign\event\submission_graded
::create_from_grade($this, $grade)->trigger();
2210 // If the conditions are met, allow another attempt.
2212 $this->reopen_submission_if_required($grade->userid
,
2221 * View the grant extension date page.
2223 * Uses url parameters 'userid'
2224 * or from parameter 'selectedusers'
2226 * @param moodleform $mform - Used for validation of the submitted data
2229 protected function view_grant_extension($mform) {
2231 require_once($CFG->dirroot
. '/mod/assign/extensionform.php');
2235 $data = new stdClass();
2236 $data->id
= $this->get_course_module()->id
;
2238 $formparams = array(
2239 'instance' => $this->get_instance(),
2243 $users = optional_param('userid', 0, PARAM_INT
);
2245 $users = required_param('selectedusers', PARAM_SEQUENCE
);
2247 $userlist = explode(',', $users);
2249 $formparams['userlist'] = $userlist;
2251 $data->selectedusers
= $users;
2254 if (empty($mform)) {
2255 $mform = new mod_assign_extension_form(null, $formparams);
2257 $mform->set_data($data);
2258 $header = new assign_header($this->get_instance(),
2259 $this->get_context(),
2260 $this->show_intro(),
2261 $this->get_course_module()->id
,
2262 get_string('grantextension', 'assign'));
2263 $o .= $this->get_renderer()->render($header);
2264 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
2265 $o .= $this->view_footer();
2270 * Get a list of the users in the same group as this user.
2272 * @param int $groupid The id of the group whose members we want or 0 for the default group
2273 * @param bool $onlyids Whether to retrieve only the user id's
2274 * @param bool $excludesuspended Whether to exclude suspended users
2275 * @return array The users (possibly id's only)
2277 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
2279 if ($groupid != 0) {
2280 $allusers = $this->list_participants($groupid, $onlyids);
2281 foreach ($allusers as $user) {
2282 if ($this->get_submission_group($user->id
)) {
2287 $allusers = $this->list_participants(null, $onlyids);
2288 foreach ($allusers as $user) {
2289 if ($this->get_submission_group($user->id
) == null) {
2294 // Exclude suspended users, if user can't see them.
2295 if ($excludesuspended ||
!has_capability('moodle/course:viewsuspendedusers', $this->context
)) {
2296 foreach ($members as $key => $member) {
2297 if (!$this->is_active_user($member->id
)) {
2298 unset($members[$key]);
2307 * Get a list of the users in the same group as this user that have not submitted the assignment.
2309 * @param int $groupid The id of the group whose members we want or 0 for the default group
2310 * @param bool $onlyids Whether to retrieve only the user id's
2311 * @return array The users (possibly id's only)
2313 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2314 $instance = $this->get_instance();
2315 if (!$instance->teamsubmission ||
!$instance->requireallteammemberssubmit
) {
2318 $members = $this->get_submission_group_members($groupid, $onlyids);
2320 foreach ($members as $id => $member) {
2321 $submission = $this->get_user_submission($member->id
, false);
2322 if ($submission && $submission->status
== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
2323 unset($members[$id]);
2325 if ($this->is_blind_marking()) {
2326 $members[$id]->alias
= get_string('hiddenuser', 'assign') .
2327 $this->get_uniqueid_for_user($id);
2335 * Load the group submission object for a particular user, optionally creating it if required.
2337 * @param int $userid The id of the user whose submission we want
2338 * @param int $groupid The id of the group for this user - may be 0 in which
2339 * case it is determined from the userid.
2340 * @param bool $create If set to true a new submission object will be created in the database
2341 * with the status set to "new".
2342 * @param int $attemptnumber - -1 means the latest attempt
2343 * @return stdClass The submission
2345 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2348 if ($groupid == 0) {
2349 $group = $this->get_submission_group($userid);
2351 $groupid = $group->id
;
2355 // Now get the group submission.
2356 $params = array('assignment'=>$this->get_instance()->id
, 'groupid'=>$groupid, 'userid'=>0);
2357 if ($attemptnumber >= 0) {
2358 $params['attemptnumber'] = $attemptnumber;
2361 // Only return the row with the highest attemptnumber.
2363 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2365 $submission = reset($submissions);
2372 $submission = new stdClass();
2373 $submission->assignment
= $this->get_instance()->id
;
2374 $submission->userid
= 0;
2375 $submission->groupid
= $groupid;
2376 $submission->timecreated
= time();
2377 $submission->timemodified
= $submission->timecreated
;
2378 if ($attemptnumber >= 0) {
2379 $submission->attemptnumber
= $attemptnumber;
2381 $submission->attemptnumber
= 0;
2383 // Work out if this is the latest submission.
2384 $submission->latest
= 0;
2385 $params = array('assignment'=>$this->get_instance()->id
, 'groupid'=>$groupid, 'userid'=>0);
2386 if ($attemptnumber == -1) {
2387 // This is a new submission so it must be the latest.
2388 $submission->latest
= 1;
2390 // We need to work this out.
2391 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2393 $latestsubmission = reset($result);
2395 if (!$latestsubmission ||
($attemptnumber == $latestsubmission->attemptnumber
)) {
2396 $submission->latest
= 1;
2399 if ($submission->latest
) {
2400 // This is the case when we need to set latest to 0 for all the other attempts.
2401 $DB->set_field('assign_submission', 'latest', 0, $params);
2403 $submission->status
= ASSIGN_SUBMISSION_STATUS_NEW
;
2404 $sid = $DB->insert_record('assign_submission', $submission);
2405 return $DB->get_record('assign_submission', array('id' => $sid));
2411 * View a summary listing of all assignments in the current course.
2415 private function view_course_index() {
2420 $course = $this->get_course();
2421 $strplural = get_string('modulenameplural', 'assign');
2423 if (!$cms = get_coursemodules_in_course('assign', $course->id
, 'm.duedate')) {
2424 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2425 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id
)));
2429 $strsectionname = '';
2430 $usesections = course_format_uses_sections($course->format
);
2431 $modinfo = get_fast_modinfo($course);
2434 $strsectionname = get_string('sectionname', 'format_'.$course->format
);
2435 $sections = $modinfo->get_section_info_all();
2437 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2441 $currentsection = '';
2442 foreach ($modinfo->instances
['assign'] as $cm) {
2443 if (!$cm->uservisible
) {
2447 $timedue = $cms[$cm->id
]->duedate
;
2450 if ($usesections && $cm->sectionnum
) {
2451 $sectionname = get_section_name($course, $sections[$cm->sectionnum
]);
2455 $context = context_module
::instance($cm->id
);
2457 $assignment = new assign($context, $cm, $course);
2459 if (has_capability('mod/assign:grade', $context)) {
2460 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED
);
2462 } else if (has_capability('mod/assign:submit', $context)) {
2463 $usersubmission = $assignment->get_user_submission($USER->id
, false);
2465 if (!empty($usersubmission->status
)) {
2466 $submitted = get_string('submissionstatus_' . $usersubmission->status
, 'assign');
2468 $submitted = get_string('submissionstatus_', 'assign');
2471 $gradinginfo = grade_get_grades($course->id
, 'mod', 'assign', $cm->instance
, $USER->id
);
2472 if (isset($gradinginfo->items
[0]->grades
[$USER->id
]) &&
2473 !$gradinginfo->items
[0]->grades
[$USER->id
]->hidden
) {
2474 $grade = $gradinginfo->items
[0]->grades
[$USER->id
]->str_grade
;
2479 $courseindexsummary->add_assign_info($cm->id
, $cm->get_formatted_name(), $sectionname, $timedue, $submitted, $grade);
2483 $o .= $this->get_renderer()->render($courseindexsummary);
2484 $o .= $this->view_footer();
2490 * View a page rendered by a plugin.
2492 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2496 protected function view_plugin_page() {
2501 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA
);
2502 $plugintype = required_param('plugin', PARAM_TEXT
);
2503 $pluginaction = required_param('pluginaction', PARAM_ALPHA
);
2505 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2507 print_error('invalidformdata', '');
2511 $o .= $plugin->view_page($pluginaction);
2518 * This is used for team assignments to get the group for the specified user.
2519 * If the user is a member of multiple or no groups this will return false
2521 * @param int $userid The id of the user whose submission we want
2522 * @return mixed The group or false
2524 public function get_submission_group($userid) {
2526 if (isset($this->usersubmissiongroups
[$userid])) {
2527 return $this->usersubmissiongroups
[$userid];
2530 $groups = $this->get_all_groups($userid);
2531 if (count($groups) != 1) {
2534 $return = array_pop($groups);
2537 // Cache the user submission group.
2538 $this->usersubmissiongroups
[$userid] = $return;
2544 * Gets all groups the user is a member of.
2546 * @param int $userid Teh id of the user who's groups we are checking
2547 * @return array The group objects
2549 public function get_all_groups($userid) {
2550 if (isset($this->usergroups
[$userid])) {
2551 return $this->usergroups
[$userid];
2554 $grouping = $this->get_instance()->teamsubmissiongroupingid
;
2555 $return = groups_get_all_groups($this->get_course()->id
, $userid, $grouping);
2557 $this->usergroups
[$userid] = $return;
2564 * Display the submission that is used by a plugin.
2566 * Uses url parameters 'sid', 'gid' and 'plugin'.
2568 * @param string $pluginsubtype
2571 protected function view_plugin_content($pluginsubtype) {
2574 $submissionid = optional_param('sid', 0, PARAM_INT
);
2575 $gradeid = optional_param('gid', 0, PARAM_INT
);
2576 $plugintype = required_param('plugin', PARAM_TEXT
);
2578 if ($pluginsubtype == 'assignsubmission') {
2579 $plugin = $this->get_submission_plugin_by_type($plugintype);
2580 if ($submissionid <= 0) {
2581 throw new coding_exception('Submission id should not be 0');
2583 $item = $this->get_submission($submissionid);
2585 // Check permissions.
2586 $this->require_view_submission($item->userid
);
2587 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2588 $this->get_context(),
2589 $this->show_intro(),
2590 $this->get_course_module()->id
,
2591 $plugin->get_name()));
2592 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2594 assign_submission_plugin_submission
::FULL
,
2595 $this->get_course_module()->id
,
2596 $this->get_return_action(),
2597 $this->get_return_params()));
2599 // Trigger event for viewing a submission.
2600 \mod_assign\event\submission_viewed
::create_from_submission($this, $item)->trigger();
2603 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2604 if ($gradeid <= 0) {
2605 throw new coding_exception('Grade id should not be 0');
2607 $item = $this->get_grade($gradeid);
2608 // Check permissions.
2609 $this->require_view_submission($item->userid
);
2610 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2611 $this->get_context(),
2612 $this->show_intro(),
2613 $this->get_course_module()->id
,
2614 $plugin->get_name()));
2615 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2617 assign_feedback_plugin_feedback
::FULL
,
2618 $this->get_course_module()->id
,
2619 $this->get_return_action(),
2620 $this->get_return_params()));
2622 // Trigger event for viewing feedback.
2623 \mod_assign\event\feedback_viewed
::create_from_grade($this, $item)->trigger();
2626 $o .= $this->view_return_links();
2628 $o .= $this->view_footer();
2634 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2636 * @param string $text - The replacement text
2637 * @param stdClass $user - The user record
2638 * @param assign_plugin $plugin - The assignment plugin
2640 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2641 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2644 $groupid = groups_get_activity_group($this->get_course_module(), true);
2645 $groupname = groups_get_group_name($groupid).'-';
2648 if ($this->is_blind_marking()) {
2649 $prefix = $groupname . get_string('participant', 'assign');
2650 $prefix = str_replace('_', ' ', $prefix);
2651 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id
) . '_');
2653 $prefix = $groupname . fullname($user);
2654 $prefix = str_replace('_', ' ', $prefix);
2655 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id
) . '_');
2658 $subtype = $plugin->get_subtype();
2659 $type = $plugin->get_type();
2660 $prefix = $prefix . $subtype . '_' . $type . '_';
2662 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2668 * Render the content in editor that is often used by plugin.
2670 * @param string $filearea
2671 * @param int $submissionid
2672 * @param string $plugintype
2673 * @param string $editor
2674 * @param string $component
2677 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2682 $plugin = $this->get_submission_plugin_by_type($plugintype);
2684 $text = $plugin->get_editor_text($editor, $submissionid);
2685 $format = $plugin->get_editor_format($editor, $submissionid);
2687 $finaltext = file_rewrite_pluginfile_urls($text,
2689 $this->get_context()->id
,
2693 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2694 $result .= format_text($finaltext, $format, $params);
2696 if ($CFG->enableportfolios
&& has_capability('mod/assign:exportownsubmission', $this->context
)) {
2697 require_once($CFG->libdir
. '/portfoliolib.php');
2699 $button = new portfolio_add_button();
2700 $portfolioparams = array('cmid' => $this->get_course_module()->id
,
2701 'sid' => $submissionid,
2702 'plugin' => $plugintype,
2703 'editor' => $editor,
2705 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2706 $fs = get_file_storage();
2708 if ($files = $fs->get_area_files($this->context
->id
,
2714 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
2716 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
2718 $result .= $button->to_html();
2724 * Display a continue page after grading.
2726 * @param string $message - The message to display.
2729 protected function view_savegrading_result($message) {
2731 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2732 $this->get_context(),
2733 $this->show_intro(),
2734 $this->get_course_module()->id
,
2735 get_string('savegradingresult', 'assign')));
2736 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2738 $this->get_course_module()->id
);
2739 $o .= $this->get_renderer()->render($gradingresult);
2740 $o .= $this->view_footer();
2744 * Display a continue page after quickgrading.
2746 * @param string $message - The message to display.
2749 protected function view_quickgrading_result($message) {
2751 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2752 $this->get_context(),
2753 $this->show_intro(),
2754 $this->get_course_module()->id
,
2755 get_string('quickgradingresult', 'assign')));
2756 $lastpage = optional_param('lastpage', null, PARAM_INT
);
2757 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2759 $this->get_course_module()->id
,
2762 $o .= $this->get_renderer()->render($gradingresult);
2763 $o .= $this->view_footer();
2768 * Display the page footer.
2772 protected function view_footer() {
2773 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2774 if (!PHPUNIT_TEST
) {
2775 return $this->get_renderer()->render_footer();
2782 * Throw an error if the permissions to view this users submission are missing.
2784 * @throws required_capability_exception
2787 public function require_view_submission($userid) {
2788 if (!$this->can_view_submission($userid)) {
2789 throw new required_capability_exception($this->context
, 'mod/assign:viewgrades', 'nopermission', '');
2794 * Throw an error if the permissions to view grades in this assignment are missing.
2796 * @throws required_capability_exception
2799 public function require_view_grades() {
2800 if (!$this->can_view_grades()) {
2801 throw new required_capability_exception($this->context
, 'mod/assign:viewgrades', 'nopermission', '');
2806 * Does this user have view grade or grade permission for this assignment?
2810 public function can_view_grades() {
2811 // Permissions check.
2812 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context
)) {
2820 * Does this user have grade permission for this assignment?
2824 public function can_grade() {
2825 // Permissions check.
2826 if (!has_capability('mod/assign:grade', $this->context
)) {
2834 * Download a zip file of all assignment submissions.
2836 * @param array $userids Array of user ids to download assignment submissions in a zip file
2837 * @return string - If an error occurs, this will contain the error page.
2839 protected function download_submissions($userids = false) {
2842 // More efficient to load this here.
2843 require_once($CFG->libdir
.'/filelib.php');
2845 // Increase the server timeout to handle the creation and sending of large zip files.
2846 core_php_time_limit
::raise();
2848 $this->require_view_grades();
2850 // Load all users with submit.
2851 $students = get_enrolled_users($this->context
, "mod/assign:submit", null, 'u.*', null, null, null,
2852 $this->show_only_active_users());
2854 // Build a list of files to zip.
2855 $filesforzipping = array();
2856 $fs = get_file_storage();
2858 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2863 $groupid = groups_get_activity_group($this->get_course_module(), true);
2864 $groupname = groups_get_group_name($groupid).'-';
2867 // Construct the zip file name.
2868 $filename = clean_filename($this->get_course()->shortname
. '-' .
2869 $this->get_instance()->name
. '-' .
2870 $groupname.$this->get_course_module()->id
. '.zip');
2872 // Get all the files for each student.
2873 foreach ($students as $student) {
2874 $userid = $student->id
;
2875 // Download all assigments submission or only selected users.
2876 if ($userids and !in_array($userid, $userids)) {
2880 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2881 // Get the plugins to add their own files to the zip.
2883 $submissiongroup = false;
2885 if ($this->get_instance()->teamsubmission
) {
2886 $submission = $this->get_group_submission($userid, 0, false);
2887 $submissiongroup = $this->get_submission_group($userid);
2888 if ($submissiongroup) {
2889 $groupname = $submissiongroup->name
. '-';
2891 $groupname = get_string('defaultteam', 'assign') . '-';
2894 $submission = $this->get_user_submission($userid, false);
2897 if ($this->is_blind_marking()) {
2898 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2899 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
2901 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2902 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
2906 $downloadasfolders = get_user_preferences('assign_downloadasfolders', 1);
2907 foreach ($this->submissionplugins
as $plugin) {
2908 if ($plugin->is_enabled() && $plugin->is_visible()) {
2909 if ($downloadasfolders) {
2910 // Create a folder for each user for each assignment plugin.
2911 // This is the default behavior for version of Moodle >= 3.1.
2912 $submission->exportfullpath
= true;
2913 $pluginfiles = $plugin->get_files($submission, $student);
2914 foreach ($pluginfiles as $zipfilepath => $file) {
2915 $subtype = $plugin->get_subtype();
2916 $type = $plugin->get_type();
2917 $zipfilename = basename($zipfilepath);
2918 $prefixedfilename = clean_filename($prefix .
2924 if ($type == 'file') {
2925 $pathfilename = $prefixedfilename . $file->get_filepath() . $zipfilename;
2926 } else if ($type == 'onlinetext') {
2927 $pathfilename = $prefixedfilename . '/' . $zipfilename;
2929 $pathfilename = $prefixedfilename . '/' . $zipfilename;
2931 $pathfilename = clean_param($pathfilename, PARAM_PATH
);
2932 $filesforzipping[$pathfilename] = $file;
2935 // Create a single folder for all users of all assignment plugins.
2936 // This was the default behavior for version of Moodle < 3.1.
2937 $submission->exportfullpath
= false;
2938 $pluginfiles = $plugin->get_files($submission, $student);
2939 foreach ($pluginfiles as $zipfilename => $file) {
2940 $subtype = $plugin->get_subtype();
2941 $type = $plugin->get_type();
2942 $prefixedfilename = clean_filename($prefix .
2949 $filesforzipping[$prefixedfilename] = $file;
2958 if (count($filesforzipping) == 0) {
2959 $header = new assign_header($this->get_instance(),
2960 $this->get_context(),
2962 $this->get_course_module()->id
,
2963 get_string('downloadall', 'assign'));
2964 $result .= $this->get_renderer()->render($header);
2965 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2966 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id
,
2967 'action'=>'grading'));
2968 $result .= $this->get_renderer()->continue_button($url);
2969 $result .= $this->view_footer();
2970 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2971 \mod_assign\event\all_submissions_downloaded
::create_from_assign($this)->trigger();
2972 // Send file and delete after sending.
2973 send_temp_file($zipfile, $filename);
2974 // We will not get here - send_temp_file calls exit.
2980 * Util function to add a message to the log.
2982 * @deprecated since 2.7 - Use new events system instead.
2983 * (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2985 * @param string $action The current action
2986 * @param string $info A detailed description of the change. But no more than 255 characters.
2987 * @param string $url The url to the assign module instance.
2988 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2989 * retrieve the arguments to use them with the new event system (Event 2).
2990 * @return void|array
2992 public function add_to_log($action = '', $info = '', $url='', $return = false) {
2995 $fullurl = 'view.php?id=' . $this->get_course_module()->id
;
2997 $fullurl .= '&' . $url;
3001 $this->get_course()->id
,
3006 $this->get_course_module()->id
3010 // We only need to call debugging when returning a value. This is because the call to
3011 // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
3012 debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER
);
3015 call_user_func_array('add_to_log', $args);
3019 * Lazy load the page renderer and expose the renderer to plugins.
3021 * @return assign_renderer
3023 public function get_renderer() {
3025 if ($this->output
) {
3026 return $this->output
;
3028 $this->output
= $PAGE->get_renderer('mod_assign', null, RENDERER_TARGET_GENERAL
);
3029 return $this->output
;
3033 * Load the submission object for a particular user, optionally creating it if required.
3035 * For team assignments there are 2 submissions - the student submission and the team submission
3036 * All files are associated with the team submission but the status of the students contribution is
3037 * recorded separately.
3039 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
3040 * @param bool $create If set to true a new submission object will be created in the database with the status set to "new".
3041 * @param int $attemptnumber - -1 means the latest attempt
3042 * @return stdClass The submission
3044 public function get_user_submission($userid, $create, $attemptnumber=-1) {
3048 $userid = $USER->id
;
3050 // If the userid is not null then use userid.
3051 $params = array('assignment'=>$this->get_instance()->id
, 'userid'=>$userid, 'groupid'=>0);
3052 if ($attemptnumber >= 0) {
3053 $params['attemptnumber'] = $attemptnumber;
3056 // Only return the row with the highest attemptnumber.
3058 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
3060 $submission = reset($submissions);
3067 $submission = new stdClass();
3068 $submission->assignment
= $this->get_instance()->id
;
3069 $submission->userid
= $userid;
3070 $submission->timecreated
= time();
3071 $submission->timemodified
= $submission->timecreated
;
3072 $submission->status
= ASSIGN_SUBMISSION_STATUS_NEW
;
3073 if ($attemptnumber >= 0) {
3074 $submission->attemptnumber
= $attemptnumber;
3076 $submission->attemptnumber
= 0;
3078 // Work out if this is the latest submission.
3079 $submission->latest
= 0;
3080 $params = array('assignment'=>$this->get_instance()->id
, 'userid'=>$userid, 'groupid'=>0);
3081 if ($attemptnumber == -1) {
3082 // This is a new submission so it must be the latest.
3083 $submission->latest
= 1;
3085 // We need to work this out.
3086 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
3087 $latestsubmission = null;
3089 $latestsubmission = reset($result);
3091 if (empty($latestsubmission) ||
($attemptnumber > $latestsubmission->attemptnumber
)) {
3092 $submission->latest
= 1;
3095 if ($submission->latest
) {
3096 // This is the case when we need to set latest to 0 for all the other attempts.
3097 $DB->set_field('assign_submission', 'latest', 0, $params);
3099 $sid = $DB->insert_record('assign_submission', $submission);
3100 return $DB->get_record('assign_submission', array('id' => $sid));
3106 * Load the submission object from it's id.
3108 * @param int $submissionid The id of the submission we want
3109 * @return stdClass The submission
3111 protected function get_submission($submissionid) {
3114 $params = array('assignment'=>$this->get_instance()->id
, 'id'=>$submissionid);
3115 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST
);
3119 * This will retrieve a user flags object from the db optionally creating it if required.
3120 * The user flags was split from the user_grades table in 2.5.
3122 * @param int $userid The user we are getting the flags for.
3123 * @param bool $create If true the flags record will be created if it does not exist
3124 * @return stdClass The flags record
3126 public function get_user_flags($userid, $create) {
3129 // If the userid is not null then use userid.
3131 $userid = $USER->id
;
3134 $params = array('assignment'=>$this->get_instance()->id
, 'userid'=>$userid);
3136 $flags = $DB->get_record('assign_user_flags', $params);
3142 $flags = new stdClass();
3143 $flags->assignment
= $this->get_instance()->id
;
3144 $flags->userid
= $userid;
3146 $flags->extensionduedate
= 0;
3147 $flags->workflowstate
= '';
3148 $flags->allocatedmarker
= 0;
3150 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
3151 // This is because students only want to be notified about certain types of update (grades and feedback).
3154 $fid = $DB->insert_record('assign_user_flags', $flags);
3162 * This will retrieve a grade object from the db, optionally creating it if required.
3164 * @param int $userid The user we are grading
3165 * @param bool $create If true the grade will be created if it does not exist
3166 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
3167 * @return stdClass The grade record
3169 public function get_user_grade($userid, $create, $attemptnumber=-1) {
3172 // If the userid is not null then use userid.
3174 $userid = $USER->id
;
3178 $params = array('assignment'=>$this->get_instance()->id
, 'userid'=>$userid);
3179 if ($attemptnumber < 0 ||
$create) {
3180 // Make sure this grade matches the latest submission attempt.
3181 if ($this->get_instance()->teamsubmission
) {
3182 $submission = $this->get_group_submission($userid, 0, true, $attemptnumber);
3184 $submission = $this->get_user_submission($userid, true, $attemptnumber);
3187 $attemptnumber = $submission->attemptnumber
;
3191 if ($attemptnumber >= 0) {
3192 $params['attemptnumber'] = $attemptnumber;
3195 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
3198 return reset($grades);
3201 $grade = new stdClass();
3202 $grade->assignment
= $this->get_instance()->id
;
3203 $grade->userid
= $userid;
3204 $grade->timecreated
= time();
3205 // If we are "auto-creating" a grade - and there is a submission
3206 // the new grade should not have a more recent timemodified value
3207 // than the submission.
3209 $grade->timemodified
= $submission->timemodified
;
3211 $grade->timemodified
= $grade->timecreated
;
3214 $grade->grader
= $USER->id
;
3215 if ($attemptnumber >= 0) {
3216 $grade->attemptnumber
= $attemptnumber;
3219 $gid = $DB->insert_record('assign_grades', $grade);
3227 * This will retrieve a grade object from the db.
3229 * @param int $gradeid The id of the grade
3230 * @return stdClass The grade record
3232 protected function get_grade($gradeid) {
3235 $params = array('assignment'=>$this->get_instance()->id
, 'id'=>$gradeid);
3236 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST
);
3240 * Print the grading page for a single user submission.
3242 * @param array $args Optional args array (better than pulling args from _GET and _POST)
3245 protected function view_single_grading_panel($args) {
3246 global $DB, $CFG, $SESSION, $PAGE;
3249 $instance = $this->get_instance();
3251 require_once($CFG->dirroot
. '/mod/assign/gradeform.php');
3253 // Need submit permission to submit an assignment.
3254 require_capability('mod/assign:grade', $this->context
);
3256 // If userid is passed - we are only grading a single student.
3257 $userid = $args['userid'];
3258 $attemptnumber = $args['attemptnumber'];
3261 $useridlist = array($userid);
3264 // This variation on the url will link direct to this student, with no next/previous links.
3265 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3266 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3267 $this->register_return_link('grade', $returnparams);
3269 $user = $DB->get_record('user', array('id' => $userid));
3270 $submission = $this->get_user_submission($userid, false, $attemptnumber);
3271 $submissiongroup = null;
3272 $teamsubmission = null;
3273 $notsubmitted = array();
3274 if ($instance->teamsubmission
) {
3275 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
3276 $submissiongroup = $this->get_submission_group($userid);
3278 if ($submissiongroup) {
3279 $groupid = $submissiongroup->id
;
3281 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3285 // Get the requested grade.
3286 $grade = $this->get_user_grade($userid, false, $attemptnumber);
3287 $flags = $this->get_user_flags($userid, false);
3288 if ($this->can_view_submission($userid)) {
3289 $gradelocked = ($flags && $flags->locked
) ||
$this->grading_disabled($userid);
3290 $extensionduedate = null;
3292 $extensionduedate = $flags->extensionduedate
;
3294 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
3295 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3296 $usergroups = $this->get_all_groups($user->id
);
3298 $submissionstatus = new assign_submission_status_compact($instance->allowsubmissionsfromdate
,
3299 $instance->alwaysshowdescription
,
3301 $instance->teamsubmission
,
3305 $this->is_any_submission_plugin_enabled(),
3307 $this->is_graded($userid),
3309 $instance->cutoffdate
,
3310 $this->get_submission_plugins(),
3311 $this->get_return_action(),
3312 $this->get_return_params(),
3313 $this->get_course_module()->id
,
3314 $this->get_course()->id
,
3315 assign_submission_status
::GRADER_VIEW
,
3320 $this->get_context(),
3321 $this->is_blind_marking(),
3323 $instance->attemptreopenmethod
,
3324 $instance->maxattempts
,
3325 $this->get_grading_status($userid),
3326 $instance->preventsubmissionnotingroup
,
3328 $o .= $this->get_renderer()->render($submissionstatus);
3332 $data = new stdClass();
3333 if ($grade->grade
!== null && $grade->grade
>= 0) {
3334 $data->grade
= format_float($grade->grade
, $this->get_grade_item()->get_decimals());
3337 $data = new stdClass();
3341 if (!empty($flags->workflowstate
)) {
3342 $data->workflowstate
= $flags->workflowstate
;
3344 if (!empty($flags->allocatedmarker
)) {
3345 $data->allocatedmarker
= $flags->allocatedmarker
;
3348 // Warning if required.
3349 $allsubmissions = $this->get_all_submissions($userid);
3351 if ($attemptnumber != -1 && ($attemptnumber +
1) != count($allsubmissions)) {
3352 $params = array('attemptnumber' => $attemptnumber +
1,
3353 'totalattempts' => count($allsubmissions));
3354 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
3355 $o .= $this->get_renderer()->notification($message);
3358 $pagination = array('rownum' => $rownum,
3359 'useridlistid' => 0,
3361 'userid' => $userid,
3362 'attemptnumber' => $attemptnumber,
3363 'gradingpanel' => true);
3365 if (!empty($args['formdata'])) {
3366 $data = (array) $data;
3367 $data = (object) array_merge($data, $args['formdata']);
3369 $formparams = array($this, $data, $pagination);
3370 $mform = new mod_assign_grade_form(null,
3374 array('class' => 'gradeform'));
3376 if (!empty($args['formdata'])) {
3377 // If we were passed form data - we want the form to check the data
3379 $mform->is_validated();
3381 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
3382 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
3384 if (count($allsubmissions) > 1) {
3385 $allgrades = $this->get_all_grades($userid);
3386 $history = new assign_attempt_history_chooser($allsubmissions,
3388 $this->get_course_module()->id
,
3391 $o .= $this->get_renderer()->render($history);
3394 \mod_assign\event\grading_form_viewed
::create_from_user($this, $user)->trigger();
3400 * Print the grading page for a single user submission.
3402 * @param moodleform $mform
3405 protected function view_single_grade_page($mform) {
3406 global $DB, $CFG, $SESSION;
3409 $instance = $this->get_instance();
3411 require_once($CFG->dirroot
. '/mod/assign/gradeform.php');
3413 // Need submit permission to submit an assignment.
3414 require_capability('mod/assign:grade', $this->context
);
3416 $header = new assign_header($instance,
3417 $this->get_context(),
3419 $this->get_course_module()->id
,
3420 get_string('grading', 'assign'));
3421 $o .= $this->get_renderer()->render($header);
3423 // If userid is passed - we are only grading a single student.
3424 $rownum = optional_param('rownum', 0, PARAM_INT
);
3425 $useridlistid = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM
);
3426 $userid = optional_param('userid', 0, PARAM_INT
);
3427 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT
);
3430 $useridlistkey = $this->get_useridlist_key($useridlistid);
3431 if (empty($SESSION->mod_assign_useridlist
[$useridlistkey])) {
3432 $SESSION->mod_assign_useridlist
[$useridlistkey] = $this->get_grading_userid_list();
3434 $useridlist = $SESSION->mod_assign_useridlist
[$useridlistkey];
3438 $useridlist = array($userid);
3441 if ($rownum < 0 ||
$rownum > count($useridlist)) {
3442 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
3446 $userid = $useridlist[$rownum];
3447 if ($rownum == count($useridlist) - 1) {
3450 // This variation on the url will link direct to this student, with no next/previous links.
3451 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3452 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3453 $this->register_return_link('grade', $returnparams);
3455 $user = $DB->get_record('user', array('id' => $userid));
3457 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3458 $usersummary = new assign_user_summary($user,
3459 $this->get_course()->id
,
3461 $this->is_blind_marking(),
3462 $this->get_uniqueid_for_user($user->id
),
3463 get_extra_user_fields($this->get_context()),
3464 !$this->is_active_user($userid));
3465 $o .= $this->get_renderer()->render($usersummary);
3467 $submission = $this->get_user_submission($userid, false, $attemptnumber);
3468 $submissiongroup = null;
3469 $teamsubmission = null;
3470 $notsubmitted = array();
3471 if ($instance->teamsubmission
) {
3472 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
3473 $submissiongroup = $this->get_submission_group($userid);
3475 if ($submissiongroup) {
3476 $groupid = $submissiongroup->id
;
3478 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3482 // Get the requested grade.
3483 $grade = $this->get_user_grade($userid, false, $attemptnumber);
3484 $flags = $this->get_user_flags($userid, false);
3485 if ($this->can_view_submission($userid)) {
3486 $gradelocked = ($flags && $flags->locked
) ||
$this->grading_disabled($userid);
3487 $extensionduedate = null;
3489 $extensionduedate = $flags->extensionduedate
;
3491 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
3492 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3493 $usergroups = $this->get_all_groups($user->id
);
3495 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate
,
3496 $instance->alwaysshowdescription
,
3498 $instance->teamsubmission
,
3502 $this->is_any_submission_plugin_enabled(),
3504 $this->is_graded($userid),
3506 $instance->cutoffdate
,
3507 $this->get_submission_plugins(),
3508 $this->get_return_action(),
3509 $this->get_return_params(),
3510 $this->get_course_module()->id
,
3511 $this->get_course()->id
,
3512 assign_submission_status
::GRADER_VIEW
,
3517 $this->get_context(),
3518 $this->is_blind_marking(),
3520 $instance->attemptreopenmethod
,
3521 $instance->maxattempts
,
3522 $this->get_grading_status($userid),
3523 $instance->preventsubmissionnotingroup
,
3525 $o .= $this->get_renderer()->render($submissionstatus);
3529 $data = new stdClass();
3530 if ($grade->grade
!== null && $grade->grade
>= 0) {
3531 $data->grade
= format_float($grade->grade
, $this->get_grade_item()->get_decimals());
3534 $data = new stdClass();
3538 if (!empty($flags->workflowstate
)) {
3539 $data->workflowstate
= $flags->workflowstate
;
3541 if (!empty($flags->allocatedmarker
)) {
3542 $data->allocatedmarker
= $flags->allocatedmarker
;
3545 // Warning if required.
3546 $allsubmissions = $this->get_all_submissions($userid);
3548 if ($attemptnumber != -1 && ($attemptnumber +
1) != count($allsubmissions)) {
3549 $params = array('attemptnumber'=>$attemptnumber +
1,
3550 'totalattempts'=>count($allsubmissions));
3551 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
3552 $o .= $this->get_renderer()->notification($message);
3555 // Now show the grading form.
3557 $pagination = array('rownum' => $rownum,
3558 'useridlistid' => $useridlistid,
3560 'userid' => $userid,
3561 'attemptnumber' => $attemptnumber);
3562 $formparams = array($this, $data, $pagination);
3563 $mform = new mod_assign_grade_form(null,
3567 array('class'=>'gradeform'));
3569 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
3570 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
3572 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
3573 $allgrades = $this->get_all_grades($userid);
3574 $history = new assign_attempt_history($allsubmissions,
3576 $this->get_submission_plugins(),
3577 $this->get_feedback_plugins(),
3578 $this->get_course_module()->id
,
3579 $this->get_return_action(),
3580 $this->get_return_params(),
3585 $o .= $this->get_renderer()->render($history);
3588 \mod_assign\event\grading_form_viewed
::create_from_user($this, $user)->trigger();
3590 $o .= $this->view_footer();
3595 * Show a confirmation page to make sure they want to release student identities.
3599 protected function view_reveal_identities_confirm() {
3600 require_capability('mod/assign:revealidentities', $this->get_context());
3603 $header = new assign_header($this->get_instance(),
3604 $this->get_context(),
3606 $this->get_course_module()->id
);
3607 $o .= $this->get_renderer()->render($header);
3609 $urlparams = array('id'=>$this->get_course_module()->id
,
3610 'action'=>'revealidentitiesconfirm',
3611 'sesskey'=>sesskey());
3612 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
3614 $urlparams = array('id'=>$this->get_course_module()->id
,
3615 'action'=>'grading');
3616 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
3618 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
3621 $o .= $this->view_footer();
3623 \mod_assign\event\reveal_identities_confirmation_page_viewed
::create_from_assign($this)->trigger();
3629 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3633 protected function view_return_links() {
3634 $returnaction = optional_param('returnaction', '', PARAM_ALPHA
);
3635 $returnparams = optional_param('returnparams', '', PARAM_TEXT
);
3638 $returnparams = str_replace('&', '&', $returnparams);
3639 parse_str($returnparams, $params);
3640 $newparams = array('id' => $this->get_course_module()->id
, 'action' => $returnaction);
3641 $params = array_merge($newparams, $params);
3643 $url = new moodle_url('/mod/assign/view.php', $params);
3644 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3648 * View the grading table of all submissions for this assignment.
3652 protected function view_grading_table() {
3653 global $USER, $CFG, $SESSION;
3655 // Include grading options form.
3656 require_once($CFG->dirroot
. '/mod/assign/gradingoptionsform.php');
3657 require_once($CFG->dirroot
. '/mod/assign/quickgradingform.php');
3658 require_once($CFG->dirroot
. '/mod/assign/gradingbatchoperationsform.php');
3660 $cmid = $this->get_course_module()->id
;
3663 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3664 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3665 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id
;
3666 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3668 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3669 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3670 $links[$downloadurl] = get_string('downloadall', 'assign');
3672 if ($this->is_blind_marking() &&
3673 has_capability('mod/assign:revealidentities', $this->get_context())) {
3674 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3675 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3677 foreach ($this->get_feedback_plugins() as $plugin) {
3678 if ($plugin->is_enabled() && $plugin->is_visible()) {
3679 foreach ($plugin->get_grading_actions() as $action => $description) {
3680 $url = '/mod/assign/view.php' .
3682 '&plugin=' . $plugin->get_type() .
3683 '&pluginsubtype=assignfeedback' .
3684 '&action=viewpluginpage&pluginaction=' . $action;
3685 $links[$url] = $description;
3690 // Sort links alphabetically based on the link description.
3691 core_collator
::asort($links);
3693 $gradingactions = new url_select($links);
3694 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
3696 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
3698 $perpage = $this->get_assign_perpage();
3699 $filter = get_user_preferences('assign_filter', '');
3700 $markerfilter = get_user_preferences('assign_markerfilter', '');
3701 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
3702 $controller = $gradingmanager->get_active_controller();
3703 $showquickgrading = empty($controller) && $this->can_grade();
3704 $quickgrading = get_user_preferences('assign_quickgrading', false);
3705 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context
);
3706 $downloadasfolders = get_user_preferences('assign_downloadasfolders', 1);
3708 $markingallocation = $this->get_instance()->markingworkflow
&&
3709 $this->get_instance()->markingallocation
&&
3710 has_capability('mod/assign:manageallocations', $this->context
);
3711 // Get markers to use in drop lists.
3712 $markingallocationoptions = array();
3713 if ($markingallocation) {
3714 list($sort, $params) = users_order_by_sql();
3715 $markers = get_users_by_capability($this->context
, 'mod/assign:grade', '', $sort);
3716 $markingallocationoptions[''] = get_string('filternone', 'assign');
3717 $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER
] = get_string('markerfilternomarker', 'assign');
3718 foreach ($markers as $marker) {
3719 $markingallocationoptions[$marker->id
] = fullname($marker);
3723 $markingworkflow = $this->get_instance()->markingworkflow
;
3724 // Get marking states to show in form.
3725 $markingworkflowoptions = array();
3726 if ($markingworkflow) {
3727 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
3728 $markingworkflowoptions[''] = get_string('filternone', 'assign');
3729 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED
] = $notmarked;
3730 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
3733 // Print options for changing the filter and changing the number of results per page.
3734 $gradingoptionsformparams = array('cm'=>$cmid,
3735 'contextid'=>$this->context
->id
,
3736 'userid'=>$USER->id
,
3737 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
3738 'showquickgrading'=>$showquickgrading,
3739 'quickgrading'=>$quickgrading,
3740 'markingworkflowopt'=>$markingworkflowoptions,
3741 'markingallocationopt'=>$markingallocationoptions,
3742 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
3743 'showonlyactiveenrol' => $this->show_only_active_users(),
3744 'downloadasfolders' => $downloadasfolders);
3746 $classoptions = array('class'=>'gradingoptionsform');
3747 $gradingoptionsform = new mod_assign_grading_options_form(null,
3748 $gradingoptionsformparams,
3753 $batchformparams = array('cm'=>$cmid,
3754 'submissiondrafts'=>$this->get_instance()->submissiondrafts
,
3755 'duedate'=>$this->get_instance()->duedate
,
3756 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod
,
3757 'feedbackplugins'=>$this->get_feedback_plugins(),
3758 'context'=>$this->get_context(),
3759 'markingworkflow'=>$markingworkflow,
3760 'markingallocation'=>$markingallocation);
3761 $classoptions = array('class'=>'gradingbatchoperationsform');
3763 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
3769 $gradingoptionsdata = new stdClass();
3770 $gradingoptionsdata->perpage
= $perpage;
3771 $gradingoptionsdata->filter
= $filter;
3772 $gradingoptionsdata->markerfilter
= $markerfilter;
3773 $gradingoptionsdata->workflowfilter
= $workflowfilter;
3774 $gradingoptionsform->set_data($gradingoptionsdata);
3776 $actionformtext = $this->get_renderer()->render($gradingactions);
3777 $header = new assign_header($this->get_instance(),
3778 $this->get_context(),
3780 $this->get_course_module()->id
,
3781 get_string('grading', 'assign'),
3783 $o .= $this->get_renderer()->render($header);
3785 $currenturl = $CFG->wwwroot
.
3786 '/mod/assign/view.php?id=' .
3787 $this->get_course_module()->id
.
3790 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
3792 // Plagiarism update status apearring in the grading book.
3793 if (!empty($CFG->enableplagiarism
)) {
3794 require_once($CFG->libdir
. '/plagiarismlib.php');
3795 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
3798 if ($this->is_blind_marking() && has_capability('mod/assign:viewblinddetails', $this->get_context())) {
3799 $o .= $this->get_renderer()->notification(get_string('blindmarkingenabledwarning', 'assign'), 'notifymessage');
3802 // Load and print the table of submissions.
3803 if ($showquickgrading && $quickgrading) {
3804 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
3805 $table = $this->get_renderer()->render($gradingtable);
3806 $page = optional_param('page', null, PARAM_INT
);
3807 $quickformparams = array('cm'=>$this->get_course_module()->id
,
3808 'gradingtable'=>$table,
3809 'sendstudentnotifications' => $this->get_instance()->sendstudentnotifications
,
3811 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
3813 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
3815 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
3816 $o .= $this->get_renderer()->render($gradingtable);
3819 if ($this->can_grade()) {
3820 // We need to store the order of uses in the table as the person may wish to grade them.
3821 // This is done based on the row number of the user.
3822 $useridlist = $gradingtable->get_column_data('userid');
3823 $SESSION->mod_assign_useridlist
[$this->get_useridlist_key()] = $useridlist;
3826 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3827 $users = array_keys($this->list_participants($currentgroup, true));
3828 if (count($users) != 0 && $this->can_grade()) {
3829 // If no enrolled user in a course then don't display the batch operations feature.
3830 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
3831 $o .= $this->get_renderer()->render($assignform);
3833 $assignform = new assign_form('gradingoptionsform',
3834 $gradingoptionsform,
3835 'M.mod_assign.init_grading_options');
3836 $o .= $this->get_renderer()->render($assignform);
3841 * View entire grader app.
3845 protected function view_grader() {
3846 global $USER, $PAGE;
3849 // Need submit permission to submit an assignment.
3850 $this->require_view_grades();
3852 $PAGE->set_pagelayout('embedded');
3854 $PAGE->set_title($this->get_context()->get_context_name());
3856 $o .= $this->get_renderer()->header();
3858 $userid = optional_param('userid', 0, PARAM_INT
);
3859 $blindid = optional_param('blindid', 0, PARAM_INT
);
3861 if (!$userid && $blindid) {
3862 $userid = $this->get_user_id_for_uniqueid($blindid);
3865 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
3866 $framegrader = new grading_app($userid, $currentgroup, $this);
3868 $o .= $this->get_renderer()->render($framegrader);
3870 $o .= $this->view_footer();
3872 \mod_assign\event\grading_table_viewed
::create_from_assign($this)->trigger();
3877 * View entire grading page.
3881 protected function view_grading_page() {
3885 // Need submit permission to submit an assignment.
3886 $this->require_view_grades();
3887 require_once($CFG->dirroot
. '/mod/assign/gradeform.php');
3889 // Only load this if it is.
3890 $o .= $this->view_grading_table();
3892 $o .= $this->view_footer();
3894 \mod_assign\event\grading_table_viewed
::create_from_assign($this)->trigger();
3900 * Capture the output of the plagiarism plugins disclosures and return it as a string.
3904 protected function plagiarism_print_disclosure() {
3908 if (!empty($CFG->enableplagiarism
)) {
3909 require_once($CFG->libdir
. '/plagiarismlib.php');
3911 $o .= plagiarism_print_disclosure($this->get_course_module()->id
);
3918 * Message for students when assignment submissions have been closed.
3920 * @param string $title The page title
3921 * @param array $notices The array of notices to show.
3924 protected function view_notices($title, $notices) {
3929 $header = new assign_header($this->get_instance(),
3930 $this->get_context(),
3931 $this->show_intro(),
3932 $this->get_course_module()->id
,
3934 $o .= $this->get_renderer()->render($header);
3936 foreach ($notices as $notice) {
3937 $o .= $this->get_renderer()->notification($notice);
3940 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id
, 'action'=>'view'));
3941 $o .= $this->get_renderer()->continue_button($url);
3943 $o .= $this->view_footer();
3949 * Get the name for a user - hiding their real name if blind marking is on.
3951 * @param stdClass $user The user record as required by fullname()
3952 * @return string The name.
3954 public function fullname($user) {
3955 if ($this->is_blind_marking()) {
3956 $hasviewblind = has_capability('mod/assign:viewblinddetails', $this->get_context());
3957 if (empty($user->recordid
)) {
3958 $uniqueid = $this->get_uniqueid_for_user($user->id
);
3960 $uniqueid = $user->recordid
;
3962 if ($hasviewblind) {
3963 return get_string('participant', 'assign') . ' ' . $uniqueid . ' (' . fullname($user) . ')';
3965 return get_string('participant', 'assign') . ' ' . $uniqueid;
3968 return fullname($user);
3973 * View edit submissions page.
3975 * @param moodleform $mform
3976 * @param array $notices A list of notices to display at the top of the
3977 * edit submission form (e.g. from plugins).
3978 * @return string The page output.
3980 protected function view_edit_submission_page($mform, $notices) {
3981 global $CFG, $USER, $DB;
3984 require_once($CFG->dirroot
. '/mod/assign/submission_form.php');
3985 // Need submit permission to submit an assignment.
3986 $userid = optional_param('userid', $USER->id
, PARAM_INT
);
3987 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
3989 // This variation on the url will link direct to this student.
3990 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3991 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3992 $this->register_return_link('editsubmission', $returnparams);
3994 if ($userid == $USER->id
) {
3995 if (!$this->can_edit_submission($userid, $USER->id
)) {
3996 print_error('nopermission');
3998 // User is editing their own submission.
3999 require_capability('mod/assign:submit', $this->context
);
4000 $title = get_string('editsubmission', 'assign');
4002 // User is editing another user's submission.
4003 if (!$this->can_edit_submission($userid, $USER->id
)) {
4004 print_error('nopermission');
4007 $name = $this->fullname($user);
4008 $title = get_string('editsubmissionother', 'assign', $name);
4011 if (!$this->submissions_open($userid)) {
4012 $message = array(get_string('submissionsclosed', 'assign'));
4013 return $this->view_notices($title, $message);
4016 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
4017 $this->get_context(),
4018 $this->show_intro(),
4019 $this->get_course_module()->id
,
4021 if ($userid == $USER->id
) {
4022 // We only show this if it their submission.
4023 $o .= $this->plagiarism_print_disclosure();
4025 $data = new stdClass();
4026 $data->userid
= $userid;
4028 $mform = new mod_assign_submission_form(null, array($this, $data));
4031 foreach ($notices as $notice) {
4032 $o .= $this->get_renderer()->notification($notice);
4035 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
4037 $o .= $this->view_footer();
4039 \mod_assign\event\submission_form_viewed
::create_from_user($this, $user)->trigger();
4045 * See if this assignment has a grade yet.
4047 * @param int $userid
4050 protected function is_graded($userid) {
4051 $grade = $this->get_user_grade($userid, false);
4053 return ($grade->grade
!== null && $grade->grade
>= 0);
4059 * Perform an access check to see if the current $USER can view this group submission.
4061 * @param int $groupid
4064 public function can_view_group_submission($groupid) {
4067 $members = $this->get_submission_group_members($groupid, true);
4068 foreach ($members as $member) {
4069 // If we can view any members submission, we can view the submission for the group.
4070 if ($this->can_view_submission($member->id
)) {
4078 * Perform an access check to see if the current $USER can view this users submission.
4080 * @param int $userid
4083 public function can_view_submission($userid) {
4086 if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context
)) {
4089 if (!is_enrolled($this->get_course_context(), $userid)) {
4092 if (has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context
)) {
4095 if ($userid == $USER->id
&& has_capability('mod/assign:submit', $this->context
)) {
4102 * Allows the plugin to show a batch grading operation page.
4104 * @param moodleform $mform
4107 protected function view_plugin_grading_batch_operation($mform) {
4108 require_capability('mod/assign:grade', $this->context
);
4109 $prefix = 'plugingradingbatchoperation_';
4111 if ($data = $mform->get_data()) {
4112 $tail = substr($data->operation
, strlen($prefix));
4113 list($plugintype, $action) = explode('_', $tail, 2);
4115 $plugin = $this->get_feedback_plugin_by_type($plugintype);
4117 $users = $data->selectedusers
;
4118 $userlist = explode(',', $users);
4119 echo $plugin->grading_batch_operation($action, $userlist);
4123 print_error('invalidformdata', '');
4127 * Ask the user to confirm they want to perform this batch operation
4129 * @param moodleform $mform Set to a grading batch operations form
4130 * @return string - the page to view after processing these actions
4132 protected function process_grading_batch_operation(& $mform) {
4134 require_once($CFG->dirroot
. '/mod/assign/gradingbatchoperationsform.php');
4137 $markingallocation = $this->get_instance()->markingworkflow
&&
4138 $this->get_instance()->markingallocation
&&
4139 has_capability('mod/assign:manageallocations', $this->context
);
4141 $batchformparams = array('cm'=>$this->get_course_module()->id
,
4142 'submissiondrafts'=>$this->get_instance()->submissiondrafts
,
4143 'duedate'=>$this->get_instance()->duedate
,
4144 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod
,
4145 'feedbackplugins'=>$this->get_feedback_plugins(),
4146 'context'=>$this->get_context(),
4147 'markingworkflow'=>$this->get_instance()->markingworkflow
,
4148 'markingallocation'=>$markingallocation);
4149 $formclasses = array('class'=>'gradingbatchoperationsform');
4150 $mform = new mod_assign_grading_batch_operations_form(null,
4156 if ($data = $mform->get_data()) {
4157 // Get the list of users.
4158 $users = $data->selectedusers
;
4159 $userlist = explode(',', $users);
4161 $prefix = 'plugingradingbatchoperation_';
4163 if ($data->operation
== 'grantextension') {
4164 // Reset the form so the grant extension page will create the extension form.
4166 return 'grantextension';
4167 } else if ($data->operation
== 'setmarkingworkflowstate') {
4168 return 'viewbatchsetmarkingworkflowstate';
4169 } else if ($data->operation
== 'setmarkingallocation') {
4170 return 'viewbatchmarkingallocation';
4171 } else if (strpos($data->operation
, $prefix) === 0) {
4172 $tail = substr($data->operation
, strlen($prefix));
4173 list($plugintype, $action) = explode('_', $tail, 2);
4175 $plugin = $this->get_feedback_plugin_by_type($plugintype);
4177 return 'plugingradingbatchoperation';
4181 if ($data->operation
== 'downloadselected') {
4182 $this->download_submissions($userlist);
4184 foreach ($userlist as $userid) {
4185 if ($data->operation
== 'lock') {
4186 $this->process_lock_submission($userid);
4187 } else if ($data->operation
== 'unlock') {
4188 $this->process_unlock_submission($userid);
4189 } else if ($data->operation
== 'reverttodraft') {
4190 $this->process_revert_to_draft($userid);
4191 } else if ($data->operation
== 'addattempt') {
4192 if (!$this->get_instance()->teamsubmission
) {
4193 $this->process_add_attempt($userid);
4198 if ($this->get_instance()->teamsubmission
&& $data->operation
== 'addattempt') {
4199 // This needs to be handled separately so that each team submission is only re-opened one time.
4200 $this->process_add_attempt_group($userlist);
4208 * Shows a form that allows the workflow state for selected submissions to be changed.
4210 * @param moodleform $mform Set to a grading batch operations form
4211 * @return string - the page to view after processing these actions
4213 protected function view_batch_set_workflow_state($mform) {
4216 require_once($CFG->dirroot
. '/mod/assign/batchsetmarkingworkflowstateform.php');
4220 $submitteddata = $mform->get_data();
4221 $users = $submitteddata->selectedusers
;
4222 $userlist = explode(',', $users);
4224 $formdata = array('id' => $this->get_course_module()->id
,
4225 'selectedusers' => $users);
4230 $extrauserfields = get_extra_user_fields($this->get_context());
4231 foreach ($userlist as $userid) {
4232 if ($usercount >= 5) {
4233 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
4236 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
4238 $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
4239 $this->get_course()->id
,
4240 has_capability('moodle/site:viewfullnames',
4241 $this->get_course_context()),
4242 $this->is_blind_marking(),
4243 $this->get_uniqueid_for_user($user->id
),
4245 !$this->is_active_user($userid)));
4249 $formparams = array(
4250 'userscount' => count($userlist),
4251 'usershtml' => $usershtml,
4252 'markingworkflowstates' => $this->get_marking_workflow_states_for_current_user()
4255 $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
4256 $mform->set_data($formdata); // Initialises the hidden elements.
4257 $header = new assign_header($this->get_instance(),
4258 $this->get_context(),
4259 $this->show_intro(),
4260 $this->get_course_module()->id
,
4261 get_string('setmarkingworkflowstate', 'assign'));
4262 $o .= $this->get_renderer()->render($header);
4263 $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
4264 $o .= $this->view_footer();
4266 \mod_assign\event\batch_set_workflow_state_viewed
::create_from_assign($this)->trigger();
4272 * Shows a form that allows the allocated marker for selected submissions to be changed.
4274 * @param moodleform $mform Set to a grading batch operations form
4275 * @return string - the page to view after processing these actions
4277 public function view_batch_markingallocation($mform) {
4280 require_once($CFG->dirroot
. '/mod/assign/batchsetallocatedmarkerform.php');
4284 $submitteddata = $mform->get_data();
4285 $users = $submitteddata->selectedusers
;
4286 $userlist = explode(',', $users);
4288 $formdata = array('id' => $this->get_course_module()->id
,
4289 'selectedusers' => $users);
4294 $extrauserfields = get_extra_user_fields($this->get_context());
4295 foreach ($userlist as $userid) {
4296 if ($usercount >= 5) {
4297 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
4300 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
4302 $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
4303 $this->get_course()->id
,
4304 has_capability('moodle/site:viewfullnames',
4305 $this->get_course_context()),
4306 $this->is_blind_marking(),
4307 $this->get_uniqueid_for_user($user->id
),
4309 !$this->is_active_user($userid)));
4313 $formparams = array(
4314 'userscount' => count($userlist),
4315 'usershtml' => $usershtml,
4318 list($sort, $params) = users_order_by_sql();
4319 $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade', '', $sort);
4320 $markerlist = array();
4321 foreach ($markers as $marker) {
4322 $markerlist[$marker->id
] = fullname($marker);
4325 $formparams['markers'] = $markerlist;
4327 $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
4328 $mform->set_data($formdata); // Initialises the hidden elements.
4329 $header = new assign_header($this->get_instance(),
4330 $this->get_context(),
4331 $this->show_intro(),
4332 $this->get_course_module()->id
,
4333 get_string('setmarkingallocation', 'assign'));
4334 $o .= $this->get_renderer()->render($header);
4335 $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
4336 $o .= $this->view_footer();
4338 \mod_assign\event\batch_set_marker_allocation_viewed
::create_from_assign($this)->trigger();
4344 * Ask the user to confirm they want to submit their work for grading.
4346 * @param moodleform $mform - null unless form validation has failed
4349 protected function check_submit_for_grading($mform) {
4352 require_once($CFG->dirroot
. '/mod/assign/submissionconfirmform.php');
4354 // Check that all of the submission plugins are ready for this submission.
4355 $notifications = array();
4356 $submission = $this->get_user_submission($USER->id
, false);
4357 $plugins = $this->get_submission_plugins();
4358 foreach ($plugins as $plugin) {
4359 if ($plugin->is_enabled() && $plugin->is_visible()) {
4360 $check = $plugin->precheck_submission($submission);
4361 if ($check !== true) {
4362 $notifications[] = $check;
4367 $data = new stdClass();
4368 $adminconfig = $this->get_admin_config();
4369 $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement
&&
4370 !empty($adminconfig->submissionstatement
);
4372 $submissionstatement = '';
4373 if (!empty($adminconfig->submissionstatement
)) {
4374 // Format the submission statement before its sent. We turn off para because this is going within
4377 'context' => $this->get_context(),
4380 $submissionstatement = format_text($adminconfig->submissionstatement
, FORMAT_MOODLE
, $options);
4383 if ($mform == null) {
4384 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
4385 $submissionstatement,
4386 $this->get_course_module()->id
,
4390 $o .= $this->get_renderer()->header();
4391 $submitforgradingpage = new assign_submit_for_grading_page($notifications,
4392 $this->get_course_module()->id
,
4394 $o .= $this->get_renderer()->render($submitforgradingpage);
4395 $o .= $this->view_footer();
4397 \mod_assign\event\submission_confirmation_form_viewed
::create_from_assign($this)->trigger();
4403 * Creates an assign_submission_status renderable.
4405 * @param stdClass $user the user to get the report for
4406 * @param bool $showlinks return plain text or links to the profile
4407 * @return assign_submission_status renderable object
4409 public function get_assign_submission_status_renderable($user, $showlinks) {
4412 $instance = $this->get_instance();
4413 $flags = $this->get_user_flags($user->id
, false);
4414 $submission = $this->get_user_submission($user->id
, false);
4416 $teamsubmission = null;
4417 $submissiongroup = null;
4418 $notsubmitted = array();
4419 if ($instance->teamsubmission
) {
4420 $teamsubmission = $this->get_group_submission($user->id
, 0, false);
4421 $submissiongroup = $this->get_submission_group($user->id
);
4423 if ($submissiongroup) {
4424 $groupid = $submissiongroup->id
;
4426 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
4429 $showedit = $showlinks &&
4430 ($this->is_any_submission_plugin_enabled()) &&
4431 $this->can_edit_submission($user->id
);
4433 $gradelocked = ($flags && $flags->locked
) ||
$this->grading_disabled($user->id
, false);
4435 // Grading criteria preview.
4436 $gradingmanager = get_grading_manager($this->context
, 'mod_assign', 'submissions');
4437 $gradingcontrollerpreview = '';
4438 if ($gradingmethod = $gradingmanager->get_active_method()) {
4439 $controller = $gradingmanager->get_controller($gradingmethod);
4440 if ($controller->is_form_defined()) {
4441 $gradingcontrollerpreview = $controller->render_preview($PAGE);
4445 $showsubmit = ($showlinks && $this->submissions_open($user->id
));
4446 $showsubmit = ($showsubmit && $this->show_submit_button($submission, $teamsubmission, $user->id
));
4448 $extensionduedate = null;
4450 $extensionduedate = $flags->extensionduedate
;
4452 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
4454 $gradingstatus = $this->get_grading_status($user->id
);
4455 $usergroups = $this->get_all_groups($user->id
);
4456 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate
,
4457 $instance->alwaysshowdescription
,
4459 $instance->teamsubmission
,
4463 $this->is_any_submission_plugin_enabled(),
4465 $this->is_graded($user->id
),
4467 $instance->cutoffdate
,
4468 $this->get_submission_plugins(),
4469 $this->get_return_action(),
4470 $this->get_return_params(),
4471 $this->get_course_module()->id
,
4472 $this->get_course()->id
,
4473 assign_submission_status
::STUDENT_VIEW
,
4478 $this->get_context(),
4479 $this->is_blind_marking(),
4480 $gradingcontrollerpreview,
4481 $instance->attemptreopenmethod
,
4482 $instance->maxattempts
,
4484 $instance->preventsubmissionnotingroup
,
4486 return $submissionstatus;
4491 * Creates an assign_feedback_status renderable.
4493 * @param stdClass $user the user to get the report for
4494 * @return assign_feedback_status renderable object
4496 public function get_assign_feedback_status_renderable($user) {
4497 global $CFG, $DB, $PAGE;
4499 require_once($CFG->libdir
.'/gradelib.php');
4500 require_once($CFG->dirroot
.'/grade/grading/lib.php');
4502 $instance = $this->get_instance();
4503 $grade = $this->get_user_grade($user->id
, false);
4504 $gradingstatus = $this->get_grading_status($user->id
);
4506 $gradinginfo = grade_get_grades($this->get_course()->id
,
4512 $gradingitem = null;
4513 $gradebookgrade = null;
4514 if (isset($gradinginfo->items
[0])) {
4515 $gradingitem = $gradinginfo->items
[0];
4516 $gradebookgrade = $gradingitem->grades
[$user->id
];
4519 // Check to see if all feedback plugins are empty.
4520 $emptyplugins = true;
4522 foreach ($this->get_feedback_plugins() as $plugin) {
4523 if ($plugin->is_visible() && $plugin->is_enabled()) {
4524 if (!$plugin->is_empty($grade)) {
4525 $emptyplugins = false;
4531 if ($this->get_instance()->markingworkflow
&& $gradingstatus != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
) {
4532 $emptyplugins = true; // Don't show feedback plugins until released either.
4535 $cangrade = has_capability('mod/assign:grade', $this->get_context());
4536 // If there is a visible grade, show the summary.
4537 if ((!is_null($gradebookgrade->grade
) ||
!$emptyplugins)
4538 && ($cangrade ||
!$gradebookgrade->hidden
)) {
4540 $gradefordisplay = null;
4543 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
4545 // Only show the grade if it is not hidden in gradebook.
4546 if (!is_null($gradebookgrade->grade
) && ($cangrade ||
!$gradebookgrade->hidden
)) {
4547 if ($controller = $gradingmanager->get_active_controller()) {
4548 $menu = make_grades_menu($this->get_instance()->grade
);
4549 $controller->set_grade_range($menu, $this->get_instance()->grade
> 0);
4550 $gradefordisplay = $controller->render_grade($PAGE,
4553 $gradebookgrade->str_long_grade
,
4556 $gradefordisplay = $this->display_grade($gradebookgrade->grade
, false);
4558 $gradeddate = $gradebookgrade->dategraded
;
4559 if (isset($grade->grader
)) {
4560 $grader = $DB->get_record('user', array('id' => $grade->grader
));
4564 $feedbackstatus = new assign_feedback_status($gradefordisplay,
4567 $this->get_feedback_plugins(),
4569 $this->get_course_module()->id
,
4570 $this->get_return_action(),
4571 $this->get_return_params());
4572 return $feedbackstatus;
4578 * Creates an assign_attempt_history renderable.
4580 * @param stdClass $user the user to get the report for
4581 * @return assign_attempt_history renderable object
4583 public function get_assign_attempt_history_renderable($user) {
4585 $allsubmissions = $this->get_all_submissions($user->id
);
4586 $allgrades = $this->get_all_grades($user->id
);
4588 $history = new assign_attempt_history($allsubmissions,
4590 $this->get_submission_plugins(),
4591 $this->get_feedback_plugins(),
4592 $this->get_course_module()->id
,
4593 $this->get_return_action(),
4594 $this->get_return_params(),
4602 * Print 2 tables of information with no action links -
4603 * the submission summary and the grading summary.
4605 * @param stdClass $user the user to print the report for
4606 * @param bool $showlinks - Return plain text or links to the profile
4607 * @return string - the html summary
4609 public function view_student_summary($user, $showlinks) {
4613 if ($this->can_view_submission($user->id
)) {
4615 if (has_capability('mod/assign:submit', $this->get_context(), $user)) {
4616 $submissionstatus = $this->get_assign_submission_status_renderable($user, $showlinks);
4617 $o .= $this->get_renderer()->render($submissionstatus);
4620 // If there is a visible grade, show the feedback.
4621 $feedbackstatus = $this->get_assign_feedback_status_renderable($user);
4622 if ($feedbackstatus) {
4623 $o .= $this->get_renderer()->render($feedbackstatus);
4626 // If there is more than one submission, show the history.
4627 $history = $this->get_assign_attempt_history_renderable($user);
4628 if (count($history->submissions
) > 1) {
4629 $o .= $this->get_renderer()->render($history);
4636 * Returns true if the submit subsission button should be shown to the user.
4638 * @param stdClass $submission The users own submission record.
4639 * @param stdClass $teamsubmission The users team submission record if there is one
4640 * @param int $userid The user
4643 protected function show_submit_button($submission = null, $teamsubmission = null, $userid = null) {
4644 if ($teamsubmission) {
4645 if ($teamsubmission->status
=== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
4646 // The assignment submission has been completed.
4648 } else if ($this->submission_empty($teamsubmission)) {
4649 // There is nothing to submit yet.
4651 } else if ($submission && $submission->status
=== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
4652 // The user has already clicked the submit button on the team submission.
4655 !empty($this->get_instance()->preventsubmissionnotingroup
)
4656 && $this->get_submission_group($userid) == false
4660 } else if ($submission) {
4661 if ($submission->status
=== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
4662 // The assignment submission has been completed.
4664 } else if ($this->submission_empty($submission)) {
4665 // There is nothing to submit.
4669 // We've not got a valid submission or team submission.
4672 // Last check is that this instance allows drafts.
4673 return $this->get_instance()->submissiondrafts
;
4677 * Get the grades for all previous attempts.
4678 * For each grade - the grader is a full user record,
4679 * and gradefordisplay is added (rendered from grading manager).
4681 * @param int $userid If not set, $USER->id will be used.
4682 * @return array $grades All grade records for this user.
4684 protected function get_all_grades($userid) {
4685 global $DB, $USER, $PAGE;
4687 // If the userid is not null then use userid.
4689 $userid = $USER->id
;
4692 $params = array('assignment'=>$this->get_instance()->id
, 'userid'=>$userid);
4694 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber ASC');
4696 $gradercache = array();
4697 $cangrade = has_capability('mod/assign:grade', $this->get_context());
4699 // Need gradingitem and gradingmanager.
4700 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
4701 $controller = $gradingmanager->get_active_controller();
4703 $gradinginfo = grade_get_grades($this->get_course()->id
,
4706 $this->get_instance()->id
,
4709 $gradingitem = null;
4710 if (isset($gradinginfo->items
[0])) {
4711 $gradingitem = $gradinginfo->items
[0];
4714 foreach ($grades as $grade) {
4715 // First lookup the grader info.
4716 if (isset($gradercache[$grade->grader
])) {
4717 $grade->grader
= $gradercache[$grade->grader
];
4719 // Not in cache - need to load the grader record.
4720 $grade->grader
= $DB->get_record('user', array('id'=>$grade->grader
));
4721 $gradercache[$grade->grader
->id
] = $grade->grader
;
4724 // Now get the gradefordisplay.
4726 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade
), $this->get_instance()->grade
> 0);
4727 $grade->gradefordisplay
= $controller->render_grade($PAGE,
4733 $grade->gradefordisplay
= $this->display_grade($grade->grade
, false);
4742 * Get the submissions for all previous attempts.
4744 * @param int $userid If not set, $USER->id will be used.
4745 * @return array $submissions All submission records for this user (or group).
4747 protected function get_all_submissions($userid) {
4750 // If the userid is not null then use userid.
4752 $userid = $USER->id
;
4757 if ($this->get_instance()->teamsubmission
) {
4759 $group = $this->get_submission_group($userid);
4761 $groupid = $group->id
;
4764 // Params to get the group submissions.
4765 $params = array('assignment'=>$this->get_instance()->id
, 'groupid'=>$groupid, 'userid'=>0);
4767 // Params to get the user submissions.
4768 $params = array('assignment'=>$this->get_instance()->id
, 'userid'=>$userid);
4771 // Return the submissions ordered by attempt.
4772 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber ASC');
4774 return $submissions;
4778 * Creates an assign_grading_summary renderable.
4780 * @return assign_grading_summary renderable object
4782 public function get_assign_grading_summary_renderable() {
4784 $instance = $this->get_instance();
4786 $draft = ASSIGN_SUBMISSION_STATUS_DRAFT
;
4787 $submitted = ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
4789 $activitygroup = groups_get_activity_group($this->get_course_module());
4791 if ($instance->teamsubmission
) {
4792 $defaultteammembers = $this->get_submission_group_members(0, true);
4793 $warnofungroupedusers = (count($defaultteammembers) > 0 && $instance->preventsubmissionnotingroup
);
4795 $summary = new assign_grading_summary($this->count_teams($activitygroup),
4796 $instance->submissiondrafts
,
4797 $this->count_submissions_with_status($draft),
4798 $this->is_any_submission_plugin_enabled(),
4799 $this->count_submissions_with_status($submitted),
4800 $instance->cutoffdate
,
4802 $this->get_course_module()->id
,
4803 $this->count_submissions_need_grading(),
4804 $instance->teamsubmission
,
4805 $warnofungroupedusers);
4807 // The active group has already been updated in groups_print_activity_menu().
4808 $countparticipants = $this->count_participants($activitygroup);
4809 $summary = new assign_grading_summary($countparticipants,
4810 $instance->submissiondrafts
,
4811 $this->count_submissions_with_status($draft),
4812 $this->is_any_submission_plugin_enabled(),
4813 $this->count_submissions_with_status($submitted),
4814 $instance->cutoffdate
,
4816 $this->get_course_module()->id
,
4817 $this->count_submissions_need_grading(),
4818 $instance->teamsubmission
,
4827 * View submissions page (contains details of current submission).
4831 protected function view_submission_page() {
4832 global $CFG, $DB, $USER, $PAGE;
4834 $instance = $this->get_instance();
4839 if ($this->has_visible_attachments()) {
4840 $postfix = $this->render_area_files('mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA
, 0);
4842 $o .= $this->get_renderer()->render(new assign_header($instance,
4843 $this->get_context(),
4844 $this->show_intro(),
4845 $this->get_course_module()->id
,
4848 // Display plugin specific headers.
4849 $plugins = array_merge($this->get_submission_plugins(), $this->get_feedback_plugins());
4850 foreach ($plugins as $plugin) {
4851 if ($plugin->is_enabled() && $plugin->is_visible()) {
4852 $o .= $this->get_renderer()->render(new assign_plugin_header($plugin));
4856 if ($this->can_view_grades()) {
4857 // Group selector will only be displayed if necessary.
4858 $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $this->get_course_module()->id
));
4859 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl->out(), true);
4861 $summary = $this->get_assign_grading_summary_renderable();
4862 $o .= $this->get_renderer()->render($summary);
4864 $grade = $this->get_user_grade($USER->id
, false);
4865 $submission = $this->get_user_submission($USER->id
, false);
4867 if ($this->can_view_submission($USER->id
)) {
4868 $o .= $this->view_student_summary($USER, true);
4871 $o .= $this->view_footer();
4873 \mod_assign\event\submission_status_viewed
::create_from_assign($this)->trigger();
4879 * Convert the final raw grade(s) in the grading table for the gradebook.
4881 * @param stdClass $grade
4884 protected function convert_grade_for_gradebook(stdClass
$grade) {
4885 $gradebookgrade = array();
4886 if ($grade->grade
>= 0) {
4887 $gradebookgrade['rawgrade'] = $grade->grade
;
4889 // Allow "no grade" to be chosen.
4890 if ($grade->grade
== -1) {
4891 $gradebookgrade['rawgrade'] = NULL;
4893 $gradebookgrade['userid'] = $grade->userid
;
4894 $gradebookgrade['usermodified'] = $grade->grader
;
4895 $gradebookgrade['datesubmitted'] = null;
4896 $gradebookgrade['dategraded'] = $grade->timemodified
;
4897 if (isset($grade->feedbackformat
)) {
4898 $gradebookgrade['feedbackformat'] = $grade->feedbackformat
;
4900 if (isset($grade->feedbacktext
)) {
4901 $gradebookgrade['feedback'] = $grade->feedbacktext
;
4904 return $gradebookgrade;
4908 * Convert submission details for the gradebook.
4910 * @param stdClass $submission
4913 protected function convert_submission_for_gradebook(stdClass
$submission) {
4914 $gradebookgrade = array();
4916 $gradebookgrade['userid'] = $submission->userid
;
4917 $gradebookgrade['usermodified'] = $submission->userid
;
4918 $gradebookgrade['datesubmitted'] = $submission->timemodified
;
4920 return $gradebookgrade;
4924 * Update grades in the gradebook.
4926 * @param mixed $submission stdClass|null
4927 * @param mixed $grade stdClass|null
4930 protected function gradebook_item_update($submission=null, $grade=null) {
4933 require_once($CFG->dirroot
.'/mod/assign/lib.php');
4934 // Do not push grade to gradebook if blind marking is active as
4935 // the gradebook would reveal the students.
4936 if ($this->is_blind_marking()) {
4940 // If marking workflow is enabled and grade is not released then remove any grade that may exist in the gradebook.
4941 if ($this->get_instance()->markingworkflow
&& !empty($grade) &&
4942 $this->get_grading_status($grade->userid
) != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
) {
4943 // Remove the grade (if it exists) from the gradebook as it is not 'final'.
4945 $grade->feedbacktext
= '';
4948 if ($submission != null) {
4949 if ($submission->userid
== 0) {
4950 // This is a group submission update.
4951 $team = groups_get_members($submission->groupid
, 'u.id');
4953 foreach ($team as $member) {
4954 $membersubmission = clone $submission;
4955 $membersubmission->groupid
= 0;
4956 $membersubmission->userid
= $member->id
;
4957 $this->gradebook_item_update($membersubmission, null);
4962 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
4965 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
4967 // Grading is disabled, return.
4968 if ($this->grading_disabled($gradebookgrade['userid'])) {
4971 $assign = clone $this->get_instance();
4972 $assign->cmidnumber
= $this->get_course_module()->idnumber
;
4973 // Set assign gradebook feedback plugin status (enabled and visible).
4974 $assign->gradefeedbackenabled
= $this->is_gradebook_feedback_enabled();
4975 return assign_grade_item_update($assign, $gradebookgrade) == GRADE_UPDATE_OK
;
4979 * Update team submission.
4981 * @param stdClass $submission
4982 * @param int $userid
4983 * @param bool $updatetime
4986 protected function update_team_submission(stdClass
$submission, $userid, $updatetime) {
4990 $submission->timemodified
= time();
4993 // First update the submission for the current user.
4994 $mysubmission = $this->get_user_submission($userid, true, $submission->attemptnumber
);
4995 $mysubmission->status
= $submission->status
;
4997 $this->update_submission($mysubmission, 0, $updatetime, false);
4999 // Now check the team settings to see if this assignment qualifies as submitted or draft.
5000 $team = $this->get_submission_group_members($submission->groupid
, true);
5002 $allsubmitted = true;
5003 $anysubmitted = false;
5005 if ($submission->status
!= ASSIGN_SUBMISSION_STATUS_REOPENED
) {
5006 foreach ($team as $member) {
5007 $membersubmission = $this->get_user_submission($member->id
, false, $submission->attemptnumber
);
5009 // If no submission found for team member and member is active then everyone has not submitted.
5010 if (!$membersubmission ||
$membersubmission->status
!= ASSIGN_SUBMISSION_STATUS_SUBMITTED
5011 && ($this->is_active_user($member->id
))) {
5012 $allsubmitted = false;
5013 if ($anysubmitted) {
5017 $anysubmitted = true;
5020 if ($this->get_instance()->requireallteammemberssubmit
) {
5021 if ($allsubmitted) {
5022 $submission->status
= ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
5024 $submission->status
= ASSIGN_SUBMISSION_STATUS_DRAFT
;
5026 $result = $DB->update_record('assign_submission', $submission);
5028 if ($anysubmitted) {
5029 $submission->status
= ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
5031 $submission->status
= ASSIGN_SUBMISSION_STATUS_DRAFT
;
5033 $result = $DB->update_record('assign_submission', $submission);
5036 // Set the group submission to reopened.
5037 foreach ($team as $member) {
5038 $membersubmission = $this->get_user_submission($member->id
, true, $submission->attemptnumber
);
5039 $membersubmission->status
= ASSIGN_SUBMISSION_STATUS_REOPENED
;
5040 $result = $DB->update_record('assign_submission', $membersubmission) && $result;
5042 $result = $DB->update_record('assign_submission', $submission) && $result;
5045 $this->gradebook_item_update($submission);
5050 * Update grades in the gradebook based on submission time.
5052 * @param stdClass $submission
5053 * @param int $userid
5054 * @param bool $updatetime
5055 * @param bool $teamsubmission
5058 protected function update_submission(stdClass
$submission, $userid, $updatetime, $teamsubmission) {
5061 if ($teamsubmission) {
5062 return $this->update_team_submission($submission, $userid, $updatetime);
5066 $submission->timemodified
= time();
5068 $result= $DB->update_record('assign_submission', $submission);
5070 $this->gradebook_item_update($submission);
5076 * Is this assignment open for submissions?
5078 * Check the due date,
5079 * prevent late submissions,
5080 * has this person already submitted,
5081 * is the assignment locked?
5083 * @param int $userid - Optional userid so we can see if a different user can submit
5084 * @param bool $skipenrolled - Skip enrollment checks (because they have been done already)
5085 * @param stdClass $submission - Pre-fetched submission record (or false to fetch it)
5086 * @param stdClass $flags - Pre-fetched user flags record (or false to fetch it)
5087 * @param stdClass $gradinginfo - Pre-fetched user gradinginfo record (or false to fetch it)
5090 public function submissions_open($userid = 0,
5091 $skipenrolled = false,
5092 $submission = false,
5094 $gradinginfo = false) {
5098 $userid = $USER->id
;
5104 if ($this->get_instance()->cutoffdate
) {
5105 $finaldate = $this->get_instance()->cutoffdate
;
5108 if ($flags === false) {
5109 $flags = $this->get_user_flags($userid, false);
5111 if ($flags && $flags->locked
) {
5117 if ($flags && $flags->extensionduedate
) {
5118 // Extension can be before cut off date.
5119 if ($flags->extensionduedate
> $finaldate) {
5120 $finaldate = $flags->extensionduedate
;
5126 $dateopen = ($this->get_instance()->allowsubmissionsfromdate
<= $time && $time <= $finaldate);
5128 $dateopen = ($this->get_instance()->allowsubmissionsfromdate
<= $time);
5135 // Now check if this user has already submitted etc.
5136 if (!$skipenrolled && !is_enrolled($this->get_course_context(), $userid)) {
5139 // Note you can pass null for submission and it will not be fetched.
5140 if ($submission === false) {
5141 if ($this->get_instance()->teamsubmission
) {
5142 $submission = $this->get_group_submission($userid, 0, false);
5144 $submission = $this->get_user_submission($userid, false);
5149 if ($this->get_instance()->submissiondrafts
&& $submission->status
== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
5150 // Drafts are tracked and the student has submitted the assignment.
5155 // See if this user grade is locked in the gradebook.
5156 if ($gradinginfo === false) {
5157 $gradinginfo = grade_get_grades($this->get_course()->id
,
5160 $this->get_instance()->id
,
5164 isset($gradinginfo->items
[0]->grades
[$userid]) &&
5165 $gradinginfo->items
[0]->grades
[$userid]->locked
) {
5173 * Render the files in file area.
5175 * @param string $component
5176 * @param string $area
5177 * @param int $submissionid
5180 public function render_area_files($component, $area, $submissionid) {
5183 return $this->get_renderer()->assign_files($this->context
, $submissionid, $area, $component);
5188 * Capability check to make sure this grader can edit this submission.
5190 * @param int $userid - The user whose submission is to be edited
5191 * @param int $graderid (optional) - The user who will do the editing (default to $USER->id).
5194 public function can_edit_submission($userid, $graderid = 0) {
5197 if (empty($graderid)) {
5198 $graderid = $USER->id
;
5201 $instance = $this->get_instance();
5202 if ($userid == $graderid &&
5203 $instance->teamsubmission
&&
5204 $instance->preventsubmissionnotingroup
&&
5205 $this->get_submission_group($userid) == false) {
5209 if ($userid == $graderid &&
5210 $this->submissions_open($userid) &&
5211 has_capability('mod/assign:submit', $this->context
, $graderid)) {
5212 // User can edit their own submission.
5216 if (!has_capability('mod/assign:editothersubmission', $this->context
, $graderid)) {
5220 $cm = $this->get_course_module();
5221 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS
) {
5222 $sharedgroupmembers = $this->get_shared_group_members($cm, $graderid);
5223 return in_array($userid, $sharedgroupmembers);
5229 * Returns IDs of the users who share group membership with the specified user.
5231 * @param stdClass|cm_info $cm Course-module
5232 * @param int $userid User ID
5233 * @return array An array of ID of users.
5235 public function get_shared_group_members($cm, $userid) {
5236 if (!isset($this->sharedgroupmembers
[$userid])) {
5237 $this->sharedgroupmembers
[$userid] = array();
5238 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
5239 foreach ($groupsids as $groupid) {
5240 $members = array_keys(groups_get_members($groupid, 'u.id'));
5241 $this->sharedgroupmembers
[$userid] = array_merge($this->sharedgroupmembers
[$userid], $members);
5245 return $this->sharedgroupmembers
[$userid];
5249 * Returns a list of teachers that should be grading given submission.
5251 * @param int $userid The submission to grade
5254 protected function get_graders($userid) {
5255 // Potential graders should be active users only.
5256 $potentialgraders = get_enrolled_users($this->context
, "mod/assign:grade", null, 'u.*', null, null, null, true);
5259 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS
) {
5260 if ($groups = groups_get_all_groups($this->get_course()->id
, $userid, $this->get_course_module()->groupingid
)) {
5261 foreach ($groups as $group) {
5262 foreach ($potentialgraders as $grader) {
5263 if ($grader->id
== $userid) {
5264 // Do not send self.
5267 if (groups_is_member($group->id
, $grader->id
)) {
5268 $graders[$grader->id
] = $grader;
5273 // User not in group, try to find graders without group.
5274 foreach ($potentialgraders as $grader) {
5275 if ($grader->id
== $userid) {
5276 // Do not send self.
5279 if (!groups_has_membership($this->get_course_module(), $grader->id
)) {
5280 $graders[$grader->id
] = $grader;
5285 foreach ($potentialgraders as $grader) {
5286 if ($grader->id
== $userid) {
5287 // Do not send self.
5290 // Must be enrolled.
5291 if (is_enrolled($this->get_course_context(), $grader->id
)) {
5292 $graders[$grader->id
] = $grader;
5300 * Returns a list of users that should receive notification about given submission.
5302 * @param int $userid The submission to grade
5305 protected function get_notifiable_users($userid) {
5306 // Potential users should be active users only.
5307 $potentialusers = get_enrolled_users($this->context
, "mod/assign:receivegradernotifications",
5308 null, 'u.*', null, null, null, true);
5310 $notifiableusers = array();
5311 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS
) {
5312 if ($groups = groups_get_all_groups($this->get_course()->id
, $userid, $this->get_course_module()->groupingid
)) {
5313 foreach ($groups as $group) {
5314 foreach ($potentialusers as $potentialuser) {
5315 if ($potentialuser->id
== $userid) {
5316 // Do not send self.
5319 if (groups_is_member($group->id
, $potentialuser->id
)) {
5320 $notifiableusers[$potentialuser->id
] = $potentialuser;
5325 // User not in group, try to find graders without group.
5326 foreach ($potentialusers as $potentialuser) {
5327 if ($potentialuser->id
== $userid) {
5328 // Do not send self.
5331 if (!groups_has_membership($this->get_course_module(), $potentialuser->id
)) {
5332 $notifiableusers[$potentialuser->id
] = $potentialuser;
5337 foreach ($potentialusers as $potentialuser) {
5338 if ($potentialuser->id
== $userid) {
5339 // Do not send self.
5342 // Must be enrolled.
5343 if (is_enrolled($this->get_course_context(), $potentialuser->id
)) {
5344 $notifiableusers[$potentialuser->id
] = $potentialuser;
5348 return $notifiableusers;
5352 * Format a notification for plain text.
5354 * @param string $messagetype
5355 * @param stdClass $info
5356 * @param stdClass $course
5357 * @param stdClass $context
5358 * @param string $modulename
5359 * @param string $assignmentname
5361 protected static function format_notification_message_text($messagetype,
5367 $formatparams = array('context' => $context->get_course_context());
5368 $posttext = format_string($course->shortname
, true, $formatparams) .
5372 format_string($assignmentname, true, $formatparams) . "\n";
5373 $posttext .= '---------------------------------------------------------------------' . "\n";
5374 $posttext .= get_string($messagetype . 'text', 'assign', $info)."\n";
5375 $posttext .= "\n---------------------------------------------------------------------\n";
5380 * Format a notification for HTML.
5382 * @param string $messagetype
5383 * @param stdClass $info
5384 * @param stdClass $course
5385 * @param stdClass $context
5386 * @param string $modulename
5387 * @param stdClass $coursemodule
5388 * @param string $assignmentname
5390 protected static function format_notification_message_html($messagetype,
5398 $formatparams = array('context' => $context->get_course_context());
5399 $posthtml = '<p><font face="sans-serif">' .
5400 '<a href="' . $CFG->wwwroot
. '/course/view.php?id=' . $course->id
. '">' .
5401 format_string($course->shortname
, true, $formatparams) .
5403 '<a href="' . $CFG->wwwroot
. '/mod/assign/index.php?id=' . $course->id
. '">' .
5406 '<a href="' . $CFG->wwwroot
. '/mod/assign/view.php?id=' . $coursemodule->id
. '">' .
5407 format_string($assignmentname, true, $formatparams) .
5409 $posthtml .= '<hr /><font face="sans-serif">';
5410 $posthtml .= '<p>' . get_string($messagetype . 'html', 'assign', $info) . '</p>';
5411 $posthtml .= '</font><hr />';
5416 * Message someone about something (static so it can be called from cron).
5418 * @param stdClass $userfrom
5419 * @param stdClass $userto
5420 * @param string $messagetype
5421 * @param string $eventtype
5422 * @param int $updatetime
5423 * @param stdClass $coursemodule
5424 * @param stdClass $context
5425 * @param stdClass $course
5426 * @param string $modulename
5427 * @param string $assignmentname
5428 * @param bool $blindmarking
5429 * @param int $uniqueidforuser
5432 public static function send_assignment_notification($userfrom,
5446 $info = new stdClass();
5447 if ($blindmarking) {
5448 $userfrom = clone($userfrom);
5449 $info->username
= get_string('participant', 'assign') . ' ' . $uniqueidforuser;
5450 $userfrom->firstname
= get_string('participant', 'assign');
5451 $userfrom->lastname
= $uniqueidforuser;
5452 $userfrom->email
= $CFG->noreplyaddress
;
5454 $info->username
= fullname($userfrom, true);
5456 $info->assignment
= format_string($assignmentname, true, array('context'=>$context));
5457 $info->url
= $CFG->wwwroot
.'/mod/assign/view.php?id='.$coursemodule->id
;
5458 $info->timeupdated
= userdate($updatetime, get_string('strftimerecentfull'));
5460 $postsubject = get_string($messagetype . 'small', 'assign', $info);
5461 $posttext = self
::format_notification_message_text($messagetype,
5468 if ($userto->mailformat
== 1) {
5469 $posthtml = self
::format_notification_message_html($messagetype,
5478 $eventdata = new \core\message\
message();
5479 $eventdata->courseid
= $course->id
;
5480 $eventdata->modulename
= 'assign';
5481 $eventdata->userfrom
= $userfrom;
5482 $eventdata->userto
= $userto;
5483 $eventdata->subject
= $postsubject;
5484 $eventdata->fullmessage
= $posttext;
5485 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
5486 $eventdata->fullmessagehtml
= $posthtml;
5487 $eventdata->smallmessage
= $postsubject;
5489 $eventdata->name
= $eventtype;
5490 $eventdata->component
= 'mod_assign';
5491 $eventdata->notification
= 1;
5492 $eventdata->contexturl
= $info->url
;
5493 $eventdata->contexturlname
= $info->assignment
;
5495 message_send($eventdata);
5499 * Message someone about something.
5501 * @param stdClass $userfrom
5502 * @param stdClass $userto
5503 * @param string $messagetype
5504 * @param string $eventtype
5505 * @param int $updatetime
5508 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
5510 $userid = core_user
::is_real_user($userfrom->id
) ?
$userfrom->id
: $USER->id
;
5511 $uniqueid = $this->get_uniqueid_for_user($userid);
5512 self
::send_assignment_notification($userfrom,
5517 $this->get_course_module(),
5518 $this->get_context(),
5519 $this->get_course(),
5520 $this->get_module_name(),
5521 $this->get_instance()->name
,
5522 $this->is_blind_marking(),
5527 * Notify student upon successful submission copy.
5529 * @param stdClass $submission
5532 protected function notify_student_submission_copied(stdClass
$submission) {
5535 $adminconfig = $this->get_admin_config();
5536 // Use the same setting for this - no need for another one.
5537 if (empty($adminconfig->submissionreceipts
)) {
5538 // No need to do anything.
5541 if ($submission->userid
) {
5542 $user = $DB->get_record('user', array('id'=>$submission->userid
), '*', MUST_EXIST
);
5546 $this->send_notification($user,
5549 'assign_notification',
5550 $submission->timemodified
);
5553 * Notify student upon successful submission.
5555 * @param stdClass $submission
5558 protected function notify_student_submission_receipt(stdClass
$submission) {
5561 $adminconfig = $this->get_admin_config();
5562 if (empty($adminconfig->submissionreceipts
)) {
5563 // No need to do anything.
5566 if ($submission->userid
) {
5567 $user = $DB->get_record('user', array('id'=>$submission->userid
), '*', MUST_EXIST
);
5571 if ($submission->userid
== $USER->id
) {
5572 $this->send_notification(core_user
::get_noreply_user(),
5574 'submissionreceipt',
5575 'assign_notification',
5576 $submission->timemodified
);
5578 $this->send_notification($USER,
5580 'submissionreceiptother',
5581 'assign_notification',
5582 $submission->timemodified
);
5587 * Send notifications to graders upon student submissions.
5589 * @param stdClass $submission
5592 protected function notify_graders(stdClass
$submission) {
5595 $instance = $this->get_instance();
5597 $late = $instance->duedate
&& ($instance->duedate
< time());
5599 if (!$instance->sendnotifications
&& !($late && $instance->sendlatenotifications
)) {
5600 // No need to do anything.
5604 if ($submission->userid
) {
5605 $user = $DB->get_record('user', array('id'=>$submission->userid
), '*', MUST_EXIST
);
5610 if ($notifyusers = $this->get_notifiable_users($user->id
)) {
5611 foreach ($notifyusers as $notifyuser) {
5612 $this->send_notification($user,
5614 'gradersubmissionupdated',
5615 'assign_notification',
5616 $submission->timemodified
);
5622 * Submit a submission for grading.
5624 * @param stdClass $data - The form data
5625 * @param array $notices - List of error messages to display on an error condition.
5626 * @return bool Return false if the submission was not submitted.
5628 public function submit_for_grading($data, $notices) {
5631 $userid = $USER->id
;
5632 if (!empty($data->userid
)) {
5633 $userid = $data->userid
;
5635 // Need submit permission to submit an assignment.
5636 if ($userid == $USER->id
) {
5637 require_capability('mod/assign:submit', $this->context
);
5639 if (!$this->can_edit_submission($userid, $USER->id
)) {
5640 print_error('nopermission');
5644 $instance = $this->get_instance();
5646 if ($instance->teamsubmission
) {
5647 $submission = $this->get_group_submission($userid, 0, true);
5649 $submission = $this->get_user_submission($userid, true);
5652 if (!$this->submissions_open($userid)) {
5653 $notices[] = get_string('submissionsclosed', 'assign');
5657 if ($instance->requiresubmissionstatement
&& empty($data->submissionstatement
) && $USER->id
== $userid) {
5661 if ($submission->status
!= ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
5662 // Give each submission plugin a chance to process the submission.
5663 $plugins = $this->get_submission_plugins();
5664 foreach ($plugins as $plugin) {
5665 if ($plugin->is_enabled() && $plugin->is_visible()) {
5666 $plugin->submit_for_grading($submission);
5670 $submission->status
= ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
5671 $this->update_submission($submission, $userid, true, $instance->teamsubmission
);
5672 $completion = new completion_info($this->get_course());
5673 if ($completion->is_enabled($this->get_course_module()) && $instance->completionsubmit
) {
5674 $this->update_activity_completion_records($instance->teamsubmission
,
5675 $instance->requireallteammemberssubmit
,
5678 COMPLETION_COMPLETE
,
5682 if (!empty($data->submissionstatement
) && $USER->id
== $userid) {
5683 \mod_assign\event\statement_accepted
::create_from_submission($this, $submission)->trigger();
5685 $this->notify_graders($submission);
5686 $this->notify_student_submission_receipt($submission);
5688 \mod_assign\event\assessable_submitted
::create_from_submission($this, $submission, false)->trigger();
5692 $notices[] = get_string('submissionsclosed', 'assign');
5697 * A students submission is submitted for grading by a teacher.
5701 protected function process_submit_other_for_grading($mform, $notices) {
5706 $userid = optional_param('userid', $USER->id
, PARAM_INT
);
5708 if (!$this->submissions_open($userid)) {
5709 $notices[] = get_string('submissionsclosed', 'assign');
5712 $data = new stdClass();
5713 $data->userid
= $userid;
5714 return $this->submit_for_grading($data, $notices);
5718 * Assignment submission is processed before grading.
5720 * @param moodleform|null $mform If validation failed when submitting this form - this is the moodleform.
5722 * @return bool Return false if the validation fails. This affects which page is displayed next.
5724 protected function process_submit_for_grading($mform, $notices) {
5727 require_once($CFG->dirroot
. '/mod/assign/submissionconfirmform.php');
5730 if (!$this->submissions_open()) {
5731 $notices[] = get_string('submissionsclosed', 'assign');
5734 $instance = $this->get_instance();
5735 $data = new stdClass();
5736 $adminconfig = $this->get_admin_config();
5737 $requiresubmissionstatement = $instance->requiresubmissionstatement
&&
5738 !empty($adminconfig->submissionstatement
);
5740 $submissionstatement = '';
5741 if (!empty($adminconfig->submissionstatement
)) {
5742 // Format the submission statement before its sent. We turn off para because this is going within
5745 'context' => $this->get_context(),
5748 $submissionstatement = format_text($adminconfig->submissionstatement
, FORMAT_MOODLE
, $options);
5751 if ($mform == null) {
5752 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
5753 $submissionstatement,
5754 $this->get_course_module()->id
,
5758 $data = $mform->get_data();
5759 if (!$mform->is_cancelled()) {
5760 if ($mform->get_data() == false) {
5763 return $this->submit_for_grading($data, $notices);
5769 * Save the extension date for a single user.
5771 * @param int $userid The user id
5772 * @param mixed $extensionduedate Either an integer date or null
5775 public function save_user_extension($userid, $extensionduedate) {
5778 // Need submit permission to submit an assignment.
5779 require_capability('mod/assign:grantextension', $this->context
);
5781 if (!is_enrolled($this->get_course_context(), $userid)) {
5784 if (!has_capability('mod/assign:submit', $this->context
, $userid)) {
5788 if ($this->get_instance()->duedate
&& $extensionduedate) {
5789 if ($this->get_instance()->duedate
> $extensionduedate) {
5793 if ($this->get_instance()->allowsubmissionsfromdate
&& $extensionduedate) {
5794 if ($this->get_instance()->allowsubmissionsfromdate
> $extensionduedate) {
5799 $flags = $this->get_user_flags($userid, true);
5800 $flags->extensionduedate
= $extensionduedate;
5802 $result = $this->update_user_flags($flags);
5805 \mod_assign\event\extension_granted
::create_from_assign($this, $userid)->trigger();
5811 * Save extension date.
5813 * @param moodleform $mform The submitted form
5816 protected function process_save_extension(& $mform) {
5819 // Include extension form.
5820 require_once($CFG->dirroot
. '/mod/assign/extensionform.php');
5823 $users = optional_param('userid', 0, PARAM_INT
);
5825 $users = required_param('selectedusers', PARAM_SEQUENCE
);
5827 $userlist = explode(',', $users);
5829 $formparams = array(
5830 'instance' => $this->get_instance(),
5832 'userlist' => $userlist
5835 $mform = new mod_assign_extension_form(null, $formparams);
5837 if ($mform->is_cancelled()) {
5841 if ($formdata = $mform->get_data()) {
5842 if (!empty($formdata->selectedusers
)) {
5843 $users = explode(',', $formdata->selectedusers
);
5845 foreach ($users as $userid) {
5846 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
5847 $result = $this->save_user_extension($user->id
, $formdata->extensionduedate
) && $result;
5851 if (!empty($formdata->userid
)) {
5852 $user = $DB->get_record('user', array('id' => $formdata->userid
), '*', MUST_EXIST
);
5853 return $this->save_user_extension($user->id
, $formdata->extensionduedate
);
5862 * Save quick grades.
5864 * @return string The result of the save operation
5866 protected function process_save_quick_grades() {
5867 global $USER, $DB, $CFG;
5869 // Need grade permission.
5870 require_capability('mod/assign:grade', $this->context
);
5873 // Make sure advanced grading is disabled.
5874 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
5875 $controller = $gradingmanager->get_active_controller();
5876 if (!empty($controller)) {
5877 return get_string('errorquickgradingvsadvancedgrading', 'assign');
5881 // First check all the last modified values.
5882 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
5883 $participants = $this->list_participants($currentgroup, true);
5885 // Gets a list of possible users and look for values based upon that.
5886 foreach ($participants as $userid => $unused) {
5887 $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT
);
5888 $attemptnumber = optional_param('gradeattempt_' . $userid, -1, PARAM_INT
);
5889 // Gather the userid, updated grade and last modified value.
5890 $record = new stdClass();
5891 $record->userid
= $userid;
5892 if ($modified >= 0) {
5893 $record->grade
= unformat_float(optional_param('quickgrade_' . $record->userid
, -1, PARAM_TEXT
));
5894 $record->workflowstate
= optional_param('quickgrade_' . $record->userid
.'_workflowstate', false, PARAM_TEXT
);
5895 $record->allocatedmarker
= optional_param('quickgrade_' . $record->userid
.'_allocatedmarker', false, PARAM_INT
);
5897 // This user was not in the grading table.
5900 $record->attemptnumber
= $attemptnumber;
5901 $record->lastmodified
= $modified;
5902 $record->gradinginfo
= grade_get_grades($this->get_course()->id
,
5905 $this->get_instance()->id
,
5907 $users[$userid] = $record;
5910 if (empty($users)) {
5911 return get_string('nousersselected', 'assign');
5914 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED
);
5915 $params['assignid1'] = $this->get_instance()->id
;
5916 $params['assignid2'] = $this->get_instance()->id
;
5918 // Check them all for currency.
5919 $grademaxattempt = 'SELECT s.userid, s.attemptnumber AS maxattempt
5920 FROM {assign_submission} s
5921 WHERE s.assignment = :assignid1 AND s.latest = 1';
5923 $sql = 'SELECT u.id AS userid, g.grade AS grade, g.timemodified AS lastmodified,
5924 uf.workflowstate, uf.allocatedmarker, gmx.maxattempt AS attemptnumber
5926 LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON u.id = gmx.userid
5927 LEFT JOIN {assign_grades} g ON
5929 g.assignment = :assignid2 AND
5930 g.attemptnumber = gmx.maxattempt
5931 LEFT JOIN {assign_user_flags} uf ON uf.assignment = g.assignment AND uf.userid = g.userid
5932 WHERE u.id ' . $userids;
5933 $currentgrades = $DB->get_recordset_sql($sql, $params);
5935 $modifiedusers = array();
5936 foreach ($currentgrades as $current) {
5937 $modified = $users[(int)$current->userid
];
5938 $grade = $this->get_user_grade($modified->userid
, false);
5939 // Check to see if the grade column was even visible.
5940 $gradecolpresent = optional_param('quickgrade_' . $modified->userid
, false, PARAM_INT
) !== false;
5942 // Check to see if the outcomes were modified.
5943 if ($CFG->enableoutcomes
) {
5944 foreach ($modified->gradinginfo
->outcomes
as $outcomeid => $outcome) {
5945 $oldoutcome = $outcome->grades
[$modified->userid
]->grade
;
5946 $paramname = 'outcome_' . $outcomeid . '_' . $modified->userid
;
5947 $newoutcome = optional_param($paramname, -1, PARAM_FLOAT
);
5948 // Check to see if the outcome column was even visible.
5949 $outcomecolpresent = optional_param($paramname, false, PARAM_FLOAT
) !== false;
5950 if ($outcomecolpresent && ($oldoutcome != $newoutcome)) {
5951 // Can't check modified time for outcomes because it is not reported.
5952 $modifiedusers[$modified->userid
] = $modified;
5958 // Let plugins participate.
5959 foreach ($this->feedbackplugins
as $plugin) {
5960 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
5961 // The plugins must handle is_quickgrading_modified correctly - ie
5962 // handle hidden columns.
5963 if ($plugin->is_quickgrading_modified($modified->userid
, $grade)) {
5964 if ((int)$current->lastmodified
> (int)$modified->lastmodified
) {
5965 return get_string('errorrecordmodified', 'assign');
5967 $modifiedusers[$modified->userid
] = $modified;
5974 if (($current->grade
< 0 ||
$current->grade
=== null) &&
5975 ($modified->grade
< 0 ||
$modified->grade
=== null)) {
5976 // Different ways to indicate no grade.
5977 $modified->grade
= $current->grade
; // Keep existing grade.
5979 // Treat 0 and null as different values.
5980 if ($current->grade
!== null) {
5981 $current->grade
= floatval($current->grade
);
5983 $gradechanged = $gradecolpresent && $current->grade
!== $modified->grade
;
5984 $markingallocationchanged = $this->get_instance()->markingworkflow
&&
5985 $this->get_instance()->markingallocation
&&
5986 ($modified->allocatedmarker
!== false) &&
5987 ($current->allocatedmarker
!= $modified->allocatedmarker
);
5988 $workflowstatechanged = $this->get_instance()->markingworkflow
&&
5989 ($modified->workflowstate
!== false) &&
5990 ($current->workflowstate
!= $modified->workflowstate
);
5991 if ($gradechanged ||
$markingallocationchanged ||
$workflowstatechanged) {
5993 if ($this->grading_disabled($modified->userid
)) {
5996 $badmodified = (int)$current->lastmodified
> (int)$modified->lastmodified
;
5997 $badattempt = (int)$current->attemptnumber
!= (int)$modified->attemptnumber
;
5998 if ($badmodified ||
$badattempt) {
5999 // Error - record has been modified since viewing the page.
6000 return get_string('errorrecordmodified', 'assign');
6002 $modifiedusers[$modified->userid
] = $modified;
6007 $currentgrades->close();
6009 $adminconfig = $this->get_admin_config();
6010 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook
;
6012 // Ok - ready to process the updates.
6013 foreach ($modifiedusers as $userid => $modified) {
6014 $grade = $this->get_user_grade($userid, true);
6015 $flags = $this->get_user_flags($userid, true);
6016 $grade->grade
= grade_floatval(unformat_float($modified->grade
));
6017 $grade->grader
= $USER->id
;
6018 $gradecolpresent = optional_param('quickgrade_' . $userid, false, PARAM_INT
) !== false;
6020 // Save plugins data.
6021 foreach ($this->feedbackplugins
as $plugin) {
6022 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
6023 $plugin->save_quickgrading_changes($userid, $grade);
6024 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
6025 // This is the feedback plugin chose to push comments to the gradebook.
6026 $grade->feedbacktext
= $plugin->text_for_gradebook($grade);
6027 $grade->feedbackformat
= $plugin->format_for_gradebook($grade);
6032 // These will be set to false if they are not present in the quickgrading
6033 // form (e.g. column hidden).
6034 $workflowstatemodified = ($modified->workflowstate
!== false) &&
6035 ($flags->workflowstate
!= $modified->workflowstate
);
6037 $allocatedmarkermodified = ($modified->allocatedmarker
!== false) &&
6038 ($flags->allocatedmarker
!= $modified->allocatedmarker
);
6040 if ($workflowstatemodified) {
6041 $flags->workflowstate
= $modified->workflowstate
;
6043 if ($allocatedmarkermodified) {
6044 $flags->allocatedmarker
= $modified->allocatedmarker
;
6046 if ($workflowstatemodified ||
$allocatedmarkermodified) {
6047 if ($this->update_user_flags($flags) && $workflowstatemodified) {
6048 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
6049 \mod_assign\event\workflow_state_updated
::create_from_user($this, $user, $flags->workflowstate
)->trigger();
6052 $this->update_grade($grade);
6054 // Allow teachers to skip sending notifications.
6055 if (optional_param('sendstudentnotifications', true, PARAM_BOOL
)) {
6056 $this->notify_grade_modified($grade, true);
6060 if ($CFG->enableoutcomes
) {
6062 foreach ($modified->gradinginfo
->outcomes
as $outcomeid => $outcome) {
6063 $oldoutcome = $outcome->grades
[$modified->userid
]->grade
;
6064 $paramname = 'outcome_' . $outcomeid . '_' . $modified->userid
;
6065 // This will be false if the input was not in the quickgrading
6066 // form (e.g. column hidden).
6067 $newoutcome = optional_param($paramname, false, PARAM_INT
);
6068 if ($newoutcome !== false && ($oldoutcome != $newoutcome)) {
6069 $data[$outcomeid] = $newoutcome;
6072 if (count($data) > 0) {
6073 grade_update_outcomes('mod/assign',
6077 $this->get_instance()->id
,
6084 return get_string('quickgradingchangessaved', 'assign');
6088 * Reveal student identities to markers (and the gradebook).
6092 public function reveal_identities() {
6095 require_capability('mod/assign:revealidentities', $this->context
);
6097 if ($this->get_instance()->revealidentities ||
empty($this->get_instance()->blindmarking
)) {
6101 // Update the assignment record.
6102 $update = new stdClass();
6103 $update->id
= $this->get_instance()->id
;
6104 $update->revealidentities
= 1;
6105 $DB->update_record('assign', $update);
6107 // Refresh the instance data.
6108 $this->instance
= null;
6110 // Release the grades to the gradebook.
6111 // First create the column in the gradebook.
6112 $this->update_gradebook(false, $this->get_course_module()->id
);
6114 // Now release all grades.
6116 $adminconfig = $this->get_admin_config();
6117 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook
;
6118 $gradebookplugin = str_replace('assignfeedback_', '', $gradebookplugin);
6119 $grades = $DB->get_records('assign_grades', array('assignment'=>$this->get_instance()->id
));
6121 $plugin = $this->get_feedback_plugin_by_type($gradebookplugin);
6123 foreach ($grades as $grade) {
6124 // Fetch any comments for this student.
6125 if ($plugin && $plugin->is_enabled() && $plugin->is_visible()) {
6126 $grade->feedbacktext
= $plugin->text_for_gradebook($grade);
6127 $grade->feedbackformat
= $plugin->format_for_gradebook($grade);
6129 $this->gradebook_item_update(null, $grade);
6132 \mod_assign\event\identities_revealed
::create_from_assign($this)->trigger();
6136 * Reveal student identities to markers (and the gradebook).
6140 protected function process_reveal_identities() {
6142 if (!confirm_sesskey()) {
6146 return $this->reveal_identities();
6151 * Save grading options.
6155 protected function process_save_grading_options() {
6158 // Include grading options form.
6159 require_once($CFG->dirroot
. '/mod/assign/gradingoptionsform.php');
6161 // Need submit permission to submit an assignment.
6162 $this->require_view_grades();
6165 // Is advanced grading enabled?
6166 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
6167 $controller = $gradingmanager->get_active_controller();
6168 $showquickgrading = empty($controller);
6169 if (!is_null($this->context
)) {
6170 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context
);
6172 $showonlyactiveenrolopt = false;
6175 $markingallocation = $this->get_instance()->markingworkflow
&&
6176 $this->get_instance()->markingallocation
&&
6177 has_capability('mod/assign:manageallocations', $this->context
);
6178 // Get markers to use in drop lists.
6179 $markingallocationoptions = array();
6180 if ($markingallocation) {
6181 $markingallocationoptions[''] = get_string('filternone', 'assign');
6182 $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER
] = get_string('markerfilternomarker', 'assign');
6183 list($sort, $params) = users_order_by_sql();
6184 $markers = get_users_by_capability($this->context
, 'mod/assign:grade', '', $sort);
6185 foreach ($markers as $marker) {
6186 $markingallocationoptions[$marker->id
] = fullname($marker);
6190 // Get marking states to show in form.
6191 $markingworkflowoptions = array();
6192 if ($this->get_instance()->markingworkflow
) {
6193 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
6194 $markingworkflowoptions[''] = get_string('filternone', 'assign');
6195 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED
] = $notmarked;
6196 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
6199 $gradingoptionsparams = array('cm'=>$this->get_course_module()->id
,
6200 'contextid'=>$this->context
->id
,
6201 'userid'=>$USER->id
,
6202 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
6203 'showquickgrading'=>$showquickgrading,
6204 'quickgrading'=>false,
6205 'markingworkflowopt' => $markingworkflowoptions,
6206 'markingallocationopt' => $markingallocationoptions,
6207 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
6208 'showonlyactiveenrol' => $this->show_only_active_users(),
6209 'downloadasfolders' => get_user_preferences('assign_downloadasfolders', 1));
6210 $mform = new mod_assign_grading_options_form(null, $gradingoptionsparams);
6211 if ($formdata = $mform->get_data()) {
6212 set_user_preference('assign_perpage', $formdata->perpage
);
6213 if (isset($formdata->filter
)) {
6214 set_user_preference('assign_filter', $formdata->filter
);
6216 if (isset($formdata->markerfilter
)) {
6217 set_user_preference('assign_markerfilter', $formdata->markerfilter
);
6219 if (isset($formdata->workflowfilter
)) {
6220 set_user_preference('assign_workflowfilter', $formdata->workflowfilter
);
6222 if ($showquickgrading) {
6223 set_user_preference('assign_quickgrading', isset($formdata->quickgrading
));
6225 if (isset($formdata->downloadasfolders
)) {
6226 set_user_preference('assign_downloadasfolders', 1); // Enabled.
6228 set_user_preference('assign_downloadasfolders', 0); // Disabled.
6230 if (!empty($showonlyactiveenrolopt)) {
6231 $showonlyactiveenrol = isset($formdata->showonlyactiveenrol
);
6232 set_user_preference('grade_report_showonlyactiveenrol', $showonlyactiveenrol);
6233 $this->showonlyactiveenrol
= $showonlyactiveenrol;
6239 * Take a grade object and print a short summary for the log file.
6240 * The size limit for the log file is 255 characters, so be careful not
6241 * to include too much information.
6243 * @deprecated since 2.7
6245 * @param stdClass $grade
6248 public function format_grade_for_log(stdClass
$grade) {
6251 $user = $DB->get_record('user', array('id' => $grade->userid
), '*', MUST_EXIST
);
6253 $info = get_string('gradestudent', 'assign', array('id'=>$user->id
, 'fullname'=>fullname($user)));
6254 if ($grade->grade
!= '') {
6255 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade
, false) . '. ';
6257 $info .= get_string('nograde', 'assign');
6263 * Take a submission object and print a short summary for the log file.
6264 * The size limit for the log file is 255 characters, so be careful not
6265 * to include too much information.
6267 * @deprecated since 2.7
6269 * @param stdClass $submission
6272 public function format_submission_for_log(stdClass
$submission) {
6276 if ($submission->userid
) {
6277 $user = $DB->get_record('user', array('id' => $submission->userid
), '*', MUST_EXIST
);
6278 $name = fullname($user);
6280 $group = $this->get_submission_group($submission->userid
);
6282 $name = $group->name
;
6284 $name = get_string('defaultteam', 'assign');
6287 $status = get_string('submissionstatus_' . $submission->status
, 'assign');
6288 $params = array('id'=>$submission->userid
, 'fullname'=>$name, 'status'=>$status);
6289 $info .= get_string('submissionlog', 'assign', $params) . ' <br>';
6291 foreach ($this->submissionplugins
as $plugin) {
6292 if ($plugin->is_enabled() && $plugin->is_visible()) {
6293 $info .= '<br>' . $plugin->format_for_log($submission);
6301 * Require a valid sess key and then call copy_previous_attempt.
6303 * @param array $notices Any error messages that should be shown
6304 * to the user at the top of the edit submission form.
6307 protected function process_copy_previous_attempt(&$notices) {
6310 return $this->copy_previous_attempt($notices);
6314 * Copy the current assignment submission from the last submitted attempt.
6316 * @param array $notices Any error messages that should be shown
6317 * to the user at the top of the edit submission form.
6320 public function copy_previous_attempt(&$notices) {
6323 require_capability('mod/assign:submit', $this->context
);
6325 $instance = $this->get_instance();
6326 if ($instance->teamsubmission
) {
6327 $submission = $this->get_group_submission($USER->id
, 0, true);
6329 $submission = $this->get_user_submission($USER->id
, true);
6331 if (!$submission ||
$submission->status
!= ASSIGN_SUBMISSION_STATUS_REOPENED
) {
6332 $notices[] = get_string('submissionnotcopiedinvalidstatus', 'assign');
6335 $flags = $this->get_user_flags($USER->id
, false);
6337 // Get the flags to check if it is locked.
6338 if ($flags && $flags->locked
) {
6339 $notices[] = get_string('submissionslocked', 'assign');
6342 if ($instance->submissiondrafts
) {
6343 $submission->status
= ASSIGN_SUBMISSION_STATUS_DRAFT
;
6345 $submission->status
= ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
6347 $this->update_submission($submission, $USER->id
, true, $instance->teamsubmission
);
6349 // Find the previous submission.
6350 if ($instance->teamsubmission
) {
6351 $previoussubmission = $this->get_group_submission($USER->id
, 0, true, $submission->attemptnumber
- 1);
6353 $previoussubmission = $this->get_user_submission($USER->id
, true, $submission->attemptnumber
- 1);
6356 if (!$previoussubmission) {
6357 // There was no previous submission so there is nothing else to do.
6361 $pluginerror = false;
6362 foreach ($this->get_submission_plugins() as $plugin) {
6363 if ($plugin->is_visible() && $plugin->is_enabled()) {
6364 if (!$plugin->copy_submission($previoussubmission, $submission)) {
6365 $notices[] = $plugin->get_error();
6366 $pluginerror = true;
6374 \mod_assign\event\submission_duplicated
::create_from_submission($this, $submission)->trigger();
6376 $complete = COMPLETION_INCOMPLETE
;
6377 if ($submission->status
== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
6378 $complete = COMPLETION_COMPLETE
;
6380 $completion = new completion_info($this->get_course());
6381 if ($completion->is_enabled($this->get_course_module()) && $instance->completionsubmit
) {
6382 $this->update_activity_completion_records($instance->teamsubmission
,
6383 $instance->requireallteammemberssubmit
,
6390 if (!$instance->submissiondrafts
) {
6391 // There is a case for not notifying the student about the submission copy,
6392 // but it provides a record of the event and if they then cancel editing it
6393 // is clear that the submission was copied.
6394 $this->notify_student_submission_copied($submission);
6395 $this->notify_graders($submission);
6397 // The same logic applies here - we could not notify teachers,
6398 // but then they would wonder why there are submitted assignments
6399 // and they haven't been notified.
6400 \mod_assign\event\assessable_submitted
::create_from_submission($this, $submission, true)->trigger();
6406 * Determine if the current submission is empty or not.
6408 * @param submission $submission the students submission record to check.
6411 public function submission_empty($submission) {
6414 foreach ($this->submissionplugins
as $plugin) {
6415 if ($plugin->is_enabled() && $plugin->is_visible()) {
6416 if (!$allempty ||
!$plugin->is_empty($submission)) {
6425 * Determine if a new submission is empty or not
6427 * @param stdClass $data Submission data
6430 public function new_submission_empty($data) {
6431 foreach ($this->submissionplugins
as $plugin) {
6432 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions() &&
6433 !$plugin->submission_is_empty($data)) {
6441 * Save assignment submission for the current user.
6443 * @param stdClass $data
6444 * @param array $notices Any error messages that should be shown
6448 public function save_submission(stdClass
$data, & $notices) {
6449 global $CFG, $USER, $DB;
6451 $userid = $USER->id
;
6452 if (!empty($data->userid
)) {
6453 $userid = $data->userid
;
6456 $user = clone($USER);
6457 if ($userid == $USER->id
) {
6458 require_capability('mod/assign:submit', $this->context
);
6460 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
6461 if (!$this->can_edit_submission($userid, $USER->id
)) {
6462 print_error('nopermission');
6465 $instance = $this->get_instance();
6467 if ($instance->teamsubmission
) {
6468 $submission = $this->get_group_submission($userid, 0, true);
6470 $submission = $this->get_user_submission($userid, true);
6473 if ($this->new_submission_empty($data)) {
6474 $notices[] = get_string('submissionempty', 'mod_assign');
6478 // Check that no one has modified the submission since we started looking at it.
6479 if (isset($data->lastmodified
) && ($submission->timemodified
> $data->lastmodified
)) {
6480 // Another user has submitted something. Notify the current user.
6481 if ($submission->status
!== ASSIGN_SUBMISSION_STATUS_NEW
) {
6482 $notices[] = $instance->teamsubmission ?
get_string('submissionmodifiedgroup', 'mod_assign')
6483 : get_string('submissionmodified', 'mod_assign');
6488 if ($instance->submissiondrafts
) {
6489 $submission->status
= ASSIGN_SUBMISSION_STATUS_DRAFT
;
6491 $submission->status
= ASSIGN_SUBMISSION_STATUS_SUBMITTED
;
6494 $flags = $this->get_user_flags($userid, false);
6496 // Get the flags to check if it is locked.
6497 if ($flags && $flags->locked
) {
6498 print_error('submissionslocked', 'assign');
6502 $pluginerror = false;
6503 foreach ($this->submissionplugins
as $plugin) {
6504 if ($plugin->is_enabled() && $plugin->is_visible()) {
6505 if (!$plugin->save($submission, $data)) {
6506 $notices[] = $plugin->get_error();
6507 $pluginerror = true;
6512 $allempty = $this->submission_empty($submission);
6513 if ($pluginerror ||
$allempty) {
6515 $notices[] = get_string('submissionempty', 'mod_assign');
6520 $this->update_submission($submission, $userid, true, $instance->teamsubmission
);
6522 if ($instance->teamsubmission
&& !$instance->requireallteammemberssubmit
) {
6523 $team = $this->get_submission_group_members($submission->groupid
, true);
6525 foreach ($team as $member) {
6526 if ($member->id
!= $userid) {
6527 $membersubmission = clone($submission);
6528 $this->update_submission($membersubmission, $member->id
, true, $instance->teamsubmission
);
6534 if (isset($data->submissionstatement
) && ($userid == $USER->id
)) {
6535 \mod_assign\event\statement_accepted
::create_from_submission($this, $submission)->trigger();
6538 $complete = COMPLETION_INCOMPLETE
;
6539 if ($submission->status
== ASSIGN_SUBMISSION_STATUS_SUBMITTED
) {
6540 $complete = COMPLETION_COMPLETE
;
6542 $completion = new completion_info($this->get_course());
6543 if ($completion->is_enabled($this->get_course_module()) && $instance->completionsubmit
) {
6544 $completion->update_state($this->get_course_module(), $complete, $userid);
6547 if (!$instance->submissiondrafts
) {
6548 $this->notify_student_submission_receipt($submission);
6549 $this->notify_graders($submission);
6550 \mod_assign\event\assessable_submitted
::create_from_submission($this, $submission, true)->trigger();
6556 * Save assignment submission.
6558 * @param moodleform $mform
6559 * @param array $notices Any error messages that should be shown
6560 * to the user at the top of the edit submission form.
6563 protected function process_save_submission(&$mform, &$notices) {
6566 // Include submission form.
6567 require_once($CFG->dirroot
. '/mod/assign/submission_form.php');
6569 $userid = optional_param('userid', $USER->id
, PARAM_INT
);
6570 // Need submit permission to submit an assignment.
6572 if (!$this->submissions_open($userid)) {
6573 $notices[] = get_string('duedatereached', 'assign');
6576 $instance = $this->get_instance();
6578 $data = new stdClass();
6579 $data->userid
= $userid;
6580 $mform = new mod_assign_submission_form(null, array($this, $data));
6581 if ($mform->is_cancelled()) {
6584 if ($data = $mform->get_data()) {
6585 return $this->save_submission($data, $notices);
6592 * Determine if this users grade can be edited.
6594 * @param int $userid - The student userid
6595 * @param bool $checkworkflow - whether to include a check for the workflow state.
6596 * @return bool $gradingdisabled
6598 public function grading_disabled($userid, $checkworkflow=true) {
6600 if ($checkworkflow && $this->get_instance()->markingworkflow
) {
6601 $grade = $this->get_user_grade($userid, false);
6602 $validstates = $this->get_marking_workflow_states_for_current_user();
6603 if (!empty($grade) && !empty($grade->workflowstate
) && !array_key_exists($grade->workflowstate
, $validstates)) {
6607 $gradinginfo = grade_get_grades($this->get_course()->id
,
6610 $this->get_instance()->id
,
6612 if (!$gradinginfo) {
6616 if (!isset($gradinginfo->items
[0]->grades
[$userid])) {
6619 $gradingdisabled = $gradinginfo->items
[0]->grades
[$userid]->locked ||
6620 $gradinginfo->items
[0]->grades
[$userid]->overridden
;
6621 return $gradingdisabled;
6626 * Get an instance of a grading form if advanced grading is enabled.
6627 * This is specific to the assignment, marker and student.
6629 * @param int $userid - The student userid
6630 * @param stdClass|false $grade - The grade record
6631 * @param bool $gradingdisabled
6632 * @return mixed gradingform_instance|null $gradinginstance
6634 protected function get_grading_instance($userid, $grade, $gradingdisabled) {
6637 $grademenu = make_grades_menu($this->get_instance()->grade
);
6638 $allowgradedecimals = $this->get_instance()->grade
> 0;
6640 $advancedgradingwarning = false;
6641 $gradingmanager = get_grading_manager($this->context
, 'mod_assign', 'submissions');
6642 $gradinginstance = null;
6643 if ($gradingmethod = $gradingmanager->get_active_method()) {
6644 $controller = $gradingmanager->get_controller($gradingmethod);
6645 if ($controller->is_form_available()) {
6648 $itemid = $grade->id
;
6650 if ($gradingdisabled && $itemid) {
6651 $gradinginstance = $controller->get_current_instance($USER->id
, $itemid);
6652 } else if (!$gradingdisabled) {
6653 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT
);
6654 $gradinginstance = $controller->get_or_create_instance($instanceid,
6659 $advancedgradingwarning = $controller->form_unavailable_notification();
6662 if ($gradinginstance) {
6663 $gradinginstance->get_controller()->set_grade_range($grademenu, $allowgradedecimals);
6665 return $gradinginstance;
6669 * Add elements to grade form.
6671 * @param MoodleQuickForm $mform
6672 * @param stdClass $data
6673 * @param array $params
6676 public function add_grade_form_elements(MoodleQuickForm
$mform, stdClass
$data, $params) {
6677 global $USER, $CFG, $SESSION;
6678 $settings = $this->get_instance();
6680 $rownum = isset($params['rownum']) ?
$params['rownum'] : 0;
6681 $last = isset($params['last']) ?
$params['last'] : true;
6682 $useridlistid = isset($params['useridlistid']) ?
$params['useridlistid'] : 0;
6683 $userid = isset($params['userid']) ?
$params['userid'] : 0;
6684 $attemptnumber = isset($params['attemptnumber']) ?
$params['attemptnumber'] : 0;
6685 $gradingpanel = !empty($params['gradingpanel']);
6686 $bothids = ($userid && $useridlistid);
6688 if (!$userid ||
$bothids) {
6689 $useridlistkey = $this->get_useridlist_key($useridlistid);
6690 if (empty($SESSION->mod_assign_useridlist
[$useridlistkey])) {
6691 $SESSION->mod_assign_useridlist
[$useridlistkey] = $this->get_grading_userid_list();
6693 $useridlist = $SESSION->mod_assign_useridlist
[$useridlistkey];
6695 $useridlist = array($userid);
6700 $userid = $useridlist[$rownum];
6701 // We need to create a grade record matching this attempt number
6702 // or the feedback plugin will have no way to know what is the correct attempt.
6703 $grade = $this->get_user_grade($userid, true, $attemptnumber);
6706 if ($this->get_instance()->teamsubmission
) {
6707 $submission = $this->get_group_submission($userid, 0, false, $attemptnumber);
6709 $submission = $this->get_user_submission($userid, false, $attemptnumber);
6712 // Add advanced grading.
6713 $gradingdisabled = $this->grading_disabled($userid);
6714 $gradinginstance = $this->get_grading_instance($userid, $grade, $gradingdisabled);
6716 $mform->addElement('header', 'gradeheader', get_string('grade'));
6717 if ($gradinginstance) {
6718 $gradingelement = $mform->addElement('grading',
6720 get_string('grade').':',
6721 array('gradinginstance' => $gradinginstance));
6722 if ($gradingdisabled) {
6723 $gradingelement->freeze();
6725 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
6726 $mform->setType('advancedgradinginstanceid', PARAM_INT
);
6729 // Use simple direct grading.
6730 if ($this->get_instance()->grade
> 0) {
6731 $name = get_string('gradeoutof', 'assign', $this->get_instance()->grade
);
6732 if (!$gradingdisabled) {
6733 $gradingelement = $mform->addElement('text', 'grade', $name);
6734 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
6735 $mform->setType('grade', PARAM_RAW
);
6737 $mform->addElement('hidden', 'grade', $name);
6738 $mform->hardFreeze('grade');
6739 $mform->setType('grade', PARAM_RAW
);
6740 $strgradelocked = get_string('gradelocked', 'assign');
6741 $mform->addElement('static', 'gradedisabled', $name, $strgradelocked);
6742 $mform->addHelpButton('gradedisabled', 'gradeoutofhelp', 'assign');
6745 $grademenu = array(-1 => get_string("nograde")) +
make_grades_menu($this->get_instance()->grade
);
6746 if (count($grademenu) > 1) {
6747 $gradingelement = $mform->addElement('select', 'grade', get_string('grade') . ':', $grademenu);
6749 // The grade is already formatted with format_float so it needs to be converted back to an integer.
6750 if (!empty($data->grade
)) {
6751 $data->grade
= (int)unformat_float($data->grade
);
6753 $mform->setType('grade', PARAM_INT
);
6754 if ($gradingdisabled) {
6755 $gradingelement->freeze();
6761 $gradinginfo = grade_get_grades($this->get_course()->id
,
6764 $this->get_instance()->id
,
6766 if (!empty($CFG->enableoutcomes
)) {
6767 foreach ($gradinginfo->outcomes
as $index => $outcome) {
6768 $options = make_grades_menu(-$outcome->scaleid
);
6769 if ($outcome->grades
[$userid]->locked
) {
6770 $options[0] = get_string('nooutcome', 'grades');
6771 $mform->addElement('static',
6772 'outcome_' . $index . '[' . $userid . ']',
6773 $outcome->name
. ':',
6774 $options[$outcome->grades
[$userid]->grade
]);
6776 $options[''] = get_string('nooutcome', 'grades');
6777 $attributes = array('id' => 'menuoutcome_' . $index );
6778 $mform->addElement('select',
6779 'outcome_' . $index . '[' . $userid . ']',
6783 $mform->setType('outcome_' . $index . '[' . $userid . ']', PARAM_INT
);
6784 $mform->setDefault('outcome_' . $index . '[' . $userid . ']',
6785 $outcome->grades
[$userid]->grade
);
6790 $capabilitylist = array('gradereport/grader:view', 'moodle/grade:viewall');
6791 if (has_all_capabilities($capabilitylist, $this->get_course_context())) {
6792 $urlparams = array('id'=>$this->get_course()->id
);
6793 $url = new moodle_url('/grade/report/grader/index.php', $urlparams);
6795 if (isset($gradinginfo->items
[0]->grades
[$userid]->str_grade
)) {
6796 $usergrade = $gradinginfo->items
[0]->grades
[$userid]->str_grade
;
6798 $gradestring = $this->get_renderer()->action_link($url, $usergrade);
6801 if (isset($gradinginfo->items
[0]->grades
[$userid]) &&
6802 !$gradinginfo->items
[0]->grades
[$userid]->hidden
) {
6803 $usergrade = $gradinginfo->items
[0]->grades
[$userid]->str_grade
;
6805 $gradestring = $usergrade;
6808 if ($this->get_instance()->markingworkflow
) {
6809 $states = $this->get_marking_workflow_states_for_current_user();
6810 $options = array('' => get_string('markingworkflowstatenotmarked', 'assign')) +
$states;
6811 $mform->addElement('select', 'workflowstate', get_string('markingworkflowstate', 'assign'), $options);
6812 $mform->addHelpButton('workflowstate', 'markingworkflowstate', 'assign');
6815 if ($this->get_instance()->markingworkflow
&&
6816 $this->get_instance()->markingallocation
&&
6817 has_capability('mod/assign:manageallocations', $this->context
)) {
6819 list($sort, $params) = users_order_by_sql();
6820 $markers = get_users_by_capability($this->context
, 'mod/assign:grade', '', $sort);
6821 $markerlist = array('' => get_string('choosemarker', 'assign'));
6822 foreach ($markers as $marker) {
6823 $markerlist[$marker->id
] = fullname($marker);
6825 $mform->addElement('select', 'allocatedmarker', get_string('allocatedmarker', 'assign'), $markerlist);
6826 $mform->addHelpButton('allocatedmarker', 'allocatedmarker', 'assign');
6827 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW
);
6828 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW
);
6829 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE
);
6830 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
);
6832 $gradestring = '<span class="currentgrade">' . $gradestring . '</span>';
6833 $mform->addElement('static', 'currentgrade', get_string('currentgrade', 'assign'), $gradestring);
6835 if (count($useridlist) > 1) {
6836 $strparams = array('current'=>$rownum+
1, 'total'=>count($useridlist));
6837 $name = get_string('outof', 'assign', $strparams);
6838 $mform->addElement('static', 'gradingstudent', get_string('gradingstudent', 'assign'), $name);
6841 // Let feedback plugins add elements to the grading form.
6842 $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
6845 $mform->addElement('hidden', 'id', $this->get_course_module()->id
);
6846 $mform->setType('id', PARAM_INT
);
6847 $mform->addElement('hidden', 'rownum', $rownum);
6848 $mform->setType('rownum', PARAM_INT
);
6849 $mform->setConstant('rownum', $rownum);
6850 $mform->addElement('hidden', 'useridlistid', $useridlistid);
6851 $mform->setType('useridlistid', PARAM_ALPHANUM
);
6852 $mform->addElement('hidden', 'attemptnumber', $attemptnumber);
6853 $mform->setType('attemptnumber', PARAM_INT
);
6854 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT
));
6855 $mform->setType('ajax', PARAM_INT
);
6856 $mform->addElement('hidden', 'userid', optional_param('userid', 0, PARAM_INT
));
6857 $mform->setType('userid', PARAM_INT
);
6859 if ($this->get_instance()->teamsubmission
) {
6860 $mform->addElement('header', 'groupsubmissionsettings', get_string('groupsubmissionsettings', 'assign'));
6861 $mform->addElement('selectyesno', 'applytoall', get_string('applytoteam', 'assign'));
6862 $mform->setDefault('applytoall', 1);
6865 // Do not show if we are editing a previous attempt.
6866 if ($attemptnumber == -1 && $this->get_instance()->attemptreopenmethod
!= ASSIGN_ATTEMPT_REOPEN_METHOD_NONE
) {
6867 $mform->addElement('header', 'attemptsettings', get_string('attemptsettings', 'assign'));
6868 $attemptreopenmethod = get_string('attemptreopenmethod_' . $this->get_instance()->attemptreopenmethod
, 'assign');
6869 $mform->addElement('static', 'attemptreopenmethod', get_string('attemptreopenmethod', 'assign'), $attemptreopenmethod);
6873 $attemptnumber = $submission->attemptnumber
;
6875 $maxattempts = $this->get_instance()->maxattempts
;
6876 if ($maxattempts == ASSIGN_UNLIMITED_ATTEMPTS
) {
6877 $maxattempts = get_string('unlimitedattempts', 'assign');
6879 $mform->addelement('static', 'maxattemptslabel', get_string('maxattempts', 'assign'), $maxattempts);
6880 $mform->addelement('static', 'attemptnumberlabel', get_string('attemptnumber', 'assign'), $attemptnumber +
1);
6882 $ismanual = $this->get_instance()->attemptreopenmethod
== ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL
;
6883 $issubmission = !empty($submission);
6884 $isunlimited = $this->get_instance()->maxattempts
== ASSIGN_UNLIMITED_ATTEMPTS
;
6885 $islessthanmaxattempts = $issubmission && ($submission->attemptnumber
< ($this->get_instance()->maxattempts
-1));
6887 if ($ismanual && (!$issubmission ||
$isunlimited ||
$islessthanmaxattempts)) {
6888 $mform->addElement('selectyesno', 'addattempt', get_string('addattempt', 'assign'));
6889 $mform->setDefault('addattempt', 0);
6892 if (!$gradingpanel) {
6893 $mform->addElement('selectyesno', 'sendstudentnotifications', get_string('sendstudentnotifications', 'assign'));
6895 $mform->addElement('hidden', 'sendstudentnotifications', get_string('sendstudentnotifications', 'assign'));
6896 $mform->setType('sendstudentnotifications', PARAM_BOOL
);
6898 // Get assignment visibility information for student.
6899 $modinfo = get_fast_modinfo($settings->course
, $userid);
6900 $cm = $modinfo->get_cm($this->get_course_module()->id
);
6902 // Don't allow notification to be sent if the student can't access the assignment,
6903 // or until in "Released" state if using marking workflow.
6904 if (!$cm->uservisible
) {
6905 $mform->setDefault('sendstudentnotifications', 0);
6906 $mform->freeze('sendstudentnotifications');
6907 } else if ($this->get_instance()->markingworkflow
) {
6908 $mform->setDefault('sendstudentnotifications', 0);
6909 $mform->disabledIf('sendstudentnotifications', 'workflowstate', 'neq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
);
6911 $mform->setDefault('sendstudentnotifications', $this->get_instance()->sendstudentnotifications
);
6914 $mform->addElement('hidden', 'action', 'submitgrade');
6915 $mform->setType('action', PARAM_ALPHA
);
6917 if (!$gradingpanel) {
6919 $buttonarray = array();
6920 $name = get_string('savechanges', 'assign');
6921 $buttonarray[] = $mform->createElement('submit', 'savegrade', $name);
6923 $name = get_string('savenext', 'assign');
6924 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', $name);
6926 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
6927 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
6928 $mform->closeHeaderBefore('buttonar');
6929 $buttonarray = array();
6932 $name = get_string('previous', 'assign');
6933 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', $name);
6937 $name = get_string('nosavebutnext', 'assign');
6938 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', $name);
6940 if (!empty($buttonarray)) {
6941 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
6944 // The grading form does not work well with shortforms.
6945 $mform->setDisableShortforms();
6949 * Add elements in submission plugin form.
6951 * @param mixed $submission stdClass|null
6952 * @param MoodleQuickForm $mform
6953 * @param stdClass $data
6954 * @param int $userid The current userid (same as $USER->id)
6957 protected function add_plugin_submission_elements($submission,
6958 MoodleQuickForm
$mform,
6961 foreach ($this->submissionplugins
as $plugin) {
6962 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
6963 $plugin->get_form_elements_for_user($submission, $mform, $data, $userid);
6969 * Check if feedback plugins installed are enabled.
6973 public function is_any_feedback_plugin_enabled() {
6974 if (!isset($this->cache
['any_feedback_plugin_enabled'])) {
6975 $this->cache
['any_feedback_plugin_enabled'] = false;
6976 foreach ($this->feedbackplugins
as $plugin) {
6977 if ($plugin->is_enabled() && $plugin->is_visible()) {
6978 $this->cache
['any_feedback_plugin_enabled'] = true;
6984 return $this->cache
['any_feedback_plugin_enabled'];
6989 * Check if submission plugins installed are enabled.
6993 public function is_any_submission_plugin_enabled() {
6994 if (!isset($this->cache
['any_submission_plugin_enabled'])) {
6995 $this->cache
['any_submission_plugin_enabled'] = false;
6996 foreach ($this->submissionplugins
as $plugin) {
6997 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
6998 $this->cache
['any_submission_plugin_enabled'] = true;
7004 return $this->cache
['any_submission_plugin_enabled'];
7009 * Add elements to submission form.
7010 * @param MoodleQuickForm $mform
7011 * @param stdClass $data
7014 public function add_submission_form_elements(MoodleQuickForm
$mform, stdClass
$data) {
7017 $userid = $data->userid
;
7018 // Team submissions.
7019 if ($this->get_instance()->teamsubmission
) {
7020 $submission = $this->get_group_submission($userid, 0, false);
7022 $submission = $this->get_user_submission($userid, false);
7025 // Submission statement.
7026 $adminconfig = $this->get_admin_config();
7028 $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement
&&
7029 !empty($adminconfig->submissionstatement
);
7031 $draftsenabled = $this->get_instance()->submissiondrafts
;
7033 // Only show submission statement if we are editing our own submission.
7034 if ($requiresubmissionstatement && !$draftsenabled && $userid == $USER->id
) {
7036 $submissionstatement = '';
7037 if (!empty($adminconfig->submissionstatement
)) {
7038 // Format the submission statement before its sent. We turn off para because this is going within
7041 'context' => $this->get_context(),
7044 $submissionstatement = format_text($adminconfig->submissionstatement
, FORMAT_MOODLE
, $options);
7046 $mform->addElement('checkbox', 'submissionstatement', '', $submissionstatement);
7047 $mform->addRule('submissionstatement', get_string('required'), 'required', null, 'client');
7050 $this->add_plugin_submission_elements($submission, $mform, $data, $userid);
7053 $mform->addElement('hidden', 'id', $this->get_course_module()->id
);
7054 $mform->setType('id', PARAM_INT
);
7056 $mform->addElement('hidden', 'userid', $userid);
7057 $mform->setType('userid', PARAM_INT
);
7059 $mform->addElement('hidden', 'action', 'savesubmission');
7060 $mform->setType('action', PARAM_TEXT
);
7066 * @param int $userid
7069 public function revert_to_draft($userid) {
7072 // Need grade permission.
7073 require_capability('mod/assign:grade', $this->context
);
7075 if ($this->get_instance()->teamsubmission
) {
7076 $submission = $this->get_group_submission($userid, 0, false);
7078 $submission = $this->get_user_submission($userid, false);
7084 $submission->status
= ASSIGN_SUBMISSION_STATUS_DRAFT
;
7085 $this->update_submission($submission, $userid, true, $this->get_instance()->teamsubmission
);
7087 // Give each submission plugin a chance to process the reverting to draft.
7088 $plugins = $this->get_submission_plugins();
7089 foreach ($plugins as $plugin) {
7090 if ($plugin->is_enabled() && $plugin->is_visible()) {
7091 $plugin->revert_to_draft($submission);
7094 // Update the modified time on the grade (grader modified).
7095 $grade = $this->get_user_grade($userid, true);
7096 $grade->grader
= $USER->id
;
7097 $this->update_grade($grade);
7099 $completion = new completion_info($this->get_course());
7100 if ($completion->is_enabled($this->get_course_module()) &&
7101 $this->get_instance()->completionsubmit
) {
7102 $completion->update_state($this->get_course_module(), COMPLETION_INCOMPLETE
, $userid);
7104 \mod_assign\event\submission_status_updated
::create_from_submission($this, $submission)->trigger();
7110 * Uses url parameter userid if userid not supplied as a parameter.
7112 * @param int $userid
7115 protected function process_revert_to_draft($userid = 0) {
7119 $userid = required_param('userid', PARAM_INT
);
7122 return $this->revert_to_draft($userid);
7126 * Prevent student updates to this submission
7128 * @param int $userid
7131 public function lock_submission($userid) {
7133 // Need grade permission.
7134 require_capability('mod/assign:grade', $this->context
);
7136 // Give each submission plugin a chance to process the locking.
7137 $plugins = $this->get_submission_plugins();
7138 $submission = $this->get_user_submission($userid, false);
7140 $flags = $this->get_user_flags($userid, true);
7142 $this->update_user_flags($flags);
7144 foreach ($plugins as $plugin) {
7145 if ($plugin->is_enabled() && $plugin->is_visible()) {
7146 $plugin->lock($submission, $flags);
7150 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
7151 \mod_assign\event\submission_locked
::create_from_user($this, $user)->trigger();
7157 * Set the workflow state for multiple users
7161 protected function process_set_batch_marking_workflow_state() {
7164 // Include batch marking workflow form.
7165 require_once($CFG->dirroot
. '/mod/assign/batchsetmarkingworkflowstateform.php');
7167 $formparams = array(
7168 'userscount' => 0, // This form is never re-displayed, so we don't need to
7169 'usershtml' => '', // initialise these parameters with real information.
7170 'markingworkflowstates' => $this->get_marking_workflow_states_for_current_user()
7173 $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
7175 if ($mform->is_cancelled()) {
7179 if ($formdata = $mform->get_data()) {
7180 $useridlist = explode(',', $formdata->selectedusers
);
7181 $state = $formdata->markingworkflowstate
;
7183 foreach ($useridlist as $userid) {
7184 $flags = $this->get_user_flags($userid, true);
7186 $flags->workflowstate
= $state;
7188 // Clear the mailed flag if notification is requested, the student hasn't been
7189 // notified previously, the student can access the assignment, and the state
7191 $modinfo = get_fast_modinfo($this->course
, $userid);
7192 $cm = $modinfo->get_cm($this->get_course_module()->id
);
7193 if ($formdata->sendstudentnotifications
&& $cm->uservisible
&&
7194 $state == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
) {
7198 $gradingdisabled = $this->grading_disabled($userid);
7200 // Will not apply update if user does not have permission to assign this workflow state.
7201 if (!$gradingdisabled && $this->update_user_flags($flags)) {
7202 if ($state == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
) {
7203 // Update Gradebook.
7204 $assign = clone $this->get_instance();
7205 $assign->cmidnumber
= $this->get_course_module()->idnumber
;
7206 // Set assign gradebook feedback plugin status.
7207 $assign->gradefeedbackenabled
= $this->is_gradebook_feedback_enabled();
7208 assign_update_grades($assign, $userid);
7211 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
7212 \mod_assign\event\workflow_state_updated
::create_from_user($this, $user, $state)->trigger();
7219 * Set the marking allocation for multiple users
7223 protected function process_set_batch_marking_allocation() {
7226 // Include batch marking allocation form.
7227 require_once($CFG->dirroot
. '/mod/assign/batchsetallocatedmarkerform.php');
7229 $formparams = array(
7230 'userscount' => 0, // This form is never re-displayed, so we don't need to
7231 'usershtml' => '' // initialise these parameters with real information.
7234 list($sort, $params) = users_order_by_sql();
7235 $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade', '', $sort);
7236 $markerlist = array();
7237 foreach ($markers as $marker) {
7238 $markerlist[$marker->id
] = fullname($marker);
7241 $formparams['markers'] = $markerlist;
7243 $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
7245 if ($mform->is_cancelled()) {
7249 if ($formdata = $mform->get_data()) {
7250 $useridlist = explode(',', $formdata->selectedusers
);
7251 $marker = $DB->get_record('user', array('id' => $formdata->allocatedmarker
), '*', MUST_EXIST
);
7253 foreach ($useridlist as $userid) {
7254 $flags = $this->get_user_flags($userid, true);
7255 if ($flags->workflowstate
== ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW ||
7256 $flags->workflowstate
== ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW ||
7257 $flags->workflowstate
== ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE ||
7258 $flags->workflowstate
== ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
) {
7260 continue; // Allocated marker can only be changed in certain workflow states.
7263 $flags->allocatedmarker
= $marker->id
;
7265 if ($this->update_user_flags($flags)) {
7266 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
7267 \mod_assign\event\marker_updated
::create_from_marker($this, $user, $marker)->trigger();
7275 * Prevent student updates to this submission.
7276 * Uses url parameter userid.
7278 * @param int $userid
7281 protected function process_lock_submission($userid = 0) {
7286 $userid = required_param('userid', PARAM_INT
);
7289 return $this->lock_submission($userid);
7293 * Unlock the student submission.
7295 * @param int $userid
7298 public function unlock_submission($userid) {
7301 // Need grade permission.
7302 require_capability('mod/assign:grade', $this->context
);
7304 // Give each submission plugin a chance to process the unlocking.
7305 $plugins = $this->get_submission_plugins();
7306 $submission = $this->get_user_submission($userid, false);
7308 $flags = $this->get_user_flags($userid, true);
7310 $this->update_user_flags($flags);
7312 foreach ($plugins as $plugin) {
7313 if ($plugin->is_enabled() && $plugin->is_visible()) {
7314 $plugin->unlock($submission, $flags);
7318 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
7319 \mod_assign\event\submission_unlocked
::create_from_user($this, $user)->trigger();
7324 * Unlock the student submission.
7325 * Uses url parameter userid.
7327 * @param int $userid
7330 protected function process_unlock_submission($userid = 0) {
7335 $userid = required_param('userid', PARAM_INT
);
7338 return $this->unlock_submission($userid);
7342 * Apply a grade from a grading form to a user (may be called multiple times for a group submission).
7344 * @param stdClass $formdata - the data from the form
7345 * @param int $userid - the user to apply the grade to
7346 * @param int $attemptnumber - The attempt number to apply the grade to.
7349 protected function apply_grade_to_user($formdata, $userid, $attemptnumber) {
7350 global $USER, $CFG, $DB;
7352 $grade = $this->get_user_grade($userid, true, $attemptnumber);
7353 $originalgrade = $grade->grade
;
7354 $gradingdisabled = $this->grading_disabled($userid);
7355 $gradinginstance = $this->get_grading_instance($userid, $grade, $gradingdisabled);
7356 if (!$gradingdisabled) {
7357 if ($gradinginstance) {
7358 $grade->grade
= $gradinginstance->submit_and_get_grade($formdata->advancedgrading
,
7361 // Handle the case when grade is set to No Grade.
7362 if (isset($formdata->grade
)) {
7363 $grade->grade
= grade_floatval(unformat_float($formdata->grade
));
7366 if (isset($formdata->workflowstate
) ||
isset($formdata->allocatedmarker
)) {
7367 $flags = $this->get_user_flags($userid, true);
7368 $oldworkflowstate = $flags->workflowstate
;
7369 $flags->workflowstate
= isset($formdata->workflowstate
) ?
$formdata->workflowstate
: $flags->workflowstate
;
7370 $flags->allocatedmarker
= isset($formdata->allocatedmarker
) ?
$formdata->allocatedmarker
: $flags->allocatedmarker
;
7371 if ($this->update_user_flags($flags) &&
7372 isset($formdata->workflowstate
) &&
7373 $formdata->workflowstate
!== $oldworkflowstate) {
7374 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
7375 \mod_assign\event\workflow_state_updated
::create_from_user($this, $user, $formdata->workflowstate
)->trigger();
7379 $grade->grader
= $USER->id
;
7381 $adminconfig = $this->get_admin_config();
7382 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook
;
7384 $feedbackmodified = false;
7386 // Call save in plugins.
7387 foreach ($this->feedbackplugins
as $plugin) {
7388 if ($plugin->is_enabled() && $plugin->is_visible()) {
7389 $gradingmodified = $plugin->is_feedback_modified($grade, $formdata);
7390 if ($gradingmodified) {
7391 if (!$plugin->save($grade, $formdata)) {
7393 print_error($plugin->get_error());
7395 // If $feedbackmodified is true, keep it true.
7396 $feedbackmodified = $feedbackmodified ||
$gradingmodified;
7398 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
7399 // This is the feedback plugin chose to push comments to the gradebook.
7400 $grade->feedbacktext
= $plugin->text_for_gradebook($grade);
7401 $grade->feedbackformat
= $plugin->format_for_gradebook($grade);
7406 // We do not want to update the timemodified if no grade was added.
7407 if (!empty($formdata->addattempt
) ||
7408 ($originalgrade !== null && $originalgrade != -1) ||
7409 ($grade->grade
!== null && $grade->grade
!= -1) ||
7410 $feedbackmodified) {
7411 $this->update_grade($grade, !empty($formdata->addattempt
));
7413 // Note the default if not provided for this option is true (e.g. webservices).
7414 // This is for backwards compatibility.
7415 if (!isset($formdata->sendstudentnotifications
) ||
$formdata->sendstudentnotifications
) {
7416 $this->notify_grade_modified($grade, true);
7422 * Save outcomes submitted from grading form.
7424 * @param int $userid
7425 * @param stdClass $formdata
7426 * @param int $sourceuserid The user ID under which the outcome data is accessible. This is relevant
7427 * for an outcome set to a user but applied to an entire group.
7429 protected function process_outcomes($userid, $formdata, $sourceuserid = null) {
7432 if (empty($CFG->enableoutcomes
)) {
7435 if ($this->grading_disabled($userid)) {
7439 require_once($CFG->libdir
.'/gradelib.php');
7442 $gradinginfo = grade_get_grades($this->get_course()->id
,
7445 $this->get_instance()->id
,
7448 if (!empty($gradinginfo->outcomes
)) {
7449 foreach ($gradinginfo->outcomes
as $index => $oldoutcome) {
7450 $name = 'outcome_'.$index;
7451 $sourceuserid = $sourceuserid !== null ?
$sourceuserid : $userid;
7452 if (isset($formdata->{$name}[$sourceuserid]) &&
7453 $oldoutcome->grades
[$userid]->grade
!= $formdata->{$name}[$sourceuserid]) {
7454 $data[$index] = $formdata->{$name}[$sourceuserid];
7458 if (count($data) > 0) {
7459 grade_update_outcomes('mod/assign',
7463 $this->get_instance()->id
,
7470 * If the requirements are met - reopen the submission for another attempt.
7471 * Only call this function when grading the latest attempt.
7473 * @param int $userid The userid.
7474 * @param stdClass $submission The submission (may be a group submission).
7475 * @param bool $addattempt - True if the "allow another attempt" checkbox was checked.
7476 * @return bool - true if another attempt was added.
7478 protected function reopen_submission_if_required($userid, $submission, $addattempt) {
7479 $instance = $this->get_instance();
7480 $maxattemptsreached = !empty($submission) &&
7481 $submission->attemptnumber
>= ($instance->maxattempts
- 1) &&
7482 $instance->maxattempts
!= ASSIGN_UNLIMITED_ATTEMPTS
;
7483 $shouldreopen = false;
7484 if ($instance->attemptreopenmethod
== ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS
) {
7485 // Check the gradetopass from the gradebook.
7486 $gradeitem = $this->get_grade_item();
7488 $gradegrade = grade_grade
::fetch(array('userid' => $userid, 'itemid' => $gradeitem->id
));
7490 // Do not reopen if is_passed returns null, e.g. if there is no pass criterion set.
7491 if ($gradegrade && ($gradegrade->is_passed() === false)) {
7492 $shouldreopen = true;
7496 if ($instance->attemptreopenmethod
== ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL
&&
7497 !empty($addattempt)) {
7498 $shouldreopen = true;
7500 if ($shouldreopen && !$maxattemptsreached) {
7501 $this->add_attempt($userid);
7508 * Save grade update.
7510 * @param int $userid
7511 * @param stdClass $data
7512 * @return bool - was the grade saved
7514 public function save_grade($userid, $data) {
7516 // Need grade permission.
7517 require_capability('mod/assign:grade', $this->context
);
7519 $instance = $this->get_instance();
7521 if ($instance->teamsubmission
) {
7522 $submission = $this->get_group_submission($userid, 0, false, $data->attemptnumber
);
7524 $submission = $this->get_user_submission($userid, false, $data->attemptnumber
);
7526 if ($instance->teamsubmission
&& !empty($data->applytoall
)) {
7528 if ($this->get_submission_group($userid)) {
7529 $group = $this->get_submission_group($userid);
7531 $groupid = $group->id
;
7534 $members = $this->get_submission_group_members($groupid, true, $this->show_only_active_users());
7535 foreach ($members as $member) {
7536 // User may exist in multple groups (which should put them in the default group).
7537 $this->apply_grade_to_user($data, $member->id
, $data->attemptnumber
);
7538 $this->process_outcomes($member->id
, $data, $userid);
7541 $this->apply_grade_to_user($data, $userid, $data->attemptnumber
);
7543 $this->process_outcomes($userid, $data);
7552 * @param moodleform $mform
7553 * @return bool - was the grade saved
7555 protected function process_save_grade(&$mform) {
7556 global $CFG, $SESSION;
7557 // Include grade form.
7558 require_once($CFG->dirroot
. '/mod/assign/gradeform.php');
7562 $instance = $this->get_instance();
7563 $rownum = required_param('rownum', PARAM_INT
);
7564 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT
);
7565 $useridlistid = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM
);
7566 $userid = optional_param('userid', 0, PARAM_INT
);
7568 if (empty($SESSION->mod_assign_useridlist
[$this->get_useridlist_key($useridlistid)])) {
7569 // If the userid list is not stored we must not save, as it is possible that the user in a
7570 // given row position may not be the same now as when the grading page was generated.
7571 $url = new moodle_url('/mod/assign/view.php', array('id' => $this->get_course_module()->id
));
7572 throw new moodle_exception('useridlistnotcached', 'mod_assign', $url);
7574 $useridlist = $SESSION->mod_assign_useridlist
[$this->get_useridlist_key($useridlistid)];
7576 $useridlist = array($userid);
7581 $userid = $useridlist[$rownum];
7582 if ($rownum == count($useridlist) - 1) {
7586 $data = new stdClass();
7588 $gradeformparams = array('rownum' => $rownum,
7589 'useridlistid' => $useridlistid,
7591 'attemptnumber' => $attemptnumber,
7592 'userid' => $userid);
7593 $mform = new mod_assign_grade_form(null,
7594 array($this, $data, $gradeformparams),
7597 array('class'=>'gradeform'));
7599 if ($formdata = $mform->get_data()) {
7600 return $this->save_grade($userid, $formdata);
7607 * This function is a static wrapper around can_upgrade.
7609 * @param string $type The plugin type
7610 * @param int $version The plugin version
7613 public static function can_upgrade_assignment($type, $version) {
7614 $assignment = new assign(null, null, null);
7615 return $assignment->can_upgrade($type, $version);
7619 * This function returns true if it can upgrade an assignment from the 2.2 module.
7621 * @param string $type The plugin type
7622 * @param int $version The plugin version
7625 public function can_upgrade($type, $version) {
7626 if ($type == 'offline' && $version >= 2011112900) {
7629 foreach ($this->submissionplugins
as $plugin) {
7630 if ($plugin->can_upgrade($type, $version)) {
7634 foreach ($this->feedbackplugins
as $plugin) {
7635 if ($plugin->can_upgrade($type, $version)) {
7643 * Copy all the files from the old assignment files area to the new one.
7644 * This is used by the plugin upgrade code.
7646 * @param int $oldcontextid The old assignment context id
7647 * @param int $oldcomponent The old assignment component ('assignment')
7648 * @param int $oldfilearea The old assignment filearea ('submissions')
7649 * @param int $olditemid The old submissionid (can be null e.g. intro)
7650 * @param int $newcontextid The new assignment context id
7651 * @param int $newcomponent The new assignment component ('assignment')
7652 * @param int $newfilearea The new assignment filearea ('submissions')
7653 * @param int $newitemid The new submissionid (can be null e.g. intro)
7654 * @return int The number of files copied
7656 public function copy_area_files_for_upgrade($oldcontextid,
7664 // Note, this code is based on some code in filestorage - but that code
7665 // deleted the old files (which we don't want).
7668 $fs = get_file_storage();
7670 $oldfiles = $fs->get_area_files($oldcontextid,
7676 foreach ($oldfiles as $oldfile) {
7677 $filerecord = new stdClass();
7678 $filerecord->contextid
= $newcontextid;
7679 $filerecord->component
= $newcomponent;
7680 $filerecord->filearea
= $newfilearea;
7681 $filerecord->itemid
= $newitemid;
7682 $fs->create_file_from_storedfile($filerecord, $oldfile);
7690 * Add a new attempt for each user in the list - but reopen each group assignment
7693 * @param array $useridlist Array of userids to reopen.
7696 protected function process_add_attempt_group($useridlist) {
7697 $groupsprocessed = array();
7700 foreach ($useridlist as $userid) {
7702 $group = $this->get_submission_group($userid);
7704 $groupid = $group->id
;
7707 if (empty($groupsprocessed[$groupid])) {
7708 $result = $this->process_add_attempt($userid) && $result;
7709 $groupsprocessed[$groupid] = true;
7716 * Check for a sess key and then call add_attempt.
7718 * @param int $userid int The user to add the attempt for
7719 * @return bool - true if successful.
7721 protected function process_add_attempt($userid) {
7724 return $this->add_attempt($userid);
7728 * Add a new attempt for a user.
7730 * @param int $userid int The user to add the attempt for
7731 * @return bool - true if successful.
7733 protected function add_attempt($userid) {
7734 require_capability('mod/assign:grade', $this->context
);
7736 if ($this->get_instance()->attemptreopenmethod
== ASSIGN_ATTEMPT_REOPEN_METHOD_NONE
) {
7740 if ($this->get_instance()->teamsubmission
) {
7741 $oldsubmission = $this->get_group_submission($userid, 0, false);
7743 $oldsubmission = $this->get_user_submission($userid, false);
7746 if (!$oldsubmission) {
7750 // No more than max attempts allowed.
7751 if ($this->get_instance()->maxattempts
!= ASSIGN_UNLIMITED_ATTEMPTS
&&
7752 $oldsubmission->attemptnumber
>= ($this->get_instance()->maxattempts
- 1)) {
7756 // Create the new submission record for the group/user.
7757 if ($this->get_instance()->teamsubmission
) {
7758 $newsubmission = $this->get_group_submission($userid, 0, true, $oldsubmission->attemptnumber +
1);
7760 $newsubmission = $this->get_user_submission($userid, true, $oldsubmission->attemptnumber +
1);
7763 // Set the status of the new attempt to reopened.
7764 $newsubmission->status
= ASSIGN_SUBMISSION_STATUS_REOPENED
;
7766 // Give each submission plugin a chance to process the add_attempt.
7767 $plugins = $this->get_submission_plugins();
7768 foreach ($plugins as $plugin) {
7769 if ($plugin->is_enabled() && $plugin->is_visible()) {
7770 $plugin->add_attempt($oldsubmission, $newsubmission);
7774 $this->update_submission($newsubmission, $userid, false, $this->get_instance()->teamsubmission
);
7775 $flags = $this->get_user_flags($userid, false);
7776 if (isset($flags->locked
) && $flags->locked
) { // May not exist.
7777 $this->process_unlock_submission($userid);
7783 * Get an upto date list of user grades and feedback for the gradebook.
7785 * @param int $userid int or 0 for all users
7786 * @return array of grade data formated for the gradebook api
7787 * The data required by the gradebook api is userid,
7795 public function get_user_grades_for_gradebook($userid) {
7798 $assignmentid = $this->get_instance()->id
;
7800 $adminconfig = $this->get_admin_config();
7801 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook
;
7802 $gradebookplugin = null;
7804 // Find the gradebook plugin.
7805 foreach ($this->feedbackplugins
as $plugin) {
7806 if ($plugin->is_enabled() && $plugin->is_visible()) {
7807 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
7808 $gradebookplugin = $plugin;
7813 $where = ' WHERE u.id = :userid ';
7815 $where = ' WHERE u.id != :userid ';
7818 // When the gradebook asks us for grades - only return the last attempt for each user.
7819 $params = array('assignid1'=>$assignmentid,
7820 'assignid2'=>$assignmentid,
7822 $graderesults = $DB->get_recordset_sql('SELECT
7824 s.timemodified as datesubmitted,
7825 g.grade as rawgrade,
7826 g.timemodified as dategraded,
7827 g.grader as usermodified
7829 LEFT JOIN {assign_submission} s
7830 ON u.id = s.userid and s.assignment = :assignid1 AND
7832 JOIN {assign_grades} g
7833 ON u.id = g.userid and g.assignment = :assignid2 AND
7834 g.attemptnumber = s.attemptnumber' .
7837 foreach ($graderesults as $result) {
7838 $gradingstatus = $this->get_grading_status($result->userid
);
7839 if (!$this->get_instance()->markingworkflow ||
$gradingstatus == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
) {
7840 $gradebookgrade = clone $result;
7841 // Now get the feedback.
7842 if ($gradebookplugin) {
7843 $grade = $this->get_user_grade($result->userid
, false);
7845 $gradebookgrade->feedback
= $gradebookplugin->text_for_gradebook($grade);
7846 $gradebookgrade->feedbackformat
= $gradebookplugin->format_for_gradebook($grade);
7849 $grades[$gradebookgrade->userid
] = $gradebookgrade;
7853 $graderesults->close();
7858 * Call the static version of this function
7860 * @param int $userid The userid to lookup
7861 * @return int The unique id
7863 public function get_uniqueid_for_user($userid) {
7864 return self
::get_uniqueid_for_user_static($this->get_instance()->id
, $userid);
7868 * Foreach participant in the course - assign them a random id.
7870 * @param int $assignid The assignid to lookup
7872 public static function allocate_unique_ids($assignid) {
7875 $cm = get_coursemodule_from_instance('assign', $assignid, 0, false, MUST_EXIST
);
7876 $context = context_module
::instance($cm->id
);
7878 $currentgroup = groups_get_activity_group($cm, true);
7879 $users = get_enrolled_users($context, "mod/assign:submit", $currentgroup, 'u.id');
7881 // Shuffle the users.
7884 foreach ($users as $user) {
7885 $record = $DB->get_record('assign_user_mapping',
7886 array('assignment'=>$assignid, 'userid'=>$user->id
),
7889 $record = new stdClass();
7890 $record->assignment
= $assignid;
7891 $record->userid
= $user->id
;
7892 $DB->insert_record('assign_user_mapping', $record);
7898 * Lookup this user id and return the unique id for this assignment.
7900 * @param int $assignid The assignment id
7901 * @param int $userid The userid to lookup
7902 * @return int The unique id
7904 public static function get_uniqueid_for_user_static($assignid, $userid) {
7907 // Search for a record.
7908 $params = array('assignment'=>$assignid, 'userid'=>$userid);
7909 if ($record = $DB->get_record('assign_user_mapping', $params, 'id')) {
7913 // Be a little smart about this - there is no record for the current user.
7914 // We should ensure any unallocated ids for the current participant
7915 // list are distrubited randomly.
7916 self
::allocate_unique_ids($assignid);
7918 // Retry the search for a record.
7919 if ($record = $DB->get_record('assign_user_mapping', $params, 'id')) {
7923 // The requested user must not be a participant. Add a record anyway.
7924 $record = new stdClass();
7925 $record->assignment
= $assignid;
7926 $record->userid
= $userid;
7928 return $DB->insert_record('assign_user_mapping', $record);
7932 * Call the static version of this function.
7934 * @param int $uniqueid The uniqueid to lookup
7935 * @return int The user id or false if they don't exist
7937 public function get_user_id_for_uniqueid($uniqueid) {
7938 return self
::get_user_id_for_uniqueid_static($this->get_instance()->id
, $uniqueid);
7942 * Lookup this unique id and return the user id for this assignment.
7944 * @param int $assignid The id of the assignment this user mapping is in
7945 * @param int $uniqueid The uniqueid to lookup
7946 * @return int The user id or false if they don't exist
7948 public static function get_user_id_for_uniqueid_static($assignid, $uniqueid) {
7951 // Search for a record.
7952 if ($record = $DB->get_record('assign_user_mapping',
7953 array('assignment'=>$assignid, 'id'=>$uniqueid),
7956 return $record->userid
;
7963 * Get the list of marking_workflow states the current user has permission to transition a grade to.
7965 * @return array of state => description
7967 public function get_marking_workflow_states_for_current_user() {
7968 if (!empty($this->markingworkflowstates
)) {
7969 return $this->markingworkflowstates
;
7972 if (has_capability('mod/assign:grade', $this->context
)) {
7973 $states[ASSIGN_MARKING_WORKFLOW_STATE_INMARKING
] = get_string('markingworkflowstateinmarking', 'assign');
7974 $states[ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW
] = get_string('markingworkflowstatereadyforreview', 'assign');
7976 if (has_any_capability(array('mod/assign:reviewgrades',
7977 'mod/assign:managegrades'), $this->context
)) {
7978 $states[ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW
] = get_string('markingworkflowstateinreview', 'assign');
7979 $states[ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE
] = get_string('markingworkflowstatereadyforrelease', 'assign');
7981 if (has_any_capability(array('mod/assign:releasegrades',
7982 'mod/assign:managegrades'), $this->context
)) {
7983 $states[ASSIGN_MARKING_WORKFLOW_STATE_RELEASED
] = get_string('markingworkflowstatereleased', 'assign');
7985 $this->markingworkflowstates
= $states;
7986 return $this->markingworkflowstates
;
7990 * Check is only active users in course should be shown.
7992 * @return bool true if only active users should be shown.
7994 public function show_only_active_users() {
7997 if (is_null($this->showonlyactiveenrol
)) {
7998 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol
);
7999 $this->showonlyactiveenrol
= get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
8001 if (!is_null($this->context
)) {
8002 $this->showonlyactiveenrol
= $this->showonlyactiveenrol ||
8003 !has_capability('moodle/course:viewsuspendedusers', $this->context
);
8006 return $this->showonlyactiveenrol
;
8010 * Return true is user is active user in course else false
8012 * @param int $userid
8013 * @return bool true is user is active in course.
8015 public function is_active_user($userid) {
8016 return !in_array($userid, get_suspended_userids($this->context
, true));
8020 * Returns true if gradebook feedback plugin is enabled
8022 * @return bool true if gradebook feedback plugin is enabled and visible else false.
8024 public function is_gradebook_feedback_enabled() {
8025 // Get default grade book feedback plugin.
8026 $adminconfig = $this->get_admin_config();
8027 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook
;
8028 $gradebookplugin = str_replace('assignfeedback_', '', $gradebookplugin);
8030 // Check if default gradebook feedback is visible and enabled.
8031 $gradebookfeedbackplugin = $this->get_feedback_plugin_by_type($gradebookplugin);
8033 if (empty($gradebookfeedbackplugin)) {
8037 if ($gradebookfeedbackplugin->is_visible() && $gradebookfeedbackplugin->is_enabled()) {
8041 // Gradebook feedback plugin is either not visible/enabled.
8046 * Returns the grading status.
8048 * @param int $userid the user id
8049 * @return string returns the grading status
8051 public function get_grading_status($userid) {
8052 if ($this->get_instance()->markingworkflow
) {
8053 $flags = $this->get_user_flags($userid, false);
8054 if (!empty($flags->workflowstate
)) {
8055 return $flags->workflowstate
;
8057 return ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED
;
8059 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT
);
8060 $grade = $this->get_user_grade($userid, false, $attemptnumber);
8062 if (!empty($grade) && $grade->grade
!== null && $grade->grade
>= 0) {
8063 return ASSIGN_GRADING_STATUS_GRADED
;
8065 return ASSIGN_GRADING_STATUS_NOT_GRADED
;
8071 * The id used to uniquily identify the cache for this instance of the assign object.
8075 public function get_useridlist_key_id() {
8076 return $this->useridlistid
;
8080 * Generates the key that should be used for an entry in the useridlist cache.
8082 * @param string $id Generate a key for this instance (optional)
8083 * @return string The key for the id, or new entry if no $id is passed.
8085 public function get_useridlist_key($id = null) {
8087 $id = $this->get_useridlist_key_id();
8089 return $this->get_course_module()->id
. '_' . $id;
8093 * Updates and creates the completion records in mdl_course_modules_completion.
8095 * @param int $teamsubmission value of 0 or 1 to indicate whether this is a group activity
8096 * @param int $requireallteammemberssubmit value of 0 or 1 to indicate whether all group members must click Submit
8097 * @param obj $submission the submission
8098 * @param int $userid the user id
8099 * @param int $complete
8100 * @param obj $completion
8104 protected function update_activity_completion_records($teamsubmission,
8105 $requireallteammemberssubmit,
8111 if (($teamsubmission && $submission->groupid
> 0 && !$requireallteammemberssubmit) ||
8112 ($teamsubmission && $submission->groupid
> 0 && $requireallteammemberssubmit &&
8113 $submission->status
== ASSIGN_SUBMISSION_STATUS_SUBMITTED
)) {
8115 $members = groups_get_members($submission->groupid
);
8117 foreach ($members as $member) {
8118 $completion->update_state($this->get_course_module(), $complete, $member->id
);
8121 $completion->update_state($this->get_course_module(), $complete, $userid);
8128 * Update the module completion status (set it viewed).
8132 public function set_module_viewed() {
8133 $completion = new completion_info($this->get_course());
8134 $completion->set_module_viewed($this->get_course_module());
8139 * Portfolio caller class for mod_assign.
8141 * @package mod_assign
8142 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
8143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8145 class assign_portfolio_caller
extends portfolio_module_caller_base
{
8147 /** @var int callback arg - the id of submission we export */
8150 /** @var string component of the submission files we export*/
8151 protected $component;
8153 /** @var string callback arg - the area of submission files we export */
8156 /** @var int callback arg - the id of file we export */
8159 /** @var int callback arg - the cmid of the assignment we export */
8162 /** @var string callback arg - the plugintype of the editor we export */
8165 /** @var string callback arg - the name of the editor field we export */
8169 * Callback arg for a single file export.
8171 public static function expected_callbackargs() {
8176 'component' => false,
8186 * @param array $callbackargs
8188 public function __construct($callbackargs) {
8189 parent
::__construct($callbackargs);
8190 $this->cm
= get_coursemodule_from_id('assign', $this->cmid
, 0, false, MUST_EXIST
);
8194 * Load data needed for the portfolio export.
8196 * If the assignment type implements portfolio_load_data(), the processing is delegated
8197 * to it. Otherwise, the caller must provide either fileid (to export single file) or
8198 * submissionid and filearea (to export all data attached to the given submission file area)
8199 * via callback arguments.
8201 * @throws portfolio_caller_exception
8203 public function load_data() {
8205 $context = context_module
::instance($this->cmid
);
8207 if (empty($this->fileid
)) {
8208 if (empty($this->sid
) ||
empty($this->area
)) {
8209 throw new portfolio_caller_exception('invalidfileandsubmissionid', 'mod_assign');
8214 // Export either an area of files or a single file (see function for more detail).
8215 // The first arg is an id or null. If it is an id, the rest of the args are ignored.
8216 // If it is null, the rest of the args are used to load a list of files from get_areafiles.
8217 $this->set_file_and_format_data($this->fileid
,
8228 * Prepares the package up before control is passed to the portfolio plugin.
8230 * @throws portfolio_caller_exception
8233 public function prepare_package() {
8235 if ($this->plugin
&& $this->editor
) {
8236 $options = portfolio_format_text_options();
8237 $context = context_module
::instance($this->cmid
);
8238 $options->context
= $context;
8240 $plugin = $this->get_submission_plugin();
8242 $text = $plugin->get_editor_text($this->editor
, $this->sid
);
8243 $format = $plugin->get_editor_format($this->editor
, $this->sid
);
8245 $html = format_text($text, $format, $options);
8246 $html = portfolio_rewrite_pluginfile_urls($html,
8251 $this->exporter
->get('format'));
8253 $exporterclass = $this->exporter
->get('formatclass');
8254 if (in_array($exporterclass, array(PORTFOLIO_FORMAT_PLAINHTML
, PORTFOLIO_FORMAT_RICHHTML
))) {
8255 if ($files = $this->exporter
->get('caller')->get('multifiles')) {
8256 foreach ($files as $file) {
8257 $this->exporter
->copy_existing_file($file);
8260 return $this->exporter
->write_new_file($html, 'assignment.html', !empty($files));
8261 } else if ($this->exporter
->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A
) {
8262 $leapwriter = $this->exporter
->get('format')->leap2a_writer();
8263 $entry = new portfolio_format_leap2a_entry($this->area
. $this->cmid
,
8264 $context->get_context_name(),
8268 $entry->add_category('web', 'resource_type');
8269 $entry->author
= $this->user
;
8270 $leapwriter->add_entry($entry);
8271 if ($files = $this->exporter
->get('caller')->get('multifiles')) {
8272 $leapwriter->link_files($entry, $files, $this->area
. $this->cmid
. 'file');
8273 foreach ($files as $file) {
8274 $this->exporter
->copy_existing_file($file);
8277 return $this->exporter
->write_new_file($leapwriter->to_xml(),
8278 $this->exporter
->get('format')->manifest_name(),
8281 debugging('invalid format class: ' . $this->exporter
->get('formatclass'));
8286 if ($this->exporter
->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A
) {
8287 $leapwriter = $this->exporter
->get('format')->leap2a_writer();
8289 if ($this->singlefile
) {
8290 $files[] = $this->singlefile
;
8291 } else if ($this->multifiles
) {
8292 $files = $this->multifiles
;
8294 throw new portfolio_caller_exception('invalidpreparepackagefile',
8296 $this->get_return_url());
8299 $entryids = array();
8300 foreach ($files as $file) {
8301 $entry = new portfolio_format_leap2a_file($file->get_filename(), $file);
8302 $entry->author
= $this->user
;
8303 $leapwriter->add_entry($entry);
8304 $this->exporter
->copy_existing_file($file);
8305 $entryids[] = $entry->id
;
8307 if (count($files) > 1) {
8308 $baseid = 'assign' . $this->cmid
. $this->area
;
8309 $context = context_module
::instance($this->cmid
);
8311 // If we have multiple files, they should be grouped together into a folder.
8312 $entry = new portfolio_format_leap2a_entry($baseid . 'group',
8313 $context->get_context_name(),
8315 $leapwriter->add_entry($entry);
8316 $leapwriter->make_selection($entry, $entryids, 'Folder');
8318 return $this->exporter
->write_new_file($leapwriter->to_xml(),
8319 $this->exporter
->get('format')->manifest_name(),
8322 return $this->prepare_package_file();
8326 * Fetch the plugin by its type.
8328 * @return assign_submission_plugin
8330 protected function get_submission_plugin() {
8332 if (!$this->plugin ||
!$this->cmid
) {
8336 require_once($CFG->dirroot
. '/mod/assign/locallib.php');
8338 $context = context_module
::instance($this->cmid
);
8340 $assignment = new assign($context, null, null);
8341 return $assignment->get_submission_plugin_by_type($this->plugin
);
8345 * Calculate a sha1 has of either a single file or a list
8346 * of files based on the data set by load_data.
8350 public function get_sha1() {
8352 if ($this->plugin
&& $this->editor
) {
8353 $plugin = $this->get_submission_plugin();
8354 $options = portfolio_format_text_options();
8355 $options->context
= context_module
::instance($this->cmid
);
8357 $text = format_text($plugin->get_editor_text($this->editor
, $this->sid
),
8358 $plugin->get_editor_format($this->editor
, $this->sid
),
8360 $textsha1 = sha1($text);
8363 $filesha1 = $this->get_sha1_file();
8364 } catch (portfolio_caller_exception
$e) {
8367 return sha1($textsha1 . $filesha1);
8369 return $this->get_sha1_file();
8373 * Calculate the time to transfer either a single file or a list
8374 * of files based on the data set by load_data.
8378 public function expected_time() {
8379 return $this->expected_time_file();
8383 * Checking the permissions.
8387 public function check_permissions() {
8388 $context = context_module
::instance($this->cmid
);
8389 return has_capability('mod/assign:exportownsubmission', $context);
8393 * Display a module name.
8397 public static function display_name() {
8398 return get_string('modulename', 'assign');
8402 * Return array of formats supported by this portfolio call back.
8406 public static function base_supported_formats() {
8407 return array(PORTFOLIO_FORMAT_FILE
, PORTFOLIO_FORMAT_LEAP2A
);