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');
81 * Standard base class for mod_assign (assignment types).
84 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
85 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
89 /** @var stdClass the assignment record that contains the global settings for this assign instance */
92 /** @var stdClass the grade_item record for this assign instance's primary grade item. */
95 /** @var context the context of the course module for this assign instance
96 * (or just the course if we are creating a new one)
100 /** @var stdClass the course this assign instance belongs to */
103 /** @var stdClass the admin config for all assign instances */
104 private $adminconfig;
106 /** @var assign_renderer the custom renderer for this module */
109 /** @var cm_info the course module for this assign instance */
110 private $coursemodule;
112 /** @var array cache for things like the coursemodule name or the scale menu -
113 * only lives for a single request.
117 /** @var array list of the installed submission plugins */
118 private $submissionplugins;
120 /** @var array list of the installed feedback plugins */
121 private $feedbackplugins;
123 /** @var string action to be used to return to this page
124 * (without repeating any form submissions etc).
126 private $returnaction = 'view';
128 /** @var array params to be used to return to this page */
129 private $returnparams = array();
131 /** @var string modulename prevents excessive calls to get_string */
132 private static $modulename = null;
134 /** @var string modulenameplural prevents excessive calls to get_string */
135 private static $modulenameplural = null;
137 /** @var array of marking workflow states for the current user */
138 private $markingworkflowstates = null;
140 /** @var bool whether to exclude users with inactive enrolment */
141 private $showonlyactiveenrol = null;
143 /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
144 private $participants = array();
146 /** @var array cached list of user groups when team submissions are enabled. The cache key will be the user. */
147 private $usersubmissiongroups = array();
149 /** @var array cached list of user groups. The cache key will be the user. */
150 private $usergroups = array();
153 * Constructor for the base assign class.
155 * Note: For $coursemodule you can supply a stdclass if you like, but it
156 * will be more efficient to supply a cm_info object.
158 * @param mixed $coursemodulecontext context|null the course module context
159 * (or the course context if the coursemodule has not been
161 * @param mixed $coursemodule the current course module if it was already loaded,
162 * otherwise this class will load one from the context as required.
163 * @param mixed $course the current course if it was already loaded,
164 * otherwise this class will load one from the context as required.
166 public function __construct($coursemodulecontext, $coursemodule, $course) {
167 $this->context = $coursemodulecontext;
168 $this->course = $course;
170 // Ensure that $this->coursemodule is a cm_info object (or null).
171 $this->coursemodule = cm_info::create($coursemodule);
173 // Temporary cache only lives for a single request - used to reduce db lookups.
174 $this->cache = array();
176 $this->submissionplugins = $this->load_plugins('assignsubmission');
177 $this->feedbackplugins = $this->load_plugins('assignfeedback');
181 * Set the action and parameters that can be used to return to the current page.
183 * @param string $action The action for the current page
184 * @param array $params An array of name value pairs which form the parameters
185 * to return to the current page.
188 public function register_return_link($action, $params) {
190 $params['action'] = $action;
191 $currenturl = $PAGE->url;
193 $currenturl->params($params);
194 $PAGE->set_url($currenturl);
198 * Return an action that can be used to get back to the current page.
200 * @return string action
202 public function get_return_action() {
205 $params = $PAGE->url->params();
207 if (!empty($params['action'])) {
208 return $params['action'];
214 * Based on the current assignment settings should we display the intro.
216 * @return bool showintro
218 public function show_intro() {
219 if ($this->get_instance()->alwaysshowdescription ||
220 time() > $this->get_instance()->allowsubmissionsfromdate) {
227 * Return a list of parameters that can be used to get back to the current page.
229 * @return array params
231 public function get_return_params() {
234 $params = $PAGE->url->params();
235 unset($params['id']);
236 unset($params['action']);
241 * Set the submitted form data.
243 * @param stdClass $data The form data (instance)
245 public function set_instance(stdClass $data) {
246 $this->instance = $data;
252 * @param context $context The new context
254 public function set_context(context $context) {
255 $this->context = $context;
259 * Set the course data.
261 * @param stdClass $course The course data
263 public function set_course(stdClass $course) {
264 $this->course = $course;
268 * Get list of feedback plugins installed.
272 public function get_feedback_plugins() {
273 return $this->feedbackplugins;
277 * Get list of submission plugins installed.
281 public function get_submission_plugins() {
282 return $this->submissionplugins;
286 * Is blind marking enabled and reveal identities not set yet?
290 public function is_blind_marking() {
291 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
295 * Does an assignment have submission(s) or grade(s) already?
299 public function has_submissions_or_grades() {
300 $allgrades = $this->count_grades();
301 $allsubmissions = $this->count_submissions();
302 if (($allgrades == 0) && ($allsubmissions == 0)) {
309 * Get a specific submission plugin by its type.
311 * @param string $subtype assignsubmission | assignfeedback
312 * @param string $type
313 * @return mixed assign_plugin|null
315 public function get_plugin_by_type($subtype, $type) {
316 $shortsubtype = substr($subtype, strlen('assign'));
317 $name = $shortsubtype . 'plugins';
318 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
321 $pluginlist = $this->$name;
322 foreach ($pluginlist as $plugin) {
323 if ($plugin->get_type() == $type) {
331 * Get a feedback plugin by type.
333 * @param string $type - The type of plugin e.g comments
334 * @return mixed assign_feedback_plugin|null
336 public function get_feedback_plugin_by_type($type) {
337 return $this->get_plugin_by_type('assignfeedback', $type);
341 * Get a submission plugin by type.
343 * @param string $type - The type of plugin e.g comments
344 * @return mixed assign_submission_plugin|null
346 public function get_submission_plugin_by_type($type) {
347 return $this->get_plugin_by_type('assignsubmission', $type);
351 * Load the plugins from the sub folders under subtype.
353 * @param string $subtype - either submission or feedback
354 * @return array - The sorted list of plugins
356 protected function load_plugins($subtype) {
360 $names = core_component::get_plugin_list($subtype);
362 foreach ($names as $name => $path) {
363 if (file_exists($path . '/locallib.php')) {
364 require_once($path . '/locallib.php');
366 $shortsubtype = substr($subtype, strlen('assign'));
367 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
369 $plugin = new $pluginclass($this, $name);
371 if ($plugin instanceof assign_plugin) {
372 $idx = $plugin->get_sort_order();
373 while (array_key_exists($idx, $result)) {
376 $result[$idx] = $plugin;
385 * Display the assignment, used by view.php
387 * The assignment is displayed differently depending on your role,
388 * the settings for the assignment and the status of the assignment.
390 * @param string $action The current action if any.
391 * @return string - The page output.
393 public function view($action='') {
398 $nextpageparams = array();
400 if (!empty($this->get_course_module()->id)) {
401 $nextpageparams['id'] = $this->get_course_module()->id;
404 // Handle form submissions first.
405 if ($action == 'savesubmission') {
406 $action = 'editsubmission';
407 if ($this->process_save_submission($mform, $notices)) {
408 $action = 'redirect';
409 $nextpageparams['action'] = 'view';
411 } else if ($action == 'editprevioussubmission') {
412 $action = 'editsubmission';
413 if ($this->process_copy_previous_attempt($notices)) {
414 $action = 'redirect';
415 $nextpageparams['action'] = 'editsubmission';
417 } else if ($action == 'lock') {
418 $this->process_lock_submission();
419 $action = 'redirect';
420 $nextpageparams['action'] = 'grading';
421 } else if ($action == 'addattempt') {
422 $this->process_add_attempt(required_param('userid', PARAM_INT));
423 $action = 'redirect';
424 $nextpageparams['action'] = 'grading';
425 } else if ($action == 'reverttodraft') {
426 $this->process_revert_to_draft();
427 $action = 'redirect';
428 $nextpageparams['action'] = 'grading';
429 } else if ($action == 'unlock') {
430 $this->process_unlock_submission();
431 $action = 'redirect';
432 $nextpageparams['action'] = 'grading';
433 } else if ($action == 'setbatchmarkingworkflowstate') {
434 $this->process_set_batch_marking_workflow_state();
435 $action = 'redirect';
436 $nextpageparams['action'] = 'grading';
437 } else if ($action == 'setbatchmarkingallocation') {
438 $this->process_set_batch_marking_allocation();
439 $action = 'redirect';
440 $nextpageparams['action'] = 'grading';
441 } else if ($action == 'confirmsubmit') {
443 if ($this->process_submit_for_grading($mform, $notices)) {
444 $action = 'redirect';
445 $nextpageparams['action'] = 'view';
446 } else if ($notices) {
447 $action = 'viewsubmitforgradingerror';
449 } else if ($action == 'submitotherforgrading') {
450 if ($this->process_submit_other_for_grading($mform, $notices)) {
451 $action = 'redirect';
452 $nextpageparams['action'] = 'grading';
454 $action = 'viewsubmitforgradingerror';
456 } else if ($action == 'gradingbatchoperation') {
457 $action = $this->process_grading_batch_operation($mform);
458 if ($action == 'grading') {
459 $action = 'redirect';
460 $nextpageparams['action'] = 'grading';
462 } else if ($action == 'submitgrade') {
463 if (optional_param('saveandshownext', null, PARAM_RAW)) {
464 // Save and show next.
466 if ($this->process_save_grade($mform)) {
467 $action = 'redirect';
468 $nextpageparams['action'] = 'grade';
469 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
470 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
472 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
473 $action = 'redirect';
474 $nextpageparams['action'] = 'grade';
475 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
476 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
477 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
478 $action = 'redirect';
479 $nextpageparams['action'] = 'grade';
480 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
481 $nextpageparams['useridlistid'] = optional_param('useridlistid', time(), PARAM_INT);
482 } else if (optional_param('savegrade', null, PARAM_RAW)) {
483 // Save changes button.
485 if ($this->process_save_grade($mform)) {
486 $action = 'redirect';
487 $nextpageparams['action'] = 'savegradingresult';
491 $action = 'redirect';
492 $nextpageparams['action'] = 'grading';
494 } else if ($action == 'quickgrade') {
495 $message = $this->process_save_quick_grades();
496 $action = 'quickgradingresult';
497 } else if ($action == 'saveoptions') {
498 $this->process_save_grading_options();
499 $action = 'redirect';
500 $nextpageparams['action'] = 'grading';
501 } else if ($action == 'saveextension') {
502 $action = 'grantextension';
503 if ($this->process_save_extension($mform)) {
504 $action = 'redirect';
505 $nextpageparams['action'] = 'grading';
507 } else if ($action == 'revealidentitiesconfirm') {
508 $this->process_reveal_identities();
509 $action = 'redirect';
510 $nextpageparams['action'] = 'grading';
513 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
514 'useridlistid'=>optional_param('useridlistid', 0, PARAM_INT));
515 $this->register_return_link($action, $returnparams);
517 // Now show the right view page.
518 if ($action == 'redirect') {
519 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
520 redirect($nextpageurl);
522 } else if ($action == 'savegradingresult') {
523 $message = get_string('gradingchangessaved', 'assign');
524 $o .= $this->view_savegrading_result($message);
525 } else if ($action == 'quickgradingresult') {
527 $o .= $this->view_quickgrading_result($message);
528 } else if ($action == 'grade') {
529 $o .= $this->view_single_grade_page($mform);
530 } else if ($action == 'viewpluginassignfeedback') {
531 $o .= $this->view_plugin_content('assignfeedback');
532 } else if ($action == 'viewpluginassignsubmission') {
533 $o .= $this->view_plugin_content('assignsubmission');
534 } else if ($action == 'editsubmission') {
535 $o .= $this->view_edit_submission_page($mform, $notices);
536 } else if ($action == 'grading') {
537 $o .= $this->view_grading_page();
538 } else if ($action == 'downloadall') {
539 $o .= $this->download_submissions();
540 } else if ($action == 'submit') {
541 $o .= $this->check_submit_for_grading($mform);
542 } else if ($action == 'grantextension') {
543 $o .= $this->view_grant_extension($mform);
544 } else if ($action == 'revealidentities') {
545 $o .= $this->view_reveal_identities_confirm($mform);
546 } else if ($action == 'plugingradingbatchoperation') {
547 $o .= $this->view_plugin_grading_batch_operation($mform);
548 } else if ($action == 'viewpluginpage') {
549 $o .= $this->view_plugin_page();
550 } else if ($action == 'viewcourseindex') {
551 $o .= $this->view_course_index();
552 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
553 $o .= $this->view_batch_set_workflow_state($mform);
554 } else if ($action == 'viewbatchmarkingallocation') {
555 $o .= $this->view_batch_markingallocation($mform);
556 } else if ($action == 'viewsubmitforgradingerror') {
557 $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
559 $o .= $this->view_submission_page();
566 * Add this instance to the database.
568 * @param stdClass $formdata The data submitted from the form
569 * @param bool $callplugins This is used to skip the plugin code
570 * when upgrading an old assignment to a new one (the plugins get called manually)
571 * @return mixed false if an error occurs or the int id of the new instance
573 public function add_instance(stdClass $formdata, $callplugins) {
575 $adminconfig = $this->get_admin_config();
579 // Add the database record.
580 $update = new stdClass();
581 $update->name = $formdata->name;
582 $update->timemodified = time();
583 $update->timecreated = time();
584 $update->course = $formdata->course;
585 $update->courseid = $formdata->course;
586 $update->intro = $formdata->intro;
587 $update->introformat = $formdata->introformat;
588 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
589 $update->submissiondrafts = $formdata->submissiondrafts;
590 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
591 $update->sendnotifications = $formdata->sendnotifications;
592 $update->sendlatenotifications = $formdata->sendlatenotifications;
593 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
594 if (isset($formdata->sendstudentnotifications)) {
595 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
597 $update->duedate = $formdata->duedate;
598 $update->cutoffdate = $formdata->cutoffdate;
599 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
600 $update->grade = $formdata->grade;
601 $update->completionsubmit = !empty($formdata->completionsubmit);
602 $update->teamsubmission = $formdata->teamsubmission;
603 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
604 if (isset($formdata->teamsubmissiongroupingid)) {
605 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
607 $update->blindmarking = $formdata->blindmarking;
608 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
609 if (!empty($formdata->attemptreopenmethod)) {
610 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
612 if (!empty($formdata->maxattempts)) {
613 $update->maxattempts = $formdata->maxattempts;
615 if (isset($formdata->preventsubmissionnotingroup)) {
616 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
618 $update->markingworkflow = $formdata->markingworkflow;
619 $update->markingallocation = $formdata->markingallocation;
620 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
621 $update->markingallocation = 0;
624 $returnid = $DB->insert_record('assign', $update);
625 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
626 // Cache the course record.
627 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
629 $this->save_intro_draft_files($formdata);
632 // Call save_settings hook for submission plugins.
633 foreach ($this->submissionplugins as $plugin) {
634 if (!$this->update_plugin_instance($plugin, $formdata)) {
635 print_error($plugin->get_error());
639 foreach ($this->feedbackplugins as $plugin) {
640 if (!$this->update_plugin_instance($plugin, $formdata)) {
641 print_error($plugin->get_error());
646 // In the case of upgrades the coursemodule has not been set,
647 // so we need to wait before calling these two.
648 $this->update_calendar($formdata->coursemodule);
649 $this->update_gradebook(false, $formdata->coursemodule);
653 $update = new stdClass();
654 $update->id = $this->get_instance()->id;
655 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
656 $DB->update_record('assign', $update);
662 * Delete all grades from the gradebook for this assignment.
666 protected function delete_grades() {
669 $result = grade_update('mod/assign',
670 $this->get_course()->id,
673 $this->get_instance()->id,
676 array('deleted'=>1));
677 return $result == GRADE_UPDATE_OK;
681 * Delete this instance from the database.
683 * @return bool false if an error occurs
685 public function delete_instance() {
689 foreach ($this->submissionplugins as $plugin) {
690 if (!$plugin->delete_instance()) {
691 print_error($plugin->get_error());
695 foreach ($this->feedbackplugins as $plugin) {
696 if (!$plugin->delete_instance()) {
697 print_error($plugin->get_error());
702 // Delete files associated with this assignment.
703 $fs = get_file_storage();
704 if (! $fs->delete_area_files($this->context->id) ) {
708 // Delete_records will throw an exception if it fails - so no need for error checking here.
709 $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id));
710 $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id));
711 $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id));
712 $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id));
713 $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id));
715 // Delete items from the gradebook.
716 if (! $this->delete_grades()) {
720 // Delete the instance.
721 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
727 * Actual implementation of the reset course functionality, delete all the
728 * assignment submissions for course $data->courseid.
730 * @param stdClass $data the data submitted from the reset course.
731 * @return array status array
733 public function reset_userdata($data) {
736 $componentstr = get_string('modulenameplural', 'assign');
739 $fs = get_file_storage();
740 if (!empty($data->reset_assign_submissions)) {
741 // Delete files associated with this assignment.
742 foreach ($this->submissionplugins as $plugin) {
743 $fileareas = array();
744 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
745 $fileareas = $plugin->get_file_areas();
746 foreach ($fileareas as $filearea => $notused) {
747 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
750 if (!$plugin->delete_instance()) {
751 $status[] = array('component'=>$componentstr,
752 'item'=>get_string('deleteallsubmissions', 'assign'),
753 'error'=>$plugin->get_error());
757 foreach ($this->feedbackplugins as $plugin) {
758 $fileareas = array();
759 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
760 $fileareas = $plugin->get_file_areas();
761 foreach ($fileareas as $filearea => $notused) {
762 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
765 if (!$plugin->delete_instance()) {
766 $status[] = array('component'=>$componentstr,
767 'item'=>get_string('deleteallsubmissions', 'assign'),
768 'error'=>$plugin->get_error());
772 $assignids = $DB->get_records('assign', array('course' => $data->courseid), '', 'id');
773 list($sql, $params) = $DB->get_in_or_equal(array_keys($assignids));
775 $DB->delete_records_select('assign_submission', "assignment $sql", $params);
776 $DB->delete_records_select('assign_user_flags', "assignment $sql", $params);
778 $status[] = array('component'=>$componentstr,
779 'item'=>get_string('deleteallsubmissions', 'assign'),
782 if (!empty($data->reset_gradebook_grades)) {
783 $DB->delete_records_select('assign_grades', "assignment $sql", $params);
784 // Remove all grades from gradebook.
785 require_once($CFG->dirroot.'/mod/assign/lib.php');
786 assign_reset_gradebook($data->courseid);
788 // Reset revealidentities if both submissions and grades have been reset.
789 if ($this->get_instance()->blindmarking && $this->get_instance()->revealidentities) {
790 $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id));
794 // Updating dates - shift may be negative too.
795 if ($data->timeshift) {
796 shift_course_mod_dates('assign',
797 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
799 $data->courseid, $this->get_instance()->id);
800 $status[] = array('component'=>$componentstr,
801 'item'=>get_string('datechanged'),
809 * Update the settings for a single plugin.
811 * @param assign_plugin $plugin The plugin to update
812 * @param stdClass $formdata The form data
813 * @return bool false if an error occurs
815 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
816 if ($plugin->is_visible()) {
817 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
818 if (!empty($formdata->$enabledname)) {
820 if (!$plugin->save_settings($formdata)) {
821 print_error($plugin->get_error());
832 * Update the gradebook information for this assignment.
834 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
835 * @param int $coursemoduleid This is required because it might not exist in the database yet
838 public function update_gradebook($reset, $coursemoduleid) {
841 require_once($CFG->dirroot.'/mod/assign/lib.php');
842 $assign = clone $this->get_instance();
843 $assign->cmidnumber = $coursemoduleid;
845 // Set assign gradebook feedback plugin status (enabled and visible).
846 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
853 return assign_grade_item_update($assign, $param);
857 * Load and cache the admin config for this module.
859 * @return stdClass the plugin config
861 public function get_admin_config() {
862 if ($this->adminconfig) {
863 return $this->adminconfig;
865 $this->adminconfig = get_config('assign');
866 return $this->adminconfig;
870 * Update the calendar entries for this assignment.
872 * @param int $coursemoduleid - Required to pass this in because it might
873 * not exist in the database yet.
876 public function update_calendar($coursemoduleid) {
878 require_once($CFG->dirroot.'/calendar/lib.php');
880 // Special case for add_instance as the coursemodule has not been set yet.
881 $instance = $this->get_instance();
883 if ($instance->duedate) {
884 $event = new stdClass();
886 $params = array('modulename'=>'assign', 'instance'=>$instance->id);
887 $event->id = $DB->get_field('event', 'id', $params);
888 $event->name = $instance->name;
889 $event->timestart = $instance->duedate;
891 // Convert the links to pluginfile. It is a bit hacky but at this stage the files
892 // might not have been saved in the module area yet.
893 $intro = $instance->intro;
894 if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
895 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
898 // We need to remove the links to files as the calendar is not ready
899 // to support module events with file areas.
900 $intro = strip_pluginfile_content($intro);
901 if ($this->show_intro()) {
902 $event->description = array(
904 'format' => $instance->introformat
907 $event->description = array(
909 'format' => $instance->introformat
914 $calendarevent = calendar_event::load($event->id);
915 $calendarevent->update($event);
918 $event->courseid = $instance->course;
921 $event->modulename = 'assign';
922 $event->instance = $instance->id;
923 $event->eventtype = 'due';
924 $event->timeduration = 0;
925 calendar_event::create($event);
928 $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$instance->id));
934 * Update this instance in the database.
936 * @param stdClass $formdata - the data submitted from the form
937 * @return bool false if an error occurs
939 public function update_instance($formdata) {
941 $adminconfig = $this->get_admin_config();
943 $update = new stdClass();
944 $update->id = $formdata->instance;
945 $update->name = $formdata->name;
946 $update->timemodified = time();
947 $update->course = $formdata->course;
948 $update->intro = $formdata->intro;
949 $update->introformat = $formdata->introformat;
950 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
951 $update->submissiondrafts = $formdata->submissiondrafts;
952 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
953 $update->sendnotifications = $formdata->sendnotifications;
954 $update->sendlatenotifications = $formdata->sendlatenotifications;
955 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
956 if (isset($formdata->sendstudentnotifications)) {
957 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
959 $update->duedate = $formdata->duedate;
960 $update->cutoffdate = $formdata->cutoffdate;
961 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
962 $update->grade = $formdata->grade;
963 if (!empty($formdata->completionunlocked)) {
964 $update->completionsubmit = !empty($formdata->completionsubmit);
966 $update->teamsubmission = $formdata->teamsubmission;
967 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
968 if (isset($formdata->teamsubmissiongroupingid)) {
969 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
971 $update->blindmarking = $formdata->blindmarking;
972 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
973 if (!empty($formdata->attemptreopenmethod)) {
974 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
976 if (!empty($formdata->maxattempts)) {
977 $update->maxattempts = $formdata->maxattempts;
979 if (isset($formdata->preventsubmissionnotingroup)) {
980 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
982 $update->markingworkflow = $formdata->markingworkflow;
983 $update->markingallocation = $formdata->markingallocation;
984 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
985 $update->markingallocation = 0;
988 $result = $DB->update_record('assign', $update);
989 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
991 $this->save_intro_draft_files($formdata);
993 // Load the assignment so the plugins have access to it.
995 // Call save_settings hook for submission plugins.
996 foreach ($this->submissionplugins as $plugin) {
997 if (!$this->update_plugin_instance($plugin, $formdata)) {
998 print_error($plugin->get_error());
1002 foreach ($this->feedbackplugins as $plugin) {
1003 if (!$this->update_plugin_instance($plugin, $formdata)) {
1004 print_error($plugin->get_error());
1009 $this->update_calendar($this->get_course_module()->id);
1010 $this->update_gradebook(false, $this->get_course_module()->id);
1012 $update = new stdClass();
1013 $update->id = $this->get_instance()->id;
1014 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
1015 $DB->update_record('assign', $update);
1021 * Save the attachments in the draft areas.
1023 * @param stdClass $formdata
1025 protected function save_intro_draft_files($formdata) {
1026 if (isset($formdata->introattachments)) {
1027 file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1028 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1033 * Add elements in grading plugin form.
1035 * @param mixed $grade stdClass|null
1036 * @param MoodleQuickForm $mform
1037 * @param stdClass $data
1038 * @param int $userid - The userid we are grading
1041 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
1042 foreach ($this->feedbackplugins as $plugin) {
1043 if ($plugin->is_enabled() && $plugin->is_visible()) {
1044 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1052 * Add one plugins settings to edit plugin form.
1054 * @param assign_plugin $plugin The plugin to add the settings from
1055 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1056 * This form is modified directly (not returned).
1057 * @param array $pluginsenabled A list of form elements to be added to a group.
1058 * The new element is added to this array by this function.
1061 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1063 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1064 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1065 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1066 $mform->setType($name, PARAM_BOOL);
1067 $plugin->get_settings($mform);
1068 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1069 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1070 $label = $plugin->get_name();
1071 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1072 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1074 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1075 if ($plugin->get_config('enabled') !== false) {
1076 $default = $plugin->is_enabled();
1078 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1080 $plugin->get_settings($mform);
1086 * Add settings to edit plugin form.
1088 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1089 * This form is modified directly (not returned).
1092 public function add_all_plugin_settings(MoodleQuickForm $mform) {
1093 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1095 $submissionpluginsenabled = array();
1096 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1097 foreach ($this->submissionplugins as $plugin) {
1098 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1100 $group->setElements($submissionpluginsenabled);
1102 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1103 $feedbackpluginsenabled = array();
1104 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1105 foreach ($this->feedbackplugins as $plugin) {
1106 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1108 $group->setElements($feedbackpluginsenabled);
1109 $mform->setExpanded('submissiontypes');
1113 * Allow each plugin an opportunity to update the defaultvalues
1114 * passed in to the settings form (needed to set up draft areas for
1115 * editor and filemanager elements)
1117 * @param array $defaultvalues
1119 public function plugin_data_preprocessing(&$defaultvalues) {
1120 foreach ($this->submissionplugins as $plugin) {
1121 if ($plugin->is_visible()) {
1122 $plugin->data_preprocessing($defaultvalues);
1125 foreach ($this->feedbackplugins as $plugin) {
1126 if ($plugin->is_visible()) {
1127 $plugin->data_preprocessing($defaultvalues);
1133 * Get the name of the current module.
1135 * @return string the module name (Assignment)
1137 protected function get_module_name() {
1138 if (isset(self::$modulename)) {
1139 return self::$modulename;
1141 self::$modulename = get_string('modulename', 'assign');
1142 return self::$modulename;
1146 * Get the plural name of the current module.
1148 * @return string the module name plural (Assignments)
1150 protected function get_module_name_plural() {
1151 if (isset(self::$modulenameplural)) {
1152 return self::$modulenameplural;
1154 self::$modulenameplural = get_string('modulenameplural', 'assign');
1155 return self::$modulenameplural;
1159 * Has this assignment been constructed from an instance?
1163 public function has_instance() {
1164 return $this->instance || $this->get_course_module();
1168 * Get the settings for the current instance of this assignment
1170 * @return stdClass The settings
1172 public function get_instance() {
1174 if ($this->instance) {
1175 return $this->instance;
1177 if ($this->get_course_module()) {
1178 $params = array('id' => $this->get_course_module()->instance);
1179 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1181 if (!$this->instance) {
1182 throw new coding_exception('Improper use of the assignment class. ' .
1183 'Cannot load the assignment record.');
1185 return $this->instance;
1189 * Get the primary grade item for this assign instance.
1191 * @return stdClass The grade_item record
1193 public function get_grade_item() {
1194 if ($this->gradeitem) {
1195 return $this->gradeitem;
1197 $instance = $this->get_instance();
1198 $params = array('itemtype' => 'mod',
1199 'itemmodule' => 'assign',
1200 'iteminstance' => $instance->id,
1201 'courseid' => $instance->course,
1203 $this->gradeitem = grade_item::fetch($params);
1204 if (!$this->gradeitem) {
1205 throw new coding_exception('Improper use of the assignment class. ' .
1206 'Cannot load the grade item.');
1208 return $this->gradeitem;
1212 * Get the context of the current course.
1214 * @return mixed context|null The course context
1216 public function get_course_context() {
1217 if (!$this->context && !$this->course) {
1218 throw new coding_exception('Improper use of the assignment class. ' .
1219 'Cannot load the course context.');
1221 if ($this->context) {
1222 return $this->context->get_course_context();
1224 return context_course::instance($this->course->id);
1230 * Get the current course module.
1232 * @return cm_info|null The course module or null if not known
1234 public function get_course_module() {
1235 if ($this->coursemodule) {
1236 return $this->coursemodule;
1238 if (!$this->context) {
1242 if ($this->context->contextlevel == CONTEXT_MODULE) {
1243 $modinfo = get_fast_modinfo($this->get_course());
1244 $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
1245 return $this->coursemodule;
1251 * Get context module.
1255 public function get_context() {
1256 return $this->context;
1260 * Get the current course.
1262 * @return mixed stdClass|null The course
1264 public function get_course() {
1267 if ($this->course) {
1268 return $this->course;
1271 if (!$this->context) {
1274 $params = array('id' => $this->get_course_context()->instanceid);
1275 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1277 return $this->course;
1281 * Count the number of intro attachments.
1285 protected function count_attachments() {
1287 $fs = get_file_storage();
1288 $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1291 return count($files);
1295 * Are there any intro attachments to display?
1299 protected function has_visible_attachments() {
1300 return ($this->count_attachments() > 0);
1304 * Return a grade in user-friendly form, whether it's a scale or not.
1306 * @param mixed $grade int|null
1307 * @param boolean $editing Are we allowing changes to this grade?
1308 * @param int $userid The user id the grade belongs to
1309 * @param int $modified Timestamp from when the grade was last modified
1310 * @return string User-friendly representation of grade
1312 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1315 static $scalegrades = array();
1319 if ($this->get_instance()->grade >= 0) {
1321 if ($editing && $this->get_instance()->grade > 0) {
1325 $displaygrade = format_float($grade, 2);
1327 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1328 get_string('usergrade', 'assign') .
1330 $o .= '<input type="text"
1331 id="quickgrade_' . $userid . '"
1332 name="quickgrade_' . $userid . '"
1333 value="' . $displaygrade . '"
1336 class="quickgrade"/>';
1337 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1340 if ($grade == -1 || $grade === null) {
1343 $item = $this->get_grade_item();
1344 $o .= grade_format_gradevalue($grade, $item);
1345 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1346 // If displaying the raw grade, also display the total value.
1347 $o .= ' / ' . format_float($this->get_instance()->grade, 2);
1355 if (empty($this->cache['scale'])) {
1356 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1357 $this->cache['scale'] = make_menu_from_list($scale->scale);
1364 $o .= '<label class="accesshide"
1365 for="quickgrade_' . $userid . '">' .
1366 get_string('usergrade', 'assign') .
1368 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1369 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1370 foreach ($this->cache['scale'] as $optionid => $option) {
1372 if ($grade == $optionid) {
1373 $selected = 'selected="selected"';
1375 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1380 $scaleid = (int)$grade;
1381 if (isset($this->cache['scale'][$scaleid])) {
1382 $o .= $this->cache['scale'][$scaleid];
1392 * Load a list of users enrolled in the current course with the specified permission and group.
1395 * @param int $currentgroup
1396 * @param bool $idsonly
1397 * @return array List of user records
1399 public function list_participants($currentgroup, $idsonly) {
1401 if (empty($currentgroup)) {
1405 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1406 if (!isset($this->participants[$key])) {
1407 $users = get_enrolled_users($this->context, 'mod/assign:submit', $currentgroup, 'u.*', null, null, null,
1408 $this->show_only_active_users());
1410 $cm = $this->get_course_module();
1411 $info = new \core_availability\info_module($cm);
1412 $users = $info->filter_user_list($users);
1414 $this->participants[$key] = $users;
1419 foreach ($this->participants[$key] as $id => $user) {
1420 $idslist[$id] = new stdClass();
1421 $idslist[$id]->id = $id;
1425 return $this->participants[$key];
1429 * Load a count of valid teams for this assignment.
1431 * @param int $activitygroup Activity active group
1432 * @return int number of valid teams
1434 public function count_teams($activitygroup = 0) {
1438 $participants = $this->list_participants($activitygroup, true);
1440 // If a team submission grouping id is provided all good as all returned groups
1441 // are the submission teams, but if no team submission grouping was specified
1442 // $groups will contain all participants groups.
1443 if ($this->get_instance()->teamsubmissiongroupingid) {
1445 // We restrict the users to the selected group ones.
1446 $groups = groups_get_all_groups($this->get_course()->id,
1447 array_keys($participants),
1448 $this->get_instance()->teamsubmissiongroupingid,
1449 'DISTINCT g.id, g.name');
1451 $count = count($groups);
1453 // When a specific group is selected we don't count the default group users.
1454 if ($activitygroup == 0) {
1455 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1456 // See if there are any users in the default group.
1457 $defaultusers = $this->get_submission_group_members(0, true);
1458 if (count($defaultusers) > 0) {
1464 // It is faster to loop around participants if no grouping was specified.
1466 foreach ($participants as $participant) {
1467 if ($group = $this->get_submission_group($participant->id)) {
1468 $groups[$group->id] = true;
1469 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1474 $count = count($groups);
1481 * Load a count of active users enrolled in the current course with the specified permission and group.
1484 * @param int $currentgroup
1485 * @return int number of matching users
1487 public function count_participants($currentgroup) {
1488 return count($this->list_participants($currentgroup, true));
1492 * Load a count of active users submissions in the current module that require grading
1493 * This means the submission modification time is more recent than the
1494 * grading modification time and the status is SUBMITTED.
1496 * @return int number of matching submissions
1498 public function count_submissions_need_grading() {
1501 if ($this->get_instance()->teamsubmission) {
1502 // This does not make sense for group assignment because the submission is shared.
1506 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1507 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1509 $params['assignid'] = $this->get_instance()->id;
1510 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1512 $sql = 'SELECT COUNT(s.userid)
1513 FROM {assign_submission} s
1514 LEFT JOIN {assign_grades} g ON
1515 s.assignment = g.assignment AND
1516 s.userid = g.userid AND
1517 g.attemptnumber = s.attemptnumber
1518 JOIN(' . $esql . ') e ON e.id = s.userid
1521 s.assignment = :assignid AND
1522 s.timemodified IS NOT NULL AND
1523 s.status = :submitted AND
1524 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL)';
1526 return $DB->count_records_sql($sql, $params);
1530 * Load a count of grades.
1532 * @return int number of grades
1534 public function count_grades() {
1537 if (!$this->has_instance()) {
1541 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1542 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1544 $params['assignid'] = $this->get_instance()->id;
1546 $sql = 'SELECT COUNT(g.userid)
1547 FROM {assign_grades} g
1548 JOIN(' . $esql . ') e ON e.id = g.userid
1549 WHERE g.assignment = :assignid';
1551 return $DB->count_records_sql($sql, $params);
1555 * Load a count of submissions.
1557 * @param bool $includenew When true, also counts the submissions with status 'new'.
1558 * @return int number of submissions
1560 public function count_submissions($includenew = false) {
1563 if (!$this->has_instance()) {
1571 $sqlnew = ' AND s.status <> :status ';
1572 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
1575 if ($this->get_instance()->teamsubmission) {
1576 // We cannot join on the enrolment tables for group submissions (no userid).
1577 $sql = 'SELECT COUNT(DISTINCT s.groupid)
1578 FROM {assign_submission} s
1580 s.assignment = :assignid AND
1581 s.timemodified IS NOT NULL AND
1582 s.userid = :groupuserid' .
1585 $params['assignid'] = $this->get_instance()->id;
1586 $params['groupuserid'] = 0;
1588 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1589 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1591 $params = array_merge($params, $enrolparams);
1592 $params['assignid'] = $this->get_instance()->id;
1594 $sql = 'SELECT COUNT(DISTINCT s.userid)
1595 FROM {assign_submission} s
1596 JOIN(' . $esql . ') e ON e.id = s.userid
1598 s.assignment = :assignid AND
1599 s.timemodified IS NOT NULL ' .
1604 return $DB->count_records_sql($sql, $params);
1608 * Load a count of submissions with a specified status.
1610 * @param string $status The submission status - should match one of the constants
1611 * @return int number of matching submissions
1613 public function count_submissions_with_status($status) {
1616 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
1617 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
1619 $params['assignid'] = $this->get_instance()->id;
1620 $params['assignid2'] = $this->get_instance()->id;
1621 $params['submissionstatus'] = $status;
1623 if ($this->get_instance()->teamsubmission) {
1626 if ($currentgroup != 0) {
1627 // If there is an active group we should only display the current group users groups.
1628 $participants = $this->list_participants($currentgroup, true);
1629 $groups = groups_get_all_groups($this->get_course()->id,
1630 array_keys($participants),
1631 $this->get_instance()->teamsubmissiongroupingid,
1632 'DISTINCT g.id, g.name');
1633 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
1634 $groupsstr = 's.groupid ' . $groupssql . ' AND';
1635 $params = $params + $groupsparams;
1637 $sql = 'SELECT COUNT(s.groupid)
1638 FROM {assign_submission} s
1641 s.assignment = :assignid AND
1642 s.timemodified IS NOT NULL AND
1643 s.userid = :groupuserid AND '
1645 s.status = :submissionstatus';
1646 $params['groupuserid'] = 0;
1648 $sql = 'SELECT COUNT(s.userid)
1649 FROM {assign_submission} s
1650 JOIN(' . $esql . ') e ON e.id = s.userid
1653 s.assignment = :assignid AND
1654 s.timemodified IS NOT NULL AND
1655 s.status = :submissionstatus';
1659 return $DB->count_records_sql($sql, $params);
1663 * Utility function to get the userid for every row in the grading table
1664 * so the order can be frozen while we iterate it.
1666 * @return array An array of userids
1668 protected function get_grading_userid_list() {
1669 $filter = get_user_preferences('assign_filter', '');
1670 $table = new assign_grading_table($this, 0, $filter, 0, false);
1672 $useridlist = $table->get_column_data('userid');
1678 * Generate zip file from array of given files.
1680 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
1681 * This array is indexed by the final file name and each
1682 * element in the array is an instance of a stored_file object.
1683 * @return path of temp file - note this returned file does
1684 * not have a .zip extension - it is a temp file.
1686 protected function pack_files($filesforzipping) {
1688 // Create path for new zip file.
1689 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
1691 $zipper = new zip_packer();
1692 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
1699 * Finds all assignment notifications that have yet to be mailed out, and mails them.
1701 * Cron function to be run periodically according to the moodle cron.
1705 public static function cron() {
1708 // Only ever send a max of one days worth of updates.
1709 $yesterday = time() - (24 * 3600);
1711 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
1713 // Collect all submissions that require mailing.
1714 // Submissions are included if all are true:
1715 // - The assignment is visible in the gradebook.
1716 // - No previous notification has been sent.
1717 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
1718 // if marking workflow is enabled, the workflow state is at 'released'.
1719 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
1720 g.*, g.timemodified as lastmodified, cm.id as cmid
1722 JOIN {assign_grades} g ON g.assignment = a.id
1723 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
1724 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
1725 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
1726 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
1727 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
1728 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
1729 uf.mailed = 0 AND gri.hidden = 0
1730 ORDER BY a.course, cm.id";
1733 'yesterday' => $yesterday,
1734 'today' => $timenow,
1735 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
1737 $submissions = $DB->get_records_sql($sql, $params);
1739 if (!empty($submissions)) {
1741 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
1743 // Preload courses we are going to need those.
1744 $courseids = array();
1745 foreach ($submissions as $submission) {
1746 $courseids[] = $submission->course;
1749 // Filter out duplicates.
1750 $courseids = array_unique($courseids);
1751 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1752 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
1753 $sql = 'SELECT c.*, ' . $ctxselect .
1755 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
1756 WHERE c.id ' . $courseidsql;
1758 $params['contextlevel'] = CONTEXT_COURSE;
1759 $courses = $DB->get_records_sql($sql, $params);
1761 // Clean up... this could go on for a while.
1764 unset($courseidsql);
1767 // Message students about new feedback.
1768 foreach ($submissions as $submission) {
1770 mtrace("Processing assignment submission $submission->id ...");
1772 // Do not cache user lookups - could be too many.
1773 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
1774 mtrace('Could not find user ' . $submission->userid);
1778 // Use a cache to prevent the same DB queries happening over and over.
1779 if (!array_key_exists($submission->course, $courses)) {
1780 mtrace('Could not find course ' . $submission->course);
1783 $course = $courses[$submission->course];
1784 if (isset($course->ctxid)) {
1785 // Context has not yet been preloaded. Do so now.
1786 context_helper::preload_from_record($course);
1789 // Override the language and timezone of the "current" user, so that
1790 // mail is customised for the receiver.
1791 cron_setup_user($user, $course);
1793 // Context lookups are already cached.
1794 $coursecontext = context_course::instance($course->id);
1795 if (!is_enrolled($coursecontext, $user->id)) {
1796 $courseshortname = format_string($course->shortname,
1798 array('context' => $coursecontext));
1799 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
1803 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
1804 mtrace('Could not find grader ' . $submission->grader);
1808 $modinfo = get_fast_modinfo($course, $user->id);
1809 $cm = $modinfo->get_cm($submission->cmid);
1810 // Context lookups are already cached.
1811 $contextmodule = context_module::instance($cm->id);
1813 if (!$cm->uservisible) {
1814 // Hold mail notification for assignments the user cannot access until later.
1818 // Need to send this to the student.
1819 $messagetype = 'feedbackavailable';
1820 $eventtype = 'assign_notification';
1821 $updatetime = $submission->lastmodified;
1822 $modulename = get_string('modulename', 'assign');
1825 if ($submission->blindmarking && !$submission->revealidentities) {
1826 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
1828 $showusers = $submission->blindmarking && !$submission->revealidentities;
1829 self::send_assignment_notification($grader,
1842 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
1845 $DB->update_record('assign_user_flags', $flags);
1847 $flags = new stdClass();
1848 $flags->userid = $user->id;
1849 $flags->assignment = $submission->assignment;
1851 $DB->insert_record('assign_user_flags', $flags);
1856 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
1860 // Free up memory just to be sure.
1864 // Update calendar events to provide a description.
1868 allowsubmissionsfromdate >= :lastcron AND
1869 allowsubmissionsfromdate <= :timenow AND
1870 alwaysshowdescription = 0';
1871 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
1872 $newlyavailable = $DB->get_records_sql($sql, $params);
1873 foreach ($newlyavailable as $record) {
1874 $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
1875 $context = context_module::instance($cm->id);
1877 $assignment = new assign($context, null, null);
1878 $assignment->update_calendar($cm->id);
1885 * Mark in the database that this grade record should have an update notification sent by cron.
1887 * @param stdClass $grade a grade record keyed on id
1888 * @param bool $mailedoverride when true, flag notification to be sent again.
1889 * @return bool true for success
1891 public function notify_grade_modified($grade, $mailedoverride = false) {
1894 $flags = $this->get_user_flags($grade->userid, true);
1895 if ($flags->mailed != 1 || $mailedoverride) {
1899 return $this->update_user_flags($flags);
1903 * Update user flags for this user in this assignment.
1905 * @param stdClass $flags a flags record keyed on id
1906 * @return bool true for success
1908 public function update_user_flags($flags) {
1910 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
1914 $result = $DB->update_record('assign_user_flags', $flags);
1919 * Update a grade in the grade table for the assignment and in the gradebook.
1921 * @param stdClass $grade a grade record keyed on id
1922 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
1923 * @return bool true for success
1925 public function update_grade($grade, $reopenattempt = false) {
1928 $grade->timemodified = time();
1930 if (!empty($grade->workflowstate)) {
1931 $validstates = $this->get_marking_workflow_states_for_current_user();
1932 if (!array_key_exists($grade->workflowstate, $validstates)) {
1937 if ($grade->grade && $grade->grade != -1) {
1938 if ($this->get_instance()->grade > 0) {
1939 if (!is_numeric($grade->grade)) {
1941 } else if ($grade->grade > $this->get_instance()->grade) {
1943 } else if ($grade->grade < 0) {
1948 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
1949 $scaleoptions = make_menu_from_list($scale->scale);
1950 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
1957 if (empty($grade->attemptnumber)) {
1958 // Set it to the default.
1959 $grade->attemptnumber = 0;
1961 $DB->update_record('assign_grades', $grade);
1964 if ($this->get_instance()->teamsubmission) {
1965 $submission = $this->get_group_submission($grade->userid, 0, false);
1967 $submission = $this->get_user_submission($grade->userid, false);
1970 // Only push to gradebook if the update is for the latest attempt.
1971 // Not the latest attempt.
1972 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
1976 if ($this->gradebook_item_update(null, $grade)) {
1977 \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
1980 // If the conditions are met, allow another attempt.
1982 $this->reopen_submission_if_required($grade->userid,
1991 * View the grant extension date page.
1993 * Uses url parameters 'userid'
1994 * or from parameter 'selectedusers'
1996 * @param moodleform $mform - Used for validation of the submitted data
1999 protected function view_grant_extension($mform) {
2001 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2004 $batchusers = optional_param('selectedusers', '', PARAM_SEQUENCE);
2005 $data = new stdClass();
2006 $data->extensionduedate = null;
2009 $userid = required_param('userid', PARAM_INT);
2011 $flags = $this->get_user_flags($userid, false);
2013 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
2016 $data->extensionduedate = $flags->extensionduedate;
2018 $data->userid = $userid;
2020 $data->batchusers = $batchusers;
2022 $header = new assign_header($this->get_instance(),
2023 $this->get_context(),
2024 $this->show_intro(),
2025 $this->get_course_module()->id,
2026 get_string('grantextension', 'assign'));
2027 $o .= $this->get_renderer()->render($header);
2030 $formparams = array($this->get_course_module()->id,
2033 $this->get_instance(),
2035 $mform = new mod_assign_extension_form(null, $formparams);
2037 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
2038 $o .= $this->view_footer();
2043 * Get a list of the users in the same group as this user.
2045 * @param int $groupid The id of the group whose members we want or 0 for the default group
2046 * @param bool $onlyids Whether to retrieve only the user id's
2047 * @param bool $excludesuspended Whether to exclude suspended users
2048 * @return array The users (possibly id's only)
2050 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
2052 if ($groupid != 0) {
2054 $allusers = groups_get_members($groupid, 'u.id');
2056 $allusers = groups_get_members($groupid);
2058 foreach ($allusers as $user) {
2059 if ($this->get_submission_group($user->id)) {
2064 $allusers = $this->list_participants(null, $onlyids);
2065 foreach ($allusers as $user) {
2066 if ($this->get_submission_group($user->id) == null) {
2071 // Exclude suspended users, if user can't see them.
2072 if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2073 foreach ($members as $key => $member) {
2074 if (!$this->is_active_user($member->id)) {
2075 unset($members[$key]);
2084 * Get a list of the users in the same group as this user that have not submitted the assignment.
2086 * @param int $groupid The id of the group whose members we want or 0 for the default group
2087 * @param bool $onlyids Whether to retrieve only the user id's
2088 * @return array The users (possibly id's only)
2090 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2091 $instance = $this->get_instance();
2092 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2095 $members = $this->get_submission_group_members($groupid, $onlyids);
2097 foreach ($members as $id => $member) {
2098 $submission = $this->get_user_submission($member->id, false);
2099 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2100 unset($members[$id]);
2102 if ($this->is_blind_marking()) {
2103 $members[$id]->alias = get_string('hiddenuser', 'assign') .
2104 $this->get_uniqueid_for_user($id);
2112 * Load the group submission object for a particular user, optionally creating it if required.
2114 * @param int $userid The id of the user whose submission we want
2115 * @param int $groupid The id of the group for this user - may be 0 in which
2116 * case it is determined from the userid.
2117 * @param bool $create If set to true a new submission object will be created in the database
2118 * with the status set to "new".
2119 * @param int $attemptnumber - -1 means the latest attempt
2120 * @return stdClass The submission
2122 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2125 if ($groupid == 0) {
2126 $group = $this->get_submission_group($userid);
2128 $groupid = $group->id;
2132 // Now get the group submission.
2133 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2134 if ($attemptnumber >= 0) {
2135 $params['attemptnumber'] = $attemptnumber;
2138 // Only return the row with the highest attemptnumber.
2140 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2142 $submission = reset($submissions);
2149 $submission = new stdClass();
2150 $submission->assignment = $this->get_instance()->id;
2151 $submission->userid = 0;
2152 $submission->groupid = $groupid;
2153 $submission->timecreated = time();
2154 $submission->timemodified = $submission->timecreated;
2155 if ($attemptnumber >= 0) {
2156 $submission->attemptnumber = $attemptnumber;
2158 $submission->attemptnumber = 0;
2160 // Work out if this is the latest submission.
2161 $submission->latest = 0;
2162 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2163 if ($attemptnumber == -1) {
2164 // This is a new submission so it must be the latest.
2165 $submission->latest = 1;
2167 // We need to work this out.
2168 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2170 $latestsubmission = reset($result);
2172 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2173 $submission->latest = 1;
2176 if ($submission->latest) {
2177 // This is the case when we need to set latest to 0 for all the other attempts.
2178 $DB->set_field('assign_submission', 'latest', 0, $params);
2180 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2181 $sid = $DB->insert_record('assign_submission', $submission);
2182 return $DB->get_record('assign_submission', array('id' => $sid));
2188 * View a summary listing of all assignments in the current course.
2192 private function view_course_index() {
2197 $course = $this->get_course();
2198 $strplural = get_string('modulenameplural', 'assign');
2200 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2201 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2202 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2206 $strsectionname = '';
2207 $usesections = course_format_uses_sections($course->format);
2208 $modinfo = get_fast_modinfo($course);
2211 $strsectionname = get_string('sectionname', 'format_'.$course->format);
2212 $sections = $modinfo->get_section_info_all();
2214 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2218 $currentsection = '';
2219 foreach ($modinfo->instances['assign'] as $cm) {
2220 if (!$cm->uservisible) {
2224 $timedue = $cms[$cm->id]->duedate;
2227 if ($usesections && $cm->sectionnum) {
2228 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2232 $context = context_module::instance($cm->id);
2234 $assignment = new assign($context, $cm, $course);
2236 if (has_capability('mod/assign:grade', $context)) {
2237 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2239 } else if (has_capability('mod/assign:submit', $context)) {
2240 $usersubmission = $assignment->get_user_submission($USER->id, false);
2242 if (!empty($usersubmission->status)) {
2243 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2245 $submitted = get_string('submissionstatus_', 'assign');
2248 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2249 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2250 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2251 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2256 $courseindexsummary->add_assign_info($cm->id, $cm->name, $sectionname, $timedue, $submitted, $grade);
2260 $o .= $this->get_renderer()->render($courseindexsummary);
2261 $o .= $this->view_footer();
2267 * View a page rendered by a plugin.
2269 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2273 protected function view_plugin_page() {
2278 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2279 $plugintype = required_param('plugin', PARAM_TEXT);
2280 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2282 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2284 print_error('invalidformdata', '');
2288 $o .= $plugin->view_page($pluginaction);
2295 * This is used for team assignments to get the group for the specified user.
2296 * If the user is a member of multiple or no groups this will return false
2298 * @param int $userid The id of the user whose submission we want
2299 * @return mixed The group or false
2301 public function get_submission_group($userid) {
2303 if (isset($this->usersubmissiongroups[$userid])) {
2304 return $this->usersubmissiongroups[$userid];
2307 $groups = $this->get_all_groups($userid);
2308 if (count($groups) != 1) {
2311 $return = array_pop($groups);
2314 // Cache the user submission group.
2315 $this->usersubmissiongroups[$userid] = $return;
2321 * Gets all groups the user is a member of.
2323 * @param int $userid Teh id of the user who's groups we are checking
2324 * @return array The group objects
2326 public function get_all_groups($userid) {
2327 if (isset($this->usergroups[$userid])) {
2328 return $this->usergroups[$userid];
2331 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2332 $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2334 $this->usergroups[$userid] = $return;
2341 * Display the submission that is used by a plugin.
2343 * Uses url parameters 'sid', 'gid' and 'plugin'.
2345 * @param string $pluginsubtype
2348 protected function view_plugin_content($pluginsubtype) {
2351 $submissionid = optional_param('sid', 0, PARAM_INT);
2352 $gradeid = optional_param('gid', 0, PARAM_INT);
2353 $plugintype = required_param('plugin', PARAM_TEXT);
2355 if ($pluginsubtype == 'assignsubmission') {
2356 $plugin = $this->get_submission_plugin_by_type($plugintype);
2357 if ($submissionid <= 0) {
2358 throw new coding_exception('Submission id should not be 0');
2360 $item = $this->get_submission($submissionid);
2362 // Check permissions.
2363 $this->require_view_submission($item->userid);
2364 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2365 $this->get_context(),
2366 $this->show_intro(),
2367 $this->get_course_module()->id,
2368 $plugin->get_name()));
2369 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2371 assign_submission_plugin_submission::FULL,
2372 $this->get_course_module()->id,
2373 $this->get_return_action(),
2374 $this->get_return_params()));
2376 // Trigger event for viewing a submission.
2377 \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2380 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2381 if ($gradeid <= 0) {
2382 throw new coding_exception('Grade id should not be 0');
2384 $item = $this->get_grade($gradeid);
2385 // Check permissions.
2386 $this->require_view_submission($item->userid);
2387 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2388 $this->get_context(),
2389 $this->show_intro(),
2390 $this->get_course_module()->id,
2391 $plugin->get_name()));
2392 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2394 assign_feedback_plugin_feedback::FULL,
2395 $this->get_course_module()->id,
2396 $this->get_return_action(),
2397 $this->get_return_params()));
2399 // Trigger event for viewing feedback.
2400 \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
2403 $o .= $this->view_return_links();
2405 $o .= $this->view_footer();
2411 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2413 * @param string $text - The replacement text
2414 * @param stdClass $user - The user record
2415 * @param assign_plugin $plugin - The assignment plugin
2417 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2418 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2421 $groupid = groups_get_activity_group($this->get_course_module(), true);
2422 $groupname = groups_get_group_name($groupid).'-';
2425 if ($this->is_blind_marking()) {
2426 $prefix = $groupname . get_string('participant', 'assign');
2427 $prefix = str_replace('_', ' ', $prefix);
2428 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2430 $prefix = $groupname . fullname($user);
2431 $prefix = str_replace('_', ' ', $prefix);
2432 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2435 $subtype = $plugin->get_subtype();
2436 $type = $plugin->get_type();
2437 $prefix = $prefix . $subtype . '_' . $type . '_';
2439 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2445 * Render the content in editor that is often used by plugin.
2447 * @param string $filearea
2448 * @param int $submissionid
2449 * @param string $plugintype
2450 * @param string $editor
2451 * @param string $component
2454 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
2459 $plugin = $this->get_submission_plugin_by_type($plugintype);
2461 $text = $plugin->get_editor_text($editor, $submissionid);
2462 $format = $plugin->get_editor_format($editor, $submissionid);
2464 $finaltext = file_rewrite_pluginfile_urls($text,
2466 $this->get_context()->id,
2470 $params = array('overflowdiv' => true, 'context' => $this->get_context());
2471 $result .= format_text($finaltext, $format, $params);
2473 if ($CFG->enableportfolios && has_capability('mod/assign:exportownsubmission', $this->context)) {
2474 require_once($CFG->libdir . '/portfoliolib.php');
2476 $button = new portfolio_add_button();
2477 $portfolioparams = array('cmid' => $this->get_course_module()->id,
2478 'sid' => $submissionid,
2479 'plugin' => $plugintype,
2480 'editor' => $editor,
2482 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
2483 $fs = get_file_storage();
2485 if ($files = $fs->get_area_files($this->context->id,
2491 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
2493 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
2495 $result .= $button->to_html();
2501 * Display a continue page after grading.
2503 * @param string $message - The message to display.
2506 protected function view_savegrading_result($message) {
2508 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2509 $this->get_context(),
2510 $this->show_intro(),
2511 $this->get_course_module()->id,
2512 get_string('savegradingresult', 'assign')));
2513 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
2515 $this->get_course_module()->id);
2516 $o .= $this->get_renderer()->render($gradingresult);
2517 $o .= $this->view_footer();
2521 * Display a continue page after quickgrading.
2523 * @param string $message - The message to display.
2526 protected function view_quickgrading_result($message) {
2528 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2529 $this->get_context(),
2530 $this->show_intro(),
2531 $this->get_course_module()->id,
2532 get_string('quickgradingresult', 'assign')));
2533 $lastpage = optional_param('lastpage', null, PARAM_INT);
2534 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
2536 $this->get_course_module()->id,
2539 $o .= $this->get_renderer()->render($gradingresult);
2540 $o .= $this->view_footer();
2545 * Display the page footer.
2549 protected function view_footer() {
2550 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
2551 if (!PHPUNIT_TEST) {
2552 return $this->get_renderer()->render_footer();
2559 * Throw an error if the permissions to view this users submission are missing.
2561 * @throws required_capability_exception
2564 public function require_view_submission($userid) {
2565 if (!$this->can_view_submission($userid)) {
2566 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2571 * Throw an error if the permissions to view grades in this assignment are missing.
2573 * @throws required_capability_exception
2576 public function require_view_grades() {
2577 if (!$this->can_view_grades()) {
2578 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
2583 * Does this user have view grade or grade permission for this assignment?
2587 public function can_view_grades() {
2588 // Permissions check.
2589 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
2597 * Does this user have grade permission for this assignment?
2601 public function can_grade() {
2602 // Permissions check.
2603 if (!has_capability('mod/assign:grade', $this->context)) {
2611 * Download a zip file of all assignment submissions.
2613 * @return string - If an error occurs, this will contain the error page.
2615 protected function download_submissions() {
2618 // More efficient to load this here.
2619 require_once($CFG->libdir.'/filelib.php');
2621 // Increase the server timeout to handle the creation and sending of large zip files.
2622 core_php_time_limit::raise();
2624 $this->require_view_grades();
2626 // Load all users with submit.
2627 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
2628 $this->show_only_active_users());
2630 // Build a list of files to zip.
2631 $filesforzipping = array();
2632 $fs = get_file_storage();
2634 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2639 $groupid = groups_get_activity_group($this->get_course_module(), true);
2640 $groupname = groups_get_group_name($groupid).'-';
2643 // Construct the zip file name.
2644 $filename = clean_filename($this->get_course()->shortname . '-' .
2645 $this->get_instance()->name . '-' .
2646 $groupname.$this->get_course_module()->id . '.zip');
2648 // Get all the files for each student.
2649 foreach ($students as $student) {
2650 $userid = $student->id;
2652 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
2653 // Get the plugins to add their own files to the zip.
2655 $submissiongroup = false;
2657 if ($this->get_instance()->teamsubmission) {
2658 $submission = $this->get_group_submission($userid, 0, false);
2659 $submissiongroup = $this->get_submission_group($userid);
2660 if ($submissiongroup) {
2661 $groupname = $submissiongroup->name . '-';
2663 $groupname = get_string('defaultteam', 'assign') . '-';
2666 $submission = $this->get_user_submission($userid, false);
2669 if ($this->is_blind_marking()) {
2670 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
2671 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2673 $prefix = str_replace('_', ' ', $groupname . fullname($student));
2674 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
2678 foreach ($this->submissionplugins as $plugin) {
2679 if ($plugin->is_enabled() && $plugin->is_visible()) {
2680 $pluginfiles = $plugin->get_files($submission, $student);
2681 foreach ($pluginfiles as $zipfilename => $file) {
2682 $subtype = $plugin->get_subtype();
2683 $type = $plugin->get_type();
2684 $prefixedfilename = clean_filename($prefix .
2690 $filesforzipping[$prefixedfilename] = $file;
2698 if (count($filesforzipping) == 0) {
2699 $header = new assign_header($this->get_instance(),
2700 $this->get_context(),
2702 $this->get_course_module()->id,
2703 get_string('downloadall', 'assign'));
2704 $result .= $this->get_renderer()->render($header);
2705 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
2706 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
2707 'action'=>'grading'));
2708 $result .= $this->get_renderer()->continue_button($url);
2709 $result .= $this->view_footer();
2710 } else if ($zipfile = $this->pack_files($filesforzipping)) {
2711 \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
2712 // Send file and delete after sending.
2713 send_temp_file($zipfile, $filename);
2714 // We will not get here - send_temp_file calls exit.
2720 * Util function to add a message to the log.
2722 * @deprecated since 2.7 - Use new events system instead.
2723 * (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
2725 * @param string $action The current action
2726 * @param string $info A detailed description of the change. But no more than 255 characters.
2727 * @param string $url The url to the assign module instance.
2728 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
2729 * retrieve the arguments to use them with the new event system (Event 2).
2730 * @return void|array
2732 public function add_to_log($action = '', $info = '', $url='', $return = false) {
2735 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
2737 $fullurl .= '&' . $url;
2741 $this->get_course()->id,
2746 $this->get_course_module()->id
2750 // We only need to call debugging when returning a value. This is because the call to
2751 // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
2752 debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
2755 call_user_func_array('add_to_log', $args);
2759 * Lazy load the page renderer and expose the renderer to plugins.
2761 * @return assign_renderer
2763 public function get_renderer() {
2765 if ($this->output) {
2766 return $this->output;
2768 $this->output = $PAGE->get_renderer('mod_assign');
2769 return $this->output;
2773 * Load the submission object for a particular user, optionally creating it if required.
2775 * For team assignments there are 2 submissions - the student submission and the team submission
2776 * All files are associated with the team submission but the status of the students contribution is
2777 * recorded separately.
2779 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
2780 * @param bool $create optional - defaults to false. If set to true a new submission object
2781 * will be created in the database with the status set to "new".
2782 * @param int $attemptnumber - -1 means the latest attempt
2783 * @return stdClass The submission
2785 public function get_user_submission($userid, $create, $attemptnumber=-1) {
2789 $userid = $USER->id;
2791 // If the userid is not null then use userid.
2792 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2793 if ($attemptnumber >= 0) {
2794 $params['attemptnumber'] = $attemptnumber;
2797 // Only return the row with the highest attemptnumber.
2799 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2801 $submission = reset($submissions);
2808 $submission = new stdClass();
2809 $submission->assignment = $this->get_instance()->id;
2810 $submission->userid = $userid;
2811 $submission->timecreated = time();
2812 $submission->timemodified = $submission->timecreated;
2813 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2814 if ($attemptnumber >= 0) {
2815 $submission->attemptnumber = $attemptnumber;
2817 $submission->attemptnumber = 0;
2819 // Work out if this is the latest submission.
2820 $submission->latest = 0;
2821 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
2822 if ($attemptnumber == -1) {
2823 // This is a new submission so it must be the latest.
2824 $submission->latest = 1;
2826 // We need to work this out.
2827 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2828 $latestsubmission = null;
2830 $latestsubmission = reset($result);
2832 if (empty($latestsubmission) || ($attemptnumber > $latestsubmission->attemptnumber)) {
2833 $submission->latest = 1;
2836 if ($submission->latest) {
2837 // This is the case when we need to set latest to 0 for all the other attempts.
2838 $DB->set_field('assign_submission', 'latest', 0, $params);
2840 $sid = $DB->insert_record('assign_submission', $submission);
2841 return $DB->get_record('assign_submission', array('id' => $sid));
2847 * Load the submission object from it's id.
2849 * @param int $submissionid The id of the submission we want
2850 * @return stdClass The submission
2852 protected function get_submission($submissionid) {
2855 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
2856 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
2860 * This will retrieve a user flags object from the db optionally creating it if required.
2861 * The user flags was split from the user_grades table in 2.5.
2863 * @param int $userid The user we are getting the flags for.
2864 * @param bool $create If true the flags record will be created if it does not exist
2865 * @return stdClass The flags record
2867 public function get_user_flags($userid, $create) {
2870 // If the userid is not null then use userid.
2872 $userid = $USER->id;
2875 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2877 $flags = $DB->get_record('assign_user_flags', $params);
2883 $flags = new stdClass();
2884 $flags->assignment = $this->get_instance()->id;
2885 $flags->userid = $userid;
2887 $flags->extensionduedate = 0;
2888 $flags->workflowstate = '';
2889 $flags->allocatedmarker = 0;
2891 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
2892 // This is because students only want to be notified about certain types of update (grades and feedback).
2895 $fid = $DB->insert_record('assign_user_flags', $flags);
2903 * This will retrieve a grade object from the db, optionally creating it if required.
2905 * @param int $userid The user we are grading
2906 * @param bool $create If true the grade will be created if it does not exist
2907 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
2908 * @return stdClass The grade record
2910 public function get_user_grade($userid, $create, $attemptnumber=-1) {
2913 // If the userid is not null then use userid.
2915 $userid = $USER->id;
2919 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
2920 if ($attemptnumber < 0 || $create) {
2921 // Make sure this grade matches the latest submission attempt.
2922 if ($this->get_instance()->teamsubmission) {
2923 $submission = $this->get_group_submission($userid, 0, true);
2925 $submission = $this->get_user_submission($userid, true);
2928 $attemptnumber = $submission->attemptnumber;
2932 if ($attemptnumber >= 0) {
2933 $params['attemptnumber'] = $attemptnumber;
2936 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
2939 return reset($grades);
2942 $grade = new stdClass();
2943 $grade->assignment = $this->get_instance()->id;
2944 $grade->userid = $userid;
2945 $grade->timecreated = time();
2946 // If we are "auto-creating" a grade - and there is a submission
2947 // the new grade should not have a more recent timemodified value
2948 // than the submission.
2950 $grade->timemodified = $submission->timemodified;
2952 $grade->timemodified = $grade->timecreated;
2955 $grade->grader = $USER->id;
2956 if ($attemptnumber >= 0) {
2957 $grade->attemptnumber = $attemptnumber;
2960 $gid = $DB->insert_record('assign_grades', $grade);
2968 * This will retrieve a grade object from the db.
2970 * @param int $gradeid The id of the grade
2971 * @return stdClass The grade record
2973 protected function get_grade($gradeid) {
2976 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
2977 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
2981 * Print the grading page for a single user submission.
2983 * @param moodleform $mform
2986 protected function view_single_grade_page($mform) {
2990 $instance = $this->get_instance();
2992 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
2994 // Need submit permission to submit an assignment.
2995 require_capability('mod/assign:grade', $this->context);
2997 $header = new assign_header($instance,
2998 $this->get_context(),
3000 $this->get_course_module()->id,
3001 get_string('grading', 'assign'));
3002 $o .= $this->get_renderer()->render($header);
3004 // If userid is passed - we are only grading a single student.
3005 $rownum = required_param('rownum', PARAM_INT);
3006 $useridlistid = optional_param('useridlistid', time(), PARAM_INT);
3007 $userid = optional_param('userid', 0, PARAM_INT);
3008 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
3010 $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
3012 if (!$useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid)) {
3013 $useridlist = $this->get_grading_userid_list();
3015 $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
3018 $useridlist = array($userid);
3021 if ($rownum < 0 || $rownum > count($useridlist)) {
3022 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
3026 $userid = $useridlist[$rownum];
3027 if ($rownum == count($useridlist) - 1) {
3030 // This variation on the url will link direct to this student, with no next/previous links.
3031 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3032 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3033 $this->register_return_link('grade', $returnparams);
3035 $user = $DB->get_record('user', array('id' => $userid));
3037 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3038 $usersummary = new assign_user_summary($user,
3039 $this->get_course()->id,
3041 $this->is_blind_marking(),
3042 $this->get_uniqueid_for_user($user->id),
3043 get_extra_user_fields($this->get_context()),
3044 !$this->is_active_user($userid));
3045 $o .= $this->get_renderer()->render($usersummary);
3047 $submission = $this->get_user_submission($userid, false, $attemptnumber);
3048 $submissiongroup = null;
3049 $teamsubmission = null;
3050 $notsubmitted = array();
3051 if ($instance->teamsubmission) {
3052 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
3053 $submissiongroup = $this->get_submission_group($userid);
3055 if ($submissiongroup) {
3056 $groupid = $submissiongroup->id;
3058 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3062 // Get the requested grade.
3063 $grade = $this->get_user_grade($userid, false, $attemptnumber);
3064 $flags = $this->get_user_flags($userid, false);
3065 if ($this->can_view_submission($userid)) {
3066 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
3067 $extensionduedate = null;
3069 $extensionduedate = $flags->extensionduedate;
3071 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
3072 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
3073 $usergroups = $this->get_all_groups($user->id);
3075 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
3076 $instance->alwaysshowdescription,
3078 $instance->teamsubmission,
3082 $this->is_any_submission_plugin_enabled(),
3084 $this->is_graded($userid),
3086 $instance->cutoffdate,
3087 $this->get_submission_plugins(),
3088 $this->get_return_action(),
3089 $this->get_return_params(),
3090 $this->get_course_module()->id,
3091 $this->get_course()->id,
3092 assign_submission_status::GRADER_VIEW,
3097 $this->get_context(),
3098 $this->is_blind_marking(),
3100 $instance->attemptreopenmethod,
3101 $instance->maxattempts,
3102 $this->get_grading_status($userid),
3103 $instance->preventsubmissionnotingroup,
3105 $o .= $this->get_renderer()->render($submissionstatus);
3109 $data = new stdClass();
3110 if ($grade->grade !== null && $grade->grade >= 0) {
3111 $data->grade = format_float($grade->grade, 2);
3114 $data = new stdClass();
3118 if (!empty($flags->workflowstate)) {
3119 $data->workflowstate = $flags->workflowstate;
3121 if (!empty($flags->allocatedmarker)) {
3122 $data->allocatedmarker = $flags->allocatedmarker;
3125 // Warning if required.
3126 $allsubmissions = $this->get_all_submissions($userid);
3128 if ($attemptnumber != -1) {
3129 $params = array('attemptnumber'=>$attemptnumber + 1,
3130 'totalattempts'=>count($allsubmissions));
3131 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
3132 $o .= $this->get_renderer()->notification($message);
3135 // Now show the grading form.
3137 $pagination = array('rownum'=>$rownum,
3138 'useridlistid'=>$useridlistid,
3140 'userid'=>optional_param('userid', 0, PARAM_INT),
3141 'attemptnumber'=>$attemptnumber);
3142 $formparams = array($this, $data, $pagination);
3143 $mform = new mod_assign_grade_form(null,
3147 array('class'=>'gradeform'));
3149 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
3150 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
3152 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
3153 $allgrades = $this->get_all_grades($userid);
3154 $history = new assign_attempt_history($allsubmissions,
3156 $this->get_submission_plugins(),
3157 $this->get_feedback_plugins(),
3158 $this->get_course_module()->id,
3159 $this->get_return_action(),
3160 $this->get_return_params(),
3165 $o .= $this->get_renderer()->render($history);
3168 \mod_assign\event\grading_form_viewed::create_from_user($this, $user)->trigger();
3170 $o .= $this->view_footer();
3175 * Show a confirmation page to make sure they want to release student identities.
3179 protected function view_reveal_identities_confirm() {
3180 require_capability('mod/assign:revealidentities', $this->get_context());
3183 $header = new assign_header($this->get_instance(),
3184 $this->get_context(),
3186 $this->get_course_module()->id);
3187 $o .= $this->get_renderer()->render($header);
3189 $urlparams = array('id'=>$this->get_course_module()->id,
3190 'action'=>'revealidentitiesconfirm',
3191 'sesskey'=>sesskey());
3192 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
3194 $urlparams = array('id'=>$this->get_course_module()->id,
3195 'action'=>'grading');
3196 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
3198 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
3201 $o .= $this->view_footer();
3203 \mod_assign\event\reveal_identities_confirmation_page_viewed::create_from_assign($this)->trigger();
3209 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3213 protected function view_return_links() {
3214 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
3215 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3218 $returnparams = str_replace('&', '&', $returnparams);
3219 parse_str($returnparams, $params);
3220 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3221 $params = array_merge($newparams, $params);
3223 $url = new moodle_url('/mod/assign/view.php', $params);
3224 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3228 * View the grading table of all submissions for this assignment.
3232 protected function view_grading_table() {
3235 // Include grading options form.
3236 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3237 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3238 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3240 $cmid = $this->get_course_module()->id;
3243 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3244 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3245 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3246 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3248 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
3249 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
3250 $links[$downloadurl] = get_string('downloadall', 'assign');
3252 if ($this->is_blind_marking() &&
3253 has_capability('mod/assign:revealidentities', $this->get_context())) {
3254 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
3255 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
3257 foreach ($this->get_feedback_plugins() as $plugin) {
3258 if ($plugin->is_enabled() && $plugin->is_visible()) {
3259 foreach ($plugin->get_grading_actions() as $action => $description) {
3260 $url = '/mod/assign/view.php' .
3262 '&plugin=' . $plugin->get_type() .
3263 '&pluginsubtype=assignfeedback' .
3264 '&action=viewpluginpage&pluginaction=' . $action;
3265 $links[$url] = $description;