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 protected 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();
1376 if ($this->get_instance()->grade >= 0) {
1378 if ($editing && $this->get_instance()->grade > 0) {
1382 $displaygrade = format_float($grade, 2);
1384 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1385 get_string('usergrade', 'assign') .
1387 $o .= '<input type="text"
1388 id="quickgrade_' . $userid . '"
1389 name="quickgrade_' . $userid . '"
1390 value="' . $displaygrade . '"
1393 class="quickgrade"/>';
1394 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1397 if ($grade == -1 || $grade === null) {
1400 $item = $this->get_grade_item();
1401 $o .= grade_format_gradevalue($grade, $item);
1402 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1403 // If displaying the raw grade, also display the total value.
1404 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1412 if (empty($this->cache['scale'])) {
1413 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1414 $this->cache['scale'] = make_menu_from_list($scale->scale);
1421 $o .= '<label class="accesshide"
1422 for="quickgrade_' . $userid . '">' .
1423 get_string('usergrade', 'assign') .
1425 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1426 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1427 foreach ($this->cache['scale'] as $optionid => $option) {
1429 if ($grade == $optionid) {
1430 $selected = 'selected="selected"';
1432 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1437 $scaleid = (int)$grade;
1438 if (isset($this->cache['scale'][$scaleid])) {
1439 $o .= $this->cache['scale'][$scaleid];
1449 * Get the submission status/grading status for all submissions in this assignment for the
1450 * given paticipants.
1452 * These statuses match the available filters (requiregrading, submitted, notsubmitted).
1453 * If this is a group assignment, group info is also returned.
1455 * @param array $participants an associative array where the key is the participant id and
1456 * the value is the participant record.
1457 * @return array an associative array where the key is the participant id and the value is
1458 * the participant record.
1460 private function get_submission_info_for_participants($participants) {
1463 if (empty($participants)) {
1464 return $participants;
1467 list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1469 $assignid = $this->get_instance()->id;
1470 $params['assignmentid1'] = $assignid;
1471 $params['assignmentid2'] = $assignid;
1473 $sql = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade FROM {user} u
1474 LEFT JOIN {assign_submission} s
1476 AND s.assignment = :assignmentid1
1478 LEFT JOIN {assign_grades} g
1480 AND g.assignment = :assignmentid2
1481 AND g.attemptnumber = s.attemptnumber
1482 WHERE u.id ' . $insql;
1484 $records = $DB->get_records_sql($sql, $params);
1486 if ($this->get_instance()->teamsubmission) {
1488 $allgroups = groups_get_all_groups($this->get_course()->id,
1489 array_keys($participants),
1490 $this->get_instance()->teamsubmissiongroupingid,
1491 'DISTINCT g.id, g.name');
1494 foreach ($participants as $userid => $participant) {
1495 $participants[$userid]->fullname = $this->fullname($participant);
1496 $participants[$userid]->submitted = false;
1497 $participants[$userid]->requiregrading = false;
1500 foreach ($records as $userid => $submissioninfo) {
1501 // These filters are 100% the same as the ones in the grading table SQL.
1503 $requiregrading = false;
1505 if (!empty($submissioninfo->stime) && $submissioninfo->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1509 if ($submitted && ($submissioninfo->stime >= $submissioninfo->gtime ||
1510 empty($submissioninfo->gtime) ||
1511 $submissioninfo->grade === null)) {
1512 $requiregrading = true;
1515 $participants[$userid]->submitted = $submitted;
1516 $participants[$userid]->requiregrading = $requiregrading;
1517 if ($this->get_instance()->teamsubmission) {
1518 $group = $this->get_submission_group($userid);
1520 $participants[$userid]->groupid = $group->id;
1521 $participants[$userid]->groupname = $group->name;
1525 return $participants;
1529 * Get the submission status/grading status for all submissions in this assignment.
1530 * These statuses match the available filters (requiregrading, submitted, notsubmitted).
1531 * If this is a group assignment, group info is also returned.
1533 * @param int $currentgroup
1534 * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'groupid', 'groupname'
1536 public function list_participants_with_filter_status_and_group($currentgroup) {
1537 $participants = $this->list_participants($currentgroup, false);
1539 if (empty($participants)) {
1540 return $participants;
1542 return $this->get_submission_info_for_participants($participants);
1547 * Load a list of users enrolled in the current course with the specified permission and group.
1550 * @param int $currentgroup
1551 * @param bool $idsonly
1552 * @return array List of user records
1554 public function list_participants($currentgroup, $idsonly) {
1556 if (empty($currentgroup)) {
1560 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1561 if (!isset($this->participants[$key])) {
1562 $order = 'u.lastname, u.firstname, u.id';
1563 if ($this->is_blind_marking()) {
1566 $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', $order, null, null,
1567 $this->show_only_active_users());
1569 $cm = $this->get_course_module();
1570 $info = new \core_availability\info_module($cm);
1571 $users = $info->filter_user_list($users);
1573 $this->participants[$key] = $users;
1578 foreach ($this->participants[$key] as $id => $user) {
1579 $idslist[$id] = new stdClass();
1580 $idslist[$id]->id = $id;
1584 return $this->participants[$key];
1588 * Load a user if they are enrolled in the current course. Populated with submission
1589 * status for this assignment.
1591 * @param int $userid
1592 * @return null|stdClass user record
1594 public function get_participant($userid) {
1597 $participant = $DB->get_record('user', array('id' => $userid));
1598 if (!$participant) {
1602 if (!is_enrolled($this->context, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
1606 $result = $this->get_submission_info_for_participants(array($participant->id => $participant));
1607 return $result[$participant->id];
1611 * Load a count of valid teams for this assignment.
1613 * @param int $activitygroup Activity active group
1614 * @return int number of valid teams
1616 public function count_teams($activitygroup = 0) {
1620 $participants = $this->list_participants($activitygroup, true);
1622 // If a team submission grouping id is provided all good as all returned groups
1623 // are the submission teams, but if no team submission grouping was specified
1624 // $groups will contain all participants groups.
1625 if ($this->get_instance()->teamsubmissiongroupingid) {
1627 // We restrict the users to the selected group ones.
1628 $groups = groups_get_all_groups($this->get_course()->id,
1629 array_keys($participants),
1630 $this->get_instance()->teamsubmissiongroupingid,
1631 'DISTINCT g.id, g.name');
1633 $count = count($groups);
1635 // When a specific group is selected we don't count the default group users.
1636 if ($activitygroup == 0) {
1637 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1638 // See if there are any users in the default group.
1639 $defaultusers = $this->get_submission_group_members(0, true);
1640 if (count($defaultusers) > 0) {
1646 // It is faster to loop around participants if no grouping was specified.
1648 foreach ($participants as $participant) {
1649 if ($group = $this->get_submission_group($participant->id)) {
1650 $groups[$group->id] = true;
1651 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1656 $count = count($groups);
1663 * Load a count of active users enrolled in the current course with the specified permission and group.
1666 * @param int $currentgroup
1667 * @return int number of matching users
1669 public function count_participants($currentgroup) {
1670 return count($this->list_participants($currentgroup, true));
1674 * Load a count of active users submissions in the current module that require grading
1675 * This means the submission modification time is more recent than the
1676 * grading modification time and the status is SUBMITTED.
1678 * @return int number of matching submissions
1680 public function count_submissions_need_grading() {
1683 if ($this->get_instance()->teamsubmission) {
1684 // This does not make sense for group assignment because the submission is shared.
1688 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1689 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1691 $params['assignid'] = $this->get_instance()->id;
1692 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1694 $sql = 'SELECT COUNT(s.userid)
1695 FROM {assign_submission} s
1696 LEFT JOIN {assign_grades} g ON
1697 s.assignment = g.assignment AND
1698 s.userid = g.userid AND
1699 g.attemptnumber = s.attemptnumber
1700 JOIN(' . $esql . ') e ON e.id = s.userid
1703 s.assignment = :assignid AND
1704 s.timemodified IS NOT NULL AND
1705 s.status = :submitted AND
1706 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL)';
1708 return $DB->count_records_sql($sql, $params);
1712 * Load a count of grades.
1714 * @return int number of grades
1716 public function count_grades() {
1719 if (!$this->has_instance()) {
1723 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1724 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1726 $params['assignid'] = $this->get_instance()->id;
1728 $sql = 'SELECT COUNT(g.userid)
1729 FROM {assign_grades} g
1730 JOIN(' . $esql . ') e ON e.id = g.userid
1731 WHERE g.assignment = :assignid';
1733 return $DB->count_records_sql($sql, $params);
1737 * Load a count of submissions.
1739 * @param bool $includenew When true, also counts the submissions with status 'new'.
1740 * @return int number of submissions
1742 public function count_submissions($includenew = false) {
1745 if (!$this->has_instance()) {
1753 $sqlnew = ' AND s.status <> :status ';
1754 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
1757 if ($this->get_instance()->teamsubmission) {
1758 // We cannot join on the enrolment tables for group submissions (no userid).
1759 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1760 FROM {assign_submission} s
1762 s.assignment = :assignid AND
1763 s.timemodified IS NOT NULL AND
1764 s.userid = :groupuserid' .
1767 $params['assignid'] = $this->get_instance()->id;
1768 $params['groupuserid'] = 0;
1770 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1771 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1773 $params = array_merge($params, $enrolparams);
1774 $params['assignid'] = $this->get_instance()->id;
1776 $sql = 'SELECT COUNT(DISTINCT s.userid)
1777 FROM {assign_submission} s
1778 JOIN(' . $esql . ') e ON e.id = s.userid
1780 s.assignment = :assignid AND
1781 s.timemodified IS NOT NULL ' .
1786 return $DB->count_records_sql($sql, $params);
1790 * Load a count of submissions with a specified status.
1792 * @param string $status The submission status - should match one of the constants
1793 * @return int number of matching submissions
1795 public function count_submissions_with_status($status) {
1798 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1799 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1801 $params['assignid'] = $this->get_instance()->id;
1802 $params['assignid2'] = $this->get_instance()->id;
1803 $params['submissionstatus'] = $status;
1805 if ($this->get_instance()->teamsubmission) {
1808 if ($currentgroup != 0) {
1809 // If there is an active group we should only display the current group users groups.
1810 $participants = $this->list_participants($currentgroup, true);
1811 $groups = groups_get_all_groups($this->get_course()->id,
1812 array_keys($participants),
1813 $this->get_instance()->teamsubmissiongroupingid,
1814 'DISTINCT g.id, g.name');
1815 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
1816 $groupsstr = 's.groupid ' . $groupssql . ' AND';
1817 $params = $params + $groupsparams;
1819 $sql = 'SELECT COUNT(s.groupid)
1820 FROM {assign_submission} s
1823 s.assignment = :assignid AND
1824 s.timemodified IS NOT NULL AND
1825 s.userid = :groupuserid AND '
1827 s.status = :submissionstatus';
1828 $params['groupuserid'] = 0;
1830 $sql = 'SELECT COUNT(s.userid)
1831 FROM {assign_submission} s
1832 JOIN(' . $esql . ') e ON e.id = s.userid
1835 s.assignment = :assignid AND
1836 s.timemodified IS NOT NULL AND
1837 s.status = :submissionstatus';
1841 return $DB->count_records_sql($sql, $params);
1845 * Utility function to get the userid for every row in the grading table
1846 * so the order can be frozen while we iterate it.
1848 * @return array An array of userids
1850 protected function get_grading_userid_list() {
1851 $filter = get_user_preferences('assign_filter', '');
1852 $table = new assign_grading_table($this, 0, $filter, 0, false);
1854 $useridlist = $table->get_column_data('userid');
1860 * Generate zip file from array of given files.
1862 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1863 * This array is indexed by the final file name and each
1864 * element in the array is an instance of a stored_file object.
1865 * @return path of temp file - note this returned file does
1866 * not have a .zip extension - it is a temp file.
1868 protected function pack_files($filesforzipping) {
1870 // Create path for new zip file.
1871 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1873 $zipper = new zip_packer();
1874 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1881 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1883 * Cron function to be run periodically according to the moodle cron.
1887 public static function cron() {
1890 // Only ever send a max of one days worth of updates.
1891 $yesterday = time() - (24 * 3600);
1893 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
1895 // Collect all submissions that require mailing.
1896 // Submissions are included if all are true:
1897 // - The assignment is visible in the gradebook.
1898 // - No previous notification has been sent.
1899 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
1900 // if marking workflow is enabled, the workflow state is at 'released'.
1901 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1902 g.*, g.timemodified as lastmodified, cm.id as cmid
1904 JOIN {assign_grades} g ON g.assignment = a.id
1905 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1906 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
1907 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
1908 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
1909 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
1910 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
1911 uf.mailed = 0 AND gri.hidden = 0
1912 ORDER BY a.course, cm.id";
1915 'yesterday' => $yesterday,
1916 'today' => $timenow,
1917 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
1919 $submissions = $DB->get_records_sql($sql, $params);
1921 if (!empty($submissions)) {
1923 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1925 // Preload courses we are going to need those.
1926 $courseids = array();
1927 foreach ($submissions as $submission) {
1928 $courseids[] = $submission->course;
1931 // Filter out duplicates.
1932 $courseids = array_unique($courseids);
1933 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1934 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1935 $sql = 'SELECT c.*, ' . $ctxselect .
1937 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1938 WHERE c.id ' . $courseidsql;
1940 $params['contextlevel'] = CONTEXT_COURSE;
1941 $courses = $DB->get_records_sql($sql, $params);
1943 // Clean up... this could go on for a while.
1946 unset($courseidsql);
1949 // Message students about new feedback.
1950 foreach ($submissions as $submission) {
1952 mtrace("Processing assignment submission $submission->id ...");
1954 // Do not cache user lookups - could be too many.
1955 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1956 mtrace('Could not find user ' . $submission->userid);
1960 // Use a cache to prevent the same DB queries happening over and over.
1961 if (!array_key_exists($submission->course, $courses)) {
1962 mtrace('Could not find course ' . $submission->course);
1965 $course = $courses[$submission->course];
1966 if (isset($course->ctxid)) {
1967 // Context has not yet been preloaded. Do so now.
1968 context_helper::preload_from_record($course);
1971 // Override the language and timezone of the "current" user, so that
1972 // mail is customised for the receiver.
1973 cron_setup_user($user, $course);
1975 // Context lookups are already cached.
1976 $coursecontext = context_course::instance($course->id);
1977 if (!is_enrolled($coursecontext, $user->id)) {
1978 $courseshortname = format_string($course->shortname,
1980 array('context' => $coursecontext));
1981 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1985 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1986 mtrace('Could not find grader ' . $submission->grader);
1990 $modinfo = get_fast_modinfo($course, $user->id);
1991 $cm = $modinfo->get_cm($submission->cmid);
1992 // Context lookups are already cached.
1993 $contextmodule = context_module::instance($cm->id);
1995 if (!$cm->uservisible) {
1996 // Hold mail notification for assignments the user cannot access until later.
2000 // Need to send this to the student.
2001 $messagetype = 'feedbackavailable';
2002 $eventtype = 'assign_notification';
2003 $updatetime = $submission->lastmodified;
2004 $modulename = get_string('modulename', 'assign');
2007 if ($submission->blindmarking && !$submission->revealidentities) {
2008 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
2010 $showusers = $submission->blindmarking && !$submission->revealidentities;
2011 self::send_assignment_notification($grader,
2024 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
2027 $DB->update_record('assign_user_flags', $flags);
2029 $flags = new stdClass();
2030 $flags->userid = $user->id;
2031 $flags->assignment = $submission->assignment;
2033 $DB->insert_record('assign_user_flags', $flags);
2038 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
2042 // Free up memory just to be sure.
2046 // Update calendar events to provide a description.
2050 allowsubmissionsfromdate >= :lastcron AND
2051 allowsubmissionsfromdate <= :timenow AND
2052 alwaysshowdescription = 0';
2053 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2054 $newlyavailable = $DB->get_records_sql($sql, $params);
2055 foreach ($newlyavailable as $record) {
2056 $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
2057 $context = context_module::instance($cm->id);
2059 $assignment = new assign($context, null, null);
2060 $assignment->update_calendar($cm->id);
2067 * Mark in the database that this grade record should have an update notification sent by cron.
2069 * @param stdClass $grade a grade record keyed on id
2070 * @param bool $mailedoverride when true, flag notification to be sent again.
2071 * @return bool true for success
2073 public function notify_grade_modified($grade, $mailedoverride = false) {
2076 $flags = $this->get_user_flags($grade->userid, true);
2077 if ($flags->mailed != 1 || $mailedoverride) {
2081 return $this->update_user_flags($flags);
2085 * Update user flags for this user in this assignment.
2087 * @param stdClass $flags a flags record keyed on id
2088 * @return bool true for success
2090 public function update_user_flags($flags) {
2092 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
2096 $result = $DB->update_record('assign_user_flags', $flags);
2101 * Update a grade in the grade table for the assignment and in the gradebook.
2103 * @param stdClass $grade a grade record keyed on id
2104 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
2105 * @return bool true for success
2107 public function update_grade($grade, $reopenattempt = false) {
2110 $grade->timemodified = time();
2112 if (!empty($grade->workflowstate)) {
2113 $validstates = $this->get_marking_workflow_states_for_current_user();
2114 if (!array_key_exists($grade->workflowstate, $validstates)) {
2119 if ($grade->grade && $grade->grade != -1) {
2120 if ($this->get_instance()->grade > 0) {
2121 if (!is_numeric($grade->grade)) {
2123 } else if ($grade->grade > $this->get_instance()->grade) {
2125 } else if ($grade->grade < 0) {
2130 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
2131 $scaleoptions = make_menu_from_list($scale->scale);
2132 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
2139 if (empty($grade->attemptnumber)) {
2140 // Set it to the default.
2141 $grade->attemptnumber = 0;
2143 $DB->update_record('assign_grades', $grade);
2146 if ($this->get_instance()->teamsubmission) {
2147 $submission = $this->get_group_submission($grade->userid, 0, false);
2149 $submission = $this->get_user_submission($grade->userid, false);
2152 // Only push to gradebook if the update is for the latest attempt.
2153 // Not the latest attempt.
2154 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
2158 if ($this->gradebook_item_update(null, $grade)) {
2159 \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
2162 // If the conditions are met, allow another attempt.
2164 $this->reopen_submission_if_required($grade->userid,
2173 * View the grant extension date page.
2175 * Uses url parameters 'userid'
2176 * or from parameter 'selectedusers'
2178 * @param moodleform $mform - Used for validation of the submitted data
2181 protected function view_grant_extension($mform) {
2183 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2187 $data = new stdClass();
2188 $data->id = $this->get_course_module()->id;
2190 $formparams = array(
2191 'instance' => $this->get_instance()
2194 $extrauserfields = get_extra_user_fields($this->get_context());
2197 $submitteddata = $mform->get_data();
2198 $users = $submitteddata->selectedusers;
2199 $userlist = explode(',', $users);
2201 $data->selectedusers = $users;
2206 foreach ($userlist as $userid) {
2207 if ($usercount >= 5) {
2208 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
2211 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
2213 $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
2214 $this->get_course()->id,
2215 has_capability('moodle/site:viewfullnames',
2216 $this->get_course_context()),
2217 $this->is_blind_marking(),
2218 $this->get_uniqueid_for_user($user->id),
2220 !$this->is_active_user($userid)));
2224 $formparams['userscount'] = count($userlist);
2225 $formparams['usershtml'] = $usershtml;
2228 $userid = required_param('userid', PARAM_INT);
2229 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
2230 $flags = $this->get_user_flags($userid, false);
2232 $data->userid = $user->id;
2234 $data->extensionduedate = $flags->extensionduedate;
2237 $usershtml = $this->get_renderer()->render(new assign_user_summary($user,
2238 $this->get_course()->id,
2239 has_capability('moodle/site:viewfullnames',
2240 $this->get_course_context()),
2241 $this->is_blind_marking(),
2242 $this->get_uniqueid_for_user($user->id),
2244 !$this->is_active_user($userid)));
2245 $formparams['usershtml'] = $usershtml;
2248 $mform = new mod_assign_extension_form(null, $formparams);
2249 $mform->set_data($data);
2250 $header = new assign_header($this->get_instance(),
2251 $this->get_context(),
2252 $this->show_intro(),
2253 $this->get_course_module()->id,
2254 get_string('grantextension', 'assign'));
2255 $o .= $this->get_renderer()->render($header);
2256 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
2257 $o .= $this->view_footer();
2262 * Get a list of the users in the same group as this user.
2264 * @param int $groupid The id of the group whose members we want or 0 for the default group
2265 * @param bool $onlyids Whether to retrieve only the user id's
2266 * @param bool $excludesuspended Whether to exclude suspended users
2267 * @return array The users (possibly id's only)
2269 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
2271 if ($groupid != 0) {
2272 $allusers = $this->list_participants($groupid, $onlyids);
2273 foreach ($allusers as $user) {
2274 if ($this->get_submission_group($user->id)) {
2279 $allusers = $this->list_participants(null, $onlyids);
2280 foreach ($allusers as $user) {
2281 if ($this->get_submission_group($user->id) == null) {
2286 // Exclude suspended users, if user can't see them.
2287 if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2288 foreach ($members as $key => $member) {
2289 if (!$this->is_active_user($member->id)) {
2290 unset($members[$key]);
2299 * Get a list of the users in the same group as this user that have not submitted the assignment.
2301 * @param int $groupid The id of the group whose members we want or 0 for the default group
2302 * @param bool $onlyids Whether to retrieve only the user id's
2303 * @return array The users (possibly id's only)
2305 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2306 $instance = $this->get_instance();
2307 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2310 $members = $this->get_submission_group_members($groupid, $onlyids);
2312 foreach ($members as $id => $member) {
2313 $submission = $this->get_user_submission($member->id, false);
2314 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2315 unset($members[$id]);
2317 if ($this->is_blind_marking()) {
2318 $members[$id]->alias = get_string('hiddenuser', 'assign') .
2319 $this->get_uniqueid_for_user($id);
2327 * Load the group submission object for a particular user, optionally creating it if required.
2329 * @param int $userid The id of the user whose submission we want
2330 * @param int $groupid The id of the group for this user - may be 0 in which
2331 * case it is determined from the userid.
2332 * @param bool $create If set to true a new submission object will be created in the database
2333 * with the status set to "new".
2334 * @param int $attemptnumber - -1 means the latest attempt
2335 * @return stdClass The submission
2337 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2340 if ($groupid == 0) {
2341 $group = $this->get_submission_group($userid);
2343 $groupid = $group->id;
2347 // Now get the group submission.
2348 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2349 if ($attemptnumber >= 0) {
2350 $params['attemptnumber'] = $attemptnumber;
2353 // Only return the row with the highest attemptnumber.
2355 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2357 $submission = reset($submissions);
2364 $submission = new stdClass();
2365 $submission->assignment = $this->get_instance()->id;
2366 $submission->userid = 0;
2367 $submission->groupid = $groupid;
2368 $submission->timecreated = time();
2369 $submission->timemodified = $submission->timecreated;
2370 if ($attemptnumber >= 0) {
2371 $submission->attemptnumber = $attemptnumber;
2373 $submission->attemptnumber = 0;
2375 // Work out if this is the latest submission.
2376 $submission->latest = 0;
2377 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2378 if ($attemptnumber == -1) {
2379 // This is a new submission so it must be the latest.
2380 $submission->latest = 1;
2382 // We need to work this out.
2383 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2385 $latestsubmission = reset($result);
2387 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2388 $submission->latest = 1;
2391 if ($submission->latest) {
2392 // This is the case when we need to set latest to 0 for all the other attempts.
2393 $DB->set_field('assign_submission', 'latest', 0, $params);
2395 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2396 $sid = $DB->insert_record('assign_submission', $submission);
2397 return $DB->get_record('assign_submission', array('id' => $sid));
2403 * View a summary listing of all assignments in the current course.
2407 private function view_course_index() {
2412 $course = $this->get_course();
2413 $strplural = get_string('modulenameplural', 'assign');
2415 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2416 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2417 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2421 $strsectionname = '';
2422 $usesections = course_format_uses_sections($course->format);
2423 $modinfo = get_fast_modinfo($course);
2426 $strsectionname = get_string('sectionname', 'format_'.$course->format);
2427 $sections = $modinfo->get_section_info_all();
2429 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2433 $currentsection = '';
2434 foreach ($modinfo->instances['assign'] as $cm) {
2435 if (!$cm->uservisible) {
2439 $timedue = $cms[$cm->id]->duedate;
2442 if ($usesections && $cm->sectionnum) {
2443 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2447 $context = context_module::instance($cm->id);
2449 $assignment = new assign($context, $cm, $course);
2451 if (has_capability('mod/assign:grade', $context)) {
2452 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2454 } else if (has_capability('mod/assign:submit', $context)) {
2455 $usersubmission = $assignment->get_user_submission($USER->id, false);
2457 if (!empty($usersubmission->status)) {
2458 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2460 $submitted = get_string('submissionstatus_', 'assign');
2463 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2464 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2465 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2466 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2471 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2475 $o .= $this->get_renderer()->render($courseindexsummary);
2476 $o .= $this->view_footer();
2482 * View a page rendered by a plugin.
2484 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2488 protected function view_plugin_page() {
2493 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2494 $plugintype = required_param('plugin', PARAM_TEXT);
2495 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2497 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2499 print_error('invalidformdata', '');
2503 $o .= $plugin->view_page($pluginaction);
2510 * This is used for team assignments to get the group for the specified user.
2511 * If the user is a member of multiple or no groups this will return false
2513 * @param int $userid The id of the user whose submission we want
2514 * @return mixed The group or false
2516 public function get_submission_group($userid) {
2518 if (isset($this->usersubmissiongroups[$userid])) {
2519 return $this->usersubmissiongroups[$userid];
2522 $groups = $this->get_all_groups($userid);
2523 if (count($groups) != 1) {
2526 $return = array_pop($groups);
2529 // Cache the user submission group.
2530 $this->usersubmissiongroups[$userid] = $return;
2536 * Gets all groups the user is a member of.
2538 * @param int $userid Teh id of the user who's groups we are checking
2539 * @return array The group objects
2541 public function get_all_groups($userid) {
2542 if (isset($this->usergroups[$userid])) {
2543 return $this->usergroups[$userid];
2546 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2547 $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2549 $this->usergroups[$userid] = $return;
2556 * Display the submission that is used by a plugin.
2558 * Uses url parameters 'sid', 'gid' and 'plugin'.
2560 * @param string $pluginsubtype
2563 protected function view_plugin_content($pluginsubtype) {
2566 $submissionid = optional_param('sid', 0, PARAM_INT);
2567 $gradeid = optional_param('gid', 0, PARAM_INT);
2568 $plugintype = required_param('plugin', PARAM_TEXT);
2570 if ($pluginsubtype == 'assignsubmission') {
2571 $plugin = $this->get_submission_plugin_by_type($plugintype);
2572 if ($submissionid <= 0) {
2573 throw new coding_exception('Submission id should not be 0');
2575 $item = $this->get_submission($submissionid);
2577 // Check permissions.
2578 $this->require_view_submission($item->userid);
2579 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2580 $this->get_context(),
2581 $this->show_intro(),
2582 $this->get_course_module()->id,
2583 $plugin->get_name()));
2584 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2586 assign_submission_plugin_submission::FULL,
2587 $this->get_course_module()->id,
2588 $this->get_return_action(),
2589 $this->get_return_params()));
2591 // Trigger event for viewing a submission.
2592 \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2595 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2596 if ($gradeid <= 0) {
2597 throw new coding_exception('Grade id should not be 0');
2599 $item = $this->get_grade($gradeid);
2600 // Check permissions.
2601 $this->require_view_submission($item->userid);
2602 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2603 $this->get_context(),
2604 $this->show_intro(),
2605 $this->get_course_module()->id,
2606 $plugin->get_name()));
2607 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2609 assign_feedback_plugin_feedback::FULL,
2610 $this->get_course_module()->id,
2611 $this->get_return_action(),
2612 $this->get_return_params()));
2614 // Trigger event for viewing feedback.
2615 \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
2618 $o .= $this->view_return_links();
2620 $o .= $this->view_footer();
2626 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2628 * @param string $text - The replacement text
2629 * @param stdClass $user - The user record
2630 * @param assign_plugin $plugin - The assignment plugin
2632 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2633 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2636 $groupid = groups_get_activity_group($this->get_course_module(), true);
2637 $groupname = groups_get_group_name($groupid).'-';
2640 if ($this->is_blind_marking()) {
2641 $prefix = $groupname . get_string('participant', 'assign');
2642 $prefix = str_replace('_', ' ', $prefix);
2643 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2645 $prefix = $groupname . fullname($user);
2646 $prefix = str_replace('_', ' ', $prefix);
2647 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2650 $subtype = $plugin->get_subtype();
2651 $type = $plugin->get_type();
2652 $prefix = $prefix . $subtype . '_' . $type . '_';
2654 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2660 * Render the content in editor that is often used by plugin.
2662 * @param string $filearea
2663 * @param int $submissionid
2664 * @param string $plugintype
2665 * @param string $editor
2666 * @param string $component
2669 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2674 $plugin = $this->get_submission_plugin_by_type($plugintype);
2676 $text = $plugin->get_editor_text($editor, $submissionid);
2677 $format = $plugin->get_editor_format($editor, $submissionid);
2679 $finaltext = file_rewrite_pluginfile_urls($text,
2681 $this->get_context()->id,
2685 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2686 $result .= format_text($finaltext, $format, $params);
2688 if ($CFG->enableportfolios && has_capability('mod/assign:exportownsubmission', $this->context)) {
2689 require_once($CFG->libdir . '/portfoliolib.php');
2691 $button = new portfolio_add_button();
2692 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2693 'sid' => $submissionid,
2694 'plugin' => $plugintype,
2695 'editor' => $editor,
2697 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2698 $fs = get_file_storage();
2700 if ($files = $fs->get_area_files($this->context->id,
2706 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2708 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2710 $result .= $button->to_html();
2716 * Display a continue page after grading.
2718 * @param string $message - The message to display.
2721 protected function view_savegrading_result($message) {
2723 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2724 $this->get_context(),
2725 $this->show_intro(),
2726 $this->get_course_module()->id,
2727 get_string('savegradingresult', 'assign')));
2728 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2730 $this->get_course_module()->id);
2731 $o .= $this->get_renderer()->render($gradingresult);
2732 $o .= $this->view_footer();
2736 * Display a continue page after quickgrading.
2738 * @param string $message - The message to display.
2741 protected function view_quickgrading_result($message) {
2743 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2744 $this->get_context(),
2745 $this->show_intro(),
2746 $this->get_course_module()->id,
2747 get_string('quickgradingresult', 'assign')));
2748 $lastpage = optional_param('lastpage', null, PARAM_INT);
2749 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2751 $this->get_course_module()->id,
2754 $o .= $this->get_renderer()->render($gradingresult);
2755 $o .= $this->view_footer();
2760 * Display the page footer.
2764 protected function view_footer() {
2765 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2766 if (!PHPUNIT_TEST) {
2767 return $this->get_renderer()->render_footer();
2774 * Throw an error if the permissions to view this users submission are missing.
2776 * @throws required_capability_exception
2779 public function require_view_submission($userid) {
2780 if (!$this->can_view_submission($userid)) {
2781 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2786 * Throw an error if the permissions to view grades in this assignment are missing.
2788 * @throws required_capability_exception
2791 public function require_view_grades() {
2792 if (!$this->can_view_grades()) {
2793 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2798 * Does this user have view grade or grade permission for this assignment?
2802 public function can_view_grades() {
2803 // Permissions check.
2804 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2812 * Does this user have grade permission for this assignment?
2816 public function can_grade() {
2817 // Permissions check.
2818 if (!has_capability('mod/assign:grade', $this->context)) {
2826 * Download a zip file of all assignment submissions.
2828 * @param array $userids Array of user ids to download assignment submissions in a zip file
2829 * @return string - If an error occurs, this will contain the error page.
2831 protected function download_submissions($userids = false) {
2834 // More efficient to load this here.
2835 require_once($CFG->libdir.'/filelib.php');
2837 // Increase the server timeout to handle the creation and sending of large zip files.
2838 core_php_time_limit::raise();
2840 $this->require_view_grades();
2842 // Load all users with submit.
2843 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2844 $this->show_only_active_users());
2846 // Build a list of files to zip.
2847 $filesforzipping = array();
2848 $fs = get_file_storage();
2850 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2855 $groupid = groups_get_activity_group($this->get_course_module(), true);
2856 $groupname = groups_get_group_name($groupid).'-';
2859 // Construct the zip file name.
2860 $filename = clean_filename($this->get_course()->shortname . '-' .
2861 $this->get_instance()->name . '-' .
2862 $groupname.$this->get_course_module()->id . '.zip');
2864 // Get all the files for each student.
2865 foreach ($students as $student) {
2866 $userid = $student->id;
2867 // Download all assigments submission or only selected users.
2868 if ($userids and !in_array($userid, $userids)) {
2872 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2873 // Get the plugins to add their own files to the zip.
2875 $submissiongroup = false;
2877 if ($this->get_instance()->teamsubmission) {
2878 $submission = $this->get_group_submission($userid, 0, false);
2879 $submissiongroup = $this->get_submission_group($userid);
2880 if ($submissiongroup) {
2881 $groupname = $submissiongroup->name . '-';
2883 $groupname = get_string('defaultteam', 'assign') . '-';
2886 $submission = $this->get_user_submission($userid, false);
2889 if ($this->is_blind_marking()) {
2890 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2891 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
2893 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2894 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
2898 foreach ($this->submissionplugins as $plugin) {
2899 if ($plugin->is_enabled() && $plugin->is_visible()) {
2900 $pluginfiles = $plugin->get_files($submission, $student);
2901 foreach ($pluginfiles as $zipfilepath => $file) {
2902 $subtype = $plugin->get_subtype();
2903 $type = $plugin->get_type();
2904 $zipfilename = basename($zipfilepath);
2905 $prefixedfilename = clean_filename($prefix .
2911 if ($type == 'file') {
2912 $pathfilename = $prefixedfilename . $file->get_filepath() . $zipfilename;
2913 } else if ($type == 'onlinetext') {
2914 $pathfilename = $prefixedfilename . '/' . $zipfilename;
2916 $pathfilename = $prefixedfilename . '/' . $zipfilename;
2918 $pathfilename = clean_param($pathfilename, PARAM_PATH);
2919 $filesforzipping[$pathfilename] = $file;
2927 if (count($filesforzipping) == 0) {
2928 $header = new assign_header($this->get_instance(),
2929 $this->get_context(),
2931 $this->get_course_module()->id,
2932 get_string('downloadall', 'assign'));
2933 $result .= $this->get_renderer()->render($header);
2934 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2935 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2936 'action'=>'grading'));
2937 $result .= $this->get_renderer()->continue_button($url);
2938 $result .= $this->view_footer();
2939 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2940 \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
2941 // Send file and delete after sending.
2942 send_temp_file($zipfile, $filename);
2943 // We will not get here - send_temp_file calls exit.
2949 * Util function to add a message to the log.
2951 * @deprecated since 2.7 - Use new events system instead.
2952 * (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2954 * @param string $action The current action
2955 * @param string $info A detailed description of the change. But no more than 255 characters.
2956 * @param string $url The url to the assign module instance.
2957 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2958 * retrieve the arguments to use them with the new event system (Event 2).
2959 * @return void|array
2961 public function add_to_log($action = '', $info = '', $url='', $return = false) {
2964 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2966 $fullurl .= '&' . $url;
2970 $this->get_course()->id,
2975 $this->get_course_module()->id
2979 // We only need to call debugging when returning a value. This is because the call to
2980 // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2981 debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2984 call_user_func_array('add_to_log', $args);
2988 * Lazy load the page renderer and expose the renderer to plugins.
2990 * @return assign_renderer
2992 public function get_renderer() {
2994 if ($this->output) {
2995 return $this->output;
2997 $this->output = $PAGE->get_renderer('mod_assign', null, RENDERER_TARGET_GENERAL);
2998 return $this->output;
3002 * Load the submission object for a particular user, optionally creating it if required.
3004 * For team assignments there are 2 submissions - the student submission and the team submission
3005 * All files are associated with the team submission but the status of the students contribution is
3006 * recorded separately.
3008 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
3009 * @param bool $create If set to true a new submission object will be created in the database with the status set to "new".
3010 * @param int $attemptnumber - -1 means the latest attempt
3011 * @return stdClass The submission
3013 public function get_user_submission($userid, $create, $attemptnumber=-1) {
3017 $userid = $USER->id;
3019 // If the userid is not null then use userid.
3020 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
3021 if ($attemptnumber >= 0) {
3022 $params['attemptnumber'] = $attemptnumber;
3025 // Only return the row with the highest attemptnumber.
3027 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
3029 $submission = reset($submissions);
3036 $submission = new stdClass();
3037 $submission->assignment = $this->get_instance()->id;
3038 $submission->userid = $userid;
3039 $submission->timecreated = time();
3040 $submission->timemodified = $submission->timecreated;
3041 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
3042 if ($attemptnumber >= 0) {
3043 $submission->attemptnumber = $attemptnumber;
3045 $submission->attemptnumber = 0;
3047 // Work out if this is the latest submission.
3048 $submission->latest = 0;
3049 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
3050 if ($attemptnumber == -1) {
3051 // This is a new submission so it must be the latest.
3052 $submission->latest = 1;
3054 // We need to work this out.
3055 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
3056 $latestsubmission = null;
3058 $latestsubmission = reset($result);
3060 if (empty($latestsubmission) || ($attemptnumber > $latestsubmission->attemptnumber)) {
3061 $submission->latest = 1;
3064 if ($submission->latest) {
3065 // This is the case when we need to set latest to 0 for all the other attempts.
3066 $DB->set_field('assign_submission', 'latest', 0, $params);
3068 $sid = $DB->insert_record('assign_submission', $submission);
3069 return $DB->get_record('assign_submission', array('id' => $sid));
3075 * Load the submission object from it's id.
3077 * @param int $submissionid The id of the submission we want
3078 * @return stdClass The submission
3080 protected function get_submission($submissionid) {
3083 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
3084 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
3088 * This will retrieve a user flags object from the db optionally creating it if required.
3089 * The user flags was split from the user_grades table in 2.5.
3091 * @param int $userid The user we are getting the flags for.
3092 * @param bool $create If true the flags record will be created if it does not exist
3093 * @return stdClass The flags record
3095 public function get_user_flags($userid, $create) {
3098 // If the userid is not null then use userid.
3100 $userid = $USER->id;
3103 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
3105 $flags = $DB->get_record('assign_user_flags', $params);
3111 $flags = new stdClass();
3112 $flags->assignment = $this->get_instance()->id;
3113 $flags->userid = $userid;
3115 $flags->extensionduedate = 0;
3116 $flags->workflowstate = '';
3117 $flags->allocatedmarker = 0;
3119 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
3120 // This is because students only want to be notified about certain types of update (grades and feedback).
3123 $fid = $DB->insert_record('assign_user_flags', $flags);
3131 * This will retrieve a grade object from the db, optionally creating it if required.
3133 * @param int $userid The user we are grading
3134 * @param bool $create If true the grade will be created if it does not exist
3135 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
3136 * @return stdClass The grade record
3138 public function get_user_grade($userid, $create, $attemptnumber=-1) {
3141 // If the userid is not null then use userid.
3143 $userid = $USER->id;
3147 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
3148 if ($attemptnumber < 0 || $create) {
3149 // Make sure this grade matches the latest submission attempt.
3150 if ($this->get_instance()->teamsubmission) {
3151 $submission = $this->get_group_submission($userid, 0, true);
3153 $submission = $this->get_user_submission($userid, true);
3156 $attemptnumber = $submission->attemptnumber;
3160 if ($attemptnumber >= 0) {
3161 $params['attemptnumber'] = $attemptnumber;
3164 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
3167 return reset($grades);
3170 $grade = new stdClass();
3171 $grade->assignment = $this->get_instance()->id;
3172 $grade->userid = $userid;
3173 $grade->timecreated = time();
3174 // If we are "auto-creating" a grade - and there is a submission
3175 // the new grade should not have a more recent timemodified value
3176 // than the submission.
3178 $grade->timemodified = $submission->timemodified;
3180 $grade->timemodified = $grade->timecreated;
3183 $grade->grader = $USER->id;
3184 if ($attemptnumber >= 0) {
3185 $grade->attemptnumber = $attemptnumber;
3188 $gid = $DB->insert_record('assign_grades', $grade);
3196 * This will retrieve a grade object from the db.
3198 * @param int $gradeid The id of the grade
3199 * @return stdClass The grade record
3201 protected function get_grade($gradeid) {
3204 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
3205 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
3209 * Print the grading page for a single user submission.
3211 * @param array $args Optional args array (better than pulling args from _GET and _POST)
3214 protected function view_single_grading_panel($args) {
3215 global $DB, $CFG, $SESSION, $PAGE;
3218 $instance = $this->get_instance();
3220 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3222 // Need submit permission to submit an assignment.
3223 require_capability('mod/assign:grade', $this->context);
3225 // If userid is passed - we are only grading a single student.
3226 $userid = $args['userid'];
3227 $attemptnumber = $args['attemptnumber'];
3230 $useridlist = array($userid);
3233 // This variation on the url will link direct to this student, with no next/previous links.
3234 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3235 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3236 $this->register_return_link('grade', $returnparams);
3238 $user = $DB->get_record('user', array('id' => $userid));
3239 $submission = $this->get_user_submission($userid, false, $attemptnumber);
3240 $submissiongroup = null;
3241 $teamsubmission = null;
3242 $notsubmitted = array();
3243 if ($instance->teamsubmission) {
3244 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
3245 $submissiongroup = $this->get_submission_group($userid);
3247 if ($submissiongroup) {
3248 $groupid = $submissiongroup->id;
3250 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3254 // Get the requested grade.
3255 $grade = $this->get_user_grade($userid, false, $attemptnumber);
3256 $flags = $this->get_user_flags($userid, false);
3257 if ($this->can_view_submission($userid)) {
3258 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
3259 $extensionduedate = null;
3261 $extensionduedate = $flags->extensionduedate;
3263 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
3264 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3265 $usergroups = $this->get_all_groups($user->id);
3267 $submissionstatus = new assign_submission_status_compact($instance->allowsubmissionsfromdate,
3268 $instance->alwaysshowdescription,
3270 $instance->teamsubmission,
3274 $this->is_any_submission_plugin_enabled(),
3276 $this->is_graded($userid),
3278 $instance->cutoffdate,
3279 $this->get_submission_plugins(),