MDL-57730 mod_assign: added action events
[moodle.git] / mod / assign / locallib.php
blob4ca21b3fcc08c12cb9fbce9dcb7eebd7c5bf6840
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * This file contains the definition for the class assignment
20 * This class provides all the functionality for the new assign module.
22 * @package mod_assign
23 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 // Assignment submission statuses.
30 define('ASSIGN_SUBMISSION_STATUS_NEW', 'new');
31 define('ASSIGN_SUBMISSION_STATUS_REOPENED', 'reopened');
32 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
33 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
35 // Search filters for grading page.
36 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
37 define('ASSIGN_FILTER_NOT_SUBMITTED', 'notsubmitted');
38 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
39 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
40 define('ASSIGN_FILTER_GRANTED_EXTENSION', 'granted_extension');
42 // Marker filter for grading page.
43 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
45 // Reopen attempt methods.
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
47 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
48 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
50 // Special value means allow unlimited attempts.
51 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
53 // Grading states.
54 define('ASSIGN_GRADING_STATUS_GRADED', 'graded');
55 define('ASSIGN_GRADING_STATUS_NOT_GRADED', 'notgraded');
57 // Marking workflow states.
58 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
59 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
60 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
61 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
62 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
63 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
65 /** ASSIGN_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
66 define("ASSIGN_MAX_EVENT_LENGTH", "432000");
68 // Name of file area for intro attachments.
69 define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
71 // Event types.
72 define('ASSIGN_EVENT_TYPE_DUE', 'due');
73 define('ASSIGN_EVENT_TYPE_GRADINGDUE', 'gradingdue');
74 define('ASSIGN_EVENT_TYPE_OPEN', 'open');
75 define('ASSIGN_EVENT_TYPE_CLOSE', 'close');
77 require_once($CFG->libdir . '/accesslib.php');
78 require_once($CFG->libdir . '/formslib.php');
79 require_once($CFG->dirroot . '/repository/lib.php');
80 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
81 require_once($CFG->libdir . '/gradelib.php');
82 require_once($CFG->dirroot . '/grade/grading/lib.php');
83 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
84 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
85 require_once($CFG->dirroot . '/mod/assign/renderable.php');
86 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
87 require_once($CFG->libdir . '/eventslib.php');
88 require_once($CFG->libdir . '/portfolio/caller.php');
90 use \mod_assign\output\grading_app;
92 /**
93 * Standard base class for mod_assign (assignment types).
95 * @package mod_assign
96 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
97 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
99 class assign {
101 /** @var stdClass the assignment record that contains the global settings for this assign instance */
102 private $instance;
104 /** @var grade_item the grade_item record for this assign instance's primary grade item. */
105 private $gradeitem;
107 /** @var context the context of the course module for this assign instance
108 * (or just the course if we are creating a new one)
110 private $context;
112 /** @var stdClass the course this assign instance belongs to */
113 private $course;
115 /** @var stdClass the admin config for all assign instances */
116 private $adminconfig;
118 /** @var assign_renderer the custom renderer for this module */
119 private $output;
121 /** @var cm_info the course module for this assign instance */
122 private $coursemodule;
124 /** @var array cache for things like the coursemodule name or the scale menu -
125 * only lives for a single request.
127 private $cache;
129 /** @var array list of the installed submission plugins */
130 private $submissionplugins;
132 /** @var array list of the installed feedback plugins */
133 private $feedbackplugins;
135 /** @var string action to be used to return to this page
136 * (without repeating any form submissions etc).
138 private $returnaction = 'view';
140 /** @var array params to be used to return to this page */
141 private $returnparams = array();
143 /** @var string modulename prevents excessive calls to get_string */
144 private static $modulename = null;
146 /** @var string modulenameplural prevents excessive calls to get_string */
147 private static $modulenameplural = null;
149 /** @var array of marking workflow states for the current user */
150 private $markingworkflowstates = null;
152 /** @var bool whether to exclude users with inactive enrolment */
153 private $showonlyactiveenrol = null;
155 /** @var string A key used to identify userlists created by this object. */
156 private $useridlistid = null;
158 /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
159 private $participants = array();
161 /** @var array cached list of user groups when team submissions are enabled. The cache key will be the user. */
162 private $usersubmissiongroups = array();
164 /** @var array cached list of user groups. The cache key will be the user. */
165 private $usergroups = array();
167 /** @var array cached list of IDs of users who share group membership with the user. The cache key will be the user. */
168 private $sharedgroupmembers = array();
171 * Constructor for the base assign class.
173 * Note: For $coursemodule you can supply a stdclass if you like, but it
174 * will be more efficient to supply a cm_info object.
176 * @param mixed $coursemodulecontext context|null the course module context
177 * (or the course context if the coursemodule has not been
178 * created yet).
179 * @param mixed $coursemodule the current course module if it was already loaded,
180 * otherwise this class will load one from the context as required.
181 * @param mixed $course the current course if it was already loaded,
182 * otherwise this class will load one from the context as required.
184 public function __construct($coursemodulecontext, $coursemodule, $course) {
185 global $SESSION;
187 $this->context = $coursemodulecontext;
188 $this->course = $course;
190 // Ensure that $this->coursemodule is a cm_info object (or null).
191 $this->coursemodule = cm_info::create($coursemodule);
193 // Temporary cache only lives for a single request - used to reduce db lookups.
194 $this->cache = array();
196 $this->submissionplugins = $this->load_plugins('assignsubmission');
197 $this->feedbackplugins = $this->load_plugins('assignfeedback');
199 // Extra entropy is required for uniqid() to work on cygwin.
200 $this->useridlistid = clean_param(uniqid('', true), PARAM_ALPHANUM);
202 if (!isset($SESSION->mod_assign_useridlist)) {
203 $SESSION->mod_assign_useridlist = [];
208 * Set the action and parameters that can be used to return to the current page.
210 * @param string $action The action for the current page
211 * @param array $params An array of name value pairs which form the parameters
212 * to return to the current page.
213 * @return void
215 public function register_return_link($action, $params) {
216 global $PAGE;
217 $params['action'] = $action;
218 $cm = $this->get_course_module();
219 if ($cm) {
220 $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $cm->id));
221 } else {
222 $currenturl = new moodle_url('/mod/assign/index.php', array('id' => $this->get_course()->id));
225 $currenturl->params($params);
226 $PAGE->set_url($currenturl);
230 * Return an action that can be used to get back to the current page.
232 * @return string action
234 public function get_return_action() {
235 global $PAGE;
237 // Web services don't set a URL, we should avoid debugging when ussing the url object.
238 if (!WS_SERVER) {
239 $params = $PAGE->url->params();
242 if (!empty($params['action'])) {
243 return $params['action'];
245 return '';
249 * Based on the current assignment settings should we display the intro.
251 * @return bool showintro
253 public function show_intro() {
254 if ($this->get_instance()->alwaysshowdescription ||
255 time() > $this->get_instance()->allowsubmissionsfromdate) {
256 return true;
258 return false;
262 * Return a list of parameters that can be used to get back to the current page.
264 * @return array params
266 public function get_return_params() {
267 global $PAGE;
269 $params = $PAGE->url->params();
270 unset($params['id']);
271 unset($params['action']);
272 return $params;
276 * Set the submitted form data.
278 * @param stdClass $data The form data (instance)
280 public function set_instance(stdClass $data) {
281 $this->instance = $data;
285 * Set the context.
287 * @param context $context The new context
289 public function set_context(context $context) {
290 $this->context = $context;
294 * Set the course data.
296 * @param stdClass $course The course data
298 public function set_course(stdClass $course) {
299 $this->course = $course;
303 * Get list of feedback plugins installed.
305 * @return array
307 public function get_feedback_plugins() {
308 return $this->feedbackplugins;
312 * Get list of submission plugins installed.
314 * @return array
316 public function get_submission_plugins() {
317 return $this->submissionplugins;
321 * Is blind marking enabled and reveal identities not set yet?
323 * @return bool
325 public function is_blind_marking() {
326 return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
330 * Does an assignment have submission(s) or grade(s) already?
332 * @return bool
334 public function has_submissions_or_grades() {
335 $allgrades = $this->count_grades();
336 $allsubmissions = $this->count_submissions();
337 if (($allgrades == 0) && ($allsubmissions == 0)) {
338 return false;
340 return true;
344 * Get a specific submission plugin by its type.
346 * @param string $subtype assignsubmission | assignfeedback
347 * @param string $type
348 * @return mixed assign_plugin|null
350 public function get_plugin_by_type($subtype, $type) {
351 $shortsubtype = substr($subtype, strlen('assign'));
352 $name = $shortsubtype . 'plugins';
353 if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
354 return null;
356 $pluginlist = $this->$name;
357 foreach ($pluginlist as $plugin) {
358 if ($plugin->get_type() == $type) {
359 return $plugin;
362 return null;
366 * Get a feedback plugin by type.
368 * @param string $type - The type of plugin e.g comments
369 * @return mixed assign_feedback_plugin|null
371 public function get_feedback_plugin_by_type($type) {
372 return $this->get_plugin_by_type('assignfeedback', $type);
376 * Get a submission plugin by type.
378 * @param string $type - The type of plugin e.g comments
379 * @return mixed assign_submission_plugin|null
381 public function get_submission_plugin_by_type($type) {
382 return $this->get_plugin_by_type('assignsubmission', $type);
386 * Load the plugins from the sub folders under subtype.
388 * @param string $subtype - either submission or feedback
389 * @return array - The sorted list of plugins
391 public function load_plugins($subtype) {
392 global $CFG;
393 $result = array();
395 $names = core_component::get_plugin_list($subtype);
397 foreach ($names as $name => $path) {
398 if (file_exists($path . '/locallib.php')) {
399 require_once($path . '/locallib.php');
401 $shortsubtype = substr($subtype, strlen('assign'));
402 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
404 $plugin = new $pluginclass($this, $name);
406 if ($plugin instanceof assign_plugin) {
407 $idx = $plugin->get_sort_order();
408 while (array_key_exists($idx, $result)) {
409 $idx +=1;
411 $result[$idx] = $plugin;
415 ksort($result);
416 return $result;
420 * Display the assignment, used by view.php
422 * The assignment is displayed differently depending on your role,
423 * the settings for the assignment and the status of the assignment.
425 * @param string $action The current action if any.
426 * @param array $args Optional arguments to pass to the view (instead of getting them from GET and POST).
427 * @return string - The page output.
429 public function view($action='', $args = array()) {
430 global $PAGE;
432 $o = '';
433 $mform = null;
434 $notices = array();
435 $nextpageparams = array();
437 if (!empty($this->get_course_module()->id)) {
438 $nextpageparams['id'] = $this->get_course_module()->id;
441 // Handle form submissions first.
442 if ($action == 'savesubmission') {
443 $action = 'editsubmission';
444 if ($this->process_save_submission($mform, $notices)) {
445 $action = 'redirect';
446 $nextpageparams['action'] = 'view';
448 } else if ($action == 'editprevioussubmission') {
449 $action = 'editsubmission';
450 if ($this->process_copy_previous_attempt($notices)) {
451 $action = 'redirect';
452 $nextpageparams['action'] = 'editsubmission';
454 } else if ($action == 'lock') {
455 $this->process_lock_submission();
456 $action = 'redirect';
457 $nextpageparams['action'] = 'grading';
458 } else if ($action == 'addattempt') {
459 $this->process_add_attempt(required_param('userid', PARAM_INT));
460 $action = 'redirect';
461 $nextpageparams['action'] = 'grading';
462 } else if ($action == 'reverttodraft') {
463 $this->process_revert_to_draft();
464 $action = 'redirect';
465 $nextpageparams['action'] = 'grading';
466 } else if ($action == 'unlock') {
467 $this->process_unlock_submission();
468 $action = 'redirect';
469 $nextpageparams['action'] = 'grading';
470 } else if ($action == 'setbatchmarkingworkflowstate') {
471 $this->process_set_batch_marking_workflow_state();
472 $action = 'redirect';
473 $nextpageparams['action'] = 'grading';
474 } else if ($action == 'setbatchmarkingallocation') {
475 $this->process_set_batch_marking_allocation();
476 $action = 'redirect';
477 $nextpageparams['action'] = 'grading';
478 } else if ($action == 'confirmsubmit') {
479 $action = 'submit';
480 if ($this->process_submit_for_grading($mform, $notices)) {
481 $action = 'redirect';
482 $nextpageparams['action'] = 'view';
483 } else if ($notices) {
484 $action = 'viewsubmitforgradingerror';
486 } else if ($action == 'submitotherforgrading') {
487 if ($this->process_submit_other_for_grading($mform, $notices)) {
488 $action = 'redirect';
489 $nextpageparams['action'] = 'grading';
490 } else {
491 $action = 'viewsubmitforgradingerror';
493 } else if ($action == 'gradingbatchoperation') {
494 $action = $this->process_grading_batch_operation($mform);
495 if ($action == 'grading') {
496 $action = 'redirect';
497 $nextpageparams['action'] = 'grading';
499 } else if ($action == 'submitgrade') {
500 if (optional_param('saveandshownext', null, PARAM_RAW)) {
501 // Save and show next.
502 $action = 'grade';
503 if ($this->process_save_grade($mform)) {
504 $action = 'redirect';
505 $nextpageparams['action'] = 'grade';
506 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
507 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
509 } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
510 $action = 'redirect';
511 $nextpageparams['action'] = 'grade';
512 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
513 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
514 } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
515 $action = 'redirect';
516 $nextpageparams['action'] = 'grade';
517 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
518 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
519 } else if (optional_param('savegrade', null, PARAM_RAW)) {
520 // Save changes button.
521 $action = 'grade';
522 if ($this->process_save_grade($mform)) {
523 $action = 'redirect';
524 $nextpageparams['action'] = 'savegradingresult';
526 } else {
527 // Cancel button.
528 $action = 'redirect';
529 $nextpageparams['action'] = 'grading';
531 } else if ($action == 'quickgrade') {
532 $message = $this->process_save_quick_grades();
533 $action = 'quickgradingresult';
534 } else if ($action == 'saveoptions') {
535 $this->process_save_grading_options();
536 $action = 'redirect';
537 $nextpageparams['action'] = 'grading';
538 } else if ($action == 'saveextension') {
539 $action = 'grantextension';
540 if ($this->process_save_extension($mform)) {
541 $action = 'redirect';
542 $nextpageparams['action'] = 'grading';
544 } else if ($action == 'revealidentitiesconfirm') {
545 $this->process_reveal_identities();
546 $action = 'redirect';
547 $nextpageparams['action'] = 'grading';
550 $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
551 'useridlistid' => optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM));
552 $this->register_return_link($action, $returnparams);
554 // Include any page action as part of the body tag CSS id.
555 if (!empty($action)) {
556 $PAGE->set_pagetype('mod-assign-' . $action);
558 // Now show the right view page.
559 if ($action == 'redirect') {
560 $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
561 redirect($nextpageurl);
562 return;
563 } else if ($action == 'savegradingresult') {
564 $message = get_string('gradingchangessaved', 'assign');
565 $o .= $this->view_savegrading_result($message);
566 } else if ($action == 'quickgradingresult') {
567 $mform = null;
568 $o .= $this->view_quickgrading_result($message);
569 } else if ($action == 'gradingpanel') {
570 $o .= $this->view_single_grading_panel($args);
571 } else if ($action == 'grade') {
572 $o .= $this->view_single_grade_page($mform);
573 } else if ($action == 'viewpluginassignfeedback') {
574 $o .= $this->view_plugin_content('assignfeedback');
575 } else if ($action == 'viewpluginassignsubmission') {
576 $o .= $this->view_plugin_content('assignsubmission');
577 } else if ($action == 'editsubmission') {
578 $o .= $this->view_edit_submission_page($mform, $notices);
579 } else if ($action == 'grader') {
580 $o .= $this->view_grader();
581 } else if ($action == 'grading') {
582 $o .= $this->view_grading_page();
583 } else if ($action == 'downloadall') {
584 $o .= $this->download_submissions();
585 } else if ($action == 'submit') {
586 $o .= $this->check_submit_for_grading($mform);
587 } else if ($action == 'grantextension') {
588 $o .= $this->view_grant_extension($mform);
589 } else if ($action == 'revealidentities') {
590 $o .= $this->view_reveal_identities_confirm($mform);
591 } else if ($action == 'plugingradingbatchoperation') {
592 $o .= $this->view_plugin_grading_batch_operation($mform);
593 } else if ($action == 'viewpluginpage') {
594 $o .= $this->view_plugin_page();
595 } else if ($action == 'viewcourseindex') {
596 $o .= $this->view_course_index();
597 } else if ($action == 'viewbatchsetmarkingworkflowstate') {
598 $o .= $this->view_batch_set_workflow_state($mform);
599 } else if ($action == 'viewbatchmarkingallocation') {
600 $o .= $this->view_batch_markingallocation($mform);
601 } else if ($action == 'viewsubmitforgradingerror') {
602 $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
603 } else {
604 $o .= $this->view_submission_page();
607 return $o;
611 * Add this instance to the database.
613 * @param stdClass $formdata The data submitted from the form
614 * @param bool $callplugins This is used to skip the plugin code
615 * when upgrading an old assignment to a new one (the plugins get called manually)
616 * @return mixed false if an error occurs or the int id of the new instance
618 public function add_instance(stdClass $formdata, $callplugins) {
619 global $DB;
620 $adminconfig = $this->get_admin_config();
622 $err = '';
624 // Add the database record.
625 $update = new stdClass();
626 $update->name = $formdata->name;
627 $update->timemodified = time();
628 $update->timecreated = time();
629 $update->course = $formdata->course;
630 $update->courseid = $formdata->course;
631 $update->intro = $formdata->intro;
632 $update->introformat = $formdata->introformat;
633 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
634 $update->submissiondrafts = $formdata->submissiondrafts;
635 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
636 $update->sendnotifications = $formdata->sendnotifications;
637 $update->sendlatenotifications = $formdata->sendlatenotifications;
638 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
639 if (isset($formdata->sendstudentnotifications)) {
640 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
642 $update->duedate = $formdata->duedate;
643 $update->cutoffdate = $formdata->cutoffdate;
644 $update->gradingduedate = $formdata->gradingduedate;
645 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
646 $update->grade = $formdata->grade;
647 $update->completionsubmit = !empty($formdata->completionsubmit);
648 $update->teamsubmission = $formdata->teamsubmission;
649 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
650 if (isset($formdata->teamsubmissiongroupingid)) {
651 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
653 $update->blindmarking = $formdata->blindmarking;
654 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
655 if (!empty($formdata->attemptreopenmethod)) {
656 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
658 if (!empty($formdata->maxattempts)) {
659 $update->maxattempts = $formdata->maxattempts;
661 if (isset($formdata->preventsubmissionnotingroup)) {
662 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
664 $update->markingworkflow = $formdata->markingworkflow;
665 $update->markingallocation = $formdata->markingallocation;
666 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
667 $update->markingallocation = 0;
670 $returnid = $DB->insert_record('assign', $update);
671 $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
672 // Cache the course record.
673 $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
675 $this->save_intro_draft_files($formdata);
677 if ($callplugins) {
678 // Call save_settings hook for submission plugins.
679 foreach ($this->submissionplugins as $plugin) {
680 if (!$this->update_plugin_instance($plugin, $formdata)) {
681 print_error($plugin->get_error());
682 return false;
685 foreach ($this->feedbackplugins as $plugin) {
686 if (!$this->update_plugin_instance($plugin, $formdata)) {
687 print_error($plugin->get_error());
688 return false;
692 // In the case of upgrades the coursemodule has not been set,
693 // so we need to wait before calling these two.
694 $this->update_calendar($formdata->coursemodule);
695 $this->update_gradebook(false, $formdata->coursemodule);
699 $update = new stdClass();
700 $update->id = $this->get_instance()->id;
701 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
702 $DB->update_record('assign', $update);
704 return $returnid;
708 * Delete all grades from the gradebook for this assignment.
710 * @return bool
712 protected function delete_grades() {
713 global $CFG;
715 $result = grade_update('mod/assign',
716 $this->get_course()->id,
717 'mod',
718 'assign',
719 $this->get_instance()->id,
721 null,
722 array('deleted'=>1));
723 return $result == GRADE_UPDATE_OK;
727 * Delete this instance from the database.
729 * @return bool false if an error occurs
731 public function delete_instance() {
732 global $DB;
733 $result = true;
735 foreach ($this->submissionplugins as $plugin) {
736 if (!$plugin->delete_instance()) {
737 print_error($plugin->get_error());
738 $result = false;
741 foreach ($this->feedbackplugins as $plugin) {
742 if (!$plugin->delete_instance()) {
743 print_error($plugin->get_error());
744 $result = false;
748 // Delete files associated with this assignment.
749 $fs = get_file_storage();
750 if (! $fs->delete_area_files($this->context->id) ) {
751 $result = false;
754 $this->delete_all_overrides();
756 // Delete_records will throw an exception if it fails - so no need for error checking here.
757 $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id));
758 $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id));
759 $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id));
760 $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id));
761 $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id));
763 // Delete items from the gradebook.
764 if (! $this->delete_grades()) {
765 $result = false;
768 // Delete the instance.
769 $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
771 return $result;
775 * Deletes a assign override from the database and clears any corresponding calendar events
777 * @param int $overrideid The id of the override being deleted
778 * @return bool true on success
780 public function delete_override($overrideid) {
781 global $CFG, $DB;
783 require_once($CFG->dirroot . '/calendar/lib.php');
785 $cm = $this->get_course_module();
786 if (empty($cm)) {
787 $instance = $this->get_instance();
788 $cm = get_coursemodule_from_instance('assign', $instance->id, $instance->course);
791 $override = $DB->get_record('assign_overrides', array('id' => $overrideid), '*', MUST_EXIST);
793 // Delete the events.
794 $conds = array('modulename' => 'assign', 'instance' => $this->get_instance()->id);
795 if (isset($override->userid)) {
796 $conds['userid'] = $override->userid;
797 } else {
798 $conds['groupid'] = $override->groupid;
800 $events = $DB->get_records('event', $conds);
801 foreach ($events as $event) {
802 $eventold = \core_calendar\event::load($event);
803 $eventold->delete();
806 $DB->delete_records('assign_overrides', array('id' => $overrideid));
808 // Set the common parameters for one of the events we will be triggering.
809 $params = array(
810 'objectid' => $override->id,
811 'context' => context_module::instance($cm->id),
812 'other' => array(
813 'assignid' => $override->assignid
816 // Determine which override deleted event to fire.
817 if (!empty($override->userid)) {
818 $params['relateduserid'] = $override->userid;
819 $event = \mod_assign\event\user_override_deleted::create($params);
820 } else {
821 $params['other']['groupid'] = $override->groupid;
822 $event = \mod_assign\event\group_override_deleted::create($params);
825 // Trigger the override deleted event.
826 $event->add_record_snapshot('assign_overrides', $override);
827 $event->trigger();
829 return true;
833 * Deletes all assign overrides from the database and clears any corresponding calendar events
835 public function delete_all_overrides() {
836 global $DB;
838 $overrides = $DB->get_records('assign_overrides', array('assignid' => $this->get_instance()->id), 'id');
839 foreach ($overrides as $override) {
840 $this->delete_override($override->id);
845 * Updates the assign properties with override information for a user.
847 * Algorithm: For each assign setting, if there is a matching user-specific override,
848 * then use that otherwise, if there are group-specific overrides, return the most
849 * lenient combination of them. If neither applies, leave the assign setting unchanged.
851 * @param int $userid The userid.
853 public function update_effective_access($userid) {
855 $override = $this->override_exists($userid);
857 // Merge with assign defaults.
858 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
859 foreach ($keys as $key) {
860 if (isset($override->{$key})) {
861 $this->get_instance()->{$key} = $override->{$key};
868 * Returns whether an assign has any overrides.
870 * @return true if any, false if not
872 public function has_overrides() {
873 global $DB;
875 $override = $DB->record_exists('assign_overrides', array('assignid' => $this->get_instance()->id));
877 if ($override) {
878 return true;
881 return false;
885 * Returns user override
887 * Algorithm: For each assign setting, if there is a matching user-specific override,
888 * then use that otherwise, if there are group-specific overrides, return the most
889 * lenient combination of them. If neither applies, leave the assign setting unchanged.
891 * @param int $userid The userid.
892 * @return override if exist
894 public function override_exists($userid) {
895 global $DB;
897 // Check for user override.
898 $override = $DB->get_record('assign_overrides', array('assignid' => $this->get_instance()->id, 'userid' => $userid));
900 if (!$override) {
901 $override = new stdClass();
902 $override->duedate = null;
903 $override->cutoffdate = null;
904 $override->allowsubmissionsfromdate = null;
907 // Check for group overrides.
908 $groupings = groups_get_user_groups($this->get_instance()->course, $userid);
910 if (!empty($groupings[0])) {
911 // Select all overrides that apply to the User's groups.
912 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
913 $sql = "SELECT * FROM {assign_overrides}
914 WHERE groupid $extra AND assignid = ?";
915 $params[] = $this->get_instance()->id;
916 $records = $DB->get_records_sql($sql, $params);
918 // Combine the overrides.
919 $duedates = array();
920 $cutoffdates = array();
921 $allowsubmissionsfromdates = array();
923 foreach ($records as $gpoverride) {
924 if (isset($gpoverride->duedate)) {
925 $duedates[] = $gpoverride->duedate;
927 if (isset($gpoverride->cutoffdate)) {
928 $cutoffdates[] = $gpoverride->cutoffdate;
930 if (isset($gpoverride->allowsubmissionsfromdate)) {
931 $allowsubmissionsfromdates[] = $gpoverride->allowsubmissionsfromdate;
934 // If there is a user override for a setting, ignore the group override.
935 if (is_null($override->allowsubmissionsfromdate) && count($allowsubmissionsfromdates)) {
936 $override->allowsubmissionsfromdate = min($allowsubmissionsfromdates);
938 if (is_null($override->cutoffdate) && count($cutoffdates)) {
939 if (in_array(0, $cutoffdates)) {
940 $override->cutoffdate = 0;
941 } else {
942 $override->cutoffdate = max($cutoffdates);
945 if (is_null($override->duedate) && count($duedates)) {
946 if (in_array(0, $duedates)) {
947 $override->duedate = 0;
948 } else {
949 $override->duedate = max($duedates);
955 return $override;
959 * Actual implementation of the reset course functionality, delete all the
960 * assignment submissions for course $data->courseid.
962 * @param stdClass $data the data submitted from the reset course.
963 * @return array status array
965 public function reset_userdata($data) {
966 global $CFG, $DB;
968 $componentstr = get_string('modulenameplural', 'assign');
969 $status = array();
971 $fs = get_file_storage();
972 if (!empty($data->reset_assign_submissions)) {
973 // Delete files associated with this assignment.
974 foreach ($this->submissionplugins as $plugin) {
975 $fileareas = array();
976 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
977 $fileareas = $plugin->get_file_areas();
978 foreach ($fileareas as $filearea => $notused) {
979 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
982 if (!$plugin->delete_instance()) {
983 $status[] = array('component'=>$componentstr,
984 'item'=>get_string('deleteallsubmissions', 'assign'),
985 'error'=>$plugin->get_error());
989 foreach ($this->feedbackplugins as $plugin) {
990 $fileareas = array();
991 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
992 $fileareas = $plugin->get_file_areas();
993 foreach ($fileareas as $filearea => $notused) {
994 $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
997 if (!$plugin->delete_instance()) {
998 $status[] = array('component'=>$componentstr,
999 'item'=>get_string('deleteallsubmissions', 'assign'),
1000 'error'=>$plugin->get_error());
1004 $assignids = $DB->get_records('assign', array('course' => $data->courseid), '', 'id');
1005 list($sql, $params) = $DB->get_in_or_equal(array_keys($assignids));
1007 $DB->delete_records_select('assign_submission', "assignment $sql", $params);
1008 $DB->delete_records_select('assign_user_flags', "assignment $sql", $params);
1010 $status[] = array('component'=>$componentstr,
1011 'item'=>get_string('deleteallsubmissions', 'assign'),
1012 'error'=>false);
1014 if (!empty($data->reset_gradebook_grades)) {
1015 $DB->delete_records_select('assign_grades', "assignment $sql", $params);
1016 // Remove all grades from gradebook.
1017 require_once($CFG->dirroot.'/mod/assign/lib.php');
1018 assign_reset_gradebook($data->courseid);
1020 // Reset revealidentities if both submissions and grades have been reset.
1021 if ($this->get_instance()->blindmarking && $this->get_instance()->revealidentities) {
1022 $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id));
1027 // Remove user overrides.
1028 if (!empty($data->reset_assign_user_overrides)) {
1029 $DB->delete_records_select('assign_overrides',
1030 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1031 $status[] = array(
1032 'component' => $componentstr,
1033 'item' => get_string('useroverridesdeleted', 'assign'),
1034 'error' => false);
1036 // Remove group overrides.
1037 if (!empty($data->reset_assign_group_overrides)) {
1038 $DB->delete_records_select('assign_overrides',
1039 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1040 $status[] = array(
1041 'component' => $componentstr,
1042 'item' => get_string('groupoverridesdeleted', 'assign'),
1043 'error' => false);
1046 // Updating dates - shift may be negative too.
1047 if ($data->timeshift) {
1048 $DB->execute("UPDATE {assign_overrides}
1049 SET allowsubmissionsfromdate = allowsubmissionsfromdate + ?
1050 WHERE assignid = ? AND allowsubmissionsfromdate <> 0",
1051 array($data->timeshift, $this->get_instance()->id));
1052 $DB->execute("UPDATE {assign_overrides}
1053 SET duedate = duedate + ?
1054 WHERE assignid = ? AND duedate <> 0",
1055 array($data->timeshift, $this->get_instance()->id));
1056 $DB->execute("UPDATE {assign_overrides}
1057 SET cutoffdate = cutoffdate + ?
1058 WHERE assignid =? AND cutoffdate <> 0",
1059 array($data->timeshift, $this->get_instance()->id));
1061 shift_course_mod_dates('assign',
1062 array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
1063 $data->timeshift,
1064 $data->courseid, $this->get_instance()->id);
1065 $status[] = array('component'=>$componentstr,
1066 'item'=>get_string('datechanged'),
1067 'error'=>false);
1070 return $status;
1074 * Update the settings for a single plugin.
1076 * @param assign_plugin $plugin The plugin to update
1077 * @param stdClass $formdata The form data
1078 * @return bool false if an error occurs
1080 protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
1081 if ($plugin->is_visible()) {
1082 $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1083 if (!empty($formdata->$enabledname)) {
1084 $plugin->enable();
1085 if (!$plugin->save_settings($formdata)) {
1086 print_error($plugin->get_error());
1087 return false;
1089 } else {
1090 $plugin->disable();
1093 return true;
1097 * Update the gradebook information for this assignment.
1099 * @param bool $reset If true, will reset all grades in the gradbook for this assignment
1100 * @param int $coursemoduleid This is required because it might not exist in the database yet
1101 * @return bool
1103 public function update_gradebook($reset, $coursemoduleid) {
1104 global $CFG;
1106 require_once($CFG->dirroot.'/mod/assign/lib.php');
1107 $assign = clone $this->get_instance();
1108 $assign->cmidnumber = $coursemoduleid;
1110 // Set assign gradebook feedback plugin status (enabled and visible).
1111 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
1113 $param = null;
1114 if ($reset) {
1115 $param = 'reset';
1118 return assign_grade_item_update($assign, $param);
1122 * Get the marking table page size
1124 * @return integer
1126 public function get_assign_perpage() {
1127 $perpage = (int) get_user_preferences('assign_perpage', 10);
1128 $adminconfig = $this->get_admin_config();
1129 $maxperpage = -1;
1130 if (isset($adminconfig->maxperpage)) {
1131 $maxperpage = $adminconfig->maxperpage;
1133 if (isset($maxperpage) &&
1134 $maxperpage != -1 &&
1135 ($perpage == -1 || $perpage > $maxperpage)) {
1136 $perpage = $maxperpage;
1138 return $perpage;
1142 * Load and cache the admin config for this module.
1144 * @return stdClass the plugin config
1146 public function get_admin_config() {
1147 if ($this->adminconfig) {
1148 return $this->adminconfig;
1150 $this->adminconfig = get_config('assign');
1151 return $this->adminconfig;
1155 * Update the calendar entries for this assignment.
1157 * @param int $coursemoduleid - Required to pass this in because it might
1158 * not exist in the database yet.
1159 * @return bool
1161 public function update_calendar($coursemoduleid) {
1162 global $DB, $CFG;
1163 require_once($CFG->dirroot.'/calendar/lib.php');
1165 // Special case for add_instance as the coursemodule has not been set yet.
1166 $instance = $this->get_instance();
1168 // Start with creating the event.
1169 $event = new stdClass();
1170 $event->modulename = 'assign';
1171 $event->courseid = $instance->course;
1172 $event->groupid = 0;
1173 $event->userid = 0;
1174 $event->instance = $instance->id;
1175 $event->name = $instance->name;
1176 $event->type = CALENDAR_EVENT_TYPE_ACTION;
1178 // Convert the links to pluginfile. It is a bit hacky but at this stage the files
1179 // might not have been saved in the module area yet.
1180 $intro = $instance->intro;
1181 if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
1182 $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
1185 // We need to remove the links to files as the calendar is not ready
1186 // to support module events with file areas.
1187 $intro = strip_pluginfile_content($intro);
1188 if ($this->show_intro()) {
1189 $event->description = array(
1190 'text' => $intro,
1191 'format' => $instance->introformat
1193 } else {
1194 $event->description = array(
1195 'text' => '',
1196 'format' => $instance->introformat
1200 $eventtype = ASSIGN_EVENT_TYPE_DUE;
1201 if ($instance->duedate) {
1202 $event->eventtype = $eventtype;
1203 $event->timestart = $instance->duedate;
1204 $event->timesort = $instance->duedate;
1205 $select = "modulename = :modulename
1206 AND instance = :instance
1207 AND eventtype = :eventtype
1208 AND groupid = 0
1209 AND courseid <> 0";
1210 $params = array('modulename' => 'assign', 'instance' => $instance->id, 'eventtype' => $eventtype);
1211 $event->id = $DB->get_field_select('event', 'id', $select, $params);
1213 // Now process the event.
1214 if ($event->id) {
1215 $calendarevent = \core_calendar\event::load($event->id);
1216 $calendarevent->update($event);
1217 } else {
1218 \core_calendar\event::create($event);
1220 } else {
1221 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1222 'eventtype' => $eventtype));
1225 $eventtype = ASSIGN_EVENT_TYPE_GRADINGDUE;
1226 if ($instance->gradingduedate) {
1227 $event->eventtype = $eventtype;
1228 $event->timestart = $instance->gradingduedate;
1229 $event->timesort = $instance->gradingduedate;
1230 $event->id = $DB->get_field('event', 'id', array('modulename' => 'assign',
1231 'instance' => $instance->id, 'eventtype' => $event->eventtype));
1233 // Now process the event.
1234 if ($event->id) {
1235 $calendarevent = \core_calendar\event::load($event->id);
1236 $calendarevent->update($event);
1237 } else {
1238 \core_calendar\event::create($event);
1240 } else {
1241 $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1242 'eventtype' => $eventtype));
1245 return true;
1249 * Update this instance in the database.
1251 * @param stdClass $formdata - the data submitted from the form
1252 * @return bool false if an error occurs
1254 public function update_instance($formdata) {
1255 global $DB;
1256 $adminconfig = $this->get_admin_config();
1258 $update = new stdClass();
1259 $update->id = $formdata->instance;
1260 $update->name = $formdata->name;
1261 $update->timemodified = time();
1262 $update->course = $formdata->course;
1263 $update->intro = $formdata->intro;
1264 $update->introformat = $formdata->introformat;
1265 $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
1266 $update->submissiondrafts = $formdata->submissiondrafts;
1267 $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
1268 $update->sendnotifications = $formdata->sendnotifications;
1269 $update->sendlatenotifications = $formdata->sendlatenotifications;
1270 $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
1271 if (isset($formdata->sendstudentnotifications)) {
1272 $update->sendstudentnotifications = $formdata->sendstudentnotifications;
1274 $update->duedate = $formdata->duedate;
1275 $update->cutoffdate = $formdata->cutoffdate;
1276 $update->gradingduedate = $formdata->gradingduedate;
1277 $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
1278 $update->grade = $formdata->grade;
1279 if (!empty($formdata->completionunlocked)) {
1280 $update->completionsubmit = !empty($formdata->completionsubmit);
1282 $update->teamsubmission = $formdata->teamsubmission;
1283 $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
1284 if (isset($formdata->teamsubmissiongroupingid)) {
1285 $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
1287 $update->blindmarking = $formdata->blindmarking;
1288 $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
1289 if (!empty($formdata->attemptreopenmethod)) {
1290 $update->attemptreopenmethod = $formdata->attemptreopenmethod;
1292 if (!empty($formdata->maxattempts)) {
1293 $update->maxattempts = $formdata->maxattempts;
1295 if (isset($formdata->preventsubmissionnotingroup)) {
1296 $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
1298 $update->markingworkflow = $formdata->markingworkflow;
1299 $update->markingallocation = $formdata->markingallocation;
1300 if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
1301 $update->markingallocation = 0;
1304 $result = $DB->update_record('assign', $update);
1305 $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
1307 $this->save_intro_draft_files($formdata);
1309 // Load the assignment so the plugins have access to it.
1311 // Call save_settings hook for submission plugins.
1312 foreach ($this->submissionplugins as $plugin) {
1313 if (!$this->update_plugin_instance($plugin, $formdata)) {
1314 print_error($plugin->get_error());
1315 return false;
1318 foreach ($this->feedbackplugins as $plugin) {
1319 if (!$this->update_plugin_instance($plugin, $formdata)) {
1320 print_error($plugin->get_error());
1321 return false;
1325 $this->update_calendar($this->get_course_module()->id);
1326 $this->update_gradebook(false, $this->get_course_module()->id);
1328 $update = new stdClass();
1329 $update->id = $this->get_instance()->id;
1330 $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
1331 $DB->update_record('assign', $update);
1333 return $result;
1337 * Save the attachments in the draft areas.
1339 * @param stdClass $formdata
1341 protected function save_intro_draft_files($formdata) {
1342 if (isset($formdata->introattachments)) {
1343 file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1344 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1349 * Add elements in grading plugin form.
1351 * @param mixed $grade stdClass|null
1352 * @param MoodleQuickForm $mform
1353 * @param stdClass $data
1354 * @param int $userid - The userid we are grading
1355 * @return void
1357 protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
1358 foreach ($this->feedbackplugins as $plugin) {
1359 if ($plugin->is_enabled() && $plugin->is_visible()) {
1360 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1368 * Add one plugins settings to edit plugin form.
1370 * @param assign_plugin $plugin The plugin to add the settings from
1371 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1372 * This form is modified directly (not returned).
1373 * @param array $pluginsenabled A list of form elements to be added to a group.
1374 * The new element is added to this array by this function.
1375 * @return void
1377 protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1378 global $CFG;
1379 if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1380 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1381 $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1382 $mform->setType($name, PARAM_BOOL);
1383 $plugin->get_settings($mform);
1384 } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1385 $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1386 $label = $plugin->get_name();
1387 $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1388 $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1390 $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1391 if ($plugin->get_config('enabled') !== false) {
1392 $default = $plugin->is_enabled();
1394 $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1396 $plugin->get_settings($mform);
1402 * Add settings to edit plugin form.
1404 * @param MoodleQuickForm $mform The form to add the configuration settings to.
1405 * This form is modified directly (not returned).
1406 * @return void
1408 public function add_all_plugin_settings(MoodleQuickForm $mform) {
1409 $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1411 $submissionpluginsenabled = array();
1412 $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1413 foreach ($this->submissionplugins as $plugin) {
1414 $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1416 $group->setElements($submissionpluginsenabled);
1418 $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1419 $feedbackpluginsenabled = array();
1420 $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1421 foreach ($this->feedbackplugins as $plugin) {
1422 $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1424 $group->setElements($feedbackpluginsenabled);
1425 $mform->setExpanded('submissiontypes');
1429 * Allow each plugin an opportunity to update the defaultvalues
1430 * passed in to the settings form (needed to set up draft areas for
1431 * editor and filemanager elements)
1433 * @param array $defaultvalues
1435 public function plugin_data_preprocessing(&$defaultvalues) {
1436 foreach ($this->submissionplugins as $plugin) {
1437 if ($plugin->is_visible()) {
1438 $plugin->data_preprocessing($defaultvalues);
1441 foreach ($this->feedbackplugins as $plugin) {
1442 if ($plugin->is_visible()) {
1443 $plugin->data_preprocessing($defaultvalues);
1449 * Get the name of the current module.
1451 * @return string the module name (Assignment)
1453 protected function get_module_name() {
1454 if (isset(self::$modulename)) {
1455 return self::$modulename;
1457 self::$modulename = get_string('modulename', 'assign');
1458 return self::$modulename;
1462 * Get the plural name of the current module.
1464 * @return string the module name plural (Assignments)
1466 protected function get_module_name_plural() {
1467 if (isset(self::$modulenameplural)) {
1468 return self::$modulenameplural;
1470 self::$modulenameplural = get_string('modulenameplural', 'assign');
1471 return self::$modulenameplural;
1475 * Has this assignment been constructed from an instance?
1477 * @return bool
1479 public function has_instance() {
1480 return $this->instance || $this->get_course_module();
1484 * Get the settings for the current instance of this assignment
1486 * @return stdClass The settings
1488 public function get_instance() {
1489 global $DB;
1490 if ($this->instance) {
1491 return $this->instance;
1493 if ($this->get_course_module()) {
1494 $params = array('id' => $this->get_course_module()->instance);
1495 $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1497 if (!$this->instance) {
1498 throw new coding_exception('Improper use of the assignment class. ' .
1499 'Cannot load the assignment record.');
1501 return $this->instance;
1505 * Get the primary grade item for this assign instance.
1507 * @return grade_item The grade_item record
1509 public function get_grade_item() {
1510 if ($this->gradeitem) {
1511 return $this->gradeitem;
1513 $instance = $this->get_instance();
1514 $params = array('itemtype' => 'mod',
1515 'itemmodule' => 'assign',
1516 'iteminstance' => $instance->id,
1517 'courseid' => $instance->course,
1518 'itemnumber' => 0);
1519 $this->gradeitem = grade_item::fetch($params);
1520 if (!$this->gradeitem) {
1521 throw new coding_exception('Improper use of the assignment class. ' .
1522 'Cannot load the grade item.');
1524 return $this->gradeitem;
1528 * Get the context of the current course.
1530 * @return mixed context|null The course context
1532 public function get_course_context() {
1533 if (!$this->context && !$this->course) {
1534 throw new coding_exception('Improper use of the assignment class. ' .
1535 'Cannot load the course context.');
1537 if ($this->context) {
1538 return $this->context->get_course_context();
1539 } else {
1540 return context_course::instance($this->course->id);
1546 * Get the current course module.
1548 * @return cm_info|null The course module or null if not known
1550 public function get_course_module() {
1551 if ($this->coursemodule) {
1552 return $this->coursemodule;
1554 if (!$this->context) {
1555 return null;
1558 if ($this->context->contextlevel == CONTEXT_MODULE) {
1559 $modinfo = get_fast_modinfo($this->get_course());
1560 $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
1561 return $this->coursemodule;
1563 return null;
1567 * Get context module.
1569 * @return context
1571 public function get_context() {
1572 return $this->context;
1576 * Get the current course.
1578 * @return mixed stdClass|null The course
1580 public function get_course() {
1581 global $DB;
1583 if ($this->course) {
1584 return $this->course;
1587 if (!$this->context) {
1588 return null;
1590 $params = array('id' => $this->get_course_context()->instanceid);
1591 $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1593 return $this->course;
1597 * Count the number of intro attachments.
1599 * @return int
1601 protected function count_attachments() {
1603 $fs = get_file_storage();
1604 $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1605 0, 'id', false);
1607 return count($files);
1611 * Are there any intro attachments to display?
1613 * @return boolean
1615 protected function has_visible_attachments() {
1616 return ($this->count_attachments() > 0);
1620 * Return a grade in user-friendly form, whether it's a scale or not.
1622 * @param mixed $grade int|null
1623 * @param boolean $editing Are we allowing changes to this grade?
1624 * @param int $userid The user id the grade belongs to
1625 * @param int $modified Timestamp from when the grade was last modified
1626 * @return string User-friendly representation of grade
1628 public function display_grade($grade, $editing, $userid=0, $modified=0) {
1629 global $DB;
1631 static $scalegrades = array();
1633 $o = '';
1635 if ($this->get_instance()->grade >= 0) {
1636 // Normal number.
1637 if ($editing && $this->get_instance()->grade > 0) {
1638 if ($grade < 0) {
1639 $displaygrade = '';
1640 } else {
1641 $displaygrade = format_float($grade, $this->get_grade_item()->get_decimals());
1643 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1644 get_string('usergrade', 'assign') .
1645 '</label>';
1646 $o .= '<input type="text"
1647 id="quickgrade_' . $userid . '"
1648 name="quickgrade_' . $userid . '"
1649 value="' . $displaygrade . '"
1650 size="6"
1651 maxlength="10"
1652 class="quickgrade"/>';
1653 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, $this->get_grade_item()->get_decimals());
1654 return $o;
1655 } else {
1656 if ($grade == -1 || $grade === null) {
1657 $o .= '-';
1658 } else {
1659 $item = $this->get_grade_item();
1660 $o .= grade_format_gradevalue($grade, $item);
1661 if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1662 // If displaying the raw grade, also display the total value.
1663 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, $item->get_decimals());
1666 return $o;
1669 } else {
1670 // Scale.
1671 if (empty($this->cache['scale'])) {
1672 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1673 $this->cache['scale'] = make_menu_from_list($scale->scale);
1674 } else {
1675 $o .= '-';
1676 return $o;
1679 if ($editing) {
1680 $o .= '<label class="accesshide"
1681 for="quickgrade_' . $userid . '">' .
1682 get_string('usergrade', 'assign') .
1683 '</label>';
1684 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1685 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1686 foreach ($this->cache['scale'] as $optionid => $option) {
1687 $selected = '';
1688 if ($grade == $optionid) {
1689 $selected = 'selected="selected"';
1691 $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1693 $o .= '</select>';
1694 return $o;
1695 } else {
1696 $scaleid = (int)$grade;
1697 if (isset($this->cache['scale'][$scaleid])) {
1698 $o .= $this->cache['scale'][$scaleid];
1699 return $o;
1701 $o .= '-';
1702 return $o;
1708 * Get the submission status/grading status for all submissions in this assignment for the
1709 * given paticipants.
1711 * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1712 * If this is a group assignment, group info is also returned.
1714 * @param array $participants an associative array where the key is the participant id and
1715 * the value is the participant record.
1716 * @return array an associative array where the key is the participant id and the value is
1717 * the participant record.
1719 private function get_submission_info_for_participants($participants) {
1720 global $DB;
1722 if (empty($participants)) {
1723 return $participants;
1726 list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1728 $assignid = $this->get_instance()->id;
1729 $params['assignmentid1'] = $assignid;
1730 $params['assignmentid2'] = $assignid;
1731 $params['assignmentid3'] = $assignid;
1733 $fields = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade, uf.extensionduedate';
1734 $from = ' FROM {user} u
1735 LEFT JOIN {assign_submission} s
1736 ON u.id = s.userid
1737 AND s.assignment = :assignmentid1
1738 AND s.latest = 1
1739 LEFT JOIN {assign_grades} g
1740 ON u.id = g.userid
1741 AND g.assignment = :assignmentid2
1742 AND g.attemptnumber = s.attemptnumber
1743 LEFT JOIN {assign_user_flags} uf
1744 ON u.id = uf.userid
1745 AND uf.assignment = :assignmentid3
1747 $where = ' WHERE u.id ' . $insql;
1749 if (!empty($this->get_instance()->blindmarking)) {
1750 $from .= 'LEFT JOIN {assign_user_mapping} um
1751 ON u.id = um.userid
1752 AND um.assignment = :assignmentid4 ';
1753 $params['assignmentid4'] = $assignid;
1754 $fields .= ', um.id as recordid ';
1757 $sql = "$fields $from $where";
1759 $records = $DB->get_records_sql($sql, $params);
1761 if ($this->get_instance()->teamsubmission) {
1762 // Get all groups.
1763 $allgroups = groups_get_all_groups($this->get_course()->id,
1764 array_keys($participants),
1765 $this->get_instance()->teamsubmissiongroupingid,
1766 'DISTINCT g.id, g.name');
1769 foreach ($participants as $userid => $participant) {
1770 $participants[$userid]->fullname = $this->fullname($participant);
1771 $participants[$userid]->submitted = false;
1772 $participants[$userid]->requiregrading = false;
1773 $participants[$userid]->grantedextension = false;
1776 foreach ($records as $userid => $submissioninfo) {
1777 // These filters are 100% the same as the ones in the grading table SQL.
1778 $submitted = false;
1779 $requiregrading = false;
1780 $grantedextension = false;
1782 if (!empty($submissioninfo->stime) && $submissioninfo->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1783 $submitted = true;
1786 if ($submitted && ($submissioninfo->stime >= $submissioninfo->gtime ||
1787 empty($submissioninfo->gtime) ||
1788 $submissioninfo->grade === null)) {
1789 $requiregrading = true;
1792 if (!empty($submissioninfo->extensionduedate)) {
1793 $grantedextension = true;
1796 $participants[$userid]->submitted = $submitted;
1797 $participants[$userid]->requiregrading = $requiregrading;
1798 $participants[$userid]->grantedextension = $grantedextension;
1799 if ($this->get_instance()->teamsubmission) {
1800 $group = $this->get_submission_group($userid);
1801 if ($group) {
1802 $participants[$userid]->groupid = $group->id;
1803 $participants[$userid]->groupname = $group->name;
1807 return $participants;
1811 * Get the submission status/grading status for all submissions in this assignment.
1812 * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1813 * If this is a group assignment, group info is also returned.
1815 * @param int $currentgroup
1816 * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'grantedextension',
1817 * 'groupid', 'groupname'
1819 public function list_participants_with_filter_status_and_group($currentgroup) {
1820 $participants = $this->list_participants($currentgroup, false);
1822 if (empty($participants)) {
1823 return $participants;
1824 } else {
1825 return $this->get_submission_info_for_participants($participants);
1830 * Load a list of users enrolled in the current course with the specified permission and group.
1831 * 0 for no group.
1833 * @param int $currentgroup
1834 * @param bool $idsonly
1835 * @return array List of user records
1837 public function list_participants($currentgroup, $idsonly) {
1838 global $DB, $USER;
1840 if (empty($currentgroup)) {
1841 $currentgroup = 0;
1844 $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1845 if (!isset($this->participants[$key])) {
1846 list($esql, $params) = get_enrolled_sql($this->context, 'mod/assign:submit', $currentgroup,
1847 $this->show_only_active_users());
1849 $fields = 'u.*';
1850 $orderby = 'u.lastname, u.firstname, u.id';
1851 $additionaljoins = '';
1852 $additionalfilters = '';
1853 $instance = $this->get_instance();
1854 if (!empty($instance->blindmarking)) {
1855 $additionaljoins .= " LEFT JOIN {assign_user_mapping} um
1856 ON u.id = um.userid
1857 AND um.assignment = :assignmentid1
1858 LEFT JOIN {assign_submission} s
1859 ON u.id = s.userid
1860 AND s.assignment = :assignmentid2
1861 AND s.latest = 1
1863 $params['assignmentid1'] = (int) $instance->id;
1864 $params['assignmentid2'] = (int) $instance->id;
1865 $fields .= ', um.id as recordid ';
1867 // Sort by submission time first, then by um.id to sort reliably by the blind marking id.
1868 // Note, different DBs have different ordering of NULL values.
1869 // Therefore we coalesce the current time into the timecreated field, and the max possible integer into
1870 // the ID field.
1871 $orderby = "COALESCE(s.timecreated, " . time() . ") ASC, COALESCE(s.id, " . PHP_INT_MAX . ") ASC, um.id ASC";
1874 if ($instance->markingworkflow &&
1875 $instance->markingallocation &&
1876 !has_capability('mod/assign:manageallocations', $this->get_context()) &&
1877 has_capability('mod/assign:grade', $this->get_context())) {
1879 $additionaljoins .= ' LEFT JOIN {assign_user_flags} uf
1880 ON u.id = uf.userid
1881 AND uf.assignment = :assignmentid3';
1883 $params['assignmentid3'] = (int) $instance->id;
1885 $additionalfilters .= ' AND uf.allocatedmarker = :markerid';
1886 $params['markerid'] = $USER->id;
1889 $sql = "SELECT $fields
1890 FROM {user} u
1891 JOIN ($esql) je ON je.id = u.id
1892 $additionaljoins
1893 WHERE u.deleted = 0
1894 $additionalfilters
1895 ORDER BY $orderby";
1897 $users = $DB->get_records_sql($sql, $params);
1899 $cm = $this->get_course_module();
1900 $info = new \core_availability\info_module($cm);
1901 $users = $info->filter_user_list($users);
1903 $this->participants[$key] = $users;
1906 if ($idsonly) {
1907 $idslist = array();
1908 foreach ($this->participants[$key] as $id => $user) {
1909 $idslist[$id] = new stdClass();
1910 $idslist[$id]->id = $id;
1912 return $idslist;
1914 return $this->participants[$key];
1918 * Load a user if they are enrolled in the current course. Populated with submission
1919 * status for this assignment.
1921 * @param int $userid
1922 * @return null|stdClass user record
1924 public function get_participant($userid) {
1925 global $DB;
1927 $participant = $DB->get_record('user', array('id' => $userid));
1928 if (!$participant) {
1929 return null;
1932 if (!is_enrolled($this->context, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
1933 return null;
1936 $result = $this->get_submission_info_for_participants(array($participant->id => $participant));
1937 return $result[$participant->id];
1941 * Load a count of valid teams for this assignment.
1943 * @param int $activitygroup Activity active group
1944 * @return int number of valid teams
1946 public function count_teams($activitygroup = 0) {
1948 $count = 0;
1950 $participants = $this->list_participants($activitygroup, true);
1952 // If a team submission grouping id is provided all good as all returned groups
1953 // are the submission teams, but if no team submission grouping was specified
1954 // $groups will contain all participants groups.
1955 if ($this->get_instance()->teamsubmissiongroupingid) {
1957 // We restrict the users to the selected group ones.
1958 $groups = groups_get_all_groups($this->get_course()->id,
1959 array_keys($participants),
1960 $this->get_instance()->teamsubmissiongroupingid,
1961 'DISTINCT g.id, g.name');
1963 $count = count($groups);
1965 // When a specific group is selected we don't count the default group users.
1966 if ($activitygroup == 0) {
1967 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1968 // See if there are any users in the default group.
1969 $defaultusers = $this->get_submission_group_members(0, true);
1970 if (count($defaultusers) > 0) {
1971 $count += 1;
1974 } else if ($activitygroup != 0 && empty($groups)) {
1975 // Set count to 1 if $groups returns empty.
1976 // It means the group is not part of $this->get_instance()->teamsubmissiongroupingid.
1977 $count = 1;
1979 } else {
1980 // It is faster to loop around participants if no grouping was specified.
1981 $groups = array();
1982 foreach ($participants as $participant) {
1983 if ($group = $this->get_submission_group($participant->id)) {
1984 $groups[$group->id] = true;
1985 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
1986 $groups[0] = true;
1990 $count = count($groups);
1993 return $count;
1997 * Load a count of active users enrolled in the current course with the specified permission and group.
1998 * 0 for no group.
2000 * @param int $currentgroup
2001 * @return int number of matching users
2003 public function count_participants($currentgroup) {
2004 return count($this->list_participants($currentgroup, true));
2008 * Load a count of active users submissions in the current module that require grading
2009 * This means the submission modification time is more recent than the
2010 * grading modification time and the status is SUBMITTED.
2012 * @return int number of matching submissions
2014 public function count_submissions_need_grading() {
2015 global $DB;
2017 if ($this->get_instance()->teamsubmission) {
2018 // This does not make sense for group assignment because the submission is shared.
2019 return 0;
2022 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2023 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2025 $params['assignid'] = $this->get_instance()->id;
2026 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2028 $sql = 'SELECT COUNT(s.userid)
2029 FROM {assign_submission} s
2030 LEFT JOIN {assign_grades} g ON
2031 s.assignment = g.assignment AND
2032 s.userid = g.userid AND
2033 g.attemptnumber = s.attemptnumber
2034 JOIN(' . $esql . ') e ON e.id = s.userid
2035 WHERE
2036 s.latest = 1 AND
2037 s.assignment = :assignid AND
2038 s.timemodified IS NOT NULL AND
2039 s.status = :submitted AND
2040 (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL)';
2042 return $DB->count_records_sql($sql, $params);
2046 * Load a count of grades.
2048 * @return int number of grades
2050 public function count_grades() {
2051 global $DB;
2053 if (!$this->has_instance()) {
2054 return 0;
2057 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2058 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2060 $params['assignid'] = $this->get_instance()->id;
2062 $sql = 'SELECT COUNT(g.userid)
2063 FROM {assign_grades} g
2064 JOIN(' . $esql . ') e ON e.id = g.userid
2065 WHERE g.assignment = :assignid';
2067 return $DB->count_records_sql($sql, $params);
2071 * Load a count of submissions.
2073 * @param bool $includenew When true, also counts the submissions with status 'new'.
2074 * @return int number of submissions
2076 public function count_submissions($includenew = false) {
2077 global $DB;
2079 if (!$this->has_instance()) {
2080 return 0;
2083 $params = array();
2084 $sqlnew = '';
2086 if (!$includenew) {
2087 $sqlnew = ' AND s.status <> :status ';
2088 $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
2091 if ($this->get_instance()->teamsubmission) {
2092 // We cannot join on the enrolment tables for group submissions (no userid).
2093 $sql = 'SELECT COUNT(DISTINCT s.groupid)
2094 FROM {assign_submission} s
2095 WHERE
2096 s.assignment = :assignid AND
2097 s.timemodified IS NOT NULL AND
2098 s.userid = :groupuserid' .
2099 $sqlnew;
2101 $params['assignid'] = $this->get_instance()->id;
2102 $params['groupuserid'] = 0;
2103 } else {
2104 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2105 list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2107 $params = array_merge($params, $enrolparams);
2108 $params['assignid'] = $this->get_instance()->id;
2110 $sql = 'SELECT COUNT(DISTINCT s.userid)
2111 FROM {assign_submission} s
2112 JOIN(' . $esql . ') e ON e.id = s.userid
2113 WHERE
2114 s.assignment = :assignid AND
2115 s.timemodified IS NOT NULL ' .
2116 $sqlnew;
2120 return $DB->count_records_sql($sql, $params);
2124 * Load a count of submissions with a specified status.
2126 * @param string $status The submission status - should match one of the constants
2127 * @return int number of matching submissions
2129 public function count_submissions_with_status($status) {
2130 global $DB;
2132 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2133 list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2135 $params['assignid'] = $this->get_instance()->id;
2136 $params['assignid2'] = $this->get_instance()->id;
2137 $params['submissionstatus'] = $status;
2139 if ($this->get_instance()->teamsubmission) {
2141 $groupsstr = '';
2142 if ($currentgroup != 0) {
2143 // If there is an active group we should only display the current group users groups.
2144 $participants = $this->list_participants($currentgroup, true);
2145 $groups = groups_get_all_groups($this->get_course()->id,
2146 array_keys($participants),
2147 $this->get_instance()->teamsubmissiongroupingid,
2148 'DISTINCT g.id, g.name');
2149 if (empty($groups)) {
2150 // If $groups is empty it means it is not part of $this->get_instance()->teamsubmissiongroupingid.
2151 // All submissions from students that do not belong to any of teamsubmissiongroupingid groups
2152 // count towards groupid = 0. Setting to true as only '0' key matters.
2153 $groups = [true];
2155 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
2156 $groupsstr = 's.groupid ' . $groupssql . ' AND';
2157 $params = $params + $groupsparams;
2159 $sql = 'SELECT COUNT(s.groupid)
2160 FROM {assign_submission} s
2161 WHERE
2162 s.latest = 1 AND
2163 s.assignment = :assignid AND
2164 s.timemodified IS NOT NULL AND
2165 s.userid = :groupuserid AND '
2166 . $groupsstr . '
2167 s.status = :submissionstatus';
2168 $params['groupuserid'] = 0;
2169 } else {
2170 $sql = 'SELECT COUNT(s.userid)
2171 FROM {assign_submission} s
2172 JOIN(' . $esql . ') e ON e.id = s.userid
2173 WHERE
2174 s.latest = 1 AND
2175 s.assignment = :assignid AND
2176 s.timemodified IS NOT NULL AND
2177 s.status = :submissionstatus';
2181 return $DB->count_records_sql($sql, $params);
2185 * Utility function to get the userid for every row in the grading table
2186 * so the order can be frozen while we iterate it.
2188 * @return array An array of userids
2190 protected function get_grading_userid_list() {
2191 $filter = get_user_preferences('assign_filter', '');
2192 $table = new assign_grading_table($this, 0, $filter, 0, false);
2194 $useridlist = $table->get_column_data('userid');
2196 return $useridlist;
2200 * Generate zip file from array of given files.
2202 * @param array $filesforzipping - array of files to pass into archive_to_pathname.
2203 * This array is indexed by the final file name and each
2204 * element in the array is an instance of a stored_file object.
2205 * @return path of temp file - note this returned file does
2206 * not have a .zip extension - it is a temp file.
2208 protected function pack_files($filesforzipping) {
2209 global $CFG;
2210 // Create path for new zip file.
2211 $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
2212 // Zip files.
2213 $zipper = new zip_packer();
2214 if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
2215 return $tempzip;
2217 return false;
2221 * Finds all assignment notifications that have yet to be mailed out, and mails them.
2223 * Cron function to be run periodically according to the moodle cron.
2225 * @return bool
2227 public static function cron() {
2228 global $DB;
2230 // Only ever send a max of one days worth of updates.
2231 $yesterday = time() - (24 * 3600);
2232 $timenow = time();
2233 $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
2235 // Collect all submissions that require mailing.
2236 // Submissions are included if all are true:
2237 // - The assignment is visible in the gradebook.
2238 // - No previous notification has been sent.
2239 // - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
2240 // if marking workflow is enabled, the workflow state is at 'released'.
2241 $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
2242 g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
2243 FROM {assign} a
2244 JOIN {assign_grades} g ON g.assignment = a.id
2245 LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
2246 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
2247 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
2248 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
2249 LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
2250 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
2251 (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
2252 uf.mailed = 0 AND gri.hidden = 0
2253 ORDER BY a.course, cm.id";
2255 $params = array(
2256 'yesterday' => $yesterday,
2257 'today' => $timenow,
2258 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
2260 $submissions = $DB->get_records_sql($sql, $params);
2262 if (!empty($submissions)) {
2264 mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
2266 // Preload courses we are going to need those.
2267 $courseids = array();
2268 foreach ($submissions as $submission) {
2269 $courseids[] = $submission->course;
2272 // Filter out duplicates.
2273 $courseids = array_unique($courseids);
2274 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2275 list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
2276 $sql = 'SELECT c.*, ' . $ctxselect .
2277 ' FROM {course} c
2278 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
2279 WHERE c.id ' . $courseidsql;
2281 $params['contextlevel'] = CONTEXT_COURSE;
2282 $courses = $DB->get_records_sql($sql, $params);
2284 // Clean up... this could go on for a while.
2285 unset($courseids);
2286 unset($ctxselect);
2287 unset($courseidsql);
2288 unset($params);
2290 // Message students about new feedback.
2291 foreach ($submissions as $submission) {
2293 mtrace("Processing assignment submission $submission->id ...");
2295 // Do not cache user lookups - could be too many.
2296 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
2297 mtrace('Could not find user ' . $submission->userid);
2298 continue;
2301 // Use a cache to prevent the same DB queries happening over and over.
2302 if (!array_key_exists($submission->course, $courses)) {
2303 mtrace('Could not find course ' . $submission->course);
2304 continue;
2306 $course = $courses[$submission->course];
2307 if (isset($course->ctxid)) {
2308 // Context has not yet been preloaded. Do so now.
2309 context_helper::preload_from_record($course);
2312 // Override the language and timezone of the "current" user, so that
2313 // mail is customised for the receiver.
2314 cron_setup_user($user, $course);
2316 // Context lookups are already cached.
2317 $coursecontext = context_course::instance($course->id);
2318 if (!is_enrolled($coursecontext, $user->id)) {
2319 $courseshortname = format_string($course->shortname,
2320 true,
2321 array('context' => $coursecontext));
2322 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
2323 continue;
2326 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
2327 mtrace('Could not find grader ' . $submission->grader);
2328 continue;
2331 $modinfo = get_fast_modinfo($course, $user->id);
2332 $cm = $modinfo->get_cm($submission->cmid);
2333 // Context lookups are already cached.
2334 $contextmodule = context_module::instance($cm->id);
2336 if (!$cm->uservisible) {
2337 // Hold mail notification for assignments the user cannot access until later.
2338 continue;
2341 // Need to send this to the student.
2342 $messagetype = 'feedbackavailable';
2343 $eventtype = 'assign_notification';
2344 $updatetime = $submission->lastmodified;
2345 $modulename = get_string('modulename', 'assign');
2347 $uniqueid = 0;
2348 if ($submission->blindmarking && !$submission->revealidentities) {
2349 if (empty($submission->recordid)) {
2350 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
2351 } else {
2352 $uniqueid = $submission->recordid;
2355 $showusers = $submission->blindmarking && !$submission->revealidentities;
2356 self::send_assignment_notification($grader,
2357 $user,
2358 $messagetype,
2359 $eventtype,
2360 $updatetime,
2361 $cm,
2362 $contextmodule,
2363 $course,
2364 $modulename,
2365 $submission->name,
2366 $showusers,
2367 $uniqueid);
2369 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
2370 if ($flags) {
2371 $flags->mailed = 1;
2372 $DB->update_record('assign_user_flags', $flags);
2373 } else {
2374 $flags = new stdClass();
2375 $flags->userid = $user->id;
2376 $flags->assignment = $submission->assignment;
2377 $flags->mailed = 1;
2378 $DB->insert_record('assign_user_flags', $flags);
2381 mtrace('Done');
2383 mtrace('Done processing ' . count($submissions) . ' assignment submissions');
2385 cron_setup_user();
2387 // Free up memory just to be sure.
2388 unset($courses);
2391 // Update calendar events to provide a description.
2392 $sql = 'SELECT id
2393 FROM {assign}
2394 WHERE
2395 allowsubmissionsfromdate >= :lastcron AND
2396 allowsubmissionsfromdate <= :timenow AND
2397 alwaysshowdescription = 0';
2398 $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2399 $newlyavailable = $DB->get_records_sql($sql, $params);
2400 foreach ($newlyavailable as $record) {
2401 $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
2402 $context = context_module::instance($cm->id);
2404 $assignment = new assign($context, null, null);
2405 $assignment->update_calendar($cm->id);
2408 return true;
2412 * Mark in the database that this grade record should have an update notification sent by cron.
2414 * @param stdClass $grade a grade record keyed on id
2415 * @param bool $mailedoverride when true, flag notification to be sent again.
2416 * @return bool true for success
2418 public function notify_grade_modified($grade, $mailedoverride = false) {
2419 global $DB;
2421 $flags = $this->get_user_flags($grade->userid, true);
2422 if ($flags->mailed != 1 || $mailedoverride) {
2423 $flags->mailed = 0;
2426 return $this->update_user_flags($flags);
2430 * Update user flags for this user in this assignment.
2432 * @param stdClass $flags a flags record keyed on id
2433 * @return bool true for success
2435 public function update_user_flags($flags) {
2436 global $DB;
2437 if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
2438 return false;
2441 $result = $DB->update_record('assign_user_flags', $flags);
2442 return $result;
2446 * Update a grade in the grade table for the assignment and in the gradebook.
2448 * @param stdClass $grade a grade record keyed on id
2449 * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
2450 * @return bool true for success
2452 public function update_grade($grade, $reopenattempt = false) {
2453 global $DB;
2455 $grade->timemodified = time();
2457 if (!empty($grade->workflowstate)) {
2458 $validstates = $this->get_marking_workflow_states_for_current_user();
2459 if (!array_key_exists($grade->workflowstate, $validstates)) {
2460 return false;
2464 if ($grade->grade && $grade->grade != -1) {
2465 if ($this->get_instance()->grade > 0) {
2466 if (!is_numeric($grade->grade)) {
2467 return false;
2468 } else if ($grade->grade > $this->get_instance()->grade) {
2469 return false;
2470 } else if ($grade->grade < 0) {
2471 return false;
2473 } else {
2474 // This is a scale.
2475 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
2476 $scaleoptions = make_menu_from_list($scale->scale);
2477 if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
2478 return false;
2484 if (empty($grade->attemptnumber)) {
2485 // Set it to the default.
2486 $grade->attemptnumber = 0;
2488 $DB->update_record('assign_grades', $grade);
2490 $submission = null;
2491 if ($this->get_instance()->teamsubmission) {
2492 $submission = $this->get_group_submission($grade->userid, 0, false);
2493 } else {
2494 $submission = $this->get_user_submission($grade->userid, false);
2497 // Only push to gradebook if the update is for the latest attempt.
2498 // Not the latest attempt.
2499 if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
2500 return true;
2503 if ($this->gradebook_item_update(null, $grade)) {
2504 \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
2507 // If the conditions are met, allow another attempt.
2508 if ($submission) {
2509 $this->reopen_submission_if_required($grade->userid,
2510 $submission,
2511 $reopenattempt);
2514 return true;
2518 * View the grant extension date page.
2520 * Uses url parameters 'userid'
2521 * or from parameter 'selectedusers'
2523 * @param moodleform $mform - Used for validation of the submitted data
2524 * @return string
2526 protected function view_grant_extension($mform) {
2527 global $CFG;
2528 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2530 $o = '';
2532 $data = new stdClass();
2533 $data->id = $this->get_course_module()->id;
2535 $formparams = array(
2536 'instance' => $this->get_instance(),
2537 'assign' => $this
2540 $users = optional_param('userid', 0, PARAM_INT);
2541 if (!$users) {
2542 $users = required_param('selectedusers', PARAM_SEQUENCE);
2544 $userlist = explode(',', $users);
2546 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
2547 $maxoverride = array('allowsubmissionsfromdate' => 0, 'duedate' => 0, 'cutoffdate' => 0);
2548 foreach ($userlist as $userid) {
2549 // To validate extension date with users overrides.
2550 $override = $this->override_exists($userid);
2551 foreach ($keys as $key) {
2552 if ($override->{$key}) {
2553 if ($maxoverride[$key] < $override->{$key}) {
2554 $maxoverride[$key] = $override->{$key};
2556 } else if ($maxoverride[$key] < $this->get_instance()->{$key}) {
2557 $maxoverride[$key] = $this->get_instance()->{$key};
2561 foreach ($keys as $key) {
2562 if ($maxoverride[$key]) {
2563 $this->get_instance()->{$key} = $maxoverride[$key];
2567 $formparams['userlist'] = $userlist;
2569 $data->selectedusers = $users;
2570 $data->userid = 0;
2572 if (empty($mform)) {
2573 $mform = new mod_assign_extension_form(null, $formparams);
2575 $mform->set_data($data);
2576 $header = new assign_header($this->get_instance(),
2577 $this->get_context(),
2578 $this->show_intro(),
2579 $this->get_course_module()->id,
2580 get_string('grantextension', 'assign'));
2581 $o .= $this->get_renderer()->render($header);
2582 $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
2583 $o .= $this->view_footer();
2584 return $o;
2588 * Get a list of the users in the same group as this user.
2590 * @param int $groupid The id of the group whose members we want or 0 for the default group
2591 * @param bool $onlyids Whether to retrieve only the user id's
2592 * @param bool $excludesuspended Whether to exclude suspended users
2593 * @return array The users (possibly id's only)
2595 public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
2596 $members = array();
2597 if ($groupid != 0) {
2598 $allusers = $this->list_participants($groupid, $onlyids);
2599 foreach ($allusers as $user) {
2600 if ($this->get_submission_group($user->id)) {
2601 $members[] = $user;
2604 } else {
2605 $allusers = $this->list_participants(null, $onlyids);
2606 foreach ($allusers as $user) {
2607 if ($this->get_submission_group($user->id) == null) {
2608 $members[] = $user;
2612 // Exclude suspended users, if user can't see them.
2613 if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2614 foreach ($members as $key => $member) {
2615 if (!$this->is_active_user($member->id)) {
2616 unset($members[$key]);
2621 return $members;
2625 * Get a list of the users in the same group as this user that have not submitted the assignment.
2627 * @param int $groupid The id of the group whose members we want or 0 for the default group
2628 * @param bool $onlyids Whether to retrieve only the user id's
2629 * @return array The users (possibly id's only)
2631 public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2632 $instance = $this->get_instance();
2633 if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2634 return array();
2636 $members = $this->get_submission_group_members($groupid, $onlyids);
2638 foreach ($members as $id => $member) {
2639 $submission = $this->get_user_submission($member->id, false);
2640 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2641 unset($members[$id]);
2642 } else {
2643 if ($this->is_blind_marking()) {
2644 $members[$id]->alias = get_string('hiddenuser', 'assign') .
2645 $this->get_uniqueid_for_user($id);
2649 return $members;
2653 * Load the group submission object for a particular user, optionally creating it if required.
2655 * @param int $userid The id of the user whose submission we want
2656 * @param int $groupid The id of the group for this user - may be 0 in which
2657 * case it is determined from the userid.
2658 * @param bool $create If set to true a new submission object will be created in the database
2659 * with the status set to "new".
2660 * @param int $attemptnumber - -1 means the latest attempt
2661 * @return stdClass The submission
2663 public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2664 global $DB;
2666 if ($groupid == 0) {
2667 $group = $this->get_submission_group($userid);
2668 if ($group) {
2669 $groupid = $group->id;
2673 // Now get the group submission.
2674 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2675 if ($attemptnumber >= 0) {
2676 $params['attemptnumber'] = $attemptnumber;
2679 // Only return the row with the highest attemptnumber.
2680 $submission = null;
2681 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2682 if ($submissions) {
2683 $submission = reset($submissions);
2686 if ($submission) {
2687 return $submission;
2689 if ($create) {
2690 $submission = new stdClass();
2691 $submission->assignment = $this->get_instance()->id;
2692 $submission->userid = 0;
2693 $submission->groupid = $groupid;
2694 $submission->timecreated = time();
2695 $submission->timemodified = $submission->timecreated;
2696 if ($attemptnumber >= 0) {
2697 $submission->attemptnumber = $attemptnumber;
2698 } else {
2699 $submission->attemptnumber = 0;
2701 // Work out if this is the latest submission.
2702 $submission->latest = 0;
2703 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2704 if ($attemptnumber == -1) {
2705 // This is a new submission so it must be the latest.
2706 $submission->latest = 1;
2707 } else {
2708 // We need to work this out.
2709 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2710 if ($result) {
2711 $latestsubmission = reset($result);
2713 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2714 $submission->latest = 1;
2717 if ($submission->latest) {
2718 // This is the case when we need to set latest to 0 for all the other attempts.
2719 $DB->set_field('assign_submission', 'latest', 0, $params);
2721 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2722 $sid = $DB->insert_record('assign_submission', $submission);
2723 return $DB->get_record('assign_submission', array('id' => $sid));
2725 return false;
2729 * View a summary listing of all assignments in the current course.
2731 * @return string
2733 private function view_course_index() {
2734 global $USER;
2736 $o = '';
2738 $course = $this->get_course();
2739 $strplural = get_string('modulenameplural', 'assign');
2741 if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2742 $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2743 $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2744 return $o;
2747 $strsectionname = '';
2748 $usesections = course_format_uses_sections($course->format);
2749 $modinfo = get_fast_modinfo($course);
2751 if ($usesections) {
2752 $strsectionname = get_string('sectionname', 'format_'.$course->format);
2753 $sections = $modinfo->get_section_info_all();
2755 $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2757 $timenow = time();
2759 $currentsection = '';
2760 foreach ($modinfo->instances['assign'] as $cm) {
2761 if (!$cm->uservisible) {
2762 continue;
2765 $timedue = $cms[$cm->id]->duedate;
2767 $sectionname = '';
2768 if ($usesections && $cm->sectionnum) {
2769 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2772 $submitted = '';
2773 $context = context_module::instance($cm->id);
2775 $assignment = new assign($context, $cm, $course);
2777 // Apply overrides.
2778 $assignment->update_effective_access($USER->id);
2779 $timedue = $assignment->get_instance()->duedate;
2781 if (has_capability('mod/assign:grade', $context)) {
2782 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2784 } else if (has_capability('mod/assign:submit', $context)) {
2785 $usersubmission = $assignment->get_user_submission($USER->id, false);
2787 if (!empty($usersubmission->status)) {
2788 $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2789 } else {
2790 $submitted = get_string('submissionstatus_', 'assign');
2793 $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2794 if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2795 !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2796 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2797 } else {
2798 $grade = '-';
2801 $courseindexsummary->add_assign_info($cm->id, $cm->get_formatted_name(), $sectionname, $timedue, $submitted, $grade);
2805 $o .= $this->get_renderer()->render($courseindexsummary);
2806 $o .= $this->view_footer();
2808 return $o;
2812 * View a page rendered by a plugin.
2814 * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2816 * @return string
2818 protected function view_plugin_page() {
2819 global $USER;
2821 $o = '';
2823 $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2824 $plugintype = required_param('plugin', PARAM_PLUGIN);
2825 $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2827 $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2828 if (!$plugin) {
2829 print_error('invalidformdata', '');
2830 return;
2833 $o .= $plugin->view_page($pluginaction);
2835 return $o;
2840 * This is used for team assignments to get the group for the specified user.
2841 * If the user is a member of multiple or no groups this will return false
2843 * @param int $userid The id of the user whose submission we want
2844 * @return mixed The group or false
2846 public function get_submission_group($userid) {
2848 if (isset($this->usersubmissiongroups[$userid])) {
2849 return $this->usersubmissiongroups[$userid];
2852 $groups = $this->get_all_groups($userid);
2853 if (count($groups) != 1) {
2854 $return = false;
2855 } else {
2856 $return = array_pop($groups);
2859 // Cache the user submission group.
2860 $this->usersubmissiongroups[$userid] = $return;
2862 return $return;
2866 * Gets all groups the user is a member of.
2868 * @param int $userid Teh id of the user who's groups we are checking
2869 * @return array The group objects
2871 public function get_all_groups($userid) {
2872 if (isset($this->usergroups[$userid])) {
2873 return $this->usergroups[$userid];
2876 $grouping = $this->get_instance()->teamsubmissiongroupingid;
2877 $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
2879 $this->usergroups[$userid] = $return;
2881 return $return;
2886 * Display the submission that is used by a plugin.
2888 * Uses url parameters 'sid', 'gid' and 'plugin'.
2890 * @param string $pluginsubtype
2891 * @return string
2893 protected function view_plugin_content($pluginsubtype) {
2894 $o = '';
2896 $submissionid = optional_param('sid', 0, PARAM_INT);
2897 $gradeid = optional_param('gid', 0, PARAM_INT);
2898 $plugintype = required_param('plugin', PARAM_PLUGIN);
2899 $item = null;
2900 if ($pluginsubtype == 'assignsubmission') {
2901 $plugin = $this->get_submission_plugin_by_type($plugintype);
2902 if ($submissionid <= 0) {
2903 throw new coding_exception('Submission id should not be 0');
2905 $item = $this->get_submission($submissionid);
2907 // Check permissions.
2908 $this->require_view_submission($item->userid);
2909 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2910 $this->get_context(),
2911 $this->show_intro(),
2912 $this->get_course_module()->id,
2913 $plugin->get_name()));
2914 $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
2915 $item,
2916 assign_submission_plugin_submission::FULL,
2917 $this->get_course_module()->id,
2918 $this->get_return_action(),
2919 $this->get_return_params()));
2921 // Trigger event for viewing a submission.
2922 \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
2924 } else {
2925 $plugin = $this->get_feedback_plugin_by_type($plugintype);
2926 if ($gradeid <= 0) {
2927 throw new coding_exception('Grade id should not be 0');
2929 $item = $this->get_grade($gradeid);
2930 // Check permissions.
2931 $this->require_view_submission($item->userid);
2932 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
2933 $this->get_context(),
2934 $this->show_intro(),
2935 $this->get_course_module()->id,
2936 $plugin->get_name()));
2937 $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
2938 $item,
2939 assign_feedback_plugin_feedback::FULL,
2940 $this->get_course_module()->id,
2941 $this->get_return_action(),
2942 $this->get_return_params()));
2944 // Trigger event for viewing feedback.
2945 \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
2948 $o .= $this->view_return_links();
2950 $o .= $this->view_footer();
2952 return $o;
2956 * Rewrite plugin file urls so they resolve correctly in an exported zip.
2958 * @param string $text - The replacement text
2959 * @param stdClass $user - The user record
2960 * @param assign_plugin $plugin - The assignment plugin
2962 public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
2963 $groupmode = groups_get_activity_groupmode($this->get_course_module());
2964 $groupname = '';
2965 if ($groupmode) {
2966 $groupid = groups_get_activity_group($this->get_course_module(), true);
2967 $groupname = groups_get_group_name($groupid).'-';
2970 if ($this->is_blind_marking()) {
2971 $prefix = $groupname . get_string('participant', 'assign');
2972 $prefix = str_replace('_', ' ', $prefix);
2973 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2974 } else {
2975 $prefix = $groupname . fullname($user);
2976 $prefix = str_replace('_', ' ', $prefix);
2977 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
2980 $subtype = $plugin->get_subtype();
2981 $type = $plugin->get_type();
2982 $prefix = $prefix . $subtype . '_' . $type . '_';
2984 $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
2986 return $result;
2990 * Render the content in editor that is often used by plugin.
2992 * @param string $filearea
2993 * @param int $submissionid
2994 * @param string $plugintype
2995 * @param string $editor
2996 * @param string $component
2997 * @return string
2999 public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
3000 global $CFG;
3002 $result = '';
3004 $plugin = $this->get_submission_plugin_by_type($plugintype);
3006 $text = $plugin->get_editor_text($editor, $submissionid);
3007 $format = $plugin->get_editor_format($editor, $submissionid);
3009 $finaltext = file_rewrite_pluginfile_urls($text,
3010 'pluginfile.php',
3011 $this->get_context()->id,
3012 $component,
3013 $filearea,
3014 $submissionid);
3015 $params = array('overflowdiv' => true, 'context' => $this->get_context());
3016 $result .= format_text($finaltext, $format, $params);
3018 if ($CFG->enableportfolios && has_capability('mod/assign:exportownsubmission', $this->context)) {
3019 require_once($CFG->libdir . '/portfoliolib.php');
3021 $button = new portfolio_add_button();
3022 $portfolioparams = array('cmid' => $this->get_course_module()->id,
3023 'sid' => $submissionid,
3024 'plugin' => $plugintype,
3025 'editor' => $editor,
3026 'area'=>$filearea);
3027 $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
3028 $fs = get_file_storage();
3030 if ($files = $fs->get_area_files($this->context->id,
3031 $component,
3032 $filearea,
3033 $submissionid,
3034 'timemodified',
3035 false)) {
3036 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3037 } else {
3038 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3040 $result .= $button->to_html();
3042 return $result;
3046 * Display a continue page after grading.
3048 * @param string $message - The message to display.
3049 * @return string
3051 protected function view_savegrading_result($message) {
3052 $o = '';
3053 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3054 $this->get_context(),
3055 $this->show_intro(),
3056 $this->get_course_module()->id,
3057 get_string('savegradingresult', 'assign')));
3058 $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
3059 $message,
3060 $this->get_course_module()->id);
3061 $o .= $this->get_renderer()->render($gradingresult);
3062 $o .= $this->view_footer();
3063 return $o;
3066 * Display a continue page after quickgrading.
3068 * @param string $message - The message to display.
3069 * @return string
3071 protected function view_quickgrading_result($message) {
3072 $o = '';
3073 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3074 $this->get_context(),
3075 $this->show_intro(),
3076 $this->get_course_module()->id,
3077 get_string('quickgradingresult', 'assign')));
3078 $lastpage = optional_param('lastpage', null, PARAM_INT);
3079 $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
3080 $message,
3081 $this->get_course_module()->id,
3082 false,
3083 $lastpage);
3084 $o .= $this->get_renderer()->render($gradingresult);
3085 $o .= $this->view_footer();
3086 return $o;
3090 * Display the page footer.
3092 * @return string
3094 protected function view_footer() {
3095 // When viewing the footer during PHPUNIT tests a set_state error is thrown.
3096 if (!PHPUNIT_TEST) {
3097 return $this->get_renderer()->render_footer();
3100 return '';
3104 * Throw an error if the permissions to view this users submission are missing.
3106 * @throws required_capability_exception
3107 * @return none
3109 public function require_view_submission($userid) {
3110 if (!$this->can_view_submission($userid)) {
3111 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3116 * Throw an error if the permissions to view grades in this assignment are missing.
3118 * @throws required_capability_exception
3119 * @return none
3121 public function require_view_grades() {
3122 if (!$this->can_view_grades()) {
3123 throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3128 * Does this user have view grade or grade permission for this assignment?
3130 * @return bool
3132 public function can_view_grades() {
3133 // Permissions check.
3134 if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
3135 return false;
3137 // Checks for the edge case when user belongs to no groups and groupmode is sep.
3138 if ($this->get_course_module()->effectivegroupmode == SEPARATEGROUPS) {
3139 $groupflag = has_capability('moodle/site:accessallgroups', $this->get_context());
3140 $groupflag = $groupflag || !empty(groups_get_activity_allowed_groups($this->get_course_module()));
3141 return (bool)$groupflag;
3143 return true;
3147 * Does this user have grade permission for this assignment?
3149 * @return bool
3151 public function can_grade() {
3152 // Permissions check.
3153 if (!has_capability('mod/assign:grade', $this->context)) {
3154 return false;
3157 return true;
3161 * Download a zip file of all assignment submissions.
3163 * @param array $userids Array of user ids to download assignment submissions in a zip file
3164 * @return string - If an error occurs, this will contain the error page.
3166 protected function download_submissions($userids = false) {
3167 global $CFG, $DB;
3169 // More efficient to load this here.
3170 require_once($CFG->libdir.'/filelib.php');
3172 // Increase the server timeout to handle the creation and sending of large zip files.
3173 core_php_time_limit::raise();
3175 $this->require_view_grades();
3177 // Load all users with submit.
3178 $students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null,
3179 $this->show_only_active_users());
3181 // Build a list of files to zip.
3182 $filesforzipping = array();
3183 $fs = get_file_storage();
3185 $groupmode = groups_get_activity_groupmode($this->get_course_module());
3186 // All users.
3187 $groupid = 0;
3188 $groupname = '';
3189 if ($groupmode) {
3190 $groupid = groups_get_activity_group($this->get_course_module(), true);
3191 $groupname = groups_get_group_name($groupid).'-';
3194 // Construct the zip file name.
3195 $filename = clean_filename($this->get_course()->shortname . '-' .
3196 $this->get_instance()->name . '-' .
3197 $groupname.$this->get_course_module()->id . '.zip');
3199 // Get all the files for each student.
3200 foreach ($students as $student) {
3201 $userid = $student->id;
3202 // Download all assigments submission or only selected users.
3203 if ($userids and !in_array($userid, $userids)) {
3204 continue;
3207 if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
3208 // Get the plugins to add their own files to the zip.
3210 $submissiongroup = false;
3211 $groupname = '';
3212 if ($this->get_instance()->teamsubmission) {
3213 $submission = $this->get_group_submission($userid, 0, false);
3214 $submissiongroup = $this->get_submission_group($userid);
3215 if ($submissiongroup) {
3216 $groupname = $submissiongroup->name . '-';
3217 } else {
3218 $groupname = get_string('defaultteam', 'assign') . '-';
3220 } else {
3221 $submission = $this->get_user_submission($userid, false);
3224 if ($this->is_blind_marking()) {
3225 $prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
3226 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
3227 } else {
3228 $prefix = str_replace('_', ' ', $groupname . fullname($student));
3229 $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid));
3232 if ($submission) {
3233 $downloadasfolders = get_user_preferences('assign_downloadasfolders', 1);
3234 foreach ($this->submissionplugins as $plugin) {
3235 if ($plugin->is_enabled() && $plugin->is_visible()) {
3236 if ($downloadasfolders) {
3237 // Create a folder for each user for each assignment plugin.
3238 // This is the default behavior for version of Moodle >= 3.1.
3239 $submission->exportfullpath = true;
3240 $pluginfiles = $plugin->get_files($submission, $student);
3241 foreach ($pluginfiles as $zipfilepath => $file) {
3242 $subtype = $plugin->get_subtype();
3243 $type = $plugin->get_type();
3244 $zipfilename = basename($zipfilepath);
3245 $prefixedfilename = clean_filename($prefix .
3246 '_' .
3247 $subtype .
3248 '_' .
3249 $type .
3250 '_');
3251 if ($type == 'file') {
3252 $pathfilename = $prefixedfilename . $file->get_filepath() . $zipfilename;
3253 } else if ($type == 'onlinetext') {
3254 $pathfilename = $prefixedfilename . '/' . $zipfilename;
3255 } else {
3256 $pathfilename = $prefixedfilename . '/' . $zipfilename;
3258 $pathfilename = clean_param($pathfilename, PARAM_PATH);
3259 $filesforzipping[$pathfilename] = $file;
3261 } else {
3262 // Create a single folder for all users of all assignment plugins.
3263 // This was the default behavior for version of Moodle < 3.1.
3264 $submission->exportfullpath = false;
3265 $pluginfiles = $plugin->get_files($submission, $student);
3266 foreach ($pluginfiles as $zipfilename => $file) {
3267 $subtype = $plugin->get_subtype();
3268 $type = $plugin->get_type();
3269 $prefixedfilename = clean_filename($prefix .
3270 '_' .
3271 $subtype .
3272 '_' .
3273 $type .
3274 '_' .
3275 $zipfilename);
3276 $filesforzipping[$prefixedfilename] = $file;
3284 $result = '';
3285 if (count($filesforzipping) == 0) {
3286 $header = new assign_header($this->get_instance(),
3287 $this->get_context(),
3289 $this->get_course_module()->id,
3290 get_string('downloadall', 'assign'));
3291 $result .= $this->get_renderer()->render($header);
3292 $result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
3293 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
3294 'action'=>'grading'));
3295 $result .= $this->get_renderer()->continue_button($url);
3296 $result .= $this->view_footer();
3297 } else if ($zipfile = $this->pack_files($filesforzipping)) {
3298 \mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
3299 // Send file and delete after sending.
3300 send_temp_file($zipfile, $filename);
3301 // We will not get here - send_temp_file calls exit.
3303 return $result;
3307 * Util function to add a message to the log.
3309 * @deprecated since 2.7 - Use new events system instead.
3310 * (see http://docs.moodle.org/dev/Migrating_logging_calls_in_plugins).
3312 * @param string $action The current action
3313 * @param string $info A detailed description of the change. But no more than 255 characters.
3314 * @param string $url The url to the assign module instance.
3315 * @param bool $return If true, returns the arguments, else adds to log. The purpose of this is to
3316 * retrieve the arguments to use them with the new event system (Event 2).
3317 * @return void|array
3319 public function add_to_log($action = '', $info = '', $url='', $return = false) {
3320 global $USER;
3322 $fullurl = 'view.php?id=' . $this->get_course_module()->id;
3323 if ($url != '') {
3324 $fullurl .= '&' . $url;
3327 $args = array(
3328 $this->get_course()->id,
3329 'assign',
3330 $action,
3331 $fullurl,
3332 $info,
3333 $this->get_course_module()->id
3336 if ($return) {
3337 // We only need to call debugging when returning a value. This is because the call to
3338 // call_user_func_array('add_to_log', $args) will trigger a debugging message of it's own.
3339 debugging('The mod_assign add_to_log() function is now deprecated.', DEBUG_DEVELOPER);
3340 return $args;
3342 call_user_func_array('add_to_log', $args);
3346 * Lazy load the page renderer and expose the renderer to plugins.
3348 * @return assign_renderer
3350 public function get_renderer() {
3351 global $PAGE;
3352 if ($this->output) {
3353 return $this->output;
3355 $this->output = $PAGE->get_renderer('mod_assign', null, RENDERER_TARGET_GENERAL);
3356 return $this->output;
3360 * Load the submission object for a particular user, optionally creating it if required.
3362 * For team assignments there are 2 submissions - the student submission and the team submission
3363 * All files are associated with the team submission but the status of the students contribution is
3364 * recorded separately.
3366 * @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
3367 * @param bool $create If set to true a new submission object will be created in the database with the status set to "new".
3368 * @param int $attemptnumber - -1 means the latest attempt
3369 * @return stdClass The submission
3371 public function get_user_submission($userid, $create, $attemptnumber=-1) {
3372 global $DB, $USER;
3374 if (!$userid) {
3375 $userid = $USER->id;
3377 // If the userid is not null then use userid.
3378 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
3379 if ($attemptnumber >= 0) {
3380 $params['attemptnumber'] = $attemptnumber;
3383 // Only return the row with the highest attemptnumber.
3384 $submission = null;
3385 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
3386 if ($submissions) {
3387 $submission = reset($submissions);
3390 if ($submission) {
3391 return $submission;
3393 if ($create) {
3394 $submission = new stdClass();
3395 $submission->assignment = $this->get_instance()->id;
3396 $submission->userid = $userid;
3397 $submission->timecreated = time();
3398 $submission->timemodified = $submission->timecreated;
3399 $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
3400 if ($attemptnumber >= 0) {
3401 $submission->attemptnumber = $attemptnumber;
3402 } else {
3403 $submission->attemptnumber = 0;
3405 // Work out if this is the latest submission.
3406 $submission->latest = 0;
3407 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
3408 if ($attemptnumber == -1) {
3409 // This is a new submission so it must be the latest.
3410 $submission->latest = 1;
3411 } else {
3412 // We need to work this out.
3413 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
3414 $latestsubmission = null;
3415 if ($result) {
3416 $latestsubmission = reset($result);
3418 if (empty($latestsubmission) || ($attemptnumber > $latestsubmission->attemptnumber)) {
3419 $submission->latest = 1;
3422 if ($submission->latest) {
3423 // This is the case when we need to set latest to 0 for all the other attempts.
3424 $DB->set_field('assign_submission', 'latest', 0, $params);
3426 $sid = $DB->insert_record('assign_submission', $submission);
3427 return $DB->get_record('assign_submission', array('id' => $sid));
3429 return false;
3433 * Load the submission object from it's id.
3435 * @param int $submissionid The id of the submission we want
3436 * @return stdClass The submission
3438 protected function get_submission($submissionid) {
3439 global $DB;
3441 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid);
3442 return $DB->get_record('assign_submission', $params, '*', MUST_EXIST);
3446 * This will retrieve a user flags object from the db optionally creating it if required.
3447 * The user flags was split from the user_grades table in 2.5.
3449 * @param int $userid The user we are getting the flags for.
3450 * @param bool $create If true the flags record will be created if it does not exist
3451 * @return stdClass The flags record
3453 public function get_user_flags($userid, $create) {
3454 global $DB, $USER;
3456 // If the userid is not null then use userid.
3457 if (!$userid) {
3458 $userid = $USER->id;
3461 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
3463 $flags = $DB->get_record('assign_user_flags', $params);
3465 if ($flags) {
3466 return $flags;
3468 if ($create) {
3469 $flags = new stdClass();
3470 $flags->assignment = $this->get_instance()->id;
3471 $flags->userid = $userid;
3472 $flags->locked = 0;
3473 $flags->extensionduedate = 0;
3474 $flags->workflowstate = '';
3475 $flags->allocatedmarker = 0;
3477 // The mailed flag can be one of 3 values: 0 is unsent, 1 is sent and 2 is do not send yet.
3478 // This is because students only want to be notified about certain types of update (grades and feedback).
3479 $flags->mailed = 2;
3481 $fid = $DB->insert_record('assign_user_flags', $flags);
3482 $flags->id = $fid;
3483 return $flags;
3485 return false;
3489 * This will retrieve a grade object from the db, optionally creating it if required.
3491 * @param int $userid The user we are grading
3492 * @param bool $create If true the grade will be created if it does not exist
3493 * @param int $attemptnumber The attempt number to retrieve the grade for. -1 means the latest submission.
3494 * @return stdClass The grade record
3496 public function get_user_grade($userid, $create, $attemptnumber=-1) {
3497 global $DB, $USER;
3499 // If the userid is not null then use userid.
3500 if (!$userid) {
3501 $userid = $USER->id;
3503 $submission = null;
3505 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
3506 if ($attemptnumber < 0 || $create) {
3507 // Make sure this grade matches the latest submission attempt.
3508 if ($this->get_instance()->teamsubmission) {
3509 $submission = $this->get_group_submission($userid, 0, true, $attemptnumber);
3510 } else {
3511 $submission = $this->get_user_submission($userid, true, $attemptnumber);
3513 if ($submission) {
3514 $attemptnumber = $submission->attemptnumber;
3518 if ($attemptnumber >= 0) {
3519 $params['attemptnumber'] = $attemptnumber;
3522 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber DESC', '*', 0, 1);
3524 if ($grades) {
3525 return reset($grades);
3527 if ($create) {
3528 $grade = new stdClass();
3529 $grade->assignment = $this->get_instance()->id;
3530 $grade->userid = $userid;
3531 $grade->timecreated = time();
3532 // If we are "auto-creating" a grade - and there is a submission
3533 // the new grade should not have a more recent timemodified value
3534 // than the submission.
3535 if ($submission) {
3536 $grade->timemodified = $submission->timemodified;
3537 } else {
3538 $grade->timemodified = $grade->timecreated;
3540 $grade->grade = -1;
3541 $grade->grader = $USER->id;
3542 if ($attemptnumber >= 0) {
3543 $grade->attemptnumber = $attemptnumber;
3546 $gid = $DB->insert_record('assign_grades', $grade);
3547 $grade->id = $gid;
3548 return $grade;
3550 return false;
3554 * This will retrieve a grade object from the db.
3556 * @param int $gradeid The id of the grade
3557 * @return stdClass The grade record
3559 protected function get_grade($gradeid) {
3560 global $DB;
3562 $params = array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid);
3563 return $DB->get_record('assign_grades', $params, '*', MUST_EXIST);
3567 * Print the grading page for a single user submission.
3569 * @param array $args Optional args array (better than pulling args from _GET and _POST)
3570 * @return string
3572 protected function view_single_grading_panel($args) {
3573 global $DB, $CFG, $SESSION, $PAGE;
3575 $o = '';
3576 $instance = $this->get_instance();
3578 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3580 // Need submit permission to submit an assignment.
3581 require_capability('mod/assign:grade', $this->context);
3583 // If userid is passed - we are only grading a single student.
3584 $userid = $args['userid'];
3585 $attemptnumber = $args['attemptnumber'];
3587 // Apply overrides.
3588 $this->update_effective_access($userid);
3590 $rownum = 0;
3591 $useridlist = array($userid);
3593 $last = true;
3594 // This variation on the url will link direct to this student, with no next/previous links.
3595 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3596 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3597 $this->register_return_link('grade', $returnparams);
3599 $user = $DB->get_record('user', array('id' => $userid));
3600 $submission = $this->get_user_submission($userid, false, $attemptnumber);
3601 $submissiongroup = null;
3602 $teamsubmission = null;
3603 $notsubmitted = array();
3604 if ($instance->teamsubmission) {
3605 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
3606 $submissiongroup = $this->get_submission_group($userid);
3607 $groupid = 0;
3608 if ($submissiongroup) {
3609 $groupid = $submissiongroup->id;
3611 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3615 // Get the requested grade.
3616 $grade = $this->get_user_grade($userid, false, $attemptnumber);
3617 $flags = $this->get_user_flags($userid, false);
3618 if ($this->can_view_submission($userid)) {
3619 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
3620 $extensionduedate = null;
3621 if ($flags) {
3622 $extensionduedate = $flags->extensionduedate;
3624 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
3625 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
3626 $usergroups = $this->get_all_groups($user->id);
3628 $submissionstatus = new assign_submission_status_compact($instance->allowsubmissionsfromdate,
3629 $instance->alwaysshowdescription,
3630 $submission,
3631 $instance->teamsubmission,
3632 $teamsubmission,
3633 $submissiongroup,
3634 $notsubmitted,
3635 $this->is_any_submission_plugin_enabled(),
3636 $gradelocked,
3637 $this->is_graded($userid),
3638 $instance->duedate,
3639 $instance->cutoffdate,
3640 $this->get_submission_plugins(),
3641 $this->get_return_action(),
3642 $this->get_return_params(),
3643 $this->get_course_module()->id,
3644 $this->get_course()->id,
3645 assign_submission_status::GRADER_VIEW,
3646 $showedit,
3647 false,
3648 $viewfullnames,
3649 $extensionduedate,
3650 $this->get_context(),
3651 $this->is_blind_marking(),
3653 $instance->attemptreopenmethod,
3654 $instance->maxattempts,
3655 $this->get_grading_status($userid),
3656 $instance->preventsubmissionnotingroup,
3657 $usergroups);
3658 $o .= $this->get_renderer()->render($submissionstatus);
3661 if ($grade) {
3662 $data = new stdClass();
3663 if ($grade->grade !== null && $grade->grade >= 0) {
3664 $data->grade = format_float($grade->grade, $this->get_grade_item()->get_decimals());
3666 } else {
3667 $data = new stdClass();
3668 $data->grade = '';
3671 if (!empty($flags->workflowstate)) {
3672 $data->workflowstate = $flags->workflowstate;
3674 if (!empty($flags->allocatedmarker)) {
3675 $data->allocatedmarker = $flags->allocatedmarker;
3678 // Warning if required.
3679 $allsubmissions = $this->get_all_submissions($userid);
3681 if ($attemptnumber != -1 && ($attemptnumber + 1) != count($allsubmissions)) {
3682 $params = array('attemptnumber' => $attemptnumber + 1,
3683 'totalattempts' => count($allsubmissions));
3684 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
3685 $o .= $this->get_renderer()->notification($message);
3688 $pagination = array('rownum' => $rownum,
3689 'useridlistid' => 0,
3690 'last' => $last,
3691 'userid' => $userid,
3692 'attemptnumber' => $attemptnumber,
3693 'gradingpanel' => true);
3695 if (!empty($args['formdata'])) {
3696 $data = (array) $data;
3697 $data = (object) array_merge($data, $args['formdata']);
3699 $formparams = array($this, $data, $pagination);
3700 $mform = new mod_assign_grade_form(null,
3701 $formparams,
3702 'post',
3704 array('class' => 'gradeform'));
3706 if (!empty($args['formdata'])) {
3707 // If we were passed form data - we want the form to check the data
3708 // and show errors.
3709 $mform->is_validated();
3711 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
3712 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
3714 if (count($allsubmissions) > 1) {
3715 $allgrades = $this->get_all_grades($userid);
3716 $history = new assign_attempt_history_chooser($allsubmissions,
3717 $allgrades,
3718 $this->get_course_module()->id,
3719 $userid);
3721 $o .= $this->get_renderer()->render($history);
3724 \mod_assign\event\grading_form_viewed::create_from_user($this, $user)->trigger();
3726 return $o;
3730 * Print the grading page for a single user submission.
3732 * @param moodleform $mform
3733 * @return string
3735 protected function view_single_grade_page($mform) {
3736 global $DB, $CFG, $SESSION;
3738 $o = '';
3739 $instance = $this->get_instance();
3741 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
3743 // Need submit permission to submit an assignment.
3744 require_capability('mod/assign:grade', $this->context);
3746 $header = new assign_header($instance,
3747 $this->get_context(),
3748 false,
3749 $this->get_course_module()->id,
3750 get_string('grading', 'assign'));
3751 $o .= $this->get_renderer()->render($header);
3753 // If userid is passed - we are only grading a single student.
3754 $rownum = optional_param('rownum', 0, PARAM_INT);
3755 $useridlistid = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
3756 $userid = optional_param('userid', 0, PARAM_INT);
3757 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
3759 if (!$userid) {
3760 $useridlistkey = $this->get_useridlist_key($useridlistid);
3761 if (empty($SESSION->mod_assign_useridlist[$useridlistkey])) {
3762 $SESSION->mod_assign_useridlist[$useridlistkey] = $this->get_grading_userid_list();
3764 $useridlist = $SESSION->mod_assign_useridlist[$useridlistkey];
3765 } else {
3766 $rownum = 0;
3767 $useridlistid = 0;
3768 $useridlist = array($userid);
3771 if ($rownum < 0 || $rownum > count($useridlist)) {
3772 throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
3775 $last = false;
3776 $userid = $useridlist[$rownum];
3777 if ($rownum == count($useridlist) - 1) {
3778 $last = true;
3780 // This variation on the url will link direct to this student, with no next/previous links.
3781 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
3782 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
3783 $this->register_return_link('grade', $returnparams);
3785 $user = $DB->get_record('user', array('id' => $userid));
3786 if ($user) {
3787 $this->update_effective_access($userid);
3788 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
3789 $usersummary = new assign_user_summary($user,
3790 $this->get_course()->id,
3791 $viewfullnames,
3792 $this->is_blind_marking(),
3793 $this->get_uniqueid_for_user($user->id),
3794 get_extra_user_fields($this->get_context()),
3795 !$this->is_active_user($userid));
3796 $o .= $this->get_renderer()->render($usersummary);
3798 $submission = $this->get_user_submission($userid, false, $attemptnumber);
3799 $submissiongroup = null;
3800 $teamsubmission = null;
3801 $notsubmitted = array();
3802 if ($instance->teamsubmission) {
3803 $teamsubmission = $this->get_group_submission($userid, 0, false, $attemptnumber);
3804 $submissiongroup = $this->get_submission_group($userid);
3805 $groupid = 0;
3806 if ($submissiongroup) {
3807 $groupid = $submissiongroup->id;
3809 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
3813 // Get the requested grade.
3814 $grade = $this->get_user_grade($userid, false, $attemptnumber);
3815 $flags = $this->get_user_flags($userid, false);
3816 if ($this->can_view_submission($userid)) {
3817 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($userid);
3818 $extensionduedate = null;
3819 if ($flags) {
3820 $extensionduedate = $flags->extensionduedate;
3822 $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());
3823 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
3824 $usergroups = $this->get_all_groups($user->id);
3826 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
3827 $instance->alwaysshowdescription,
3828 $submission,
3829 $instance->teamsubmission,
3830 $teamsubmission,
3831 $submissiongroup,
3832 $notsubmitted,
3833 $this->is_any_submission_plugin_enabled(),
3834 $gradelocked,
3835 $this->is_graded($userid),
3836 $instance->duedate,
3837 $instance->cutoffdate,
3838 $this->get_submission_plugins(),
3839 $this->get_return_action(),
3840 $this->get_return_params(),
3841 $this->get_course_module()->id,
3842 $this->get_course()->id,
3843 assign_submission_status::GRADER_VIEW,
3844 $showedit,
3845 false,
3846 $viewfullnames,
3847 $extensionduedate,
3848 $this->get_context(),
3849 $this->is_blind_marking(),
3851 $instance->attemptreopenmethod,
3852 $instance->maxattempts,
3853 $this->get_grading_status($userid),
3854 $instance->preventsubmissionnotingroup,
3855 $usergroups);
3856 $o .= $this->get_renderer()->render($submissionstatus);
3859 if ($grade) {
3860 $data = new stdClass();
3861 if ($grade->grade !== null && $grade->grade >= 0) {
3862 $data->grade = format_float($grade->grade, $this->get_grade_item()->get_decimals());
3864 } else {
3865 $data = new stdClass();
3866 $data->grade = '';
3869 if (!empty($flags->workflowstate)) {
3870 $data->workflowstate = $flags->workflowstate;
3872 if (!empty($flags->allocatedmarker)) {
3873 $data->allocatedmarker = $flags->allocatedmarker;
3876 // Warning if required.
3877 $allsubmissions = $this->get_all_submissions($userid);
3879 if ($attemptnumber != -1 && ($attemptnumber + 1) != count($allsubmissions)) {
3880 $params = array('attemptnumber'=>$attemptnumber + 1,
3881 'totalattempts'=>count($allsubmissions));
3882 $message = get_string('editingpreviousfeedbackwarning', 'assign', $params);
3883 $o .= $this->get_renderer()->notification($message);
3886 // Now show the grading form.
3887 if (!$mform) {
3888 $pagination = array('rownum' => $rownum,
3889 'useridlistid' => $useridlistid,
3890 'last' => $last,
3891 'userid' => $userid,
3892 'attemptnumber' => $attemptnumber);
3893 $formparams = array($this, $data, $pagination);
3894 $mform = new mod_assign_grade_form(null,
3895 $formparams,
3896 'post',
3898 array('class'=>'gradeform'));
3900 $o .= $this->get_renderer()->heading(get_string('grade'), 3);
3901 $o .= $this->get_renderer()->render(new assign_form('gradingform', $mform));
3903 if (count($allsubmissions) > 1 && $attemptnumber == -1) {
3904 $allgrades = $this->get_all_grades($userid);
3905 $history = new assign_attempt_history($allsubmissions,
3906 $allgrades,
3907 $this->get_submission_plugins(),
3908 $this->get_feedback_plugins(),
3909 $this->get_course_module()->id,
3910 $this->get_return_action(),
3911 $this->get_return_params(),
3912 true,
3913 $useridlistid,
3914 $rownum);
3916 $o .= $this->get_renderer()->render($history);
3919 \mod_assign\event\grading_form_viewed::create_from_user($this, $user)->trigger();
3921 $o .= $this->view_footer();
3922 return $o;
3926 * Show a confirmation page to make sure they want to release student identities.
3928 * @return string
3930 protected function view_reveal_identities_confirm() {
3931 require_capability('mod/assign:revealidentities', $this->get_context());
3933 $o = '';
3934 $header = new assign_header($this->get_instance(),
3935 $this->get_context(),
3936 false,
3937 $this->get_course_module()->id);
3938 $o .= $this->get_renderer()->render($header);
3940 $urlparams = array('id'=>$this->get_course_module()->id,
3941 'action'=>'revealidentitiesconfirm',
3942 'sesskey'=>sesskey());
3943 $confirmurl = new moodle_url('/mod/assign/view.php', $urlparams);
3945 $urlparams = array('id'=>$this->get_course_module()->id,
3946 'action'=>'grading');
3947 $cancelurl = new moodle_url('/mod/assign/view.php', $urlparams);
3949 $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'),
3950 $confirmurl,
3951 $cancelurl);
3952 $o .= $this->view_footer();
3954 \mod_assign\event\reveal_identities_confirmation_page_viewed::create_from_assign($this)->trigger();
3956 return $o;
3960 * View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
3962 * @return string
3964 protected function view_return_links() {
3965 $returnaction = optional_param('returnaction', '', PARAM_ALPHA);
3966 $returnparams = optional_param('returnparams', '', PARAM_TEXT);
3968 $params = array();
3969 $returnparams = str_replace('&amp;', '&', $returnparams);
3970 parse_str($returnparams, $params);
3971 $newparams = array('id' => $this->get_course_module()->id, 'action' => $returnaction);
3972 $params = array_merge($newparams, $params);
3974 $url = new moodle_url('/mod/assign/view.php', $params);
3975 return $this->get_renderer()->single_button($url, get_string('back'), 'get');
3979 * View the grading table of all submissions for this assignment.
3981 * @return string
3983 protected function view_grading_table() {
3984 global $USER, $CFG, $SESSION;
3986 // Include grading options form.
3987 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
3988 require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
3989 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
3990 $o = '';
3991 $cmid = $this->get_course_module()->id;
3993 $links = array();
3994 if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
3995 has_capability('moodle/grade:viewall', $this->get_course_context())) {
3996 $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
3997 $links[$gradebookurl] = get_string('viewgradebook', 'assign');
3999 if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
4000 $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
4001 $links[$downloadurl] = get_string('downloadall', 'assign');
4003 if ($this->is_blind_marking() &&
4004 has_capability('mod/assign:revealidentities', $this->get_context())) {
4005 $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
4006 $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
4008 foreach ($this->get_feedback_plugins() as $plugin) {
4009 if ($plugin->is_enabled() && $plugin->is_visible()) {
4010 foreach ($plugin->get_grading_actions() as $action => $description) {
4011 $url = '/mod/assign/view.php' .
4012 '?id=' . $cmid .
4013 '&plugin=' . $plugin->get_type() .
4014 '&pluginsubtype=assignfeedback' .
4015 '&action=viewpluginpage&pluginaction=' . $action;
4016 $links[$url] = $description;
4021 // Sort links alphabetically based on the link description.
4022 core_collator::asort($links);
4024 $gradingactions = new url_select($links);
4025 $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
4027 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
4029 $perpage = $this->get_assign_perpage();
4030 $filter = get_user_preferences('assign_filter', '');
4031 $markerfilter = get_user_preferences('assign_markerfilter', '');
4032 $workflowfilter = get_user_preferences('assign_workflowfilter', '');
4033 $controller = $gradingmanager->get_active_controller();
4034 $showquickgrading = empty($controller) && $this->can_grade();
4035 $quickgrading = get_user_preferences('assign_quickgrading', false);
4036 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
4037 $downloadasfolders = get_user_preferences('assign_downloadasfolders', 1);
4039 $markingallocation = $this->get_instance()->markingworkflow &&
4040 $this->get_instance()->markingallocation &&
4041 has_capability('mod/assign:manageallocations', $this->context);
4042 // Get markers to use in drop lists.
4043 $markingallocationoptions = array();
4044 if ($markingallocation) {
4045 list($sort, $params) = users_order_by_sql();
4046 $markers = get_users_by_capability($this->context, 'mod/assign:grade', '', $sort);
4047 $markingallocationoptions[''] = get_string('filternone', 'assign');
4048 $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
4049 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
4050 foreach ($markers as $marker) {
4051 $markingallocationoptions[$marker->id] = fullname($marker, $viewfullnames);
4055 $markingworkflow = $this->get_instance()->markingworkflow;
4056 // Get marking states to show in form.
4057 $markingworkflowoptions = array();
4058 if ($markingworkflow) {
4059 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
4060 $markingworkflowoptions[''] = get_string('filternone', 'assign');
4061 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
4062 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
4065 // Print options for changing the filter and changing the number of results per page.
4066 $gradingoptionsformparams = array('cm'=>$cmid,
4067 'contextid'=>$this->context->id,
4068 'userid'=>$USER->id,
4069 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
4070 'showquickgrading'=>$showquickgrading,
4071 'quickgrading'=>$quickgrading,
4072 'markingworkflowopt'=>$markingworkflowoptions,
4073 'markingallocationopt'=>$markingallocationoptions,
4074 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
4075 'showonlyactiveenrol' => $this->show_only_active_users(),
4076 'downloadasfolders' => $downloadasfolders);
4078 $classoptions = array('class'=>'gradingoptionsform');
4079 $gradingoptionsform = new mod_assign_grading_options_form(null,
4080 $gradingoptionsformparams,
4081 'post',
4083 $classoptions);
4085 $batchformparams = array('cm'=>$cmid,
4086 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
4087 'duedate'=>$this->get_instance()->duedate,
4088 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
4089 'feedbackplugins'=>$this->get_feedback_plugins(),
4090 'context'=>$this->get_context(),
4091 'markingworkflow'=>$markingworkflow,
4092 'markingallocation'=>$markingallocation);
4093 $classoptions = array('class'=>'gradingbatchoperationsform');
4095 $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
4096 $batchformparams,
4097 'post',
4099 $classoptions);
4101 $gradingoptionsdata = new stdClass();
4102 $gradingoptionsdata->perpage = $perpage;
4103 $gradingoptionsdata->filter = $filter;
4104 $gradingoptionsdata->markerfilter = $markerfilter;
4105 $gradingoptionsdata->workflowfilter = $workflowfilter;
4106 $gradingoptionsform->set_data($gradingoptionsdata);
4108 $actionformtext = $this->get_renderer()->render($gradingactions);
4109 $header = new assign_header($this->get_instance(),
4110 $this->get_context(),
4111 false,
4112 $this->get_course_module()->id,
4113 get_string('grading', 'assign'),
4114 $actionformtext);
4115 $o .= $this->get_renderer()->render($header);
4117 $currenturl = $CFG->wwwroot .
4118 '/mod/assign/view.php?id=' .
4119 $this->get_course_module()->id .
4120 '&action=grading';
4122 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
4124 // Plagiarism update status apearring in the grading book.
4125 if (!empty($CFG->enableplagiarism)) {
4126 require_once($CFG->libdir . '/plagiarismlib.php');
4127 $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
4130 if ($this->is_blind_marking() && has_capability('mod/assign:viewblinddetails', $this->get_context())) {
4131 $o .= $this->get_renderer()->notification(get_string('blindmarkingenabledwarning', 'assign'), 'notifymessage');
4134 // Load and print the table of submissions.
4135 if ($showquickgrading && $quickgrading) {
4136 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
4137 $table = $this->get_renderer()->render($gradingtable);
4138 $page = optional_param('page', null, PARAM_INT);
4139 $quickformparams = array('cm'=>$this->get_course_module()->id,
4140 'gradingtable'=>$table,
4141 'sendstudentnotifications' => $this->get_instance()->sendstudentnotifications,
4142 'page' => $page);
4143 $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
4145 $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
4146 } else {
4147 $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
4148 $o .= $this->get_renderer()->render($gradingtable);
4151 if ($this->can_grade()) {
4152 // We need to store the order of uses in the table as the person may wish to grade them.
4153 // This is done based on the row number of the user.
4154 $useridlist = $gradingtable->get_column_data('userid');
4155 $SESSION->mod_assign_useridlist[$this->get_useridlist_key()] = $useridlist;
4158 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
4159 $users = array_keys($this->list_participants($currentgroup, true));
4160 if (count($users) != 0 && $this->can_grade()) {
4161 // If no enrolled user in a course then don't display the batch operations feature.
4162 $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
4163 $o .= $this->get_renderer()->render($assignform);
4165 $assignform = new assign_form('gradingoptionsform',
4166 $gradingoptionsform,
4167 'M.mod_assign.init_grading_options');
4168 $o .= $this->get_renderer()->render($assignform);
4169 return $o;
4173 * View entire grader app.
4175 * @return string
4177 protected function view_grader() {
4178 global $USER, $PAGE;
4180 $o = '';
4181 // Need submit permission to submit an assignment.
4182 $this->require_view_grades();
4184 $PAGE->set_pagelayout('embedded');
4186 $PAGE->set_title($this->get_context()->get_context_name());
4188 $o .= $this->get_renderer()->header();
4190 $userid = optional_param('userid', 0, PARAM_INT);
4191 $blindid = optional_param('blindid', 0, PARAM_INT);
4193 if (!$userid && $blindid) {
4194 $userid = $this->get_user_id_for_uniqueid($blindid);
4197 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
4198 $framegrader = new grading_app($userid, $currentgroup, $this);
4200 $this->update_effective_access($userid);
4202 $o .= $this->get_renderer()->render($framegrader);
4204 $o .= $this->view_footer();
4206 \mod_assign\event\grading_table_viewed::create_from_assign($this)->trigger();
4208 return $o;
4211 * View entire grading page.
4213 * @return string
4215 protected function view_grading_page() {
4216 global $CFG;
4218 $o = '';
4219 // Need submit permission to submit an assignment.
4220 $this->require_view_grades();
4221 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
4223 // Only load this if it is.
4224 $o .= $this->view_grading_table();
4226 $o .= $this->view_footer();
4228 \mod_assign\event\grading_table_viewed::create_from_assign($this)->trigger();
4230 return $o;
4234 * Capture the output of the plagiarism plugins disclosures and return it as a string.
4236 * @return string
4238 protected function plagiarism_print_disclosure() {
4239 global $CFG;
4240 $o = '';
4242 if (!empty($CFG->enableplagiarism)) {
4243 require_once($CFG->libdir . '/plagiarismlib.php');
4245 $o .= plagiarism_print_disclosure($this->get_course_module()->id);
4248 return $o;
4252 * Message for students when assignment submissions have been closed.
4254 * @param string $title The page title
4255 * @param array $notices The array of notices to show.
4256 * @return string
4258 protected function view_notices($title, $notices) {
4259 global $CFG;
4261 $o = '';
4263 $header = new assign_header($this->get_instance(),
4264 $this->get_context(),
4265 $this->show_intro(),
4266 $this->get_course_module()->id,
4267 $title);
4268 $o .= $this->get_renderer()->render($header);
4270 foreach ($notices as $notice) {
4271 $o .= $this->get_renderer()->notification($notice);
4274 $url = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id, 'action'=>'view'));
4275 $o .= $this->get_renderer()->continue_button($url);
4277 $o .= $this->view_footer();
4279 return $o;
4283 * Get the name for a user - hiding their real name if blind marking is on.
4285 * @param stdClass $user The user record as required by fullname()
4286 * @return string The name.
4288 public function fullname($user) {
4289 if ($this->is_blind_marking()) {
4290 $hasviewblind = has_capability('mod/assign:viewblinddetails', $this->get_context());
4291 if (empty($user->recordid)) {
4292 $uniqueid = $this->get_uniqueid_for_user($user->id);
4293 } else {
4294 $uniqueid = $user->recordid;
4296 if ($hasviewblind) {
4297 return get_string('participant', 'assign') . ' ' . $uniqueid . ' (' .
4298 fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())) . ')';
4299 } else {
4300 return get_string('participant', 'assign') . ' ' . $uniqueid;
4302 } else {
4303 return fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context()));
4308 * View edit submissions page.
4310 * @param moodleform $mform
4311 * @param array $notices A list of notices to display at the top of the
4312 * edit submission form (e.g. from plugins).
4313 * @return string The page output.
4315 protected function view_edit_submission_page($mform, $notices) {
4316 global $CFG, $USER, $DB;
4318 $o = '';
4319 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
4320 // Need submit permission to submit an assignment.
4321 $userid = optional_param('userid', $USER->id, PARAM_INT);
4322 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
4324 // This variation on the url will link direct to this student.
4325 // The benefit is the url will be the same every time for this student, so Atto autosave drafts can match up.
4326 $returnparams = array('userid' => $userid, 'rownum' => 0, 'useridlistid' => 0);
4327 $this->register_return_link('editsubmission', $returnparams);
4329 if ($userid == $USER->id) {
4330 if (!$this->can_edit_submission($userid, $USER->id)) {
4331 print_error('nopermission');
4333 // User is editing their own submission.
4334 require_capability('mod/assign:submit', $this->context);
4335 $title = get_string('editsubmission', 'assign');
4336 } else {
4337 // User is editing another user's submission.
4338 if (!$this->can_edit_submission($userid, $USER->id)) {
4339 print_error('nopermission');
4342 $name = $this->fullname($user);
4343 $title = get_string('editsubmissionother', 'assign', $name);
4346 if (!$this->submissions_open($userid)) {
4347 $message = array(get_string('submissionsclosed', 'assign'));
4348 return $this->view_notices($title, $message);
4351 $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
4352 $this->get_context(),
4353 $this->show_intro(),
4354 $this->get_course_module()->id,
4355 $title));
4356 if ($userid == $USER->id) {
4357 // We only show this if it their submission.
4358 $o .= $this->plagiarism_print_disclosure();
4360 $data = new stdClass();
4361 $data->userid = $userid;
4362 if (!$mform) {
4363 $mform = new mod_assign_submission_form(null, array($this, $data));
4366 foreach ($notices as $notice) {
4367 $o .= $this->get_renderer()->notification($notice);
4370 $o .= $this->get_renderer()->render(new assign_form('editsubmissionform', $mform));
4372 $o .= $this->view_footer();
4374 \mod_assign\event\submission_form_viewed::create_from_user($this, $user)->trigger();
4376 return $o;
4380 * See if this assignment has a grade yet.
4382 * @param int $userid
4383 * @return bool
4385 protected function is_graded($userid) {
4386 $grade = $this->get_user_grade($userid, false);
4387 if ($grade) {
4388 return ($grade->grade !== null && $grade->grade >= 0);
4390 return false;
4394 * Perform an access check to see if the current $USER can view this group submission.
4396 * @param int $groupid
4397 * @return bool
4399 public function can_view_group_submission($groupid) {
4400 global $USER;
4402 $members = $this->get_submission_group_members($groupid, true);
4403 foreach ($members as $member) {
4404 // If we can view any members submission, we can view the submission for the group.
4405 if ($this->can_view_submission($member->id)) {
4406 return true;
4409 return false;
4413 * Perform an access check to see if the current $USER can view this users submission.
4415 * @param int $userid
4416 * @return bool
4418 public function can_view_submission($userid) {
4419 global $USER;
4421 if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
4422 return false;
4424 if (!is_enrolled($this->get_course_context(), $userid)) {
4425 return false;
4427 if (has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
4428 return true;
4430 if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
4431 return true;
4433 return false;
4437 * Allows the plugin to show a batch grading operation page.
4439 * @param moodleform $mform
4440 * @return none
4442 protected function view_plugin_grading_batch_operation($mform) {
4443 require_capability('mod/assign:grade', $this->context);
4444 $prefix = 'plugingradingbatchoperation_';
4446 if ($data = $mform->get_data()) {
4447 $tail = substr($data->operation, strlen($prefix));
4448 list($plugintype, $action) = explode('_', $tail, 2);
4450 $plugin = $this->get_feedback_plugin_by_type($plugintype);
4451 if ($plugin) {
4452 $users = $data->selectedusers;
4453 $userlist = explode(',', $users);
4454 echo $plugin->grading_batch_operation($action, $userlist);
4455 return;
4458 print_error('invalidformdata', '');
4462 * Ask the user to confirm they want to perform this batch operation
4464 * @param moodleform $mform Set to a grading batch operations form
4465 * @return string - the page to view after processing these actions
4467 protected function process_grading_batch_operation(& $mform) {
4468 global $CFG;
4469 require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
4470 require_sesskey();
4472 $markingallocation = $this->get_instance()->markingworkflow &&
4473 $this->get_instance()->markingallocation &&
4474 has_capability('mod/assign:manageallocations', $this->context);
4476 $batchformparams = array('cm'=>$this->get_course_module()->id,
4477 'submissiondrafts'=>$this->get_instance()->submissiondrafts,
4478 'duedate'=>$this->get_instance()->duedate,
4479 'attemptreopenmethod'=>$this->get_instance()->attemptreopenmethod,
4480 'feedbackplugins'=>$this->get_feedback_plugins(),
4481 'context'=>$this->get_context(),
4482 'markingworkflow'=>$this->get_instance()->markingworkflow,
4483 'markingallocation'=>$markingallocation);
4484 $formclasses = array('class'=>'gradingbatchoperationsform');
4485 $mform = new mod_assign_grading_batch_operations_form(null,
4486 $batchformparams,
4487 'post',
4489 $formclasses);
4491 if ($data = $mform->get_data()) {
4492 // Get the list of users.
4493 $users = $data->selectedusers;
4494 $userlist = explode(',', $users);
4496 $prefix = 'plugingradingbatchoperation_';
4498 if ($data->operation == 'grantextension') {
4499 // Reset the form so the grant extension page will create the extension form.
4500 $mform = null;
4501 return 'grantextension';
4502 } else if ($data->operation == 'setmarkingworkflowstate') {
4503 return 'viewbatchsetmarkingworkflowstate';
4504 } else if ($data->operation == 'setmarkingallocation') {
4505 return 'viewbatchmarkingallocation';
4506 } else if (strpos($data->operation, $prefix) === 0) {
4507 $tail = substr($data->operation, strlen($prefix));
4508 list($plugintype, $action) = explode('_', $tail, 2);
4510 $plugin = $this->get_feedback_plugin_by_type($plugintype);
4511 if ($plugin) {
4512 return 'plugingradingbatchoperation';
4516 if ($data->operation == 'downloadselected') {
4517 $this->download_submissions($userlist);
4518 } else {
4519 foreach ($userlist as $userid) {
4520 if ($data->operation == 'lock') {
4521 $this->process_lock_submission($userid);
4522 } else if ($data->operation == 'unlock') {
4523 $this->process_unlock_submission($userid);
4524 } else if ($data->operation == 'reverttodraft') {
4525 $this->process_revert_to_draft($userid);
4526 } else if ($data->operation == 'addattempt') {
4527 if (!$this->get_instance()->teamsubmission) {
4528 $this->process_add_attempt($userid);
4533 if ($this->get_instance()->teamsubmission && $data->operation == 'addattempt') {
4534 // This needs to be handled separately so that each team submission is only re-opened one time.
4535 $this->process_add_attempt_group($userlist);
4539 return 'grading';
4543 * Shows a form that allows the workflow state for selected submissions to be changed.
4545 * @param moodleform $mform Set to a grading batch operations form
4546 * @return string - the page to view after processing these actions
4548 protected function view_batch_set_workflow_state($mform) {
4549 global $CFG, $DB;
4551 require_once($CFG->dirroot . '/mod/assign/batchsetmarkingworkflowstateform.php');
4553 $o = '';
4555 $submitteddata = $mform->get_data();
4556 $users = $submitteddata->selectedusers;
4557 $userlist = explode(',', $users);
4559 $formdata = array('id' => $this->get_course_module()->id,
4560 'selectedusers' => $users);
4562 $usershtml = '';
4564 $usercount = 0;
4565 $extrauserfields = get_extra_user_fields($this->get_context());
4566 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
4567 foreach ($userlist as $userid) {
4568 if ($usercount >= 5) {
4569 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
4570 break;
4572 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
4574 $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
4575 $this->get_course()->id,
4576 $viewfullnames,
4577 $this->is_blind_marking(),
4578 $this->get_uniqueid_for_user($user->id),
4579 $extrauserfields,
4580 !$this->is_active_user($userid)));
4581 $usercount += 1;
4584 $formparams = array(
4585 'userscount' => count($userlist),
4586 'usershtml' => $usershtml,
4587 'markingworkflowstates' => $this->get_marking_workflow_states_for_current_user()
4590 $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
4591 $mform->set_data($formdata); // Initialises the hidden elements.
4592 $header = new assign_header($this->get_instance(),
4593 $this->get_context(),
4594 $this->show_intro(),
4595 $this->get_course_module()->id,
4596 get_string('setmarkingworkflowstate', 'assign'));
4597 $o .= $this->get_renderer()->render($header);
4598 $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
4599 $o .= $this->view_footer();
4601 \mod_assign\event\batch_set_workflow_state_viewed::create_from_assign($this)->trigger();
4603 return $o;
4607 * Shows a form that allows the allocated marker for selected submissions to be changed.
4609 * @param moodleform $mform Set to a grading batch operations form
4610 * @return string - the page to view after processing these actions
4612 public function view_batch_markingallocation($mform) {
4613 global $CFG, $DB;
4615 require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');
4617 $o = '';
4619 $submitteddata = $mform->get_data();
4620 $users = $submitteddata->selectedusers;
4621 $userlist = explode(',', $users);
4623 $formdata = array('id' => $this->get_course_module()->id,
4624 'selectedusers' => $users);
4626 $usershtml = '';
4628 $usercount = 0;
4629 $extrauserfields = get_extra_user_fields($this->get_context());
4630 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
4631 foreach ($userlist as $userid) {
4632 if ($usercount >= 5) {
4633 $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
4634 break;
4636 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
4638 $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
4639 $this->get_course()->id,
4640 $viewfullnames,
4641 $this->is_blind_marking(),
4642 $this->get_uniqueid_for_user($user->id),
4643 $extrauserfields,
4644 !$this->is_active_user($userid)));
4645 $usercount += 1;
4648 $formparams = array(
4649 'userscount' => count($userlist),
4650 'usershtml' => $usershtml,
4653 list($sort, $params) = users_order_by_sql();
4654 $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade', '', $sort);
4655 $markerlist = array();
4656 foreach ($markers as $marker) {
4657 $markerlist[$marker->id] = fullname($marker);
4660 $formparams['markers'] = $markerlist;
4662 $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
4663 $mform->set_data($formdata); // Initialises the hidden elements.
4664 $header = new assign_header($this->get_instance(),
4665 $this->get_context(),
4666 $this->show_intro(),
4667 $this->get_course_module()->id,
4668 get_string('setmarkingallocation', 'assign'));
4669 $o .= $this->get_renderer()->render($header);
4670 $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
4671 $o .= $this->view_footer();
4673 \mod_assign\event\batch_set_marker_allocation_viewed::create_from_assign($this)->trigger();
4675 return $o;
4679 * Ask the user to confirm they want to submit their work for grading.
4681 * @param moodleform $mform - null unless form validation has failed
4682 * @return string
4684 protected function check_submit_for_grading($mform) {
4685 global $USER, $CFG;
4687 require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
4689 // Check that all of the submission plugins are ready for this submission.
4690 $notifications = array();
4691 $submission = $this->get_user_submission($USER->id, false);
4692 $plugins = $this->get_submission_plugins();
4693 foreach ($plugins as $plugin) {
4694 if ($plugin->is_enabled() && $plugin->is_visible()) {
4695 $check = $plugin->precheck_submission($submission);
4696 if ($check !== true) {
4697 $notifications[] = $check;
4702 $data = new stdClass();
4703 $adminconfig = $this->get_admin_config();
4704 $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement &&
4705 !empty($adminconfig->submissionstatement);
4707 $submissionstatement = '';
4708 if (!empty($adminconfig->submissionstatement)) {
4709 // Format the submission statement before its sent. We turn off para because this is going within
4710 // a form element.
4711 $options = array(
4712 'context' => $this->get_context(),
4713 'para' => false
4715 $submissionstatement = format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $options);
4718 if ($mform == null) {
4719 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
4720 $submissionstatement,
4721 $this->get_course_module()->id,
4722 $data));
4724 $o = '';
4725 $o .= $this->get_renderer()->header();
4726 $submitforgradingpage = new assign_submit_for_grading_page($notifications,
4727 $this->get_course_module()->id,
4728 $mform);
4729 $o .= $this->get_renderer()->render($submitforgradingpage);
4730 $o .= $this->view_footer();
4732 \mod_assign\event\submission_confirmation_form_viewed::create_from_assign($this)->trigger();
4734 return $o;
4738 * Creates an assign_submission_status renderable.
4740 * @param stdClass $user the user to get the report for
4741 * @param bool $showlinks return plain text or links to the profile
4742 * @return assign_submission_status renderable object
4744 public function get_assign_submission_status_renderable($user, $showlinks) {
4745 global $PAGE;
4747 $instance = $this->get_instance();
4748 $flags = $this->get_user_flags($user->id, false);
4749 $submission = $this->get_user_submission($user->id, false);
4751 $teamsubmission = null;
4752 $submissiongroup = null;
4753 $notsubmitted = array();
4754 if ($instance->teamsubmission) {
4755 $teamsubmission = $this->get_group_submission($user->id, 0, false);
4756 $submissiongroup = $this->get_submission_group($user->id);
4757 $groupid = 0;
4758 if ($submissiongroup) {
4759 $groupid = $submissiongroup->id;
4761 $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
4764 $showedit = $showlinks &&
4765 ($this->is_any_submission_plugin_enabled()) &&
4766 $this->can_edit_submission($user->id);
4768 $gradelocked = ($flags && $flags->locked) || $this->grading_disabled($user->id, false);
4770 // Grading criteria preview.
4771 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
4772 $gradingcontrollerpreview = '';
4773 if ($gradingmethod = $gradingmanager->get_active_method()) {
4774 $controller = $gradingmanager->get_controller($gradingmethod);
4775 if ($controller->is_form_defined()) {
4776 $gradingcontrollerpreview = $controller->render_preview($PAGE);
4780 $showsubmit = ($showlinks && $this->submissions_open($user->id));
4781 $showsubmit = ($showsubmit && $this->show_submit_button($submission, $teamsubmission, $user->id));
4783 $extensionduedate = null;
4784 if ($flags) {
4785 $extensionduedate = $flags->extensionduedate;
4787 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
4789 $gradingstatus = $this->get_grading_status($user->id);
4790 $usergroups = $this->get_all_groups($user->id);
4791 $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
4792 $instance->alwaysshowdescription,
4793 $submission,
4794 $instance->teamsubmission,
4795 $teamsubmission,
4796 $submissiongroup,
4797 $notsubmitted,
4798 $this->is_any_submission_plugin_enabled(),
4799 $gradelocked,
4800 $this->is_graded($user->id),
4801 $instance->duedate,
4802 $instance->cutoffdate,
4803 $this->get_submission_plugins(),
4804 $this->get_return_action(),
4805 $this->get_return_params(),
4806 $this->get_course_module()->id,
4807 $this->get_course()->id,
4808 assign_submission_status::STUDENT_VIEW,
4809 $showedit,
4810 $showsubmit,
4811 $viewfullnames,
4812 $extensionduedate,
4813 $this->get_context(),
4814 $this->is_blind_marking(),
4815 $gradingcontrollerpreview,
4816 $instance->attemptreopenmethod,
4817 $instance->maxattempts,
4818 $gradingstatus,
4819 $instance->preventsubmissionnotingroup,
4820 $usergroups);
4821 return $submissionstatus;
4826 * Creates an assign_feedback_status renderable.
4828 * @param stdClass $user the user to get the report for
4829 * @return assign_feedback_status renderable object
4831 public function get_assign_feedback_status_renderable($user) {
4832 global $CFG, $DB, $PAGE;
4834 require_once($CFG->libdir.'/gradelib.php');
4835 require_once($CFG->dirroot.'/grade/grading/lib.php');
4837 $instance = $this->get_instance();
4838 $grade = $this->get_user_grade($user->id, false);
4839 $gradingstatus = $this->get_grading_status($user->id);
4841 $gradinginfo = grade_get_grades($this->get_course()->id,
4842 'mod',
4843 'assign',
4844 $instance->id,
4845 $user->id);
4847 $gradingitem = null;
4848 $gradebookgrade = null;
4849 if (isset($gradinginfo->items[0])) {
4850 $gradingitem = $gradinginfo->items[0];
4851 $gradebookgrade = $gradingitem->grades[$user->id];
4854 // Check to see if all feedback plugins are empty.
4855 $emptyplugins = true;
4856 if ($grade) {
4857 foreach ($this->get_feedback_plugins() as $plugin) {
4858 if ($plugin->is_visible() && $plugin->is_enabled()) {
4859 if (!$plugin->is_empty($grade)) {
4860 $emptyplugins = false;
4866 if ($this->get_instance()->markingworkflow && $gradingstatus != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
4867 $emptyplugins = true; // Don't show feedback plugins until released either.
4870 $cangrade = has_capability('mod/assign:grade', $this->get_context());
4871 // If there is a visible grade, show the summary.
4872 if (!is_null($gradebookgrade) && (!is_null($gradebookgrade->grade) || !$emptyplugins)
4873 && ($cangrade || !$gradebookgrade->hidden)) {
4875 $gradefordisplay = null;
4876 $gradeddate = null;
4877 $grader = null;
4878 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
4880 // Only show the grade if it is not hidden in gradebook.
4881 if (!is_null($gradebookgrade->grade) && ($cangrade || !$gradebookgrade->hidden)) {
4882 if ($controller = $gradingmanager->get_active_controller()) {
4883 $menu = make_grades_menu($this->get_instance()->grade);
4884 $controller->set_grade_range($menu, $this->get_instance()->grade > 0);
4885 $gradefordisplay = $controller->render_grade($PAGE,
4886 $grade->id,
4887 $gradingitem,
4888 $gradebookgrade->str_long_grade,
4889 $cangrade);
4890 } else {
4891 $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
4893 $gradeddate = $gradebookgrade->dategraded;
4894 if (isset($grade->grader)) {
4895 $grader = $DB->get_record('user', array('id' => $grade->grader));
4899 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
4901 $feedbackstatus = new assign_feedback_status($gradefordisplay,
4902 $gradeddate,
4903 $grader,
4904 $this->get_feedback_plugins(),
4905 $grade,
4906 $this->get_course_module()->id,
4907 $this->get_return_action(),
4908 $this->get_return_params(),
4909 $viewfullnames);
4910 return $feedbackstatus;
4912 return;
4916 * Creates an assign_attempt_history renderable.
4918 * @param stdClass $user the user to get the report for
4919 * @return assign_attempt_history renderable object
4921 public function get_assign_attempt_history_renderable($user) {
4923 $allsubmissions = $this->get_all_submissions($user->id);
4924 $allgrades = $this->get_all_grades($user->id);
4926 $history = new assign_attempt_history($allsubmissions,
4927 $allgrades,
4928 $this->get_submission_plugins(),
4929 $this->get_feedback_plugins(),
4930 $this->get_course_module()->id,
4931 $this->get_return_action(),
4932 $this->get_return_params(),
4933 false,
4936 return $history;
4940 * Print 2 tables of information with no action links -
4941 * the submission summary and the grading summary.
4943 * @param stdClass $user the user to print the report for
4944 * @param bool $showlinks - Return plain text or links to the profile
4945 * @return string - the html summary
4947 public function view_student_summary($user, $showlinks) {
4949 $o = '';
4951 if ($this->can_view_submission($user->id)) {
4953 if (has_capability('mod/assign:submit', $this->get_context(), $user, false)) {
4954 $submissionstatus = $this->get_assign_submission_status_renderable($user, $showlinks);
4955 $o .= $this->get_renderer()->render($submissionstatus);
4958 // If there is a visible grade, show the feedback.
4959 $feedbackstatus = $this->get_assign_feedback_status_renderable($user);
4960 if ($feedbackstatus) {
4961 $o .= $this->get_renderer()->render($feedbackstatus);
4964 // If there is more than one submission, show the history.
4965 $history = $this->get_assign_attempt_history_renderable($user);
4966 if (count($history->submissions) > 1) {
4967 $o .= $this->get_renderer()->render($history);
4970 return $o;
4974 * Returns true if the submit subsission button should be shown to the user.
4976 * @param stdClass $submission The users own submission record.
4977 * @param stdClass $teamsubmission The users team submission record if there is one
4978 * @param int $userid The user
4979 * @return bool
4981 protected function show_submit_button($submission = null, $teamsubmission = null, $userid = null) {
4982 if ($teamsubmission) {
4983 if ($teamsubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
4984 // The assignment submission has been completed.
4985 return false;
4986 } else if ($this->submission_empty($teamsubmission)) {
4987 // There is nothing to submit yet.
4988 return false;
4989 } else if ($submission && $submission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
4990 // The user has already clicked the submit button on the team submission.
4991 return false;
4992 } else if (
4993 !empty($this->get_instance()->preventsubmissionnotingroup)
4994 && $this->get_submission_group($userid) == false
4996 return false;
4998 } else if ($submission) {
4999 if ($submission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
5000 // The assignment submission has been completed.
5001 return false;
5002 } else if ($this->submission_empty($submission)) {
5003 // There is nothing to submit.
5004 return false;
5006 } else {
5007 // We've not got a valid submission or team submission.
5008 return false;
5010 // Last check is that this instance allows drafts.
5011 return $this->get_instance()->submissiondrafts;
5015 * Get the grades for all previous attempts.
5016 * For each grade - the grader is a full user record,
5017 * and gradefordisplay is added (rendered from grading manager).
5019 * @param int $userid If not set, $USER->id will be used.
5020 * @return array $grades All grade records for this user.
5022 protected function get_all_grades($userid) {
5023 global $DB, $USER, $PAGE;
5025 // If the userid is not null then use userid.
5026 if (!$userid) {
5027 $userid = $USER->id;
5030 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
5032 $grades = $DB->get_records('assign_grades', $params, 'attemptnumber ASC');
5034 $gradercache = array();
5035 $cangrade = has_capability('mod/assign:grade', $this->get_context());
5037 // Need gradingitem and gradingmanager.
5038 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
5039 $controller = $gradingmanager->get_active_controller();
5041 $gradinginfo = grade_get_grades($this->get_course()->id,
5042 'mod',
5043 'assign',
5044 $this->get_instance()->id,
5045 $userid);
5047 $gradingitem = null;
5048 if (isset($gradinginfo->items[0])) {
5049 $gradingitem = $gradinginfo->items[0];
5052 foreach ($grades as $grade) {
5053 // First lookup the grader info.
5054 if (isset($gradercache[$grade->grader])) {
5055 $grade->grader = $gradercache[$grade->grader];
5056 } else {
5057 // Not in cache - need to load the grader record.
5058 $grade->grader = $DB->get_record('user', array('id'=>$grade->grader));
5059 $gradercache[$grade->grader->id] = $grade->grader;
5062 // Now get the gradefordisplay.
5063 if ($controller) {
5064 $controller->set_grade_range(make_grades_menu($this->get_instance()->grade), $this->get_instance()->grade > 0);
5065 $grade->gradefordisplay = $controller->render_grade($PAGE,
5066 $grade->id,
5067 $gradingitem,
5068 $grade->grade,
5069 $cangrade);
5070 } else {
5071 $grade->gradefordisplay = $this->display_grade($grade->grade, false);
5076 return $grades;
5080 * Get the submissions for all previous attempts.
5082 * @param int $userid If not set, $USER->id will be used.
5083 * @return array $submissions All submission records for this user (or group).
5085 protected function get_all_submissions($userid) {
5086 global $DB, $USER;
5088 // If the userid is not null then use userid.
5089 if (!$userid) {
5090 $userid = $USER->id;
5093 $params = array();
5095 if ($this->get_instance()->teamsubmission) {
5096 $groupid = 0;
5097 $group = $this->get_submission_group($userid);
5098 if ($group) {
5099 $groupid = $group->id;
5102 // Params to get the group submissions.
5103 $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
5104 } else {
5105 // Params to get the user submissions.
5106 $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid);
5109 // Return the submissions ordered by attempt.
5110 $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber ASC');
5112 return $submissions;
5116 * Creates an assign_grading_summary renderable.
5118 * @return assign_grading_summary renderable object
5120 public function get_assign_grading_summary_renderable() {
5122 $instance = $this->get_instance();
5124 $draft = ASSIGN_SUBMISSION_STATUS_DRAFT;
5125 $submitted = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
5127 $activitygroup = groups_get_activity_group($this->get_course_module());
5129 if ($instance->teamsubmission) {
5130 $defaultteammembers = $this->get_submission_group_members(0, true);
5131 $warnofungroupedusers = (count($defaultteammembers) > 0 && $instance->preventsubmissionnotingroup);
5133 $summary = new assign_grading_summary($this->count_teams($activitygroup),
5134 $instance->submissiondrafts,
5135 $this->count_submissions_with_status($draft),
5136 $this->is_any_submission_plugin_enabled(),
5137 $this->count_submissions_with_status($submitted),
5138 $instance->cutoffdate,
5139 $instance->duedate,
5140 $this->get_course_module()->id,
5141 $this->count_submissions_need_grading(),
5142 $instance->teamsubmission,
5143 $warnofungroupedusers);
5144 } else {
5145 // The active group has already been updated in groups_print_activity_menu().
5146 $countparticipants = $this->count_participants($activitygroup);
5147 $summary = new assign_grading_summary($countparticipants,
5148 $instance->submissiondrafts,
5149 $this->count_submissions_with_status($draft),
5150 $this->is_any_submission_plugin_enabled(),
5151 $this->count_submissions_with_status($submitted),
5152 $instance->cutoffdate,
5153 $instance->duedate,
5154 $this->get_course_module()->id,
5155 $this->count_submissions_need_grading(),
5156 $instance->teamsubmission,
5157 false);
5161 return $summary;
5165 * View submissions page (contains details of current submission).
5167 * @return string
5169 protected function view_submission_page() {
5170 global $CFG, $DB, $USER, $PAGE;
5172 $instance = $this->get_instance();
5174 $o = '';
5176 $postfix = '';
5177 if ($this->has_visible_attachments()) {
5178 $postfix = $this->render_area_files('mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
5180 $o .= $this->get_renderer()->render(new assign_header($instance,
5181 $this->get_context(),
5182 $this->show_intro(),
5183 $this->get_course_module()->id,
5184 '', '', $postfix));
5186 // Display plugin specific headers.
5187 $plugins = array_merge($this->get_submission_plugins(), $this->get_feedback_plugins());
5188 foreach ($plugins as $plugin) {
5189 if ($plugin->is_enabled() && $plugin->is_visible()) {
5190 $o .= $this->get_renderer()->render(new assign_plugin_header($plugin));
5194 if ($this->can_view_grades()) {
5195 // Group selector will only be displayed if necessary.
5196 $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $this->get_course_module()->id));
5197 $o .= groups_print_activity_menu($this->get_course_module(), $currenturl->out(), true);
5199 $summary = $this->get_assign_grading_summary_renderable();
5200 $o .= $this->get_renderer()->render($summary);
5202 $grade = $this->get_user_grade($USER->id, false);
5203 $submission = $this->get_user_submission($USER->id, false);
5205 if ($this->can_view_submission($USER->id)) {
5206 $o .= $this->view_student_summary($USER, true);
5209 $o .= $this->view_footer();
5211 \mod_assign\event\submission_status_viewed::create_from_assign($this)->trigger();
5213 return $o;
5217 * Convert the final raw grade(s) in the grading table for the gradebook.
5219 * @param stdClass $grade
5220 * @return array
5222 protected function convert_grade_for_gradebook(stdClass $grade) {
5223 $gradebookgrade = array();
5224 if ($grade->grade >= 0) {
5225 $gradebookgrade['rawgrade'] = $grade->grade;
5227 // Allow "no grade" to be chosen.
5228 if ($grade->grade == -1) {
5229 $gradebookgrade['rawgrade'] = NULL;
5231 $gradebookgrade['userid'] = $grade->userid;
5232 $gradebookgrade['usermodified'] = $grade->grader;
5233 $gradebookgrade['datesubmitted'] = null;
5234 $gradebookgrade['dategraded'] = $grade->timemodified;
5235 if (isset($grade->feedbackformat)) {
5236 $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
5238 if (isset($grade->feedbacktext)) {
5239 $gradebookgrade['feedback'] = $grade->feedbacktext;
5242 return $gradebookgrade;
5246 * Convert submission details for the gradebook.
5248 * @param stdClass $submission
5249 * @return array
5251 protected function convert_submission_for_gradebook(stdClass $submission) {
5252 $gradebookgrade = array();
5254 $gradebookgrade['userid'] = $submission->userid;
5255 $gradebookgrade['usermodified'] = $submission->userid;
5256 $gradebookgrade['datesubmitted'] = $submission->timemodified;
5258 return $gradebookgrade;
5262 * Update grades in the gradebook.
5264 * @param mixed $submission stdClass|null
5265 * @param mixed $grade stdClass|null
5266 * @return bool
5268 protected function gradebook_item_update($submission=null, $grade=null) {
5269 global $CFG;
5271 require_once($CFG->dirroot.'/mod/assign/lib.php');
5272 // Do not push grade to gradebook if blind marking is active as
5273 // the gradebook would reveal the students.
5274 if ($this->is_blind_marking()) {
5275 return false;
5278 // If marking workflow is enabled and grade is not released then remove any grade that may exist in the gradebook.
5279 if ($this->get_instance()->markingworkflow && !empty($grade) &&
5280 $this->get_grading_status($grade->userid) != ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
5281 // Remove the grade (if it exists) from the gradebook as it is not 'final'.
5282 $grade->grade = -1;
5283 $grade->feedbacktext = '';
5286 if ($submission != null) {
5287 if ($submission->userid == 0) {
5288 // This is a group submission update.
5289 $team = groups_get_members($submission->groupid, 'u.id');
5291 foreach ($team as $member) {
5292 $membersubmission = clone $submission;
5293 $membersubmission->groupid = 0;
5294 $membersubmission->userid = $member->id;
5295 $this->gradebook_item_update($membersubmission, null);
5297 return;
5300 $gradebookgrade = $this->convert_submission_for_gradebook($submission);
5302 } else {
5303 $gradebookgrade = $this->convert_grade_for_gradebook($grade);
5305 // Grading is disabled, return.
5306 if ($this->grading_disabled($gradebookgrade['userid'])) {
5307 return false;
5309 $assign = clone $this->get_instance();
5310 $assign->cmidnumber = $this->get_course_module()->idnumber;
5311 // Set assign gradebook feedback plugin status (enabled and visible).
5312 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
5313 return assign_grade_item_update($assign, $gradebookgrade) == GRADE_UPDATE_OK;
5317 * Update team submission.
5319 * @param stdClass $submission
5320 * @param int $userid
5321 * @param bool $updatetime
5322 * @return bool
5324 protected function update_team_submission(stdClass $submission, $userid, $updatetime) {
5325 global $DB;
5327 if ($updatetime) {
5328 $submission->timemodified = time();
5331 // First update the submission for the current user.
5332 $mysubmission = $this->get_user_submission($userid, true, $submission->attemptnumber);
5333 $mysubmission->status = $submission->status;
5335 $this->update_submission($mysubmission, 0, $updatetime, false);
5337 // Now check the team settings to see if this assignment qualifies as submitted or draft.
5338 $team = $this->get_submission_group_members($submission->groupid, true);
5340 $allsubmitted = true;
5341 $anysubmitted = false;
5342 $result = true;
5343 if ($submission->status != ASSIGN_SUBMISSION_STATUS_REOPENED) {
5344 foreach ($team as $member) {
5345 $membersubmission = $this->get_user_submission($member->id, false, $submission->attemptnumber);
5347 // If no submission found for team member and member is active then everyone has not submitted.
5348 if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED
5349 && ($this->is_active_user($member->id))) {
5350 $allsubmitted = false;
5351 if ($anysubmitted) {
5352 break;
5354 } else {
5355 $anysubmitted = true;
5358 if ($this->get_instance()->requireallteammemberssubmit) {
5359 if ($allsubmitted) {
5360 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
5361 } else {
5362 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
5364 $result = $DB->update_record('assign_submission', $submission);
5365 } else {
5366 if ($anysubmitted) {
5367 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
5368 } else {
5369 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
5371 $result = $DB->update_record('assign_submission', $submission);
5373 } else {
5374 // Set the group submission to reopened.
5375 foreach ($team as $member) {
5376 $membersubmission = $this->get_user_submission($member->id, true, $submission->attemptnumber);
5377 $membersubmission->status = ASSIGN_SUBMISSION_STATUS_REOPENED;
5378 $result = $DB->update_record('assign_submission', $membersubmission) && $result;
5380 $result = $DB->update_record('assign_submission', $submission) && $result;
5383 $this->gradebook_item_update($submission);
5384 return $result;
5388 * Update grades in the gradebook based on submission time.
5390 * @param stdClass $submission
5391 * @param int $userid
5392 * @param bool $updatetime
5393 * @param bool $teamsubmission
5394 * @return bool
5396 protected function update_submission(stdClass $submission, $userid, $updatetime, $teamsubmission) {
5397 global $DB;
5399 if ($teamsubmission) {
5400 return $this->update_team_submission($submission, $userid, $updatetime);
5403 if ($updatetime) {
5404 $submission->timemodified = time();
5406 $result= $DB->update_record('assign_submission', $submission);
5407 if ($result) {
5408 $this->gradebook_item_update($submission);
5410 return $result;
5414 * Is this assignment open for submissions?
5416 * Check the due date,
5417 * prevent late submissions,
5418 * has this person already submitted,
5419 * is the assignment locked?
5421 * @param int $userid - Optional userid so we can see if a different user can submit
5422 * @param bool $skipenrolled - Skip enrollment checks (because they have been done already)
5423 * @param stdClass $submission - Pre-fetched submission record (or false to fetch it)
5424 * @param stdClass $flags - Pre-fetched user flags record (or false to fetch it)
5425 * @param stdClass $gradinginfo - Pre-fetched user gradinginfo record (or false to fetch it)
5426 * @return bool
5428 public function submissions_open($userid = 0,
5429 $skipenrolled = false,
5430 $submission = false,
5431 $flags = false,
5432 $gradinginfo = false) {
5433 global $USER;
5435 if (!$userid) {
5436 $userid = $USER->id;
5439 $time = time();
5440 $dateopen = true;
5441 $finaldate = false;
5442 if ($this->get_instance()->cutoffdate) {
5443 $finaldate = $this->get_instance()->cutoffdate;
5446 if ($flags === false) {
5447 $flags = $this->get_user_flags($userid, false);
5449 if ($flags && $flags->locked) {
5450 return false;
5453 // User extensions.
5454 if ($finaldate) {
5455 if ($flags && $flags->extensionduedate) {
5456 // Extension can be before cut off date.
5457 if ($flags->extensionduedate > $finaldate) {
5458 $finaldate = $flags->extensionduedate;
5463 if ($finaldate) {
5464 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $finaldate);
5465 } else {
5466 $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
5469 if (!$dateopen) {
5470 return false;
5473 // Now check if this user has already submitted etc.
5474 if (!$skipenrolled && !is_enrolled($this->get_course_context(), $userid)) {
5475 return false;
5477 // Note you can pass null for submission and it will not be fetched.
5478 if ($submission === false) {
5479 if ($this->get_instance()->teamsubmission) {
5480 $submission = $this->get_group_submission($userid, 0, false);
5481 } else {
5482 $submission = $this->get_user_submission($userid, false);
5485 if ($submission) {
5487 if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
5488 // Drafts are tracked and the student has submitted the assignment.
5489 return false;
5493 // See if this user grade is locked in the gradebook.
5494 if ($gradinginfo === false) {
5495 $gradinginfo = grade_get_grades($this->get_course()->id,
5496 'mod',
5497 'assign',
5498 $this->get_instance()->id,
5499 array($userid));
5501 if ($gradinginfo &&
5502 isset($gradinginfo->items[0]->grades[$userid]) &&
5503 $gradinginfo->items[0]->grades[$userid]->locked) {
5504 return false;
5507 return true;
5511 * Render the files in file area.
5513 * @param string $component
5514 * @param string $area
5515 * @param int $submissionid
5516 * @return string
5518 public function render_area_files($component, $area, $submissionid) {
5519 global $USER;
5521 return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);
5526 * Capability check to make sure this grader can edit this submission.
5528 * @param int $userid - The user whose submission is to be edited
5529 * @param int $graderid (optional) - The user who will do the editing (default to $USER->id).
5530 * @return bool
5532 public function can_edit_submission($userid, $graderid = 0) {
5533 global $USER;
5535 if (empty($graderid)) {
5536 $graderid = $USER->id;
5539 $instance = $this->get_instance();
5540 if ($userid == $graderid &&
5541 $instance->teamsubmission &&
5542 $instance->preventsubmissionnotingroup &&
5543 $this->get_submission_group($userid) == false) {
5544 return false;
5547 if ($userid == $graderid &&
5548 $this->submissions_open($userid) &&
5549 has_capability('mod/assign:submit', $this->context, $graderid)) {
5550 // User can edit their own submission.
5551 return true;
5554 if (!has_capability('mod/assign:editothersubmission', $this->context, $graderid)) {
5555 return false;
5558 $cm = $this->get_course_module();
5559 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
5560 $sharedgroupmembers = $this->get_shared_group_members($cm, $graderid);
5561 return in_array($userid, $sharedgroupmembers);
5563 return true;
5567 * Returns IDs of the users who share group membership with the specified user.
5569 * @param stdClass|cm_info $cm Course-module
5570 * @param int $userid User ID
5571 * @return array An array of ID of users.
5573 public function get_shared_group_members($cm, $userid) {
5574 if (!isset($this->sharedgroupmembers[$userid])) {
5575 $this->sharedgroupmembers[$userid] = array();
5576 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
5577 foreach ($groupsids as $groupid) {
5578 $members = array_keys(groups_get_members($groupid, 'u.id'));
5579 $this->sharedgroupmembers[$userid] = array_merge($this->sharedgroupmembers[$userid], $members);
5583 return $this->sharedgroupmembers[$userid];
5587 * Returns a list of teachers that should be grading given submission.
5589 * @param int $userid The submission to grade
5590 * @return array
5592 protected function get_graders($userid) {
5593 // Potential graders should be active users only.
5594 $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade", null, 'u.*', null, null, null, true);
5596 $graders = array();
5597 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
5598 if ($groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_course_module()->groupingid)) {
5599 foreach ($groups as $group) {
5600 foreach ($potentialgraders as $grader) {
5601 if ($grader->id == $userid) {
5602 // Do not send self.
5603 continue;
5605 if (groups_is_member($group->id, $grader->id)) {
5606 $graders[$grader->id] = $grader;
5610 } else {
5611 // User not in group, try to find graders without group.
5612 foreach ($potentialgraders as $grader) {
5613 if ($grader->id == $userid) {
5614 // Do not send self.
5615 continue;
5617 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
5618 $graders[$grader->id] = $grader;
5622 } else {
5623 foreach ($potentialgraders as $grader) {
5624 if ($grader->id == $userid) {
5625 // Do not send self.
5626 continue;
5628 // Must be enrolled.
5629 if (is_enrolled($this->get_course_context(), $grader->id)) {
5630 $graders[$grader->id] = $grader;
5634 return $graders;
5638 * Returns a list of users that should receive notification about given submission.
5640 * @param int $userid The submission to grade
5641 * @return array
5643 protected function get_notifiable_users($userid) {
5644 // Potential users should be active users only.
5645 $potentialusers = get_enrolled_users($this->context, "mod/assign:receivegradernotifications",
5646 null, 'u.*', null, null, null, true);
5648 $notifiableusers = array();
5649 if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
5650 if ($groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_course_module()->groupingid)) {
5651 foreach ($groups as $group) {
5652 foreach ($potentialusers as $potentialuser) {
5653 if ($potentialuser->id == $userid) {
5654 // Do not send self.
5655 continue;
5657 if (groups_is_member($group->id, $potentialuser->id)) {
5658 $notifiableusers[$potentialuser->id] = $potentialuser;
5662 } else {
5663 // User not in group, try to find graders without group.
5664 foreach ($potentialusers as $potentialuser) {
5665 if ($potentialuser->id == $userid) {
5666 // Do not send self.
5667 continue;
5669 if (!groups_has_membership($this->get_course_module(), $potentialuser->id)) {
5670 $notifiableusers[$potentialuser->id] = $potentialuser;
5674 } else {
5675 foreach ($potentialusers as $potentialuser) {
5676 if ($potentialuser->id == $userid) {
5677 // Do not send self.
5678 continue;
5680 // Must be enrolled.
5681 if (is_enrolled($this->get_course_context(), $potentialuser->id)) {
5682 $notifiableusers[$potentialuser->id] = $potentialuser;
5686 return $notifiableusers;
5690 * Format a notification for plain text.
5692 * @param string $messagetype
5693 * @param stdClass $info
5694 * @param stdClass $course
5695 * @param stdClass $context
5696 * @param string $modulename
5697 * @param string $assignmentname
5699 protected static function format_notification_message_text($messagetype,
5700 $info,
5701 $course,
5702 $context,
5703 $modulename,
5704 $assignmentname) {
5705 $formatparams = array('context' => $context->get_course_context());
5706 $posttext = format_string($course->shortname, true, $formatparams) .
5707 ' -> ' .
5708 $modulename .
5709 ' -> ' .
5710 format_string($assignmentname, true, $formatparams) . "\n";
5711 $posttext .= '---------------------------------------------------------------------' . "\n";
5712 $posttext .= get_string($messagetype . 'text', 'assign', $info)."\n";
5713 $posttext .= "\n---------------------------------------------------------------------\n";
5714 return $posttext;
5718 * Format a notification for HTML.
5720 * @param string $messagetype
5721 * @param stdClass $info
5722 * @param stdClass $course
5723 * @param stdClass $context
5724 * @param string $modulename
5725 * @param stdClass $coursemodule
5726 * @param string $assignmentname
5728 protected static function format_notification_message_html($messagetype,
5729 $info,
5730 $course,
5731 $context,
5732 $modulename,
5733 $coursemodule,
5734 $assignmentname) {
5735 global $CFG;
5736 $formatparams = array('context' => $context->get_course_context());
5737 $posthtml = '<p><font face="sans-serif">' .
5738 '<a href="' . $CFG->wwwroot . '/course/view.php?id=' . $course->id . '">' .
5739 format_string($course->shortname, true, $formatparams) .
5740 '</a> ->' .
5741 '<a href="' . $CFG->wwwroot . '/mod/assign/index.php?id=' . $course->id . '">' .
5742 $modulename .
5743 '</a> ->' .
5744 '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $coursemodule->id . '">' .
5745 format_string($assignmentname, true, $formatparams) .
5746 '</a></font></p>';
5747 $posthtml .= '<hr /><font face="sans-serif">';
5748 $posthtml .= '<p>' . get_string($messagetype . 'html', 'assign', $info) . '</p>';
5749 $posthtml .= '</font><hr />';
5750 return $posthtml;
5754 * Message someone about something (static so it can be called from cron).
5756 * @param stdClass $userfrom
5757 * @param stdClass $userto
5758 * @param string $messagetype
5759 * @param string $eventtype
5760 * @param int $updatetime
5761 * @param stdClass $coursemodule
5762 * @param stdClass $context
5763 * @param stdClass $course
5764 * @param string $modulename
5765 * @param string $assignmentname
5766 * @param bool $blindmarking
5767 * @param int $uniqueidforuser
5768 * @return void
5770 public static function send_assignment_notification($userfrom,
5771 $userto,
5772 $messagetype,
5773 $eventtype,
5774 $updatetime,
5775 $coursemodule,
5776 $context,
5777 $course,
5778 $modulename,
5779 $assignmentname,
5780 $blindmarking,
5781 $uniqueidforuser) {
5782 global $CFG;
5784 $info = new stdClass();
5785 if ($blindmarking) {
5786 $userfrom = clone($userfrom);
5787 $info->username = get_string('participant', 'assign') . ' ' . $uniqueidforuser;
5788 $userfrom->firstname = get_string('participant', 'assign');
5789 $userfrom->lastname = $uniqueidforuser;
5790 $userfrom->email = $CFG->noreplyaddress;
5791 } else {
5792 $info->username = fullname($userfrom, true);
5794 $info->assignment = format_string($assignmentname, true, array('context'=>$context));
5795 $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
5796 $info->timeupdated = userdate($updatetime, get_string('strftimerecentfull'));
5798 $postsubject = get_string($messagetype . 'small', 'assign', $info);
5799 $posttext = self::format_notification_message_text($messagetype,
5800 $info,
5801 $course,
5802 $context,
5803 $modulename,
5804 $assignmentname);
5805 $posthtml = '';
5806 if ($userto->mailformat == 1) {
5807 $posthtml = self::format_notification_message_html($messagetype,
5808 $info,
5809 $course,
5810 $context,
5811 $modulename,
5812 $coursemodule,
5813 $assignmentname);
5816 $eventdata = new \core\message\message();
5817 $eventdata->courseid = $course->id;
5818 $eventdata->modulename = 'assign';
5819 $eventdata->userfrom = $userfrom;
5820 $eventdata->userto = $userto;
5821 $eventdata->subject = $postsubject;
5822 $eventdata->fullmessage = $posttext;
5823 $eventdata->fullmessageformat = FORMAT_PLAIN;
5824 $eventdata->fullmessagehtml = $posthtml;
5825 $eventdata->smallmessage = $postsubject;
5827 $eventdata->name = $eventtype;
5828 $eventdata->component = 'mod_assign';
5829 $eventdata->notification = 1;
5830 $eventdata->contexturl = $info->url;
5831 $eventdata->contexturlname = $info->assignment;
5833 message_send($eventdata);
5837 * Message someone about something.
5839 * @param stdClass $userfrom
5840 * @param stdClass $userto
5841 * @param string $messagetype
5842 * @param string $eventtype
5843 * @param int $updatetime
5844 * @return void
5846 public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
5847 global $USER;
5848 $userid = core_user::is_real_user($userfrom->id) ? $userfrom->id : $USER->id;
5849 $uniqueid = $this->get_uniqueid_for_user($userid);
5850 self::send_assignment_notification($userfrom,
5851 $userto,
5852 $messagetype,
5853 $eventtype,
5854 $updatetime,
5855 $this->get_course_module(),
5856 $this->get_context(),
5857 $this->get_course(),
5858 $this->get_module_name(),
5859 $this->get_instance()->name,
5860 $this->is_blind_marking(),
5861 $uniqueid);
5865 * Notify student upon successful submission copy.
5867 * @param stdClass $submission
5868 * @return void
5870 protected function notify_student_submission_copied(stdClass $submission) {
5871 global $DB, $USER;
5873 $adminconfig = $this->get_admin_config();
5874 // Use the same setting for this - no need for another one.
5875 if (empty($adminconfig->submissionreceipts)) {
5876 // No need to do anything.
5877 return;
5879 if ($submission->userid) {
5880 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
5881 } else {
5882 $user = $USER;
5884 $this->send_notification($user,
5885 $user,
5886 'submissioncopied',
5887 'assign_notification',
5888 $submission->timemodified);
5891 * Notify student upon successful submission.
5893 * @param stdClass $submission
5894 * @return void
5896 protected function notify_student_submission_receipt(stdClass $submission) {
5897 global $DB, $USER;
5899 $adminconfig = $this->get_admin_config();
5900 if (empty($adminconfig->submissionreceipts)) {
5901 // No need to do anything.
5902 return;
5904 if ($submission->userid) {
5905 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
5906 } else {
5907 $user = $USER;
5909 if ($submission->userid == $USER->id) {
5910 $this->send_notification(core_user::get_noreply_user(),
5911 $user,
5912 'submissionreceipt',
5913 'assign_notification',
5914 $submission->timemodified);
5915 } else {
5916 $this->send_notification($USER,
5917 $user,
5918 'submissionreceiptother',
5919 'assign_notification',
5920 $submission->timemodified);
5925 * Send notifications to graders upon student submissions.
5927 * @param stdClass $submission
5928 * @return void
5930 protected function notify_graders(stdClass $submission) {
5931 global $DB, $USER;
5933 $instance = $this->get_instance();
5935 $late = $instance->duedate && ($instance->duedate < time());
5937 if (!$instance->sendnotifications && !($late && $instance->sendlatenotifications)) {
5938 // No need to do anything.
5939 return;
5942 if ($submission->userid) {
5943 $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
5944 } else {
5945 $user = $USER;
5948 if ($notifyusers = $this->get_notifiable_users($user->id)) {
5949 foreach ($notifyusers as $notifyuser) {
5950 $this->send_notification($user,
5951 $notifyuser,
5952 'gradersubmissionupdated',
5953 'assign_notification',
5954 $submission->timemodified);
5960 * Submit a submission for grading.
5962 * @param stdClass $data - The form data
5963 * @param array $notices - List of error messages to display on an error condition.
5964 * @return bool Return false if the submission was not submitted.
5966 public function submit_for_grading($data, $notices) {
5967 global $USER;
5969 $userid = $USER->id;
5970 if (!empty($data->userid)) {
5971 $userid = $data->userid;
5973 // Need submit permission to submit an assignment.
5974 if ($userid == $USER->id) {
5975 require_capability('mod/assign:submit', $this->context);
5976 } else {
5977 if (!$this->can_edit_submission($userid, $USER->id)) {
5978 print_error('nopermission');
5982 $instance = $this->get_instance();
5984 if ($instance->teamsubmission) {
5985 $submission = $this->get_group_submission($userid, 0, true);
5986 } else {
5987 $submission = $this->get_user_submission($userid, true);
5990 if (!$this->submissions_open($userid)) {
5991 $notices[] = get_string('submissionsclosed', 'assign');
5992 return false;
5995 if ($instance->requiresubmissionstatement && empty($data->submissionstatement) && $USER->id == $userid) {
5996 return false;
5999 if ($submission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
6000 // Give each submission plugin a chance to process the submission.
6001 $plugins = $this->get_submission_plugins();
6002 foreach ($plugins as $plugin) {
6003 if ($plugin->is_enabled() && $plugin->is_visible()) {
6004 $plugin->submit_for_grading($submission);
6008 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
6009 $this->update_submission($submission, $userid, true, $instance->teamsubmission);
6010 $completion = new completion_info($this->get_course());
6011 if ($completion->is_enabled($this->get_course_module()) && $instance->completionsubmit) {
6012 $this->update_activity_completion_records($instance->teamsubmission,
6013 $instance->requireallteammemberssubmit,
6014 $submission,
6015 $userid,
6016 COMPLETION_COMPLETE,
6017 $completion);
6020 if (!empty($data->submissionstatement) && $USER->id == $userid) {
6021 \mod_assign\event\statement_accepted::create_from_submission($this, $submission)->trigger();
6023 $this->notify_graders($submission);
6024 $this->notify_student_submission_receipt($submission);
6026 \mod_assign\event\assessable_submitted::create_from_submission($this, $submission, false)->trigger();
6028 return true;
6030 $notices[] = get_string('submissionsclosed', 'assign');
6031 return false;
6035 * A students submission is submitted for grading by a teacher.
6037 * @return bool
6039 protected function process_submit_other_for_grading($mform, $notices) {
6040 global $USER, $CFG;
6042 require_sesskey();
6044 $userid = optional_param('userid', $USER->id, PARAM_INT);
6046 if (!$this->submissions_open($userid)) {
6047 $notices[] = get_string('submissionsclosed', 'assign');
6048 return false;
6050 $data = new stdClass();
6051 $data->userid = $userid;
6052 return $this->submit_for_grading($data, $notices);
6056 * Assignment submission is processed before grading.
6058 * @param moodleform|null $mform If validation failed when submitting this form - this is the moodleform.
6059 * It can be null.
6060 * @return bool Return false if the validation fails. This affects which page is displayed next.
6062 protected function process_submit_for_grading($mform, $notices) {
6063 global $CFG;
6065 require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
6066 require_sesskey();
6068 if (!$this->submissions_open()) {
6069 $notices[] = get_string('submissionsclosed', 'assign');
6070 return false;
6072 $instance = $this->get_instance();
6073 $data = new stdClass();
6074 $adminconfig = $this->get_admin_config();
6075 $requiresubmissionstatement = $instance->requiresubmissionstatement &&
6076 !empty($adminconfig->submissionstatement);
6078 $submissionstatement = '';
6079 if (!empty($adminconfig->submissionstatement)) {
6080 // Format the submission statement before its sent. We turn off para because this is going within
6081 // a form element.
6082 $options = array(
6083 'context' => $this->get_context(),
6084 'para' => false
6086 $submissionstatement = format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $options);
6089 if ($mform == null) {
6090 $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
6091 $submissionstatement,
6092 $this->get_course_module()->id,
6093 $data));
6096 $data = $mform->get_data();
6097 if (!$mform->is_cancelled()) {
6098 if ($mform->get_data() == false) {
6099 return false;
6101 return $this->submit_for_grading($data, $notices);
6103 return true;
6107 * Save the extension date for a single user.
6109 * @param int $userid The user id
6110 * @param mixed $extensionduedate Either an integer date or null
6111 * @return boolean
6113 public function save_user_extension($userid, $extensionduedate) {
6114 global $DB;
6116 // Need submit permission to submit an assignment.
6117 require_capability('mod/assign:grantextension', $this->context);
6119 if (!is_enrolled($this->get_course_context(), $userid)) {
6120 return false;
6122 if (!has_capability('mod/assign:submit', $this->context, $userid)) {
6123 return false;
6126 if ($this->get_instance()->duedate && $extensionduedate) {
6127 if ($this->get_instance()->duedate > $extensionduedate) {
6128 return false;
6131 if ($this->get_instance()->allowsubmissionsfromdate && $extensionduedate) {
6132 if ($this->get_instance()->allowsubmissionsfromdate > $extensionduedate) {
6133 return false;
6137 $flags = $this->get_user_flags($userid, true);
6138 $flags->extensionduedate = $extensionduedate;
6140 $result = $this->update_user_flags($flags);
6142 if ($result) {
6143 \mod_assign\event\extension_granted::create_from_assign($this, $userid)->trigger();
6145 return $result;
6149 * Save extension date.
6151 * @param moodleform $mform The submitted form
6152 * @return boolean
6154 protected function process_save_extension(& $mform) {
6155 global $DB, $CFG;
6157 // Include extension form.
6158 require_once($CFG->dirroot . '/mod/assign/extensionform.php');
6159 require_sesskey();
6161 $users = optional_param('userid', 0, PARAM_INT);
6162 if (!$users) {
6163 $users = required_param('selectedusers', PARAM_SEQUENCE);
6165 $userlist = explode(',', $users);
6167 $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
6168 $maxoverride = array('allowsubmissionsfromdate' => 0, 'duedate' => 0, 'cutoffdate' => 0);
6169 foreach ($userlist as $userid) {
6170 // To validate extension date with users overrides.
6171 $override = $this->override_exists($userid);
6172 foreach ($keys as $key) {
6173 if ($override->{$key}) {
6174 if ($maxoverride[$key] < $override->{$key}) {
6175 $maxoverride[$key] = $override->{$key};
6177 } else if ($maxoverride[$key] < $this->get_instance()->{$key}) {
6178 $maxoverride[$key] = $this->get_instance()->{$key};
6182 foreach ($keys as $key) {
6183 if ($maxoverride[$key]) {
6184 $this->get_instance()->{$key} = $maxoverride[$key];
6188 $formparams = array(
6189 'instance' => $this->get_instance(),
6190 'assign' => $this,
6191 'userlist' => $userlist
6194 $mform = new mod_assign_extension_form(null, $formparams);
6196 if ($mform->is_cancelled()) {
6197 return true;
6200 if ($formdata = $mform->get_data()) {
6201 if (!empty($formdata->selectedusers)) {
6202 $users = explode(',', $formdata->selectedusers);
6203 $result = true;
6204 foreach ($users as $userid) {
6205 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
6206 $result = $this->save_user_extension($user->id, $formdata->extensionduedate) && $result;
6208 return $result;
6210 if (!empty($formdata->userid)) {
6211 $user = $DB->get_record('user', array('id' => $formdata->userid), '*', MUST_EXIST);
6212 return $this->save_user_extension($user->id, $formdata->extensionduedate);
6216 return false;
6220 * Save quick grades.
6222 * @return string The result of the save operation
6224 protected function process_save_quick_grades() {
6225 global $USER, $DB, $CFG;
6227 // Need grade permission.
6228 require_capability('mod/assign:grade', $this->context);
6229 require_sesskey();
6231 // Make sure advanced grading is disabled.
6232 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
6233 $controller = $gradingmanager->get_active_controller();
6234 if (!empty($controller)) {
6235 return get_string('errorquickgradingvsadvancedgrading', 'assign');
6238 $users = array();
6239 // First check all the last modified values.
6240 $currentgroup = groups_get_activity_group($this->get_course_module(), true);
6241 $participants = $this->list_participants($currentgroup, true);
6243 // Gets a list of possible users and look for values based upon that.
6244 foreach ($participants as $userid => $unused) {
6245 $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
6246 $attemptnumber = optional_param('gradeattempt_' . $userid, -1, PARAM_INT);
6247 // Gather the userid, updated grade and last modified value.
6248 $record = new stdClass();
6249 $record->userid = $userid;
6250 if ($modified >= 0) {
6251 $record->grade = unformat_float(optional_param('quickgrade_' . $record->userid, -1, PARAM_TEXT));
6252 $record->workflowstate = optional_param('quickgrade_' . $record->userid.'_workflowstate', false, PARAM_ALPHA);
6253 $record->allocatedmarker = optional_param('quickgrade_' . $record->userid.'_allocatedmarker', false, PARAM_INT);
6254 } else {
6255 // This user was not in the grading table.
6256 continue;
6258 $record->attemptnumber = $attemptnumber;
6259 $record->lastmodified = $modified;
6260 $record->gradinginfo = grade_get_grades($this->get_course()->id,
6261 'mod',
6262 'assign',
6263 $this->get_instance()->id,
6264 array($userid));
6265 $users[$userid] = $record;
6268 if (empty($users)) {
6269 return get_string('nousersselected', 'assign');
6272 list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
6273 $params['assignid1'] = $this->get_instance()->id;
6274 $params['assignid2'] = $this->get_instance()->id;
6276 // Check them all for currency.
6277 $grademaxattempt = 'SELECT s.userid, s.attemptnumber AS maxattempt
6278 FROM {assign_submission} s
6279 WHERE s.assignment = :assignid1 AND s.latest = 1';
6281 $sql = 'SELECT u.id AS userid, g.grade AS grade, g.timemodified AS lastmodified,
6282 uf.workflowstate, uf.allocatedmarker, gmx.maxattempt AS attemptnumber
6283 FROM {user} u
6284 LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON u.id = gmx.userid
6285 LEFT JOIN {assign_grades} g ON
6286 u.id = g.userid AND
6287 g.assignment = :assignid2 AND
6288 g.attemptnumber = gmx.maxattempt
6289 LEFT JOIN {assign_user_flags} uf ON uf.assignment = g.assignment AND uf.userid = g.userid
6290 WHERE u.id ' . $userids;
6291 $currentgrades = $DB->get_recordset_sql($sql, $params);
6293 $modifiedusers = array();
6294 foreach ($currentgrades as $current) {
6295 $modified = $users[(int)$current->userid];
6296 $grade = $this->get_user_grade($modified->userid, false);
6297 // Check to see if the grade column was even visible.
6298 $gradecolpresent = optional_param('quickgrade_' . $modified->userid, false, PARAM_INT) !== false;
6300 // Check to see if the outcomes were modified.
6301 if ($CFG->enableoutcomes) {
6302 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
6303 $oldoutcome = $outcome->grades[$modified->userid]->grade;
6304 $paramname = 'outcome_' . $outcomeid . '_' . $modified->userid;
6305 $newoutcome = optional_param($paramname, -1, PARAM_FLOAT);
6306 // Check to see if the outcome column was even visible.
6307 $outcomecolpresent = optional_param($paramname, false, PARAM_FLOAT) !== false;
6308 if ($outcomecolpresent && ($oldoutcome != $newoutcome)) {
6309 // Can't check modified time for outcomes because it is not reported.
6310 $modifiedusers[$modified->userid] = $modified;
6311 continue;
6316 // Let plugins participate.
6317 foreach ($this->feedbackplugins as $plugin) {
6318 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
6319 // The plugins must handle is_quickgrading_modified correctly - ie
6320 // handle hidden columns.
6321 if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
6322 if ((int)$current->lastmodified > (int)$modified->lastmodified) {
6323 return get_string('errorrecordmodified', 'assign');
6324 } else {
6325 $modifiedusers[$modified->userid] = $modified;
6326 continue;
6332 if (($current->grade < 0 || $current->grade === null) &&
6333 ($modified->grade < 0 || $modified->grade === null)) {
6334 // Different ways to indicate no grade.
6335 $modified->grade = $current->grade; // Keep existing grade.
6337 // Treat 0 and null as different values.
6338 if ($current->grade !== null) {
6339 $current->grade = floatval($current->grade);
6341 $gradechanged = $gradecolpresent && grade_floats_different($current->grade, $modified->grade);
6342 $markingallocationchanged = $this->get_instance()->markingworkflow &&
6343 $this->get_instance()->markingallocation &&
6344 ($modified->allocatedmarker !== false) &&
6345 ($current->allocatedmarker != $modified->allocatedmarker);
6346 $workflowstatechanged = $this->get_instance()->markingworkflow &&
6347 ($modified->workflowstate !== false) &&
6348 ($current->workflowstate != $modified->workflowstate);
6349 if ($gradechanged || $markingallocationchanged || $workflowstatechanged) {
6350 // Grade changed.
6351 if ($this->grading_disabled($modified->userid)) {
6352 continue;
6354 $badmodified = (int)$current->lastmodified > (int)$modified->lastmodified;
6355 $badattempt = (int)$current->attemptnumber != (int)$modified->attemptnumber;
6356 if ($badmodified || $badattempt) {
6357 // Error - record has been modified since viewing the page.
6358 return get_string('errorrecordmodified', 'assign');
6359 } else {
6360 $modifiedusers[$modified->userid] = $modified;
6365 $currentgrades->close();
6367 $adminconfig = $this->get_admin_config();
6368 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
6370 // Ok - ready to process the updates.
6371 foreach ($modifiedusers as $userid => $modified) {
6372 $grade = $this->get_user_grade($userid, true);
6373 $flags = $this->get_user_flags($userid, true);
6374 $grade->grade= grade_floatval(unformat_float($modified->grade));
6375 $grade->grader= $USER->id;
6376 $gradecolpresent = optional_param('quickgrade_' . $userid, false, PARAM_INT) !== false;
6378 // Save plugins data.
6379 foreach ($this->feedbackplugins as $plugin) {
6380 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
6381 $plugin->save_quickgrading_changes($userid, $grade);
6382 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
6383 // This is the feedback plugin chose to push comments to the gradebook.
6384 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
6385 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
6390 // These will be set to false if they are not present in the quickgrading
6391 // form (e.g. column hidden).
6392 $workflowstatemodified = ($modified->workflowstate !== false) &&
6393 ($flags->workflowstate != $modified->workflowstate);
6395 $allocatedmarkermodified = ($modified->allocatedmarker !== false) &&
6396 ($flags->allocatedmarker != $modified->allocatedmarker);
6398 if ($workflowstatemodified) {
6399 $flags->workflowstate = $modified->workflowstate;
6401 if ($allocatedmarkermodified) {
6402 $flags->allocatedmarker = $modified->allocatedmarker;
6404 if ($workflowstatemodified || $allocatedmarkermodified) {
6405 if ($this->update_user_flags($flags) && $workflowstatemodified) {
6406 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
6407 \mod_assign\event\workflow_state_updated::create_from_user($this, $user, $flags->workflowstate)->trigger();
6410 $this->update_grade($grade);
6412 // Allow teachers to skip sending notifications.
6413 if (optional_param('sendstudentnotifications', true, PARAM_BOOL)) {
6414 $this->notify_grade_modified($grade, true);
6417 // Save outcomes.
6418 if ($CFG->enableoutcomes) {
6419 $data = array();
6420 foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
6421 $oldoutcome = $outcome->grades[$modified->userid]->grade;
6422 $paramname = 'outcome_' . $outcomeid . '_' . $modified->userid;
6423 // This will be false if the input was not in the quickgrading
6424 // form (e.g. column hidden).
6425 $newoutcome = optional_param($paramname, false, PARAM_INT);
6426 if ($newoutcome !== false && ($oldoutcome != $newoutcome)) {
6427 $data[$outcomeid] = $newoutcome;
6430 if (count($data) > 0) {
6431 grade_update_outcomes('mod/assign',
6432 $this->course->id,
6433 'mod',
6434 'assign',
6435 $this->get_instance()->id,
6436 $userid,
6437 $data);
6442 return get_string('quickgradingchangessaved', 'assign');
6446 * Reveal student identities to markers (and the gradebook).
6448 * @return void
6450 public function reveal_identities() {
6451 global $DB;
6453 require_capability('mod/assign:revealidentities', $this->context);
6455 if ($this->get_instance()->revealidentities || empty($this->get_instance()->blindmarking)) {
6456 return false;
6459 // Update the assignment record.
6460 $update = new stdClass();
6461 $update->id = $this->get_instance()->id;
6462 $update->revealidentities = 1;
6463 $DB->update_record('assign', $update);
6465 // Refresh the instance data.
6466 $this->instance = null;
6468 // Release the grades to the gradebook.
6469 // First create the column in the gradebook.
6470 $this->update_gradebook(false, $this->get_course_module()->id);
6472 // Now release all grades.
6474 $adminconfig = $this->get_admin_config();
6475 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
6476 $gradebookplugin = str_replace('assignfeedback_', '', $gradebookplugin);
6477 $grades = $DB->get_records('assign_grades', array('assignment'=>$this->get_instance()->id));
6479 $plugin = $this->get_feedback_plugin_by_type($gradebookplugin);
6481 foreach ($grades as $grade) {
6482 // Fetch any comments for this student.
6483 if ($plugin && $plugin->is_enabled() && $plugin->is_visible()) {
6484 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
6485 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
6487 $this->gradebook_item_update(null, $grade);
6490 \mod_assign\event\identities_revealed::create_from_assign($this)->trigger();
6494 * Reveal student identities to markers (and the gradebook).
6496 * @return void
6498 protected function process_reveal_identities() {
6500 if (!confirm_sesskey()) {
6501 return false;
6504 return $this->reveal_identities();
6509 * Save grading options.
6511 * @return void
6513 protected function process_save_grading_options() {
6514 global $USER, $CFG;
6516 // Include grading options form.
6517 require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
6519 // Need submit permission to submit an assignment.
6520 $this->require_view_grades();
6521 require_sesskey();
6523 // Is advanced grading enabled?
6524 $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
6525 $controller = $gradingmanager->get_active_controller();
6526 $showquickgrading = empty($controller);
6527 if (!is_null($this->context)) {
6528 $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
6529 } else {
6530 $showonlyactiveenrolopt = false;
6533 $markingallocation = $this->get_instance()->markingworkflow &&
6534 $this->get_instance()->markingallocation &&
6535 has_capability('mod/assign:manageallocations', $this->context);
6536 // Get markers to use in drop lists.
6537 $markingallocationoptions = array();
6538 if ($markingallocation) {
6539 $markingallocationoptions[''] = get_string('filternone', 'assign');
6540 $markingallocationoptions[ASSIGN_MARKER_FILTER_NO_MARKER] = get_string('markerfilternomarker', 'assign');
6541 list($sort, $params) = users_order_by_sql();
6542 $markers = get_users_by_capability($this->context, 'mod/assign:grade', '', $sort);
6543 foreach ($markers as $marker) {
6544 $markingallocationoptions[$marker->id] = fullname($marker);
6548 // Get marking states to show in form.
6549 $markingworkflowoptions = array();
6550 if ($this->get_instance()->markingworkflow) {
6551 $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
6552 $markingworkflowoptions[''] = get_string('filternone', 'assign');
6553 $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
6554 $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
6557 $gradingoptionsparams = array('cm'=>$this->get_course_module()->id,
6558 'contextid'=>$this->context->id,
6559 'userid'=>$USER->id,
6560 'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
6561 'showquickgrading'=>$showquickgrading,
6562 'quickgrading'=>false,
6563 'markingworkflowopt' => $markingworkflowoptions,
6564 'markingallocationopt' => $markingallocationoptions,
6565 'showonlyactiveenrolopt'=>$showonlyactiveenrolopt,
6566 'showonlyactiveenrol' => $this->show_only_active_users(),
6567 'downloadasfolders' => get_user_preferences('assign_downloadasfolders', 1));
6568 $mform = new mod_assign_grading_options_form(null, $gradingoptionsparams);
6569 if ($formdata = $mform->get_data()) {
6570 set_user_preference('assign_perpage', $formdata->perpage);
6571 if (isset($formdata->filter)) {
6572 set_user_preference('assign_filter', $formdata->filter);
6574 if (isset($formdata->markerfilter)) {
6575 set_user_preference('assign_markerfilter', $formdata->markerfilter);
6577 if (isset($formdata->workflowfilter)) {
6578 set_user_preference('assign_workflowfilter', $formdata->workflowfilter);
6580 if ($showquickgrading) {
6581 set_user_preference('assign_quickgrading', isset($formdata->quickgrading));
6583 if (isset($formdata->downloadasfolders)) {
6584 set_user_preference('assign_downloadasfolders', 1); // Enabled.
6585 } else {
6586 set_user_preference('assign_downloadasfolders', 0); // Disabled.
6588 if (!empty($showonlyactiveenrolopt)) {
6589 $showonlyactiveenrol = isset($formdata->showonlyactiveenrol);
6590 set_user_preference('grade_report_showonlyactiveenrol', $showonlyactiveenrol);
6591 $this->showonlyactiveenrol = $showonlyactiveenrol;
6597 * Take a grade object and print a short summary for the log file.
6598 * The size limit for the log file is 255 characters, so be careful not
6599 * to include too much information.
6601 * @deprecated since 2.7
6603 * @param stdClass $grade
6604 * @return string
6606 public function format_grade_for_log(stdClass $grade) {
6607 global $DB;
6609 $user = $DB->get_record('user', array('id' => $grade->userid), '*', MUST_EXIST);
6611 $info = get_string('gradestudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
6612 if ($grade->grade != '') {
6613 $info .= get_string('grade') . ': ' . $this->display_grade($grade->grade, false) . '. ';
6614 } else {
6615 $info .= get_string('nograde', 'assign');
6617 return $info;
6621 * Take a submission object and print a short summary for the log file.
6622 * The size limit for the log file is 255 characters, so be careful not
6623 * to include too much information.
6625 * @deprecated since 2.7
6627 * @param stdClass $submission
6628 * @return string
6630 public function format_submission_for_log(stdClass $submission) {
6631 global $DB;
6633 $info = '';
6634 if ($submission->userid) {
6635 $user = $DB->get_record('user', array('id' => $submission->userid), '*', MUST_EXIST);
6636 $name = fullname($user);
6637 } else {
6638 $group = $this->get_submission_group($submission->userid);
6639 if ($group) {
6640 $name = $group->name;
6641 } else {
6642 $name = get_string('defaultteam', 'assign');
6645 $status = get_string('submissionstatus_' . $submission->status, 'assign');
6646 $params = array('id'=>$submission->userid, 'fullname'=>$name, 'status'=>$status);
6647 $info .= get_string('submissionlog', 'assign', $params) . ' <br>';
6649 foreach ($this->submissionplugins as $plugin) {
6650 if ($plugin->is_enabled() && $plugin->is_visible()) {
6651 $info .= '<br>' . $plugin->format_for_log($submission);
6655 return $info;
6659 * Require a valid sess key and then call copy_previous_attempt.
6661 * @param array $notices Any error messages that should be shown
6662 * to the user at the top of the edit submission form.
6663 * @return bool
6665 protected function process_copy_previous_attempt(&$notices) {
6666 require_sesskey();
6668 return $this->copy_previous_attempt($notices);
6672 * Copy the current assignment submission from the last submitted attempt.
6674 * @param array $notices Any error messages that should be shown
6675 * to the user at the top of the edit submission form.
6676 * @return bool
6678 public function copy_previous_attempt(&$notices) {
6679 global $USER, $CFG;
6681 require_capability('mod/assign:submit', $this->context);
6683 $instance = $this->get_instance();
6684 if ($instance->teamsubmission) {
6685 $submission = $this->get_group_submission($USER->id, 0, true);
6686 } else {
6687 $submission = $this->get_user_submission($USER->id, true);
6689 if (!$submission || $submission->status != ASSIGN_SUBMISSION_STATUS_REOPENED) {
6690 $notices[] = get_string('submissionnotcopiedinvalidstatus', 'assign');
6691 return false;
6693 $flags = $this->get_user_flags($USER->id, false);
6695 // Get the flags to check if it is locked.
6696 if ($flags && $flags->locked) {
6697 $notices[] = get_string('submissionslocked', 'assign');
6698 return false;
6700 if ($instance->submissiondrafts) {
6701 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
6702 } else {
6703 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
6705 $this->update_submission($submission, $USER->id, true, $instance->teamsubmission);
6707 // Find the previous submission.
6708 if ($instance->teamsubmission) {
6709 $previoussubmission = $this->get_group_submission($USER->id, 0, true, $submission->attemptnumber - 1);
6710 } else {
6711 $previoussubmission = $this->get_user_submission($USER->id, true, $submission->attemptnumber - 1);
6714 if (!$previoussubmission) {
6715 // There was no previous submission so there is nothing else to do.
6716 return true;
6719 $pluginerror = false;
6720 foreach ($this->get_submission_plugins() as $plugin) {
6721 if ($plugin->is_visible() && $plugin->is_enabled()) {
6722 if (!$plugin->copy_submission($previoussubmission, $submission)) {
6723 $notices[] = $plugin->get_error();
6724 $pluginerror = true;
6728 if ($pluginerror) {
6729 return false;
6732 \mod_assign\event\submission_duplicated::create_from_submission($this, $submission)->trigger();
6734 $complete = COMPLETION_INCOMPLETE;
6735 if ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
6736 $complete = COMPLETION_COMPLETE;
6738 $completion = new completion_info($this->get_course());
6739 if ($completion->is_enabled($this->get_course_module()) && $instance->completionsubmit) {
6740 $this->update_activity_completion_records($instance->teamsubmission,
6741 $instance->requireallteammemberssubmit,
6742 $submission,
6743 $USER->id,
6744 $complete,
6745 $completion);
6748 if (!$instance->submissiondrafts) {
6749 // There is a case for not notifying the student about the submission copy,
6750 // but it provides a record of the event and if they then cancel editing it
6751 // is clear that the submission was copied.
6752 $this->notify_student_submission_copied($submission);
6753 $this->notify_graders($submission);
6755 // The same logic applies here - we could not notify teachers,
6756 // but then they would wonder why there are submitted assignments
6757 // and they haven't been notified.
6758 \mod_assign\event\assessable_submitted::create_from_submission($this, $submission, true)->trigger();
6760 return true;
6764 * Determine if the current submission is empty or not.
6766 * @param submission $submission the students submission record to check.
6767 * @return bool
6769 public function submission_empty($submission) {
6770 $allempty = true;
6772 foreach ($this->submissionplugins as $plugin) {
6773 if ($plugin->is_enabled() && $plugin->is_visible()) {
6774 if (!$allempty || !$plugin->is_empty($submission)) {
6775 $allempty = false;
6779 return $allempty;
6783 * Determine if a new submission is empty or not
6785 * @param stdClass $data Submission data
6786 * @return bool
6788 public function new_submission_empty($data) {
6789 foreach ($this->submissionplugins as $plugin) {
6790 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions() &&
6791 !$plugin->submission_is_empty($data)) {
6792 return false;
6795 return true;
6799 * Save assignment submission for the current user.
6801 * @param stdClass $data
6802 * @param array $notices Any error messages that should be shown
6803 * to the user.
6804 * @return bool
6806 public function save_submission(stdClass $data, & $notices) {
6807 global $CFG, $USER, $DB;
6809 $userid = $USER->id;
6810 if (!empty($data->userid)) {
6811 $userid = $data->userid;
6814 $user = clone($USER);
6815 if ($userid == $USER->id) {
6816 require_capability('mod/assign:submit', $this->context);
6817 } else {
6818 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
6819 if (!$this->can_edit_submission($userid, $USER->id)) {
6820 print_error('nopermission');
6823 $instance = $this->get_instance();
6825 if ($instance->teamsubmission) {
6826 $submission = $this->get_group_submission($userid, 0, true);
6827 } else {
6828 $submission = $this->get_user_submission($userid, true);
6831 if ($this->new_submission_empty($data)) {
6832 $notices[] = get_string('submissionempty', 'mod_assign');
6833 return false;
6836 // Check that no one has modified the submission since we started looking at it.
6837 if (isset($data->lastmodified) && ($submission->timemodified > $data->lastmodified)) {
6838 // Another user has submitted something. Notify the current user.
6839 if ($submission->status !== ASSIGN_SUBMISSION_STATUS_NEW) {
6840 $notices[] = $instance->teamsubmission ? get_string('submissionmodifiedgroup', 'mod_assign')
6841 : get_string('submissionmodified', 'mod_assign');
6842 return false;
6846 if ($instance->submissiondrafts) {
6847 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
6848 } else {
6849 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
6852 $flags = $this->get_user_flags($userid, false);
6854 // Get the flags to check if it is locked.
6855 if ($flags && $flags->locked) {
6856 print_error('submissionslocked', 'assign');
6857 return true;
6860 $pluginerror = false;
6861 foreach ($this->submissionplugins as $plugin) {
6862 if ($plugin->is_enabled() && $plugin->is_visible()) {
6863 if (!$plugin->save($submission, $data)) {
6864 $notices[] = $plugin->get_error();
6865 $pluginerror = true;
6870 $allempty = $this->submission_empty($submission);
6871 if ($pluginerror || $allempty) {
6872 if ($allempty) {
6873 $notices[] = get_string('submissionempty', 'mod_assign');
6875 return false;
6878 $this->update_submission($submission, $userid, true, $instance->teamsubmission);
6880 if ($instance->teamsubmission && !$instance->requireallteammemberssubmit) {
6881 $team = $this->get_submission_group_members($submission->groupid, true);
6883 foreach ($team as $member) {
6884 if ($member->id != $userid) {
6885 $membersubmission = clone($submission);
6886 $this->update_submission($membersubmission, $member->id, true, $instance->teamsubmission);
6891 // Logging.
6892 if (isset($data->submissionstatement) && ($userid == $USER->id)) {
6893 \mod_assign\event\statement_accepted::create_from_submission($this, $submission)->trigger();
6896 $complete = COMPLETION_INCOMPLETE;
6897 if ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
6898 $complete = COMPLETION_COMPLETE;
6900 $completion = new completion_info($this->get_course());
6901 if ($completion->is_enabled($this->get_course_module()) && $instance->completionsubmit) {
6902 $completion->update_state($this->get_course_module(), $complete, $userid);
6905 if (!$instance->submissiondrafts) {
6906 $this->notify_student_submission_receipt($submission);
6907 $this->notify_graders($submission);
6908 \mod_assign\event\assessable_submitted::create_from_submission($this, $submission, true)->trigger();
6910 return true;
6914 * Save assignment submission.
6916 * @param moodleform $mform
6917 * @param array $notices Any error messages that should be shown
6918 * to the user at the top of the edit submission form.
6919 * @return bool
6921 protected function process_save_submission(&$mform, &$notices) {
6922 global $CFG, $USER;
6924 // Include submission form.
6925 require_once($CFG->dirroot . '/mod/assign/submission_form.php');
6927 $userid = optional_param('userid', $USER->id, PARAM_INT);
6928 // Need submit permission to submit an assignment.
6929 require_sesskey();
6930 if (!$this->submissions_open($userid)) {
6931 $notices[] = get_string('duedatereached', 'assign');
6932 return false;
6934 $instance = $this->get_instance();
6936 $data = new stdClass();
6937 $data->userid = $userid;
6938 $mform = new mod_assign_submission_form(null, array($this, $data));
6939 if ($mform->is_cancelled()) {
6940 return true;
6942 if ($data = $mform->get_data()) {
6943 return $this->save_submission($data, $notices);
6945 return false;
6950 * Determine if this users grade can be edited.
6952 * @param int $userid - The student userid
6953 * @param bool $checkworkflow - whether to include a check for the workflow state.
6954 * @return bool $gradingdisabled
6956 public function grading_disabled($userid, $checkworkflow=true) {
6957 global $CFG;
6958 if ($checkworkflow && $this->get_instance()->markingworkflow) {
6959 $grade = $this->get_user_grade($userid, false);
6960 $validstates = $this->get_marking_workflow_states_for_current_user();
6961 if (!empty($grade) && !empty($grade->workflowstate) && !array_key_exists($grade->workflowstate, $validstates)) {
6962 return true;
6965 $gradinginfo = grade_get_grades($this->get_course()->id,
6966 'mod',
6967 'assign',
6968 $this->get_instance()->id,
6969 array($userid));
6970 if (!$gradinginfo) {
6971 return false;
6974 if (!isset($gradinginfo->items[0]->grades[$userid])) {
6975 return false;
6977 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked ||
6978 $gradinginfo->items[0]->grades[$userid]->overridden;
6979 return $gradingdisabled;
6984 * Get an instance of a grading form if advanced grading is enabled.
6985 * This is specific to the assignment, marker and student.
6987 * @param int $userid - The student userid
6988 * @param stdClass|false $grade - The grade record
6989 * @param bool $gradingdisabled
6990 * @return mixed gradingform_instance|null $gradinginstance
6992 protected function get_grading_instance($userid, $grade, $gradingdisabled) {
6993 global $CFG, $USER;
6995 $grademenu = make_grades_menu($this->get_instance()->grade);
6996 $allowgradedecimals = $this->get_instance()->grade > 0;
6998 $advancedgradingwarning = false;
6999 $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
7000 $gradinginstance = null;
7001 if ($gradingmethod = $gradingmanager->get_active_method()) {
7002 $controller = $gradingmanager->get_controller($gradingmethod);
7003 if ($controller->is_form_available()) {
7004 $itemid = null;
7005 if ($grade) {
7006 $itemid = $grade->id;
7008 if ($gradingdisabled && $itemid) {
7009 $gradinginstance = $controller->get_current_instance($USER->id, $itemid);
7010 } else if (!$gradingdisabled) {
7011 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
7012 $gradinginstance = $controller->get_or_create_instance($instanceid,
7013 $USER->id,
7014 $itemid);
7016 } else {
7017 $advancedgradingwarning = $controller->form_unavailable_notification();
7020 if ($gradinginstance) {
7021 $gradinginstance->get_controller()->set_grade_range($grademenu, $allowgradedecimals);
7023 return $gradinginstance;
7027 * Add elements to grade form.
7029 * @param MoodleQuickForm $mform
7030 * @param stdClass $data
7031 * @param array $params
7032 * @return void
7034 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params) {
7035 global $USER, $CFG, $SESSION;
7036 $settings = $this->get_instance();
7038 $rownum = isset($params['rownum']) ? $params['rownum'] : 0;
7039 $last = isset($params['last']) ? $params['last'] : true;
7040 $useridlistid = isset($params['useridlistid']) ? $params['useridlistid'] : 0;
7041 $userid = isset($params['userid']) ? $params['userid'] : 0;
7042 $attemptnumber = isset($params['attemptnumber']) ? $params['attemptnumber'] : 0;
7043 $gradingpanel = !empty($params['gradingpanel']);
7044 $bothids = ($userid && $useridlistid);
7046 if (!$userid || $bothids) {
7047 $useridlistkey = $this->get_useridlist_key($useridlistid);
7048 if (empty($SESSION->mod_assign_useridlist[$useridlistkey])) {
7049 $SESSION->mod_assign_useridlist[$useridlistkey] = $this->get_grading_userid_list();
7051 $useridlist = $SESSION->mod_assign_useridlist[$useridlistkey];
7052 } else {
7053 $useridlist = array($userid);
7054 $rownum = 0;
7055 $useridlistid = '';
7058 $userid = $useridlist[$rownum];
7059 // We need to create a grade record matching this attempt number
7060 // or the feedback plugin will have no way to know what is the correct attempt.
7061 $grade = $this->get_user_grade($userid, true, $attemptnumber);
7063 $submission = null;
7064 if ($this->get_instance()->teamsubmission) {
7065 $submission = $this->get_group_submission($userid, 0, false, $attemptnumber);
7066 } else {
7067 $submission = $this->get_user_submission($userid, false, $attemptnumber);
7070 // Add advanced grading.
7071 $gradingdisabled = $this->grading_disabled($userid);
7072 $gradinginstance = $this->get_grading_instance($userid, $grade, $gradingdisabled);
7074 $mform->addElement('header', 'gradeheader', get_string('grade'));
7075 if ($gradinginstance) {
7076 $gradingelement = $mform->addElement('grading',
7077 'advancedgrading',
7078 get_string('grade').':',
7079 array('gradinginstance' => $gradinginstance));
7080 if ($gradingdisabled) {
7081 $gradingelement->freeze();
7082 } else {
7083 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
7084 $mform->setType('advancedgradinginstanceid', PARAM_INT);
7086 } else {
7087 // Use simple direct grading.
7088 if ($this->get_instance()->grade > 0) {
7089 $name = get_string('gradeoutof', 'assign', $this->get_instance()->grade);
7090 if (!$gradingdisabled) {
7091 $gradingelement = $mform->addElement('text', 'grade', $name);
7092 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
7093 $mform->setType('grade', PARAM_RAW);
7094 } else {
7095 $mform->addElement('hidden', 'grade', $name);
7096 $mform->hardFreeze('grade');
7097 $mform->setType('grade', PARAM_RAW);
7098 $strgradelocked = get_string('gradelocked', 'assign');
7099 $mform->addElement('static', 'gradedisabled', $name, $strgradelocked);
7100 $mform->addHelpButton('gradedisabled', 'gradeoutofhelp', 'assign');
7102 } else {
7103 $grademenu = array(-1 => get_string("nograde")) + make_grades_menu($this->get_instance()->grade);
7104 if (count($grademenu) > 1) {
7105 $gradingelement = $mform->addElement('select', 'grade', get_string('grade') . ':', $grademenu);
7107 // The grade is already formatted with format_float so it needs to be converted back to an integer.
7108 if (!empty($data->grade)) {
7109 $data->grade = (int)unformat_float($data->grade);
7111 $mform->setType('grade', PARAM_INT);
7112 if ($gradingdisabled) {
7113 $gradingelement->freeze();
7119 $gradinginfo = grade_get_grades($this->get_course()->id,
7120 'mod',
7121 'assign',
7122 $this->get_instance()->id,
7123 $userid);
7124 if (!empty($CFG->enableoutcomes)) {
7125 foreach ($gradinginfo->outcomes as $index => $outcome) {
7126 $options = make_grades_menu(-$outcome->scaleid);
7127 $options[0] = get_string('nooutcome', 'grades');
7128 if ($outcome->grades[$userid]->locked) {
7129 $mform->addElement('static',
7130 'outcome_' . $index . '[' . $userid . ']',
7131 $outcome->name . ':',
7132 $options[$outcome->grades[$userid]->grade]);
7133 } else {
7134 $attributes = array('id' => 'menuoutcome_' . $index );
7135 $mform->addElement('select',
7136 'outcome_' . $index . '[' . $userid . ']',
7137 $outcome->name.':',
7138 $options,
7139 $attributes);
7140 $mform->setType('outcome_' . $index . '[' . $userid . ']', PARAM_INT);
7141 $mform->setDefault('outcome_' . $index . '[' . $userid . ']',
7142 $outcome->grades[$userid]->grade);
7147 $capabilitylist = array('gradereport/grader:view', 'moodle/grade:viewall');
7148 if (has_all_capabilities($capabilitylist, $this->get_course_context())) {
7149 $urlparams = array('id'=>$this->get_course()->id);
7150 $url = new moodle_url('/grade/report/grader/index.php', $urlparams);
7151 $usergrade = '-';
7152 if (isset($gradinginfo->items[0]->grades[$userid]->str_grade)) {
7153 $usergrade = $gradinginfo->items[0]->grades[$userid]->str_grade;
7155 $gradestring = $this->get_renderer()->action_link($url, $usergrade);
7156 } else {
7157 $usergrade = '-';
7158 if (isset($gradinginfo->items[0]->grades[$userid]) &&
7159 !$gradinginfo->items[0]->grades[$userid]->hidden) {
7160 $usergrade = $gradinginfo->items[0]->grades[$userid]->str_grade;
7162 $gradestring = $usergrade;
7165 if ($this->get_instance()->markingworkflow) {
7166 $states = $this->get_marking_workflow_states_for_current_user();
7167 $options = array('' => get_string('markingworkflowstatenotmarked', 'assign')) + $states;
7168 $mform->addElement('select', 'workflowstate', get_string('markingworkflowstate', 'assign'), $options);
7169 $mform->addHelpButton('workflowstate', 'markingworkflowstate', 'assign');
7172 if ($this->get_instance()->markingworkflow &&
7173 $this->get_instance()->markingallocation &&
7174 has_capability('mod/assign:manageallocations', $this->context)) {
7176 list($sort, $params) = users_order_by_sql();
7177 $markers = get_users_by_capability($this->context, 'mod/assign:grade', '', $sort);
7178 $markerlist = array('' => get_string('choosemarker', 'assign'));
7179 $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
7180 foreach ($markers as $marker) {
7181 $markerlist[$marker->id] = fullname($marker, $viewfullnames);
7183 $mform->addElement('select', 'allocatedmarker', get_string('allocatedmarker', 'assign'), $markerlist);
7184 $mform->addHelpButton('allocatedmarker', 'allocatedmarker', 'assign');
7185 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW);
7186 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW);
7187 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE);
7188 $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
7190 $gradestring = '<span class="currentgrade">' . $gradestring . '</span>';
7191 $mform->addElement('static', 'currentgrade', get_string('currentgrade', 'assign'), $gradestring);
7193 if (count($useridlist) > 1) {
7194 $strparams = array('current'=>$rownum+1, 'total'=>count($useridlist));
7195 $name = get_string('outof', 'assign', $strparams);
7196 $mform->addElement('static', 'gradingstudent', get_string('gradingstudent', 'assign'), $name);
7199 // Let feedback plugins add elements to the grading form.
7200 $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
7202 // Hidden params.
7203 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
7204 $mform->setType('id', PARAM_INT);
7205 $mform->addElement('hidden', 'rownum', $rownum);
7206 $mform->setType('rownum', PARAM_INT);
7207 $mform->setConstant('rownum', $rownum);
7208 $mform->addElement('hidden', 'useridlistid', $useridlistid);
7209 $mform->setType('useridlistid', PARAM_ALPHANUM);
7210 $mform->addElement('hidden', 'attemptnumber', $attemptnumber);
7211 $mform->setType('attemptnumber', PARAM_INT);
7212 $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
7213 $mform->setType('ajax', PARAM_INT);
7214 $mform->addElement('hidden', 'userid', optional_param('userid', 0, PARAM_INT));
7215 $mform->setType('userid', PARAM_INT);
7217 if ($this->get_instance()->teamsubmission) {
7218 $mform->addElement('header', 'groupsubmissionsettings', get_string('groupsubmissionsettings', 'assign'));
7219 $mform->addElement('selectyesno', 'applytoall', get_string('applytoteam', 'assign'));
7220 $mform->setDefault('applytoall', 1);
7223 // Do not show if we are editing a previous attempt.
7224 if ($attemptnumber == -1 && $this->get_instance()->attemptreopenmethod != ASSIGN_ATTEMPT_REOPEN_METHOD_NONE) {
7225 $mform->addElement('header', 'attemptsettings', get_string('attemptsettings', 'assign'));
7226 $attemptreopenmethod = get_string('attemptreopenmethod_' . $this->get_instance()->attemptreopenmethod, 'assign');
7227 $mform->addElement('static', 'attemptreopenmethod', get_string('attemptreopenmethod', 'assign'), $attemptreopenmethod);
7229 $attemptnumber = 0;
7230 if ($submission) {
7231 $attemptnumber = $submission->attemptnumber;
7233 $maxattempts = $this->get_instance()->maxattempts;
7234 if ($maxattempts == ASSIGN_UNLIMITED_ATTEMPTS) {
7235 $maxattempts = get_string('unlimitedattempts', 'assign');
7237 $mform->addelement('static', 'maxattemptslabel', get_string('maxattempts', 'assign'), $maxattempts);
7238 $mform->addelement('static', 'attemptnumberlabel', get_string('attemptnumber', 'assign'), $attemptnumber + 1);
7240 $ismanual = $this->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL;
7241 $issubmission = !empty($submission);
7242 $isunlimited = $this->get_instance()->maxattempts == ASSIGN_UNLIMITED_ATTEMPTS;
7243 $islessthanmaxattempts = $issubmission && ($submission->attemptnumber < ($this->get_instance()->maxattempts-1));
7245 if ($ismanual && (!$issubmission || $isunlimited || $islessthanmaxattempts)) {
7246 $mform->addElement('selectyesno', 'addattempt', get_string('addattempt', 'assign'));
7247 $mform->setDefault('addattempt', 0);
7250 if (!$gradingpanel) {
7251 $mform->addElement('selectyesno', 'sendstudentnotifications', get_string('sendstudentnotifications', 'assign'));
7252 } else {
7253 $mform->addElement('hidden', 'sendstudentnotifications', get_string('sendstudentnotifications', 'assign'));
7254 $mform->setType('sendstudentnotifications', PARAM_BOOL);
7256 // Get assignment visibility information for student.
7257 $modinfo = get_fast_modinfo($settings->course, $userid);
7258 $cm = $modinfo->get_cm($this->get_course_module()->id);
7260 // Don't allow notification to be sent if the student can't access the assignment,
7261 // or until in "Released" state if using marking workflow.
7262 if (!$cm->uservisible) {
7263 $mform->setDefault('sendstudentnotifications', 0);
7264 $mform->freeze('sendstudentnotifications');
7265 } else if ($this->get_instance()->markingworkflow) {
7266 $mform->setDefault('sendstudentnotifications', 0);
7267 if (!$gradingpanel) {
7268 $mform->disabledIf('sendstudentnotifications', 'workflowstate', 'neq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
7270 } else {
7271 $mform->setDefault('sendstudentnotifications', $this->get_instance()->sendstudentnotifications);
7274 $mform->addElement('hidden', 'action', 'submitgrade');
7275 $mform->setType('action', PARAM_ALPHA);
7277 if (!$gradingpanel) {
7279 $buttonarray = array();
7280 $name = get_string('savechanges', 'assign');
7281 $buttonarray[] = $mform->createElement('submit', 'savegrade', $name);
7282 if (!$last) {
7283 $name = get_string('savenext', 'assign');
7284 $buttonarray[] = $mform->createElement('submit', 'saveandshownext', $name);
7286 $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
7287 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
7288 $mform->closeHeaderBefore('buttonar');
7289 $buttonarray = array();
7291 if ($rownum > 0) {
7292 $name = get_string('previous', 'assign');
7293 $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', $name);
7296 if (!$last) {
7297 $name = get_string('nosavebutnext', 'assign');
7298 $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', $name);
7300 if (!empty($buttonarray)) {
7301 $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
7304 // The grading form does not work well with shortforms.
7305 $mform->setDisableShortforms();
7309 * Add elements in submission plugin form.
7311 * @param mixed $submission stdClass|null
7312 * @param MoodleQuickForm $mform
7313 * @param stdClass $data
7314 * @param int $userid The current userid (same as $USER->id)
7315 * @return void
7317 protected function add_plugin_submission_elements($submission,
7318 MoodleQuickForm $mform,
7319 stdClass $data,
7320 $userid) {
7321 foreach ($this->submissionplugins as $plugin) {
7322 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
7323 $plugin->get_form_elements_for_user($submission, $mform, $data, $userid);
7329 * Check if feedback plugins installed are enabled.
7331 * @return bool
7333 public function is_any_feedback_plugin_enabled() {
7334 if (!isset($this->cache['any_feedback_plugin_enabled'])) {
7335 $this->cache['any_feedback_plugin_enabled'] = false;
7336 foreach ($this->feedbackplugins as $plugin) {
7337 if ($plugin->is_enabled() && $plugin->is_visible()) {
7338 $this->cache['any_feedback_plugin_enabled'] = true;
7339 break;
7344 return $this->cache['any_feedback_plugin_enabled'];
7349 * Check if submission plugins installed are enabled.
7351 * @return bool
7353 public function is_any_submission_plugin_enabled() {
7354 if (!isset($this->cache['any_submission_plugin_enabled'])) {
7355 $this->cache['any_submission_plugin_enabled'] = false;
7356 foreach ($this->submissionplugins as $plugin) {
7357 if ($plugin->is_enabled() && $plugin->is_visible() && $plugin->allow_submissions()) {
7358 $this->cache['any_submission_plugin_enabled'] = true;
7359 break;
7364 return $this->cache['any_submission_plugin_enabled'];
7369 * Add elements to submission form.
7370 * @param MoodleQuickForm $mform
7371 * @param stdClass $data
7372 * @return void
7374 public function add_submission_form_elements(MoodleQuickForm $mform, stdClass $data) {
7375 global $USER;
7377 $userid = $data->userid;
7378 // Team submissions.
7379 if ($this->get_instance()->teamsubmission) {
7380 $submission = $this->get_group_submission($userid, 0, false);
7381 } else {
7382 $submission = $this->get_user_submission($userid, false);
7385 // Submission statement.
7386 $adminconfig = $this->get_admin_config();
7388 $requiresubmissionstatement = $this->get_instance()->requiresubmissionstatement &&
7389 !empty($adminconfig->submissionstatement);
7391 $draftsenabled = $this->get_instance()->submissiondrafts;
7393 // Only show submission statement if we are editing our own submission.
7394 if ($requiresubmissionstatement && !$draftsenabled && $userid == $USER->id) {
7396 $submissionstatement = '';
7397 if (!empty($adminconfig->submissionstatement)) {
7398 // Format the submission statement before its sent. We turn off para because this is going within
7399 // a form element.
7400 $options = array(
7401 'context' => $this->get_context(),
7402 'para' => false
7404 $submissionstatement = format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $options);
7406 $mform->addElement('checkbox', 'submissionstatement', '', $submissionstatement);
7407 $mform->addRule('submissionstatement', get_string('required'), 'required', null, 'client');
7410 $this->add_plugin_submission_elements($submission, $mform, $data, $userid);
7412 // Hidden params.
7413 $mform->addElement('hidden', 'id', $this->get_course_module()->id);
7414 $mform->setType('id', PARAM_INT);
7416 $mform->addElement('hidden', 'userid', $userid);
7417 $mform->setType('userid', PARAM_INT);
7419 $mform->addElement('hidden', 'action', 'savesubmission');
7420 $mform->setType('action', PARAM_ALPHA);
7424 * Revert to draft.
7426 * @param int $userid
7427 * @return boolean
7429 public function revert_to_draft($userid) {
7430 global $DB, $USER;
7432 // Need grade permission.
7433 require_capability('mod/assign:grade', $this->context);
7435 if ($this->get_instance()->teamsubmission) {
7436 $submission = $this->get_group_submission($userid, 0, false);
7437 } else {
7438 $submission = $this->get_user_submission($userid, false);
7441 if (!$submission) {
7442 return false;
7444 $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
7445 $this->update_submission($submission, $userid, true, $this->get_instance()->teamsubmission);
7447 // Give each submission plugin a chance to process the reverting to draft.
7448 $plugins = $this->get_submission_plugins();
7449 foreach ($plugins as $plugin) {
7450 if ($plugin->is_enabled() && $plugin->is_visible()) {
7451 $plugin->revert_to_draft($submission);
7454 // Update the modified time on the grade (grader modified).
7455 $grade = $this->get_user_grade($userid, true);
7456 $grade->grader = $USER->id;
7457 $this->update_grade($grade);
7459 $completion = new completion_info($this->get_course());
7460 if ($completion->is_enabled($this->get_course_module()) &&
7461 $this->get_instance()->completionsubmit) {
7462 $completion->update_state($this->get_course_module(), COMPLETION_INCOMPLETE, $userid);
7464 \mod_assign\event\submission_status_updated::create_from_submission($this, $submission)->trigger();
7465 return true;
7469 * Revert to draft.
7470 * Uses url parameter userid if userid not supplied as a parameter.
7472 * @param int $userid
7473 * @return boolean
7475 protected function process_revert_to_draft($userid = 0) {
7476 require_sesskey();
7478 if (!$userid) {
7479 $userid = required_param('userid', PARAM_INT);
7482 return $this->revert_to_draft($userid);
7486 * Prevent student updates to this submission
7488 * @param int $userid
7489 * @return bool
7491 public function lock_submission($userid) {
7492 global $USER, $DB;
7493 // Need grade permission.
7494 require_capability('mod/assign:grade', $this->context);
7496 // Give each submission plugin a chance to process the locking.
7497 $plugins = $this->get_submission_plugins();
7498 $submission = $this->get_user_submission($userid, false);
7500 $flags = $this->get_user_flags($userid, true);
7501 $flags->locked = 1;
7502 $this->update_user_flags($flags);
7504 foreach ($plugins as $plugin) {
7505 if ($plugin->is_enabled() && $plugin->is_visible()) {
7506 $plugin->lock($submission, $flags);
7510 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
7511 \mod_assign\event\submission_locked::create_from_user($this, $user)->trigger();
7512 return true;
7517 * Set the workflow state for multiple users
7519 * @return void
7521 protected function process_set_batch_marking_workflow_state() {
7522 global $CFG, $DB;
7524 // Include batch marking workflow form.
7525 require_once($CFG->dirroot . '/mod/assign/batchsetmarkingworkflowstateform.php');
7527 $formparams = array(
7528 'userscount' => 0, // This form is never re-displayed, so we don't need to
7529 'usershtml' => '', // initialise these parameters with real information.
7530 'markingworkflowstates' => $this->get_marking_workflow_states_for_current_user()
7533 $mform = new mod_assign_batch_set_marking_workflow_state_form(null, $formparams);
7535 if ($mform->is_cancelled()) {
7536 return true;
7539 if ($formdata = $mform->get_data()) {
7540 $useridlist = explode(',', $formdata->selectedusers);
7541 $state = $formdata->markingworkflowstate;
7543 foreach ($useridlist as $userid) {
7544 $flags = $this->get_user_flags($userid, true);
7546 $flags->workflowstate = $state;
7548 // Clear the mailed flag if notification is requested, the student hasn't been
7549 // notified previously, the student can access the assignment, and the state
7550 // is "Released".
7551 $modinfo = get_fast_modinfo($this->course, $userid);
7552 $cm = $modinfo->get_cm($this->get_course_module()->id);
7553 if ($formdata->sendstudentnotifications && $cm->uservisible &&
7554 $state == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
7555 $flags->mailed = 0;
7558 $gradingdisabled = $this->grading_disabled($userid);
7560 // Will not apply update if user does not have permission to assign this workflow state.
7561 if (!$gradingdisabled && $this->update_user_flags($flags)) {
7562 if ($state == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
7563 // Update Gradebook.
7564 $assign = clone $this->get_instance();
7565 $assign->cmidnumber = $this->get_course_module()->idnumber;
7566 // Set assign gradebook feedback plugin status.
7567 $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
7568 assign_update_grades($assign, $userid);
7571 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
7572 \mod_assign\event\workflow_state_updated::create_from_user($this, $user, $state)->trigger();
7579 * Set the marking allocation for multiple users
7581 * @return void
7583 protected function process_set_batch_marking_allocation() {
7584 global $CFG, $DB;
7586 // Include batch marking allocation form.
7587 require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');
7589 $formparams = array(
7590 'userscount' => 0, // This form is never re-displayed, so we don't need to
7591 'usershtml' => '' // initialise these parameters with real information.
7594 list($sort, $params) = users_order_by_sql();
7595 $markers = get_users_by_capability($this->get_context(), 'mod/assign:grade', '', $sort);
7596 $markerlist = array();
7597 foreach ($markers as $marker) {
7598 $markerlist[$marker->id] = fullname($marker);
7601 $formparams['markers'] = $markerlist;
7603 $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
7605 if ($mform->is_cancelled()) {
7606 return true;
7609 if ($formdata = $mform->get_data()) {
7610 $useridlist = explode(',', $formdata->selectedusers);
7611 $marker = $DB->get_record('user', array('id' => $formdata->allocatedmarker), '*', MUST_EXIST);
7613 foreach ($useridlist as $userid) {
7614 $flags = $this->get_user_flags($userid, true);
7615 if ($flags->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW ||
7616 $flags->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW ||
7617 $flags->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE ||
7618 $flags->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
7620 continue; // Allocated marker can only be changed in certain workflow states.
7623 $flags->allocatedmarker = $marker->id;
7625 if ($this->update_user_flags($flags)) {
7626 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
7627 \mod_assign\event\marker_updated::create_from_marker($this, $user, $marker)->trigger();
7635 * Prevent student updates to this submission.
7636 * Uses url parameter userid.
7638 * @param int $userid
7639 * @return void
7641 protected function process_lock_submission($userid = 0) {
7643 require_sesskey();
7645 if (!$userid) {
7646 $userid = required_param('userid', PARAM_INT);
7649 return $this->lock_submission($userid);
7653 * Unlock the student submission.
7655 * @param int $userid
7656 * @return bool
7658 public function unlock_submission($userid) {
7659 global $USER, $DB;
7661 // Need grade permission.
7662 require_capability('mod/assign:grade', $this->context);
7664 // Give each submission plugin a chance to process the unlocking.
7665 $plugins = $this->get_submission_plugins();
7666 $submission = $this->get_user_submission($userid, false);
7668 $flags = $this->get_user_flags($userid, true);
7669 $flags->locked = 0;
7670 $this->update_user_flags($flags);
7672 foreach ($plugins as $plugin) {
7673 if ($plugin->is_enabled() && $plugin->is_visible()) {
7674 $plugin->unlock($submission, $flags);
7678 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
7679 \mod_assign\event\submission_unlocked::create_from_user($this, $user)->trigger();
7680 return true;
7684 * Unlock the student submission.
7685 * Uses url parameter userid.
7687 * @param int $userid
7688 * @return bool
7690 protected function process_unlock_submission($userid = 0) {
7692 require_sesskey();
7694 if (!$userid) {
7695 $userid = required_param('userid', PARAM_INT);
7698 return $this->unlock_submission($userid);
7702 * Apply a grade from a grading form to a user (may be called multiple times for a group submission).
7704 * @param stdClass $formdata - the data from the form
7705 * @param int $userid - the user to apply the grade to
7706 * @param int $attemptnumber - The attempt number to apply the grade to.
7707 * @return void
7709 protected function apply_grade_to_user($formdata, $userid, $attemptnumber) {
7710 global $USER, $CFG, $DB;
7712 $grade = $this->get_user_grade($userid, true, $attemptnumber);
7713 $originalgrade = $grade->grade;
7714 $gradingdisabled = $this->grading_disabled($userid);
7715 $gradinginstance = $this->get_grading_instance($userid, $grade, $gradingdisabled);
7716 if (!$gradingdisabled) {
7717 if ($gradinginstance) {
7718 $grade->grade = $gradinginstance->submit_and_get_grade($formdata->advancedgrading,
7719 $grade->id);
7720 } else {
7721 // Handle the case when grade is set to No Grade.
7722 if (isset($formdata->grade)) {
7723 $grade->grade = grade_floatval(unformat_float($formdata->grade));
7726 if (isset($formdata->workflowstate) || isset($formdata->allocatedmarker)) {
7727 $flags = $this->get_user_flags($userid, true);
7728 $oldworkflowstate = $flags->workflowstate;
7729 $flags->workflowstate = isset($formdata->workflowstate) ? $formdata->workflowstate : $flags->workflowstate;
7730 $flags->allocatedmarker = isset($formdata->allocatedmarker) ? $formdata->allocatedmarker : $flags->allocatedmarker;
7731 if ($this->update_user_flags($flags) &&
7732 isset($formdata->workflowstate) &&
7733 $formdata->workflowstate !== $oldworkflowstate) {
7734 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
7735 \mod_assign\event\workflow_state_updated::create_from_user($this, $user, $formdata->workflowstate)->trigger();
7739 $grade->grader= $USER->id;
7741 $adminconfig = $this->get_admin_config();
7742 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
7744 $feedbackmodified = false;
7746 // Call save in plugins.
7747 foreach ($this->feedbackplugins as $plugin) {
7748 if ($plugin->is_enabled() && $plugin->is_visible()) {
7749 $gradingmodified = $plugin->is_feedback_modified($grade, $formdata);
7750 if ($gradingmodified) {
7751 if (!$plugin->save($grade, $formdata)) {
7752 $result = false;
7753 print_error($plugin->get_error());
7755 // If $feedbackmodified is true, keep it true.
7756 $feedbackmodified = $feedbackmodified || $gradingmodified;
7758 if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
7759 // This is the feedback plugin chose to push comments to the gradebook.
7760 $grade->feedbacktext = $plugin->text_for_gradebook($grade);
7761 $grade->feedbackformat = $plugin->format_for_gradebook($grade);
7766 // We do not want to update the timemodified if no grade was added.
7767 if (!empty($formdata->addattempt) ||
7768 ($originalgrade !== null && $originalgrade != -1) ||
7769 ($grade->grade !== null && $grade->grade != -1) ||
7770 $feedbackmodified) {
7771 $this->update_grade($grade, !empty($formdata->addattempt));
7773 // Note the default if not provided for this option is true (e.g. webservices).
7774 // This is for backwards compatibility.
7775 if (!isset($formdata->sendstudentnotifications) || $formdata->sendstudentnotifications) {
7776 $this->notify_grade_modified($grade, true);
7782 * Save outcomes submitted from grading form.
7784 * @param int $userid
7785 * @param stdClass $formdata
7786 * @param int $sourceuserid The user ID under which the outcome data is accessible. This is relevant
7787 * for an outcome set to a user but applied to an entire group.
7789 protected function process_outcomes($userid, $formdata, $sourceuserid = null) {
7790 global $CFG, $USER;
7792 if (empty($CFG->enableoutcomes)) {
7793 return;
7795 if ($this->grading_disabled($userid)) {
7796 return;
7799 require_once($CFG->libdir.'/gradelib.php');
7801 $data = array();
7802 $gradinginfo = grade_get_grades($this->get_course()->id,
7803 'mod',
7804 'assign',
7805 $this->get_instance()->id,
7806 $userid);
7808 if (!empty($gradinginfo->outcomes)) {
7809 foreach ($gradinginfo->outcomes as $index => $oldoutcome) {
7810 $name = 'outcome_'.$index;
7811 $sourceuserid = $sourceuserid !== null ? $sourceuserid : $userid;
7812 if (isset($formdata->{$name}[$sourceuserid]) &&
7813 $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$sourceuserid]) {
7814 $data[$index] = $formdata->{$name}[$sourceuserid];
7818 if (count($data) > 0) {
7819 grade_update_outcomes('mod/assign',
7820 $this->course->id,
7821 'mod',
7822 'assign',
7823 $this->get_instance()->id,
7824 $userid,
7825 $data);
7830 * If the requirements are met - reopen the submission for another attempt.
7831 * Only call this function when grading the latest attempt.
7833 * @param int $userid The userid.
7834 * @param stdClass $submission The submission (may be a group submission).
7835 * @param bool $addattempt - True if the "allow another attempt" checkbox was checked.
7836 * @return bool - true if another attempt was added.
7838 protected function reopen_submission_if_required($userid, $submission, $addattempt) {
7839 $instance = $this->get_instance();
7840 $maxattemptsreached = !empty($submission) &&
7841 $submission->attemptnumber >= ($instance->maxattempts - 1) &&
7842 $instance->maxattempts != ASSIGN_UNLIMITED_ATTEMPTS;
7843 $shouldreopen = false;
7844 if ($instance->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS) {
7845 // Check the gradetopass from the gradebook.
7846 $gradeitem = $this->get_grade_item();
7847 if ($gradeitem) {
7848 $gradegrade = grade_grade::fetch(array('userid' => $userid, 'itemid' => $gradeitem->id));
7850 // Do not reopen if is_passed returns null, e.g. if there is no pass criterion set.
7851 if ($gradegrade && ($gradegrade->is_passed() === false)) {
7852 $shouldreopen = true;
7856 if ($instance->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL &&
7857 !empty($addattempt)) {
7858 $shouldreopen = true;
7860 if ($shouldreopen && !$maxattemptsreached) {
7861 $this->add_attempt($userid);
7862 return true;
7864 return false;
7868 * Save grade update.
7870 * @param int $userid
7871 * @param stdClass $data
7872 * @return bool - was the grade saved
7874 public function save_grade($userid, $data) {
7876 // Need grade permission.
7877 require_capability('mod/assign:grade', $this->context);
7879 $instance = $this->get_instance();
7880 $submission = null;
7881 if ($instance->teamsubmission) {
7882 $submission = $this->get_group_submission($userid, 0, false, $data->attemptnumber);
7883 } else {
7884 $submission = $this->get_user_submission($userid, false, $data->attemptnumber);
7886 if ($instance->teamsubmission && !empty($data->applytoall)) {
7887 $groupid = 0;
7888 if ($this->get_submission_group($userid)) {
7889 $group = $this->get_submission_group($userid);
7890 if ($group) {
7891 $groupid = $group->id;
7894 $members = $this->get_submission_group_members($groupid, true, $this->show_only_active_users());
7895 foreach ($members as $member) {
7896 // User may exist in multple groups (which should put them in the default group).
7897 $this->apply_grade_to_user($data, $member->id, $data->attemptnumber);
7898 $this->process_outcomes($member->id, $data, $userid);
7900 } else {
7901 $this->apply_grade_to_user($data, $userid, $data->attemptnumber);
7903 $this->process_outcomes($userid, $data);
7906 return true;
7910 * Save grade.
7912 * @param moodleform $mform
7913 * @return bool - was the grade saved
7915 protected function process_save_grade(&$mform) {
7916 global $CFG, $SESSION;
7917 // Include grade form.
7918 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
7920 require_sesskey();
7922 $instance = $this->get_instance();
7923 $rownum = required_param('rownum', PARAM_INT);
7924 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
7925 $useridlistid = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
7926 $userid = optional_param('userid', 0, PARAM_INT);
7927 if (!$userid) {
7928 if (empty($SESSION->mod_assign_useridlist[$this->get_useridlist_key($useridlistid)])) {
7929 // If the userid list is not stored we must not save, as it is possible that the user in a
7930 // given row position may not be the same now as when the grading page was generated.
7931 $url = new moodle_url('/mod/assign/view.php', array('id' => $this->get_course_module()->id));
7932 throw new moodle_exception('useridlistnotcached', 'mod_assign', $url);
7934 $useridlist = $SESSION->mod_assign_useridlist[$this->get_useridlist_key($useridlistid)];
7935 } else {
7936 $useridlist = array($userid);
7937 $rownum = 0;
7940 $last = false;
7941 $userid = $useridlist[$rownum];
7942 if ($rownum == count($useridlist) - 1) {
7943 $last = true;
7946 $data = new stdClass();
7948 $gradeformparams = array('rownum' => $rownum,
7949 'useridlistid' => $useridlistid,
7950 'last' => $last,
7951 'attemptnumber' => $attemptnumber,
7952 'userid' => $userid);
7953 $mform = new mod_assign_grade_form(null,
7954 array($this, $data, $gradeformparams),
7955 'post',
7957 array('class'=>'gradeform'));
7959 if ($formdata = $mform->get_data()) {
7960 return $this->save_grade($userid, $formdata);
7961 } else {
7962 return false;
7967 * This function is a static wrapper around can_upgrade.
7969 * @param string $type The plugin type
7970 * @param int $version The plugin version
7971 * @return bool
7973 public static function can_upgrade_assignment($type, $version) {
7974 $assignment = new assign(null, null, null);
7975 return $assignment->can_upgrade($type, $version);
7979 * This function returns true if it can upgrade an assignment from the 2.2 module.
7981 * @param string $type The plugin type
7982 * @param int $version The plugin version
7983 * @return bool
7985 public function can_upgrade($type, $version) {
7986 if ($type == 'offline' && $version >= 2011112900) {
7987 return true;
7989 foreach ($this->submissionplugins as $plugin) {
7990 if ($plugin->can_upgrade($type, $version)) {
7991 return true;
7994 foreach ($this->feedbackplugins as $plugin) {
7995 if ($plugin->can_upgrade($type, $version)) {
7996 return true;
7999 return false;
8003 * Copy all the files from the old assignment files area to the new one.
8004 * This is used by the plugin upgrade code.
8006 * @param int $oldcontextid The old assignment context id
8007 * @param int $oldcomponent The old assignment component ('assignment')
8008 * @param int $oldfilearea The old assignment filearea ('submissions')
8009 * @param int $olditemid The old submissionid (can be null e.g. intro)
8010 * @param int $newcontextid The new assignment context id
8011 * @param int $newcomponent The new assignment component ('assignment')
8012 * @param int $newfilearea The new assignment filearea ('submissions')
8013 * @param int $newitemid The new submissionid (can be null e.g. intro)
8014 * @return int The number of files copied
8016 public function copy_area_files_for_upgrade($oldcontextid,
8017 $oldcomponent,
8018 $oldfilearea,
8019 $olditemid,
8020 $newcontextid,
8021 $newcomponent,
8022 $newfilearea,
8023 $newitemid) {
8024 // Note, this code is based on some code in filestorage - but that code
8025 // deleted the old files (which we don't want).
8026 $count = 0;
8028 $fs = get_file_storage();
8030 $oldfiles = $fs->get_area_files($oldcontextid,
8031 $oldcomponent,
8032 $oldfilearea,
8033 $olditemid,
8034 'id',
8035 false);
8036 foreach ($oldfiles as $oldfile) {
8037 $filerecord = new stdClass();
8038 $filerecord->contextid = $newcontextid;
8039 $filerecord->component = $newcomponent;
8040 $filerecord->filearea = $newfilearea;
8041 $filerecord->itemid = $newitemid;
8042 $fs->create_file_from_storedfile($filerecord, $oldfile);
8043 $count += 1;
8046 return $count;
8050 * Add a new attempt for each user in the list - but reopen each group assignment
8051 * at most 1 time.
8053 * @param array $useridlist Array of userids to reopen.
8054 * @return bool
8056 protected function process_add_attempt_group($useridlist) {
8057 $groupsprocessed = array();
8058 $result = true;
8060 foreach ($useridlist as $userid) {
8061 $groupid = 0;
8062 $group = $this->get_submission_group($userid);
8063 if ($group) {
8064 $groupid = $group->id;
8067 if (empty($groupsprocessed[$groupid])) {
8068 $result = $this->process_add_attempt($userid) && $result;
8069 $groupsprocessed[$groupid] = true;
8072 return $result;
8076 * Check for a sess key and then call add_attempt.
8078 * @param int $userid int The user to add the attempt for
8079 * @return bool - true if successful.
8081 protected function process_add_attempt($userid) {
8082 require_sesskey();
8084 return $this->add_attempt($userid);
8088 * Add a new attempt for a user.
8090 * @param int $userid int The user to add the attempt for
8091 * @return bool - true if successful.
8093 protected function add_attempt($userid) {
8094 require_capability('mod/assign:grade', $this->context);
8096 if ($this->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_NONE) {
8097 return false;
8100 if ($this->get_instance()->teamsubmission) {
8101 $oldsubmission = $this->get_group_submission($userid, 0, false);
8102 } else {
8103 $oldsubmission = $this->get_user_submission($userid, false);
8106 if (!$oldsubmission) {
8107 return false;
8110 // No more than max attempts allowed.
8111 if ($this->get_instance()->maxattempts != ASSIGN_UNLIMITED_ATTEMPTS &&
8112 $oldsubmission->attemptnumber >= ($this->get_instance()->maxattempts - 1)) {
8113 return false;
8116 // Create the new submission record for the group/user.
8117 if ($this->get_instance()->teamsubmission) {
8118 $newsubmission = $this->get_group_submission($userid, 0, true, $oldsubmission->attemptnumber + 1);
8119 } else {
8120 $newsubmission = $this->get_user_submission($userid, true, $oldsubmission->attemptnumber + 1);
8123 // Set the status of the new attempt to reopened.
8124 $newsubmission->status = ASSIGN_SUBMISSION_STATUS_REOPENED;
8126 // Give each submission plugin a chance to process the add_attempt.
8127 $plugins = $this->get_submission_plugins();
8128 foreach ($plugins as $plugin) {
8129 if ($plugin->is_enabled() && $plugin->is_visible()) {
8130 $plugin->add_attempt($oldsubmission, $newsubmission);
8134 $this->update_submission($newsubmission, $userid, false, $this->get_instance()->teamsubmission);
8135 $flags = $this->get_user_flags($userid, false);
8136 if (isset($flags->locked) && $flags->locked) { // May not exist.
8137 $this->process_unlock_submission($userid);
8139 return true;
8143 * Get an upto date list of user grades and feedback for the gradebook.
8145 * @param int $userid int or 0 for all users
8146 * @return array of grade data formated for the gradebook api
8147 * The data required by the gradebook api is userid,
8148 * rawgrade,
8149 * feedback,
8150 * feedbackformat,
8151 * usermodified,
8152 * dategraded,
8153 * datesubmitted
8155 public function get_user_grades_for_gradebook($userid) {
8156 global $DB, $CFG;
8157 $grades = array();
8158 $assignmentid = $this->get_instance()->id;
8160 $adminconfig = $this->get_admin_config();
8161 $gradebookpluginname = $adminconfig->feedback_plugin_for_gradebook;
8162 $gradebookplugin = null;
8164 // Find the gradebook plugin.
8165 foreach ($this->feedbackplugins as $plugin) {
8166 if ($plugin->is_enabled() && $plugin->is_visible()) {
8167 if (('assignfeedback_' . $plugin->get_type()) == $gradebookpluginname) {
8168 $gradebookplugin = $plugin;
8172 if ($userid) {
8173 $where = ' WHERE u.id = :userid ';
8174 } else {
8175 $where = ' WHERE u.id != :userid ';
8178 // When the gradebook asks us for grades - only return the last attempt for each user.
8179 $params = array('assignid1'=>$assignmentid,
8180 'assignid2'=>$assignmentid,
8181 'userid'=>$userid);
8182 $graderesults = $DB->get_recordset_sql('SELECT
8183 u.id as userid,
8184 s.timemodified as datesubmitted,
8185 g.grade as rawgrade,
8186 g.timemodified as dategraded,
8187 g.grader as usermodified
8188 FROM {user} u
8189 LEFT JOIN {assign_submission} s
8190 ON u.id = s.userid and s.assignment = :assignid1 AND
8191 s.latest = 1
8192 JOIN {assign_grades} g
8193 ON u.id = g.userid and g.assignment = :assignid2 AND
8194 g.attemptnumber = s.attemptnumber' .
8195 $where, $params);
8197 foreach ($graderesults as $result) {
8198 $gradingstatus = $this->get_grading_status($result->userid);
8199 if (!$this->get_instance()->markingworkflow || $gradingstatus == ASSIGN_MARKING_WORKFLOW_STATE_RELEASED) {
8200 $gradebookgrade = clone $result;
8201 // Now get the feedback.
8202 if ($gradebookplugin) {
8203 $grade = $this->get_user_grade($result->userid, false);
8204 if ($grade) {
8205 $gradebookgrade->feedback = $gradebookplugin->text_for_gradebook($grade);
8206 $gradebookgrade->feedbackformat = $gradebookplugin->format_for_gradebook($grade);
8209 $grades[$gradebookgrade->userid] = $gradebookgrade;
8213 $graderesults->close();
8214 return $grades;
8218 * Call the static version of this function
8220 * @param int $userid The userid to lookup
8221 * @return int The unique id
8223 public function get_uniqueid_for_user($userid) {
8224 return self::get_uniqueid_for_user_static($this->get_instance()->id, $userid);
8228 * Foreach participant in the course - assign them a random id.
8230 * @param int $assignid The assignid to lookup
8232 public static function allocate_unique_ids($assignid) {
8233 global $DB;
8235 $cm = get_coursemodule_from_instance('assign', $assignid, 0, false, MUST_EXIST);
8236 $context = context_module::instance($cm->id);
8238 $currentgroup = groups_get_activity_group($cm, true);
8239 $users = get_enrolled_users($context, "mod/assign:submit", $currentgroup, 'u.id');
8241 // Shuffle the users.
8242 shuffle($users);
8244 foreach ($users as $user) {
8245 $record = $DB->get_record('assign_user_mapping',
8246 array('assignment'=>$assignid, 'userid'=>$user->id),
8247 'id');
8248 if (!$record) {
8249 $record = new stdClass();
8250 $record->assignment = $assignid;
8251 $record->userid = $user->id;
8252 $DB->insert_record('assign_user_mapping', $record);
8258 * Lookup this user id and return the unique id for this assignment.
8260 * @param int $assignid The assignment id
8261 * @param int $userid The userid to lookup
8262 * @return int The unique id
8264 public static function get_uniqueid_for_user_static($assignid, $userid) {
8265 global $DB;
8267 // Search for a record.
8268 $params = array('assignment'=>$assignid, 'userid'=>$userid);
8269 if ($record = $DB->get_record('assign_user_mapping', $params, 'id')) {
8270 return $record->id;
8273 // Be a little smart about this - there is no record for the current user.
8274 // We should ensure any unallocated ids for the current participant
8275 // list are distrubited randomly.
8276 self::allocate_unique_ids($assignid);
8278 // Retry the search for a record.
8279 if ($record = $DB->get_record('assign_user_mapping', $params, 'id')) {
8280 return $record->id;
8283 // The requested user must not be a participant. Add a record anyway.
8284 $record = new stdClass();
8285 $record->assignment = $assignid;
8286 $record->userid = $userid;
8288 return $DB->insert_record('assign_user_mapping', $record);
8292 * Call the static version of this function.
8294 * @param int $uniqueid The uniqueid to lookup
8295 * @return int The user id or false if they don't exist
8297 public function get_user_id_for_uniqueid($uniqueid) {
8298 return self::get_user_id_for_uniqueid_static($this->get_instance()->id, $uniqueid);
8302 * Lookup this unique id and return the user id for this assignment.
8304 * @param int $assignid The id of the assignment this user mapping is in
8305 * @param int $uniqueid The uniqueid to lookup
8306 * @return int The user id or false if they don't exist
8308 public static function get_user_id_for_uniqueid_static($assignid, $uniqueid) {
8309 global $DB;
8311 // Search for a record.
8312 if ($record = $DB->get_record('assign_user_mapping',
8313 array('assignment'=>$assignid, 'id'=>$uniqueid),
8314 'userid',
8315 IGNORE_MISSING)) {
8316 return $record->userid;
8319 return false;
8323 * Get the list of marking_workflow states the current user has permission to transition a grade to.
8325 * @return array of state => description
8327 public function get_marking_workflow_states_for_current_user() {
8328 if (!empty($this->markingworkflowstates)) {
8329 return $this->markingworkflowstates;
8331 $states = array();
8332 if (has_capability('mod/assign:grade', $this->context)) {
8333 $states[ASSIGN_MARKING_WORKFLOW_STATE_INMARKING] = get_string('markingworkflowstateinmarking', 'assign');
8334 $states[ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW] = get_string('markingworkflowstatereadyforreview', 'assign');
8336 if (has_any_capability(array('mod/assign:reviewgrades',
8337 'mod/assign:managegrades'), $this->context)) {
8338 $states[ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW] = get_string('markingworkflowstateinreview', 'assign');
8339 $states[ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE] = get_string('markingworkflowstatereadyforrelease', 'assign');
8341 if (has_any_capability(array('mod/assign:releasegrades',
8342 'mod/assign:managegrades'), $this->context)) {
8343 $states[ASSIGN_MARKING_WORKFLOW_STATE_RELEASED] = get_string('markingworkflowstatereleased', 'assign');
8345 $this->markingworkflowstates = $states;
8346 return $this->markingworkflowstates;
8350 * Check is only active users in course should be shown.
8352 * @return bool true if only active users should be shown.
8354 public function show_only_active_users() {
8355 global $CFG;
8357 if (is_null($this->showonlyactiveenrol)) {
8358 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
8359 $this->showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
8361 if (!is_null($this->context)) {
8362 $this->showonlyactiveenrol = $this->showonlyactiveenrol ||
8363 !has_capability('moodle/course:viewsuspendedusers', $this->context);
8366 return $this->showonlyactiveenrol;
8370 * Return true is user is active user in course else false
8372 * @param int $userid
8373 * @return bool true is user is active in course.
8375 public function is_active_user($userid) {
8376 return !in_array($userid, get_suspended_userids($this->context, true));
8380 * Returns true if gradebook feedback plugin is enabled
8382 * @return bool true if gradebook feedback plugin is enabled and visible else false.
8384 public function is_gradebook_feedback_enabled() {
8385 // Get default grade book feedback plugin.
8386 $adminconfig = $this->get_admin_config();
8387 $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;
8388 $gradebookplugin = str_replace('assignfeedback_', '', $gradebookplugin);
8390 // Check if default gradebook feedback is visible and enabled.
8391 $gradebookfeedbackplugin = $this->get_feedback_plugin_by_type($gradebookplugin);
8393 if (empty($gradebookfeedbackplugin)) {
8394 return false;
8397 if ($gradebookfeedbackplugin->is_visible() && $gradebookfeedbackplugin->is_enabled()) {
8398 return true;
8401 // Gradebook feedback plugin is either not visible/enabled.
8402 return false;
8406 * Returns the grading status.
8408 * @param int $userid the user id
8409 * @return string returns the grading status
8411 public function get_grading_status($userid) {
8412 if ($this->get_instance()->markingworkflow) {
8413 $flags = $this->get_user_flags($userid, false);
8414 if (!empty($flags->workflowstate)) {
8415 return $flags->workflowstate;
8417 return ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
8418 } else {
8419 $attemptnumber = optional_param('attemptnumber', -1, PARAM_INT);
8420 $grade = $this->get_user_grade($userid, false, $attemptnumber);
8422 if (!empty($grade) && $grade->grade !== null && $grade->grade >= 0) {
8423 return ASSIGN_GRADING_STATUS_GRADED;
8424 } else {
8425 return ASSIGN_GRADING_STATUS_NOT_GRADED;
8431 * The id used to uniquily identify the cache for this instance of the assign object.
8433 * @return string
8435 public function get_useridlist_key_id() {
8436 return $this->useridlistid;
8440 * Generates the key that should be used for an entry in the useridlist cache.
8442 * @param string $id Generate a key for this instance (optional)
8443 * @return string The key for the id, or new entry if no $id is passed.
8445 public function get_useridlist_key($id = null) {
8446 if ($id === null) {
8447 $id = $this->get_useridlist_key_id();
8449 return $this->get_course_module()->id . '_' . $id;
8453 * Updates and creates the completion records in mdl_course_modules_completion.
8455 * @param int $teamsubmission value of 0 or 1 to indicate whether this is a group activity
8456 * @param int $requireallteammemberssubmit value of 0 or 1 to indicate whether all group members must click Submit
8457 * @param obj $submission the submission
8458 * @param int $userid the user id
8459 * @param int $complete
8460 * @param obj $completion
8462 * @return null
8464 protected function update_activity_completion_records($teamsubmission,
8465 $requireallteammemberssubmit,
8466 $submission,
8467 $userid,
8468 $complete,
8469 $completion) {
8471 if (($teamsubmission && $submission->groupid > 0 && !$requireallteammemberssubmit) ||
8472 ($teamsubmission && $submission->groupid > 0 && $requireallteammemberssubmit &&
8473 $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
8475 $members = groups_get_members($submission->groupid);
8477 foreach ($members as $member) {
8478 $completion->update_state($this->get_course_module(), $complete, $member->id);
8480 } else {
8481 $completion->update_state($this->get_course_module(), $complete, $userid);
8484 return;
8488 * Update the module completion status (set it viewed).
8490 * @since Moodle 3.2
8492 public function set_module_viewed() {
8493 $completion = new completion_info($this->get_course());
8494 $completion->set_module_viewed($this->get_course_module());
8499 * Portfolio caller class for mod_assign.
8501 * @package mod_assign
8502 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
8503 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8505 class assign_portfolio_caller extends portfolio_module_caller_base {
8507 /** @var int callback arg - the id of submission we export */
8508 protected $sid;
8510 /** @var string component of the submission files we export*/
8511 protected $component;
8513 /** @var string callback arg - the area of submission files we export */
8514 protected $area;
8516 /** @var int callback arg - the id of file we export */
8517 protected $fileid;
8519 /** @var int callback arg - the cmid of the assignment we export */
8520 protected $cmid;
8522 /** @var string callback arg - the plugintype of the editor we export */
8523 protected $plugin;
8525 /** @var string callback arg - the name of the editor field we export */
8526 protected $editor;
8529 * Callback arg for a single file export.
8531 public static function expected_callbackargs() {
8532 return array(
8533 'cmid' => true,
8534 'sid' => false,
8535 'area' => false,
8536 'component' => false,
8537 'fileid' => false,
8538 'plugin' => false,
8539 'editor' => false,
8544 * The constructor.
8546 * @param array $callbackargs
8548 public function __construct($callbackargs) {
8549 parent::__construct($callbackargs);
8550 $this->cm = get_coursemodule_from_id('assign', $this->cmid, 0, false, MUST_EXIST);
8554 * Load data needed for the portfolio export.
8556 * If the assignment type implements portfolio_load_data(), the processing is delegated
8557 * to it. Otherwise, the caller must provide either fileid (to export single file) or
8558 * submissionid and filearea (to export all data attached to the given submission file area)
8559 * via callback arguments.
8561 * @throws portfolio_caller_exception
8563 public function load_data() {
8565 $context = context_module::instance($this->cmid);
8567 if (empty($this->fileid)) {
8568 if (empty($this->sid) || empty($this->area)) {
8569 throw new portfolio_caller_exception('invalidfileandsubmissionid', 'mod_assign');
8574 // Export either an area of files or a single file (see function for more detail).
8575 // The first arg is an id or null. If it is an id, the rest of the args are ignored.
8576 // If it is null, the rest of the args are used to load a list of files from get_areafiles.
8577 $this->set_file_and_format_data($this->fileid,
8578 $context->id,
8579 $this->component,
8580 $this->area,
8581 $this->sid,
8582 'timemodified',
8583 false);
8588 * Prepares the package up before control is passed to the portfolio plugin.
8590 * @throws portfolio_caller_exception
8591 * @return mixed
8593 public function prepare_package() {
8595 if ($this->plugin && $this->editor) {
8596 $options = portfolio_format_text_options();
8597 $context = context_module::instance($this->cmid);
8598 $options->context = $context;
8600 $plugin = $this->get_submission_plugin();
8602 $text = $plugin->get_editor_text($this->editor, $this->sid);
8603 $format = $plugin->get_editor_format($this->editor, $this->sid);
8605 $html = format_text($text, $format, $options);
8606 $html = portfolio_rewrite_pluginfile_urls($html,
8607 $context->id,
8608 'mod_assign',
8609 $this->area,
8610 $this->sid,
8611 $this->exporter->get('format'));
8613 $exporterclass = $this->exporter->get('formatclass');
8614 if (in_array($exporterclass, array(PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_RICHHTML))) {
8615 if ($files = $this->exporter->get('caller')->get('multifiles')) {
8616 foreach ($files as $file) {
8617 $this->exporter->copy_existing_file($file);
8620 return $this->exporter->write_new_file($html, 'assignment.html', !empty($files));
8621 } else if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
8622 $leapwriter = $this->exporter->get('format')->leap2a_writer();
8623 $entry = new portfolio_format_leap2a_entry($this->area . $this->cmid,
8624 $context->get_context_name(),
8625 'resource',
8626 $html);
8628 $entry->add_category('web', 'resource_type');
8629 $entry->author = $this->user;
8630 $leapwriter->add_entry($entry);
8631 if ($files = $this->exporter->get('caller')->get('multifiles')) {
8632 $leapwriter->link_files($entry, $files, $this->area . $this->cmid . 'file');
8633 foreach ($files as $file) {
8634 $this->exporter->copy_existing_file($file);
8637 return $this->exporter->write_new_file($leapwriter->to_xml(),
8638 $this->exporter->get('format')->manifest_name(),
8639 true);
8640 } else {
8641 debugging('invalid format class: ' . $this->exporter->get('formatclass'));
8646 if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
8647 $leapwriter = $this->exporter->get('format')->leap2a_writer();
8648 $files = array();
8649 if ($this->singlefile) {
8650 $files[] = $this->singlefile;
8651 } else if ($this->multifiles) {
8652 $files = $this->multifiles;
8653 } else {
8654 throw new portfolio_caller_exception('invalidpreparepackagefile',
8655 'portfolio',
8656 $this->get_return_url());
8659 $entryids = array();
8660 foreach ($files as $file) {
8661 $entry = new portfolio_format_leap2a_file($file->get_filename(), $file);
8662 $entry->author = $this->user;
8663 $leapwriter->add_entry($entry);
8664 $this->exporter->copy_existing_file($file);
8665 $entryids[] = $entry->id;
8667 if (count($files) > 1) {
8668 $baseid = 'assign' . $this->cmid . $this->area;
8669 $context = context_module::instance($this->cmid);
8671 // If we have multiple files, they should be grouped together into a folder.
8672 $entry = new portfolio_format_leap2a_entry($baseid . 'group',
8673 $context->get_context_name(),
8674 'selection');
8675 $leapwriter->add_entry($entry);
8676 $leapwriter->make_selection($entry, $entryids, 'Folder');
8678 return $this->exporter->write_new_file($leapwriter->to_xml(),
8679 $this->exporter->get('format')->manifest_name(),
8680 true);
8682 return $this->prepare_package_file();
8686 * Fetch the plugin by its type.
8688 * @return assign_submission_plugin
8690 protected function get_submission_plugin() {
8691 global $CFG;
8692 if (!$this->plugin || !$this->cmid) {
8693 return null;
8696 require_once($CFG->dirroot . '/mod/assign/locallib.php');
8698 $context = context_module::instance($this->cmid);
8700 $assignment = new assign($context, null, null);
8701 return $assignment->get_submission_plugin_by_type($this->plugin);
8705 * Calculate a sha1 has of either a single file or a list
8706 * of files based on the data set by load_data.
8708 * @return string
8710 public function get_sha1() {
8712 if ($this->plugin && $this->editor) {
8713 $plugin = $this->get_submission_plugin();
8714 $options = portfolio_format_text_options();
8715 $options->context = context_module::instance($this->cmid);
8717 $text = format_text($plugin->get_editor_text($this->editor, $this->sid),
8718 $plugin->get_editor_format($this->editor, $this->sid),
8719 $options);
8720 $textsha1 = sha1($text);
8721 $filesha1 = '';
8722 try {
8723 $filesha1 = $this->get_sha1_file();
8724 } catch (portfolio_caller_exception $e) {
8725 // No files.
8727 return sha1($textsha1 . $filesha1);
8729 return $this->get_sha1_file();
8733 * Calculate the time to transfer either a single file or a list
8734 * of files based on the data set by load_data.
8736 * @return int
8738 public function expected_time() {
8739 return $this->expected_time_file();
8743 * Checking the permissions.
8745 * @return bool
8747 public function check_permissions() {
8748 $context = context_module::instance($this->cmid);
8749 return has_capability('mod/assign:exportownsubmission', $context);
8753 * Display a module name.
8755 * @return string
8757 public static function display_name() {
8758 return get_string('modulename', 'assign');
8762 * Return array of formats supported by this portfolio call back.
8764 * @return array
8766 public static function base_supported_formats() {
8767 return array(PORTFOLIO_FORMAT_FILE, PORTFOLIO_FORMAT_LEAP2A);
8772 * Logic to happen when a/some group(s) has/have been deleted in a course.
8774 * @param int $courseid The course ID.
8775 * @param int $groupid The group id if it is known
8776 * @return void
8778 function assign_process_group_deleted_in_course($courseid, $groupid = null) {
8779 global $DB;
8781 $params = array('courseid' => $courseid);
8782 if ($groupid) {
8783 $params['groupid'] = $groupid;
8784 // We just update the group that was deleted.
8785 $sql = "SELECT o.id, o.assignid
8786 FROM {assign_overrides} o
8787 JOIN {assign} assign ON assign.id = o.assignid
8788 WHERE assign.course = :courseid
8789 AND o.groupid = :groupid";
8790 } else {
8791 // No groupid, we update all orphaned group overrides for all assign in course.
8792 $sql = "SELECT o.id, o.assignid
8793 FROM {assign_overrides} o
8794 JOIN {assign} assign ON assign.id = o.assignid
8795 LEFT JOIN {groups} grp ON grp.id = o.groupid
8796 WHERE assign.course = :courseid
8797 AND o.groupid IS NOT NULL
8798 AND grp.id IS NULL";
8800 $records = $DB->get_records_sql_menu($sql, $params);
8801 if (!$records) {
8802 return; // Nothing to do.
8804 $DB->delete_records_list('assign_overrides', 'id', array_keys($records));
8808 * Change the sort order of an override
8810 * @param int $id of the override
8811 * @param string $move direction of move
8812 * @param int $assignid of the assignment
8813 * @return bool success of operation
8815 function move_group_override($id, $move, $assignid) {
8816 global $DB;
8818 // Get the override object.
8819 if (!$override = $DB->get_record('assign_overrides', array('id' => $id), 'id, sortorder')) {
8820 return false;
8822 // Count the number of group overrides.
8823 $overridecountgroup = $DB->count_records('assign_overrides', array('userid' => null, 'assignid' => $assignid));
8825 // Calculate the new sortorder.
8826 if ( ($move == 'up') and ($override->sortorder > 1)) {
8827 $neworder = $override->sortorder - 1;
8828 } else if (($move == 'down') and ($override->sortorder < $overridecountgroup)) {
8829 $neworder = $override->sortorder + 1;
8830 } else {
8831 return false;
8834 // Retrieve the override object that is currently residing in the new position.
8835 $params = array('sortorder' => $neworder, 'assignid' => $assignid);
8836 if ($swapoverride = $DB->get_record('assign_overrides', $params, 'id, sortorder')) {
8838 // Swap the sortorders.
8839 $swapoverride->sortorder = $override->sortorder;
8840 $override->sortorder = $neworder;
8842 // Update the override records.
8843 $DB->update_record('assign_overrides', $override);
8844 $DB->update_record('assign_overrides', $swapoverride);
8847 reorder_group_overrides($assignid);
8848 return true;
8852 * Reorder the overrides starting at the override at the given startorder.
8854 * @param int $assignid of the assigment
8856 function reorder_group_overrides($assignid) {
8857 global $DB;
8859 $i = 1;
8860 if ($overrides = $DB->get_records('assign_overrides', array('userid' => null, 'assignid' => $assignid), 'sortorder ASC')) {
8861 foreach ($overrides as $override) {
8862 $f = new stdClass();
8863 $f->id = $override->id;
8864 $f->sortorder = $i++;
8865 $DB->update_record('assign_overrides', $f);
8867 // Update priorities of group overrides.
8868 $params = [
8869 'modulename' => 'assign',
8870 'instance' => $override->assignid,
8871 'groupid' => $override->groupid
8873 $DB->set_field('event', 'priority', $f->sortorder, $params);