MDL-62772 mod_assign: Show disclosure for all submitters
[moodle.git] / mod / assign / locallib.php
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.
13 //
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
19  *
20  * This class provides all the functionality for the new assign module.
21  *
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
25  */
27 defined('MOODLE_INTERNAL') || die();
29 // Assignment submission statuses.
30 define('ASSIGN_SUBMISSION_STATUS_NEW', 'new');
31 define('ASSIGN_SUBMISSION_STATUS_REOPENED', 'reopened');
32 define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft');
33 define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted');
35 // Search filters for grading page.
36 define('ASSIGN_FILTER_SUBMITTED', 'submitted');
37 define('ASSIGN_FILTER_NOT_SUBMITTED', 'notsubmitted');
38 define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
39 define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');
40 define('ASSIGN_FILTER_GRANTED_EXTENSION', 'granted_extension');
42 // Marker filter for grading page.
43 define('ASSIGN_MARKER_FILTER_NO_MARKER', -1);
45 // Reopen attempt methods.
46 define('ASSIGN_ATTEMPT_REOPEN_METHOD_NONE', 'none');
47 define('ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL', 'manual');
48 define('ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS', 'untilpass');
50 // Special value means allow unlimited attempts.
51 define('ASSIGN_UNLIMITED_ATTEMPTS', -1);
53 // Special value means no grade has been set.
54 define('ASSIGN_GRADE_NOT_SET', -1);
56 // Grading states.
57 define('ASSIGN_GRADING_STATUS_GRADED', 'graded');
58 define('ASSIGN_GRADING_STATUS_NOT_GRADED', 'notgraded');
60 // Marking workflow states.
61 define('ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED', 'notmarked');
62 define('ASSIGN_MARKING_WORKFLOW_STATE_INMARKING', 'inmarking');
63 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW', 'readyforreview');
64 define('ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW', 'inreview');
65 define('ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE', 'readyforrelease');
66 define('ASSIGN_MARKING_WORKFLOW_STATE_RELEASED', 'released');
68 /** ASSIGN_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
69 define("ASSIGN_MAX_EVENT_LENGTH", "432000");
71 // Name of file area for intro attachments.
72 define('ASSIGN_INTROATTACHMENT_FILEAREA', 'introattachment');
74 // Event types.
75 define('ASSIGN_EVENT_TYPE_DUE', 'due');
76 define('ASSIGN_EVENT_TYPE_GRADINGDUE', 'gradingdue');
77 define('ASSIGN_EVENT_TYPE_OPEN', 'open');
78 define('ASSIGN_EVENT_TYPE_CLOSE', 'close');
80 require_once($CFG->libdir . '/accesslib.php');
81 require_once($CFG->libdir . '/formslib.php');
82 require_once($CFG->dirroot . '/repository/lib.php');
83 require_once($CFG->dirroot . '/mod/assign/mod_form.php');
84 require_once($CFG->libdir . '/gradelib.php');
85 require_once($CFG->dirroot . '/grade/grading/lib.php');
86 require_once($CFG->dirroot . '/mod/assign/feedbackplugin.php');
87 require_once($CFG->dirroot . '/mod/assign/submissionplugin.php');
88 require_once($CFG->dirroot . '/mod/assign/renderable.php');
89 require_once($CFG->dirroot . '/mod/assign/gradingtable.php');
90 require_once($CFG->libdir . '/eventslib.php');
91 require_once($CFG->libdir . '/portfolio/caller.php');
93 use \mod_assign\output\grading_app;
95 /**
96  * Standard base class for mod_assign (assignment types).
97  *
98  * @package   mod_assign
99  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
100  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
101  */
102 class assign {
104     /** @var stdClass the assignment record that contains the global settings for this assign instance */
105     private $instance;
107     /** @var grade_item the grade_item record for this assign instance's primary grade item. */
108     private $gradeitem;
110     /** @var context the context of the course module for this assign instance
111      *               (or just the course if we are creating a new one)
112      */
113     private $context;
115     /** @var stdClass the course this assign instance belongs to */
116     private $course;
118     /** @var stdClass the admin config for all assign instances  */
119     private $adminconfig;
121     /** @var assign_renderer the custom renderer for this module */
122     private $output;
124     /** @var cm_info the course module for this assign instance */
125     private $coursemodule;
127     /** @var array cache for things like the coursemodule name or the scale menu -
128      *             only lives for a single request.
129      */
130     private $cache;
132     /** @var array list of the installed submission plugins */
133     private $submissionplugins;
135     /** @var array list of the installed feedback plugins */
136     private $feedbackplugins;
138     /** @var string action to be used to return to this page
139      *              (without repeating any form submissions etc).
140      */
141     private $returnaction = 'view';
143     /** @var array params to be used to return to this page */
144     private $returnparams = array();
146     /** @var string modulename prevents excessive calls to get_string */
147     private static $modulename = null;
149     /** @var string modulenameplural prevents excessive calls to get_string */
150     private static $modulenameplural = null;
152     /** @var array of marking workflow states for the current user */
153     private $markingworkflowstates = null;
155     /** @var bool whether to exclude users with inactive enrolment */
156     private $showonlyactiveenrol = null;
158     /** @var string A key used to identify userlists created by this object. */
159     private $useridlistid = null;
161     /** @var array cached list of participants for this assignment. The cache key will be group, showactive and the context id */
162     private $participants = array();
164     /** @var array cached list of user groups when team submissions are enabled. The cache key will be the user. */
165     private $usersubmissiongroups = array();
167     /** @var array cached list of user groups. The cache key will be the user. */
168     private $usergroups = array();
170     /** @var array cached list of IDs of users who share group membership with the user. The cache key will be the user. */
171     private $sharedgroupmembers = array();
173     /**
174      * @var stdClass The most recent team submission. Used to determine additional attempt numbers and whether
175      * to update the gradebook.
176      */
177     private $mostrecentteamsubmission = null;
179     /**
180      * Constructor for the base assign class.
181      *
182      * Note: For $coursemodule you can supply a stdclass if you like, but it
183      * will be more efficient to supply a cm_info object.
184      *
185      * @param mixed $coursemodulecontext context|null the course module context
186      *                                   (or the course context if the coursemodule has not been
187      *                                   created yet).
188      * @param mixed $coursemodule the current course module if it was already loaded,
189      *                            otherwise this class will load one from the context as required.
190      * @param mixed $course the current course  if it was already loaded,
191      *                      otherwise this class will load one from the context as required.
192      */
193     public function __construct($coursemodulecontext, $coursemodule, $course) {
194         global $SESSION;
196         $this->context = $coursemodulecontext;
197         $this->course = $course;
199         // Ensure that $this->coursemodule is a cm_info object (or null).
200         $this->coursemodule = cm_info::create($coursemodule);
202         // Temporary cache only lives for a single request - used to reduce db lookups.
203         $this->cache = array();
205         $this->submissionplugins = $this->load_plugins('assignsubmission');
206         $this->feedbackplugins = $this->load_plugins('assignfeedback');
208         // Extra entropy is required for uniqid() to work on cygwin.
209         $this->useridlistid = clean_param(uniqid('', true), PARAM_ALPHANUM);
211         if (!isset($SESSION->mod_assign_useridlist)) {
212             $SESSION->mod_assign_useridlist = [];
213         }
214     }
216     /**
217      * Set the action and parameters that can be used to return to the current page.
218      *
219      * @param string $action The action for the current page
220      * @param array $params An array of name value pairs which form the parameters
221      *                      to return to the current page.
222      * @return void
223      */
224     public function register_return_link($action, $params) {
225         global $PAGE;
226         $params['action'] = $action;
227         $cm = $this->get_course_module();
228         if ($cm) {
229             $currenturl = new moodle_url('/mod/assign/view.php', array('id' => $cm->id));
230         } else {
231             $currenturl = new moodle_url('/mod/assign/index.php', array('id' => $this->get_course()->id));
232         }
234         $currenturl->params($params);
235         $PAGE->set_url($currenturl);
236     }
238     /**
239      * Return an action that can be used to get back to the current page.
240      *
241      * @return string action
242      */
243     public function get_return_action() {
244         global $PAGE;
246         // Web services don't set a URL, we should avoid debugging when ussing the url object.
247         if (!WS_SERVER) {
248             $params = $PAGE->url->params();
249         }
251         if (!empty($params['action'])) {
252             return $params['action'];
253         }
254         return '';
255     }
257     /**
258      * Based on the current assignment settings should we display the intro.
259      *
260      * @return bool showintro
261      */
262     public function show_intro() {
263         if ($this->get_instance()->alwaysshowdescription ||
264                 time() > $this->get_instance()->allowsubmissionsfromdate) {
265             return true;
266         }
267         return false;
268     }
270     /**
271      * Return a list of parameters that can be used to get back to the current page.
272      *
273      * @return array params
274      */
275     public function get_return_params() {
276         global $PAGE;
278         $params = $PAGE->url->params();
279         unset($params['id']);
280         unset($params['action']);
281         return $params;
282     }
284     /**
285      * Set the submitted form data.
286      *
287      * @param stdClass $data The form data (instance)
288      */
289     public function set_instance(stdClass $data) {
290         $this->instance = $data;
291     }
293     /**
294      * Set the context.
295      *
296      * @param context $context The new context
297      */
298     public function set_context(context $context) {
299         $this->context = $context;
300     }
302     /**
303      * Set the course data.
304      *
305      * @param stdClass $course The course data
306      */
307     public function set_course(stdClass $course) {
308         $this->course = $course;
309     }
311     /**
312      * Get list of feedback plugins installed.
313      *
314      * @return array
315      */
316     public function get_feedback_plugins() {
317         return $this->feedbackplugins;
318     }
320     /**
321      * Get list of submission plugins installed.
322      *
323      * @return array
324      */
325     public function get_submission_plugins() {
326         return $this->submissionplugins;
327     }
329     /**
330      * Is blind marking enabled and reveal identities not set yet?
331      *
332      * @return bool
333      */
334     public function is_blind_marking() {
335         return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
336     }
338     /**
339      * Does an assignment have submission(s) or grade(s) already?
340      *
341      * @return bool
342      */
343     public function has_submissions_or_grades() {
344         $allgrades = $this->count_grades();
345         $allsubmissions = $this->count_submissions();
346         if (($allgrades == 0) && ($allsubmissions == 0)) {
347             return false;
348         }
349         return true;
350     }
352     /**
353      * Get a specific submission plugin by its type.
354      *
355      * @param string $subtype assignsubmission | assignfeedback
356      * @param string $type
357      * @return mixed assign_plugin|null
358      */
359     public function get_plugin_by_type($subtype, $type) {
360         $shortsubtype = substr($subtype, strlen('assign'));
361         $name = $shortsubtype . 'plugins';
362         if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
363             return null;
364         }
365         $pluginlist = $this->$name;
366         foreach ($pluginlist as $plugin) {
367             if ($plugin->get_type() == $type) {
368                 return $plugin;
369             }
370         }
371         return null;
372     }
374     /**
375      * Get a feedback plugin by type.
376      *
377      * @param string $type - The type of plugin e.g comments
378      * @return mixed assign_feedback_plugin|null
379      */
380     public function get_feedback_plugin_by_type($type) {
381         return $this->get_plugin_by_type('assignfeedback', $type);
382     }
384     /**
385      * Get a submission plugin by type.
386      *
387      * @param string $type - The type of plugin e.g comments
388      * @return mixed assign_submission_plugin|null
389      */
390     public function get_submission_plugin_by_type($type) {
391         return $this->get_plugin_by_type('assignsubmission', $type);
392     }
394     /**
395      * Load the plugins from the sub folders under subtype.
396      *
397      * @param string $subtype - either submission or feedback
398      * @return array - The sorted list of plugins
399      */
400     public function load_plugins($subtype) {
401         global $CFG;
402         $result = array();
404         $names = core_component::get_plugin_list($subtype);
406         foreach ($names as $name => $path) {
407             if (file_exists($path . '/locallib.php')) {
408                 require_once($path . '/locallib.php');
410                 $shortsubtype = substr($subtype, strlen('assign'));
411                 $pluginclass = 'assign_' . $shortsubtype . '_' . $name;
413                 $plugin = new $pluginclass($this, $name);
415                 if ($plugin instanceof assign_plugin) {
416                     $idx = $plugin->get_sort_order();
417                     while (array_key_exists($idx, $result)) {
418                         $idx +=1;
419                     }
420                     $result[$idx] = $plugin;
421                 }
422             }
423         }
424         ksort($result);
425         return $result;
426     }
428     /**
429      * Display the assignment, used by view.php
430      *
431      * The assignment is displayed differently depending on your role,
432      * the settings for the assignment and the status of the assignment.
433      *
434      * @param string $action The current action if any.
435      * @param array $args Optional arguments to pass to the view (instead of getting them from GET and POST).
436      * @return string - The page output.
437      */
438     public function view($action='', $args = array()) {
439         global $PAGE;
441         $o = '';
442         $mform = null;
443         $notices = array();
444         $nextpageparams = array();
446         if (!empty($this->get_course_module()->id)) {
447             $nextpageparams['id'] = $this->get_course_module()->id;
448         }
450         // Handle form submissions first.
451         if ($action == 'savesubmission') {
452             $action = 'editsubmission';
453             if ($this->process_save_submission($mform, $notices)) {
454                 $action = 'redirect';
455                 $nextpageparams['action'] = 'view';
456             }
457         } else if ($action == 'editprevioussubmission') {
458             $action = 'editsubmission';
459             if ($this->process_copy_previous_attempt($notices)) {
460                 $action = 'redirect';
461                 $nextpageparams['action'] = 'editsubmission';
462             }
463         } else if ($action == 'lock') {
464             $this->process_lock_submission();
465             $action = 'redirect';
466             $nextpageparams['action'] = 'grading';
467         } else if ($action == 'addattempt') {
468             $this->process_add_attempt(required_param('userid', PARAM_INT));
469             $action = 'redirect';
470             $nextpageparams['action'] = 'grading';
471         } else if ($action == 'reverttodraft') {
472             $this->process_revert_to_draft();
473             $action = 'redirect';
474             $nextpageparams['action'] = 'grading';
475         } else if ($action == 'unlock') {
476             $this->process_unlock_submission();
477             $action = 'redirect';
478             $nextpageparams['action'] = 'grading';
479         } else if ($action == 'setbatchmarkingworkflowstate') {
480             $this->process_set_batch_marking_workflow_state();
481             $action = 'redirect';
482             $nextpageparams['action'] = 'grading';
483         } else if ($action == 'setbatchmarkingallocation') {
484             $this->process_set_batch_marking_allocation();
485             $action = 'redirect';
486             $nextpageparams['action'] = 'grading';
487         } else if ($action == 'confirmsubmit') {
488             $action = 'submit';
489             if ($this->process_submit_for_grading($mform, $notices)) {
490                 $action = 'redirect';
491                 $nextpageparams['action'] = 'view';
492             } else if ($notices) {
493                 $action = 'viewsubmitforgradingerror';
494             }
495         } else if ($action == 'submitotherforgrading') {
496             if ($this->process_submit_other_for_grading($mform, $notices)) {
497                 $action = 'redirect';
498                 $nextpageparams['action'] = 'grading';
499             } else {
500                 $action = 'viewsubmitforgradingerror';
501             }
502         } else if ($action == 'gradingbatchoperation') {
503             $action = $this->process_grading_batch_operation($mform);
504             if ($action == 'grading') {
505                 $action = 'redirect';
506                 $nextpageparams['action'] = 'grading';
507             }
508         } else if ($action == 'submitgrade') {
509             if (optional_param('saveandshownext', null, PARAM_RAW)) {
510                 // Save and show next.
511                 $action = 'grade';
512                 if ($this->process_save_grade($mform)) {
513                     $action = 'redirect';
514                     $nextpageparams['action'] = 'grade';
515                     $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
516                     $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
517                 }
518             } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
519                 $action = 'redirect';
520                 $nextpageparams['action'] = 'grade';
521                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) - 1;
522                 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
523             } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
524                 $action = 'redirect';
525                 $nextpageparams['action'] = 'grade';
526                 $nextpageparams['rownum'] = optional_param('rownum', 0, PARAM_INT) + 1;
527                 $nextpageparams['useridlistid'] = optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM);
528             } else if (optional_param('savegrade', null, PARAM_RAW)) {
529                 // Save changes button.
530                 $action = 'grade';
531                 if ($this->process_save_grade($mform)) {
532                     $action = 'redirect';
533                     $nextpageparams['action'] = 'savegradingresult';
534                 }
535             } else {
536                 // Cancel button.
537                 $action = 'redirect';
538                 $nextpageparams['action'] = 'grading';
539             }
540         } else if ($action == 'quickgrade') {
541             $message = $this->process_save_quick_grades();
542             $action = 'quickgradingresult';
543         } else if ($action == 'saveoptions') {
544             $this->process_save_grading_options();
545             $action = 'redirect';
546             $nextpageparams['action'] = 'grading';
547         } else if ($action == 'saveextension') {
548             $action = 'grantextension';
549             if ($this->process_save_extension($mform)) {
550                 $action = 'redirect';
551                 $nextpageparams['action'] = 'grading';
552             }
553         } else if ($action == 'revealidentitiesconfirm') {
554             $this->process_reveal_identities();
555             $action = 'redirect';
556             $nextpageparams['action'] = 'grading';
557         }
559         $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT),
560                               'useridlistid' => optional_param('useridlistid', $this->get_useridlist_key_id(), PARAM_ALPHANUM));
561         $this->register_return_link($action, $returnparams);
563         // Include any page action as part of the body tag CSS id.
564         if (!empty($action)) {
565             $PAGE->set_pagetype('mod-assign-' . $action);
566         }
567         // Now show the right view page.
568         if ($action == 'redirect') {
569             $nextpageurl = new moodle_url('/mod/assign/view.php', $nextpageparams);
570             redirect($nextpageurl);
571             return;
572         } else if ($action == 'savegradingresult') {
573             $message = get_string('gradingchangessaved', 'assign');
574             $o .= $this->view_savegrading_result($message);
575         } else if ($action == 'quickgradingresult') {
576             $mform = null;
577             $o .= $this->view_quickgrading_result($message);
578         } else if ($action == 'gradingpanel') {
579             $o .= $this->view_single_grading_panel($args);
580         } else if ($action == 'grade') {
581             $o .= $this->view_single_grade_page($mform);
582         } else if ($action == 'viewpluginassignfeedback') {
583             $o .= $this->view_plugin_content('assignfeedback');
584         } else if ($action == 'viewpluginassignsubmission') {
585             $o .= $this->view_plugin_content('assignsubmission');
586         } else if ($action == 'editsubmission') {
587             $o .= $this->view_edit_submission_page($mform, $notices);
588         } else if ($action == 'grader') {
589             $o .= $this->view_grader();
590         } else if ($action == 'grading') {
591             $o .= $this->view_grading_page();
592         } else if ($action == 'downloadall') {
593             $o .= $this->download_submissions();
594         } else if ($action == 'submit') {
595             $o .= $this->check_submit_for_grading($mform);
596         } else if ($action == 'grantextension') {
597             $o .= $this->view_grant_extension($mform);
598         } else if ($action == 'revealidentities') {
599             $o .= $this->view_reveal_identities_confirm($mform);
600         } else if ($action == 'plugingradingbatchoperation') {
601             $o .= $this->view_plugin_grading_batch_operation($mform);
602         } else if ($action == 'viewpluginpage') {
603              $o .= $this->view_plugin_page();
604         } else if ($action == 'viewcourseindex') {
605              $o .= $this->view_course_index();
606         } else if ($action == 'viewbatchsetmarkingworkflowstate') {
607              $o .= $this->view_batch_set_workflow_state($mform);
608         } else if ($action == 'viewbatchmarkingallocation') {
609             $o .= $this->view_batch_markingallocation($mform);
610         } else if ($action == 'viewsubmitforgradingerror') {
611             $o .= $this->view_error_page(get_string('submitforgrading', 'assign'), $notices);
612         } else if ($action == 'fixrescalednullgrades') {
613             $o .= $this->view_fix_rescaled_null_grades();
614         } else {
615             $o .= $this->view_submission_page();
616         }
618         return $o;
619     }
621     /**
622      * Add this instance to the database.
623      *
624      * @param stdClass $formdata The data submitted from the form
625      * @param bool $callplugins This is used to skip the plugin code
626      *             when upgrading an old assignment to a new one (the plugins get called manually)
627      * @return mixed false if an error occurs or the int id of the new instance
628      */
629     public function add_instance(stdClass $formdata, $callplugins) {
630         global $DB;
631         $adminconfig = $this->get_admin_config();
633         $err = '';
635         // Add the database record.
636         $update = new stdClass();
637         $update->name = $formdata->name;
638         $update->timemodified = time();
639         $update->timecreated = time();
640         $update->course = $formdata->course;
641         $update->courseid = $formdata->course;
642         $update->intro = $formdata->intro;
643         $update->introformat = $formdata->introformat;
644         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
645         $update->submissiondrafts = $formdata->submissiondrafts;
646         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
647         $update->sendnotifications = $formdata->sendnotifications;
648         $update->sendlatenotifications = $formdata->sendlatenotifications;
649         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
650         if (isset($formdata->sendstudentnotifications)) {
651             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
652         }
653         $update->duedate = $formdata->duedate;
654         $update->cutoffdate = $formdata->cutoffdate;
655         $update->gradingduedate = $formdata->gradingduedate;
656         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
657         $update->grade = $formdata->grade;
658         $update->completionsubmit = !empty($formdata->completionsubmit);
659         $update->teamsubmission = $formdata->teamsubmission;
660         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
661         if (isset($formdata->teamsubmissiongroupingid)) {
662             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
663         }
664         $update->blindmarking = $formdata->blindmarking;
665         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
666         if (!empty($formdata->attemptreopenmethod)) {
667             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
668         }
669         if (!empty($formdata->maxattempts)) {
670             $update->maxattempts = $formdata->maxattempts;
671         }
672         if (isset($formdata->preventsubmissionnotingroup)) {
673             $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
674         }
675         $update->markingworkflow = $formdata->markingworkflow;
676         $update->markingallocation = $formdata->markingallocation;
677         if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
678             $update->markingallocation = 0;
679         }
681         $returnid = $DB->insert_record('assign', $update);
682         $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
683         // Cache the course record.
684         $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);
686         $this->save_intro_draft_files($formdata);
688         if ($callplugins) {
689             // Call save_settings hook for submission plugins.
690             foreach ($this->submissionplugins as $plugin) {
691                 if (!$this->update_plugin_instance($plugin, $formdata)) {
692                     print_error($plugin->get_error());
693                     return false;
694                 }
695             }
696             foreach ($this->feedbackplugins as $plugin) {
697                 if (!$this->update_plugin_instance($plugin, $formdata)) {
698                     print_error($plugin->get_error());
699                     return false;
700                 }
701             }
703             // In the case of upgrades the coursemodule has not been set,
704             // so we need to wait before calling these two.
705             $this->update_calendar($formdata->coursemodule);
706             if (!empty($formdata->completionexpected)) {
707                 \core_completion\api::update_completion_date_event($formdata->coursemodule, 'assign', $this->instance,
708                         $formdata->completionexpected);
709             }
710             $this->update_gradebook(false, $formdata->coursemodule);
712         }
714         $update = new stdClass();
715         $update->id = $this->get_instance()->id;
716         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
717         $DB->update_record('assign', $update);
719         return $returnid;
720     }
722     /**
723      * Delete all grades from the gradebook for this assignment.
724      *
725      * @return bool
726      */
727     protected function delete_grades() {
728         global $CFG;
730         $result = grade_update('mod/assign',
731                                $this->get_course()->id,
732                                'mod',
733                                'assign',
734                                $this->get_instance()->id,
735                                0,
736                                null,
737                                array('deleted'=>1));
738         return $result == GRADE_UPDATE_OK;
739     }
741     /**
742      * Delete this instance from the database.
743      *
744      * @return bool false if an error occurs
745      */
746     public function delete_instance() {
747         global $DB;
748         $result = true;
750         foreach ($this->submissionplugins as $plugin) {
751             if (!$plugin->delete_instance()) {
752                 print_error($plugin->get_error());
753                 $result = false;
754             }
755         }
756         foreach ($this->feedbackplugins as $plugin) {
757             if (!$plugin->delete_instance()) {
758                 print_error($plugin->get_error());
759                 $result = false;
760             }
761         }
763         // Delete files associated with this assignment.
764         $fs = get_file_storage();
765         if (! $fs->delete_area_files($this->context->id) ) {
766             $result = false;
767         }
769         $this->delete_all_overrides();
771         // Delete_records will throw an exception if it fails - so no need for error checking here.
772         $DB->delete_records('assign_submission', array('assignment' => $this->get_instance()->id));
773         $DB->delete_records('assign_grades', array('assignment' => $this->get_instance()->id));
774         $DB->delete_records('assign_plugin_config', array('assignment' => $this->get_instance()->id));
775         $DB->delete_records('assign_user_flags', array('assignment' => $this->get_instance()->id));
776         $DB->delete_records('assign_user_mapping', array('assignment' => $this->get_instance()->id));
778         // Delete items from the gradebook.
779         if (! $this->delete_grades()) {
780             $result = false;
781         }
783         // Delete the instance.
784         $DB->delete_records('assign', array('id'=>$this->get_instance()->id));
786         return $result;
787     }
789     /**
790      * Deletes a assign override from the database and clears any corresponding calendar events
791      *
792      * @param int $overrideid The id of the override being deleted
793      * @return bool true on success
794      */
795     public function delete_override($overrideid) {
796         global $CFG, $DB;
798         require_once($CFG->dirroot . '/calendar/lib.php');
800         $cm = $this->get_course_module();
801         if (empty($cm)) {
802             $instance = $this->get_instance();
803             $cm = get_coursemodule_from_instance('assign', $instance->id, $instance->course);
804         }
806         $override = $DB->get_record('assign_overrides', array('id' => $overrideid), '*', MUST_EXIST);
808         // Delete the events.
809         $conds = array('modulename' => 'assign', 'instance' => $this->get_instance()->id);
810         if (isset($override->userid)) {
811             $conds['userid'] = $override->userid;
812         } else {
813             $conds['groupid'] = $override->groupid;
814         }
815         $events = $DB->get_records('event', $conds);
816         foreach ($events as $event) {
817             $eventold = calendar_event::load($event);
818             $eventold->delete();
819         }
821         $DB->delete_records('assign_overrides', array('id' => $overrideid));
823         // Set the common parameters for one of the events we will be triggering.
824         $params = array(
825             'objectid' => $override->id,
826             'context' => context_module::instance($cm->id),
827             'other' => array(
828                 'assignid' => $override->assignid
829             )
830         );
831         // Determine which override deleted event to fire.
832         if (!empty($override->userid)) {
833             $params['relateduserid'] = $override->userid;
834             $event = \mod_assign\event\user_override_deleted::create($params);
835         } else {
836             $params['other']['groupid'] = $override->groupid;
837             $event = \mod_assign\event\group_override_deleted::create($params);
838         }
840         // Trigger the override deleted event.
841         $event->add_record_snapshot('assign_overrides', $override);
842         $event->trigger();
844         return true;
845     }
847     /**
848      * Deletes all assign overrides from the database and clears any corresponding calendar events
849      */
850     public function delete_all_overrides() {
851         global $DB;
853         $overrides = $DB->get_records('assign_overrides', array('assignid' => $this->get_instance()->id), 'id');
854         foreach ($overrides as $override) {
855             $this->delete_override($override->id);
856         }
857     }
859     /**
860      * Updates the assign properties with override information for a user.
861      *
862      * Algorithm:  For each assign setting, if there is a matching user-specific override,
863      *   then use that otherwise, if there are group-specific overrides, return the most
864      *   lenient combination of them.  If neither applies, leave the assign setting unchanged.
865      *
866      * @param int $userid The userid.
867      */
868     public function update_effective_access($userid) {
870         $override = $this->override_exists($userid);
872         // Merge with assign defaults.
873         $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
874         foreach ($keys as $key) {
875             if (isset($override->{$key})) {
876                 $this->get_instance()->{$key} = $override->{$key};
877             }
878         }
880     }
882     /**
883      * Returns whether an assign has any overrides.
884      *
885      * @return true if any, false if not
886      */
887     public function has_overrides() {
888         global $DB;
890         $override = $DB->record_exists('assign_overrides', array('assignid' => $this->get_instance()->id));
892         if ($override) {
893             return true;
894         }
896         return false;
897     }
899     /**
900      * Returns user override
901      *
902      * Algorithm:  For each assign setting, if there is a matching user-specific override,
903      *   then use that otherwise, if there are group-specific overrides, use the one with the
904      *   lowest sort order. If neither applies, leave the assign setting unchanged.
905      *
906      * @param int $userid The userid.
907      * @return stdClass The override
908      */
909     public function override_exists($userid) {
910         global $DB;
912         // Gets an assoc array containing the keys for defined user overrides only.
913         $getuseroverride = function($userid) use ($DB) {
914             $useroverride = $DB->get_record('assign_overrides', ['assignid' => $this->get_instance()->id, 'userid' => $userid]);
915             return $useroverride ? get_object_vars($useroverride) : [];
916         };
918         // Gets an assoc array containing the keys for defined group overrides only.
919         $getgroupoverride = function($userid) use ($DB) {
920             $groupings = groups_get_user_groups($this->get_instance()->course, $userid);
922             if (empty($groupings[0])) {
923                 return [];
924             }
926             // Select all overrides that apply to the User's groups.
927             list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
928             $sql = "SELECT * FROM {assign_overrides}
929                     WHERE groupid $extra AND assignid = ? ORDER BY sortorder ASC";
930             $params[] = $this->get_instance()->id;
931             $groupoverride = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
933             return $groupoverride ? get_object_vars($groupoverride) : [];
934         };
936         // Later arguments clobber earlier ones with array_merge. The two helper functions
937         // return arrays containing keys for only the defined overrides. So we get the
938         // desired behaviour as per the algorithm.
939         return (object)array_merge(
940             ['duedate' => null, 'cutoffdate' => null, 'allowsubmissionsfromdate' => null],
941             $getgroupoverride($userid),
942             $getuseroverride($userid)
943         );
944     }
946     /**
947      * Check if the given calendar_event is either a user or group override
948      * event.
949      *
950      * @return bool
951      */
952     public function is_override_calendar_event(\calendar_event $event) {
953         global $DB;
955         if (!isset($event->modulename)) {
956             return false;
957         }
959         if ($event->modulename != 'assign') {
960             return false;
961         }
963         if (!isset($event->instance)) {
964             return false;
965         }
967         if (!isset($event->userid) && !isset($event->groupid)) {
968             return false;
969         }
971         $overrideparams = [
972             'assignid' => $event->instance
973         ];
975         if (isset($event->groupid)) {
976             $overrideparams['groupid'] = $event->groupid;
977         } else if (isset($event->userid)) {
978             $overrideparams['userid'] = $event->userid;
979         }
981         if ($DB->get_record('assign_overrides', $overrideparams)) {
982             return true;
983         } else {
984             return false;
985         }
986     }
988     /**
989      * This function calculates the minimum and maximum cutoff values for the timestart of
990      * the given event.
991      *
992      * It will return an array with two values, the first being the minimum cutoff value and
993      * the second being the maximum cutoff value. Either or both values can be null, which
994      * indicates there is no minimum or maximum, respectively.
995      *
996      * If a cutoff is required then the function must return an array containing the cutoff
997      * timestamp and error string to display to the user if the cutoff value is violated.
998      *
999      * A minimum and maximum cutoff return value will look like:
1000      * [
1001      *     [1505704373, 'The due date must be after the sbumission start date'],
1002      *     [1506741172, 'The due date must be before the cutoff date']
1003      * ]
1004      *
1005      * If the event does not have a valid timestart range then [false, false] will
1006      * be returned.
1007      *
1008      * @param calendar_event $event The calendar event to get the time range for
1009      * @return array
1010      */
1011     function get_valid_calendar_event_timestart_range(\calendar_event $event) {
1012         $instance = $this->get_instance();
1013         $submissionsfromdate = $instance->allowsubmissionsfromdate;
1014         $cutoffdate = $instance->cutoffdate;
1015         $duedate = $instance->duedate;
1016         $gradingduedate = $instance->gradingduedate;
1017         $mindate = null;
1018         $maxdate = null;
1020         if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
1021             // This check is in here because due date events are currently
1022             // the only events that can be overridden, so we can save a DB
1023             // query if we don't bother checking other events.
1024             if ($this->is_override_calendar_event($event)) {
1025                 // This is an override event so there is no valid timestart
1026                 // range to set it to.
1027                 return [false, false];
1028             }
1030             if ($submissionsfromdate) {
1031                 $mindate = [
1032                     $submissionsfromdate,
1033                     get_string('duedatevalidation', 'assign'),
1034                 ];
1035             }
1037             if ($cutoffdate) {
1038                 $maxdate = [
1039                     $cutoffdate,
1040                     get_string('cutoffdatevalidation', 'assign'),
1041                 ];
1042             }
1044             if ($gradingduedate) {
1045                 // If we don't have a cutoff date or we've got a grading due date
1046                 // that is earlier than the cutoff then we should use that as the
1047                 // upper limit for the due date.
1048                 if (!$cutoffdate || $gradingduedate < $cutoffdate) {
1049                     $maxdate = [
1050                         $gradingduedate,
1051                         get_string('gradingdueduedatevalidation', 'assign'),
1052                     ];
1053                 }
1054             }
1055         } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1056             if ($duedate) {
1057                 $mindate = [
1058                     $duedate,
1059                     get_string('gradingdueduedatevalidation', 'assign'),
1060                 ];
1061             } else if ($submissionsfromdate) {
1062                 $mindate = [
1063                     $submissionsfromdate,
1064                     get_string('gradingduefromdatevalidation', 'assign'),
1065                 ];
1066             }
1067         }
1069         return [$mindate, $maxdate];
1070     }
1072     /**
1073      * Actual implementation of the reset course functionality, delete all the
1074      * assignment submissions for course $data->courseid.
1075      *
1076      * @param stdClass $data the data submitted from the reset course.
1077      * @return array status array
1078      */
1079     public function reset_userdata($data) {
1080         global $CFG, $DB;
1082         $componentstr = get_string('modulenameplural', 'assign');
1083         $status = array();
1085         $fs = get_file_storage();
1086         if (!empty($data->reset_assign_submissions)) {
1087             // Delete files associated with this assignment.
1088             foreach ($this->submissionplugins as $plugin) {
1089                 $fileareas = array();
1090                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
1091                 $fileareas = $plugin->get_file_areas();
1092                 foreach ($fileareas as $filearea => $notused) {
1093                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
1094                 }
1096                 if (!$plugin->delete_instance()) {
1097                     $status[] = array('component'=>$componentstr,
1098                                       'item'=>get_string('deleteallsubmissions', 'assign'),
1099                                       'error'=>$plugin->get_error());
1100                 }
1101             }
1103             foreach ($this->feedbackplugins as $plugin) {
1104                 $fileareas = array();
1105                 $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
1106                 $fileareas = $plugin->get_file_areas();
1107                 foreach ($fileareas as $filearea => $notused) {
1108                     $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
1109                 }
1111                 if (!$plugin->delete_instance()) {
1112                     $status[] = array('component'=>$componentstr,
1113                                       'item'=>get_string('deleteallsubmissions', 'assign'),
1114                                       'error'=>$plugin->get_error());
1115                 }
1116             }
1118             $assignids = $DB->get_records('assign', array('course' => $data->courseid), '', 'id');
1119             list($sql, $params) = $DB->get_in_or_equal(array_keys($assignids));
1121             $DB->delete_records_select('assign_submission', "assignment $sql", $params);
1122             $DB->delete_records_select('assign_user_flags', "assignment $sql", $params);
1124             $status[] = array('component'=>$componentstr,
1125                               'item'=>get_string('deleteallsubmissions', 'assign'),
1126                               'error'=>false);
1128             if (!empty($data->reset_gradebook_grades)) {
1129                 $DB->delete_records_select('assign_grades', "assignment $sql", $params);
1130                 // Remove all grades from gradebook.
1131                 require_once($CFG->dirroot.'/mod/assign/lib.php');
1132                 assign_reset_gradebook($data->courseid);
1133             }
1135             // Reset revealidentities for assign if blindmarking is enabled.
1136             if ($this->get_instance()->blindmarking) {
1137                 $DB->set_field('assign', 'revealidentities', 0, array('id' => $this->get_instance()->id));
1138             }
1139         }
1141         // Remove user overrides.
1142         if (!empty($data->reset_assign_user_overrides)) {
1143             $DB->delete_records_select('assign_overrides',
1144                 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1145             $status[] = array(
1146                 'component' => $componentstr,
1147                 'item' => get_string('useroverridesdeleted', 'assign'),
1148                 'error' => false);
1149         }
1150         // Remove group overrides.
1151         if (!empty($data->reset_assign_group_overrides)) {
1152             $DB->delete_records_select('assign_overrides',
1153                 'assignid IN (SELECT id FROM {assign} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1154             $status[] = array(
1155                 'component' => $componentstr,
1156                 'item' => get_string('groupoverridesdeleted', 'assign'),
1157                 'error' => false);
1158         }
1160         // Updating dates - shift may be negative too.
1161         if ($data->timeshift) {
1162             $DB->execute("UPDATE {assign_overrides}
1163                          SET allowsubmissionsfromdate = allowsubmissionsfromdate + ?
1164                        WHERE assignid = ? AND allowsubmissionsfromdate <> 0",
1165                 array($data->timeshift, $this->get_instance()->id));
1166             $DB->execute("UPDATE {assign_overrides}
1167                          SET duedate = duedate + ?
1168                        WHERE assignid = ? AND duedate <> 0",
1169                 array($data->timeshift, $this->get_instance()->id));
1170             $DB->execute("UPDATE {assign_overrides}
1171                          SET cutoffdate = cutoffdate + ?
1172                        WHERE assignid =? AND cutoffdate <> 0",
1173                 array($data->timeshift, $this->get_instance()->id));
1175             // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1176             // See MDL-9367.
1177             shift_course_mod_dates('assign',
1178                                     array('duedate', 'allowsubmissionsfromdate', 'cutoffdate'),
1179                                     $data->timeshift,
1180                                     $data->courseid, $this->get_instance()->id);
1181             $status[] = array('component'=>$componentstr,
1182                               'item'=>get_string('datechanged'),
1183                               'error'=>false);
1184         }
1186         return $status;
1187     }
1189     /**
1190      * Update the settings for a single plugin.
1191      *
1192      * @param assign_plugin $plugin The plugin to update
1193      * @param stdClass $formdata The form data
1194      * @return bool false if an error occurs
1195      */
1196     protected function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
1197         if ($plugin->is_visible()) {
1198             $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1199             if (!empty($formdata->$enabledname)) {
1200                 $plugin->enable();
1201                 if (!$plugin->save_settings($formdata)) {
1202                     print_error($plugin->get_error());
1203                     return false;
1204                 }
1205             } else {
1206                 $plugin->disable();
1207             }
1208         }
1209         return true;
1210     }
1212     /**
1213      * Update the gradebook information for this assignment.
1214      *
1215      * @param bool $reset If true, will reset all grades in the gradbook for this assignment
1216      * @param int $coursemoduleid This is required because it might not exist in the database yet
1217      * @return bool
1218      */
1219     public function update_gradebook($reset, $coursemoduleid) {
1220         global $CFG;
1222         require_once($CFG->dirroot.'/mod/assign/lib.php');
1223         $assign = clone $this->get_instance();
1224         $assign->cmidnumber = $coursemoduleid;
1226         // Set assign gradebook feedback plugin status (enabled and visible).
1227         $assign->gradefeedbackenabled = $this->is_gradebook_feedback_enabled();
1229         $param = null;
1230         if ($reset) {
1231             $param = 'reset';
1232         }
1234         return assign_grade_item_update($assign, $param);
1235     }
1237     /**
1238      * Get the marking table page size
1239      *
1240      * @return integer
1241      */
1242     public function get_assign_perpage() {
1243         $perpage = (int) get_user_preferences('assign_perpage', 10);
1244         $adminconfig = $this->get_admin_config();
1245         $maxperpage = -1;
1246         if (isset($adminconfig->maxperpage)) {
1247             $maxperpage = $adminconfig->maxperpage;
1248         }
1249         if (isset($maxperpage) &&
1250             $maxperpage != -1 &&
1251             ($perpage == -1 || $perpage > $maxperpage)) {
1252             $perpage = $maxperpage;
1253         }
1254         return $perpage;
1255     }
1257     /**
1258      * Load and cache the admin config for this module.
1259      *
1260      * @return stdClass the plugin config
1261      */
1262     public function get_admin_config() {
1263         if ($this->adminconfig) {
1264             return $this->adminconfig;
1265         }
1266         $this->adminconfig = get_config('assign');
1267         return $this->adminconfig;
1268     }
1270     /**
1271      * Update the calendar entries for this assignment.
1272      *
1273      * @param int $coursemoduleid - Required to pass this in because it might
1274      *                              not exist in the database yet.
1275      * @return bool
1276      */
1277     public function update_calendar($coursemoduleid) {
1278         global $DB, $CFG;
1279         require_once($CFG->dirroot.'/calendar/lib.php');
1281         // Special case for add_instance as the coursemodule has not been set yet.
1282         $instance = $this->get_instance();
1284         // Start with creating the event.
1285         $event = new stdClass();
1286         $event->modulename  = 'assign';
1287         $event->courseid = $instance->course;
1288         $event->groupid = 0;
1289         $event->userid  = 0;
1290         $event->instance  = $instance->id;
1291         $event->type = CALENDAR_EVENT_TYPE_ACTION;
1293         // Convert the links to pluginfile. It is a bit hacky but at this stage the files
1294         // might not have been saved in the module area yet.
1295         $intro = $instance->intro;
1296         if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
1297             $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
1298         }
1300         // We need to remove the links to files as the calendar is not ready
1301         // to support module events with file areas.
1302         $intro = strip_pluginfile_content($intro);
1303         if ($this->show_intro()) {
1304             $event->description = array(
1305                 'text' => $intro,
1306                 'format' => $instance->introformat
1307             );
1308         } else {
1309             $event->description = array(
1310                 'text' => '',
1311                 'format' => $instance->introformat
1312             );
1313         }
1315         $eventtype = ASSIGN_EVENT_TYPE_DUE;
1316         if ($instance->duedate) {
1317             $event->name = get_string('calendardue', 'assign', $instance->name);
1318             $event->eventtype = $eventtype;
1319             $event->timestart = $instance->duedate;
1320             $event->timesort = $instance->duedate;
1321             $select = "modulename = :modulename
1322                        AND instance = :instance
1323                        AND eventtype = :eventtype
1324                        AND groupid = 0
1325                        AND courseid <> 0";
1326             $params = array('modulename' => 'assign', 'instance' => $instance->id, 'eventtype' => $eventtype);
1327             $event->id = $DB->get_field_select('event', 'id', $select, $params);
1329             // Now process the event.
1330             if ($event->id) {
1331                 $calendarevent = calendar_event::load($event->id);
1332                 $calendarevent->update($event);
1333             } else {
1334                 calendar_event::create($event);
1335             }
1336         } else {
1337             $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1338                 'eventtype' => $eventtype));
1339         }
1341         $eventtype = ASSIGN_EVENT_TYPE_GRADINGDUE;
1342         if ($instance->gradingduedate) {
1343             $event->name = get_string('calendargradingdue', 'assign', $instance->name);
1344             $event->eventtype = $eventtype;
1345             $event->timestart = $instance->gradingduedate;
1346             $event->timesort = $instance->gradingduedate;
1347             $event->id = $DB->get_field('event', 'id', array('modulename' => 'assign',
1348                 'instance' => $instance->id, 'eventtype' => $event->eventtype));
1350             // Now process the event.
1351             if ($event->id) {
1352                 $calendarevent = calendar_event::load($event->id);
1353                 $calendarevent->update($event);
1354             } else {
1355                 calendar_event::create($event);
1356             }
1357         } else {
1358             $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
1359                 'eventtype' => $eventtype));
1360         }
1362         return true;
1363     }
1365     /**
1366      * Update this instance in the database.
1367      *
1368      * @param stdClass $formdata - the data submitted from the form
1369      * @return bool false if an error occurs
1370      */
1371     public function update_instance($formdata) {
1372         global $DB;
1373         $adminconfig = $this->get_admin_config();
1375         $update = new stdClass();
1376         $update->id = $formdata->instance;
1377         $update->name = $formdata->name;
1378         $update->timemodified = time();
1379         $update->course = $formdata->course;
1380         $update->intro = $formdata->intro;
1381         $update->introformat = $formdata->introformat;
1382         $update->alwaysshowdescription = !empty($formdata->alwaysshowdescription);
1383         $update->submissiondrafts = $formdata->submissiondrafts;
1384         $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
1385         $update->sendnotifications = $formdata->sendnotifications;
1386         $update->sendlatenotifications = $formdata->sendlatenotifications;
1387         $update->sendstudentnotifications = $adminconfig->sendstudentnotifications;
1388         if (isset($formdata->sendstudentnotifications)) {
1389             $update->sendstudentnotifications = $formdata->sendstudentnotifications;
1390         }
1391         $update->duedate = $formdata->duedate;
1392         $update->cutoffdate = $formdata->cutoffdate;
1393         $update->gradingduedate = $formdata->gradingduedate;
1394         $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
1395         $update->grade = $formdata->grade;
1396         if (!empty($formdata->completionunlocked)) {
1397             $update->completionsubmit = !empty($formdata->completionsubmit);
1398         }
1399         $update->teamsubmission = $formdata->teamsubmission;
1400         $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
1401         if (isset($formdata->teamsubmissiongroupingid)) {
1402             $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
1403         }
1404         $update->blindmarking = $formdata->blindmarking;
1405         $update->attemptreopenmethod = ASSIGN_ATTEMPT_REOPEN_METHOD_NONE;
1406         if (!empty($formdata->attemptreopenmethod)) {
1407             $update->attemptreopenmethod = $formdata->attemptreopenmethod;
1408         }
1409         if (!empty($formdata->maxattempts)) {
1410             $update->maxattempts = $formdata->maxattempts;
1411         }
1412         if (isset($formdata->preventsubmissionnotingroup)) {
1413             $update->preventsubmissionnotingroup = $formdata->preventsubmissionnotingroup;
1414         }
1415         $update->markingworkflow = $formdata->markingworkflow;
1416         $update->markingallocation = $formdata->markingallocation;
1417         if (empty($update->markingworkflow)) { // If marking workflow is disabled, make sure allocation is disabled.
1418             $update->markingallocation = 0;
1419         }
1421         $result = $DB->update_record('assign', $update);
1422         $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);
1424         $this->save_intro_draft_files($formdata);
1426         // Load the assignment so the plugins have access to it.
1428         // Call save_settings hook for submission plugins.
1429         foreach ($this->submissionplugins as $plugin) {
1430             if (!$this->update_plugin_instance($plugin, $formdata)) {
1431                 print_error($plugin->get_error());
1432                 return false;
1433             }
1434         }
1435         foreach ($this->feedbackplugins as $plugin) {
1436             if (!$this->update_plugin_instance($plugin, $formdata)) {
1437                 print_error($plugin->get_error());
1438                 return false;
1439             }
1440         }
1442         $this->update_calendar($this->get_course_module()->id);
1443         $completionexpected = (!empty($formdata->completionexpected)) ? $formdata->completionexpected : null;
1444         \core_completion\api::update_completion_date_event($this->get_course_module()->id, 'assign', $this->instance,
1445                 $completionexpected);
1446         $this->update_gradebook(false, $this->get_course_module()->id);
1448         $update = new stdClass();
1449         $update->id = $this->get_instance()->id;
1450         $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
1451         $DB->update_record('assign', $update);
1453         return $result;
1454     }
1456     /**
1457      * Save the attachments in the draft areas.
1458      *
1459      * @param stdClass $formdata
1460      */
1461     protected function save_intro_draft_files($formdata) {
1462         if (isset($formdata->introattachments)) {
1463             file_save_draft_area_files($formdata->introattachments, $this->get_context()->id,
1464                                        'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
1465         }
1466     }
1468     /**
1469      * Add elements in grading plugin form.
1470      *
1471      * @param mixed $grade stdClass|null
1472      * @param MoodleQuickForm $mform
1473      * @param stdClass $data
1474      * @param int $userid - The userid we are grading
1475      * @return void
1476      */
1477     protected function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
1478         foreach ($this->feedbackplugins as $plugin) {
1479             if ($plugin->is_enabled() && $plugin->is_visible()) {
1480                 $plugin->get_form_elements_for_user($grade, $mform, $data, $userid);
1481             }
1482         }
1483     }
1487     /**
1488      * Add one plugins settings to edit plugin form.
1489      *
1490      * @param assign_plugin $plugin The plugin to add the settings from
1491      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1492      *                               This form is modified directly (not returned).
1493      * @param array $pluginsenabled A list of form elements to be added to a group.
1494      *                              The new element is added to this array by this function.
1495      * @return void
1496      */
1497     protected function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform, & $pluginsenabled) {
1498         global $CFG;
1499         if ($plugin->is_visible() && !$plugin->is_configurable() && $plugin->is_enabled()) {
1500             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1501             $pluginsenabled[] = $mform->createElement('hidden', $name, 1);
1502             $mform->setType($name, PARAM_BOOL);
1503             $plugin->get_settings($mform);
1504         } else if ($plugin->is_visible() && $plugin->is_configurable()) {
1505             $name = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
1506             $label = $plugin->get_name();
1507             $label .= ' ' . $this->get_renderer()->help_icon('enabled', $plugin->get_subtype() . '_' . $plugin->get_type());
1508             $pluginsenabled[] = $mform->createElement('checkbox', $name, '', $label);
1510             $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
1511             if ($plugin->get_config('enabled') !== false) {
1512                 $default = $plugin->is_enabled();
1513             }
1514             $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);
1516             $plugin->get_settings($mform);
1518         }
1519     }
1521     /**
1522      * Add settings to edit plugin form.
1523      *
1524      * @param MoodleQuickForm $mform The form to add the configuration settings to.
1525      *                               This form is modified directly (not returned).
1526      * @return void
1527      */
1528     public function add_all_plugin_settings(MoodleQuickForm $mform) {
1529         $mform->addElement('header', 'submissiontypes', get_string('submissiontypes', 'assign'));
1531         $submissionpluginsenabled = array();
1532         $group = $mform->addGroup(array(), 'submissionplugins', get_string('submissiontypes', 'assign'), array(' '), false);
1533         foreach ($this->submissionplugins as $plugin) {
1534             $this->add_plugin_settings($plugin, $mform, $submissionpluginsenabled);
1535         }
1536         $group->setElements($submissionpluginsenabled);
1538         $mform->addElement('header', 'feedbacktypes', get_string('feedbacktypes', 'assign'));
1539         $feedbackpluginsenabled = array();
1540         $group = $mform->addGroup(array(), 'feedbackplugins', get_string('feedbacktypes', 'assign'), array(' '), false);
1541         foreach ($this->feedbackplugins as $plugin) {
1542             $this->add_plugin_settings($plugin, $mform, $feedbackpluginsenabled);
1543         }
1544         $group->setElements($feedbackpluginsenabled);
1545         $mform->setExpanded('submissiontypes');
1546     }
1548     /**
1549      * Allow each plugin an opportunity to update the defaultvalues
1550      * passed in to the settings form (needed to set up draft areas for
1551      * editor and filemanager elements)
1552      *
1553      * @param array $defaultvalues
1554      */
1555     public function plugin_data_preprocessing(&$defaultvalues) {
1556         foreach ($this->submissionplugins as $plugin) {
1557             if ($plugin->is_visible()) {
1558                 $plugin->data_preprocessing($defaultvalues);
1559             }
1560         }
1561         foreach ($this->feedbackplugins as $plugin) {
1562             if ($plugin->is_visible()) {
1563                 $plugin->data_preprocessing($defaultvalues);
1564             }
1565         }
1566     }
1568     /**
1569      * Get the name of the current module.
1570      *
1571      * @return string the module name (Assignment)
1572      */
1573     protected function get_module_name() {
1574         if (isset(self::$modulename)) {
1575             return self::$modulename;
1576         }
1577         self::$modulename = get_string('modulename', 'assign');
1578         return self::$modulename;
1579     }
1581     /**
1582      * Get the plural name of the current module.
1583      *
1584      * @return string the module name plural (Assignments)
1585      */
1586     protected function get_module_name_plural() {
1587         if (isset(self::$modulenameplural)) {
1588             return self::$modulenameplural;
1589         }
1590         self::$modulenameplural = get_string('modulenameplural', 'assign');
1591         return self::$modulenameplural;
1592     }
1594     /**
1595      * Has this assignment been constructed from an instance?
1596      *
1597      * @return bool
1598      */
1599     public function has_instance() {
1600         return $this->instance || $this->get_course_module();
1601     }
1603     /**
1604      * Get the settings for the current instance of this assignment
1605      *
1606      * @return stdClass The settings
1607      */
1608     public function get_instance() {
1609         global $DB;
1610         if ($this->instance) {
1611             return $this->instance;
1612         }
1613         if ($this->get_course_module()) {
1614             $params = array('id' => $this->get_course_module()->instance);
1615             $this->instance = $DB->get_record('assign', $params, '*', MUST_EXIST);
1616         }
1617         if (!$this->instance) {
1618             throw new coding_exception('Improper use of the assignment class. ' .
1619                                        'Cannot load the assignment record.');
1620         }
1621         return $this->instance;
1622     }
1624     /**
1625      * Get the primary grade item for this assign instance.
1626      *
1627      * @return grade_item The grade_item record
1628      */
1629     public function get_grade_item() {
1630         if ($this->gradeitem) {
1631             return $this->gradeitem;
1632         }
1633         $instance = $this->get_instance();
1634         $params = array('itemtype' => 'mod',
1635                         'itemmodule' => 'assign',
1636                         'iteminstance' => $instance->id,
1637                         'courseid' => $instance->course,
1638                         'itemnumber' => 0);
1639         $this->gradeitem = grade_item::fetch($params);
1640         if (!$this->gradeitem) {
1641             throw new coding_exception('Improper use of the assignment class. ' .
1642                                        'Cannot load the grade item.');
1643         }
1644         return $this->gradeitem;
1645     }
1647     /**
1648      * Get the context of the current course.
1649      *
1650      * @return mixed context|null The course context
1651      */
1652     public function get_course_context() {
1653         if (!$this->context && !$this->course) {
1654             throw new coding_exception('Improper use of the assignment class. ' .
1655                                        'Cannot load the course context.');
1656         }
1657         if ($this->context) {
1658             return $this->context->get_course_context();
1659         } else {
1660             return context_course::instance($this->course->id);
1661         }
1662     }
1665     /**
1666      * Get the current course module.
1667      *
1668      * @return cm_info|null The course module or null if not known
1669      */
1670     public function get_course_module() {
1671         if ($this->coursemodule) {
1672             return $this->coursemodule;
1673         }
1674         if (!$this->context) {
1675             return null;
1676         }
1678         if ($this->context->contextlevel == CONTEXT_MODULE) {
1679             $modinfo = get_fast_modinfo($this->get_course());
1680             $this->coursemodule = $modinfo->get_cm($this->context->instanceid);
1681             return $this->coursemodule;
1682         }
1683         return null;
1684     }
1686     /**
1687      * Get context module.
1688      *
1689      * @return context
1690      */
1691     public function get_context() {
1692         return $this->context;
1693     }
1695     /**
1696      * Get the current course.
1697      *
1698      * @return mixed stdClass|null The course
1699      */
1700     public function get_course() {
1701         global $DB;
1703         if ($this->course) {
1704             return $this->course;
1705         }
1707         if (!$this->context) {
1708             return null;
1709         }
1710         $params = array('id' => $this->get_course_context()->instanceid);
1711         $this->course = $DB->get_record('course', $params, '*', MUST_EXIST);
1713         return $this->course;
1714     }
1716     /**
1717      * Count the number of intro attachments.
1718      *
1719      * @return int
1720      */
1721     protected function count_attachments() {
1723         $fs = get_file_storage();
1724         $files = $fs->get_area_files($this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
1725                         0, 'id', false);
1727         return count($files);
1728     }
1730     /**
1731      * Are there any intro attachments to display?
1732      *
1733      * @return boolean
1734      */
1735     protected function has_visible_attachments() {
1736         return ($this->count_attachments() > 0);
1737     }
1739     /**
1740      * Return a grade in user-friendly form, whether it's a scale or not.
1741      *
1742      * @param mixed $grade int|null
1743      * @param boolean $editing Are we allowing changes to this grade?
1744      * @param int $userid The user id the grade belongs to
1745      * @param int $modified Timestamp from when the grade was last modified
1746      * @return string User-friendly representation of grade
1747      */
1748     public function display_grade($grade, $editing, $userid=0, $modified=0) {
1749         global $DB;
1751         static $scalegrades = array();
1753         $o = '';
1755         if ($this->get_instance()->grade >= 0) {
1756             // Normal number.
1757             if ($editing && $this->get_instance()->grade > 0) {
1758                 if ($grade < 0) {
1759                     $displaygrade = '';
1760                 } else {
1761                     $displaygrade = format_float($grade, $this->get_grade_item()->get_decimals());
1762                 }
1763                 $o .= '<label class="accesshide" for="quickgrade_' . $userid . '">' .
1764                        get_string('usergrade', 'assign') .
1765                        '</label>';
1766                 $o .= '<input type="text"
1767                               id="quickgrade_' . $userid . '"
1768                               name="quickgrade_' . $userid . '"
1769                               value="' .  $displaygrade . '"
1770                               size="6"
1771                               maxlength="10"
1772                               class="quickgrade"/>';
1773                 $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, $this->get_grade_item()->get_decimals());
1774                 return $o;
1775             } else {
1776                 if ($grade == -1 || $grade === null) {
1777                     $o .= '-';
1778                 } else {
1779                     $item = $this->get_grade_item();
1780                     $o .= grade_format_gradevalue($grade, $item);
1781                     if ($item->get_displaytype() == GRADE_DISPLAY_TYPE_REAL) {
1782                         // If displaying the raw grade, also display the total value.
1783                         $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade, $item->get_decimals());
1784                     }
1785                 }
1786                 return $o;
1787             }
1789         } else {
1790             // Scale.
1791             if (empty($this->cache['scale'])) {
1792                 if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
1793                     $this->cache['scale'] = make_menu_from_list($scale->scale);
1794                 } else {
1795                     $o .= '-';
1796                     return $o;
1797                 }
1798             }
1799             if ($editing) {
1800                 $o .= '<label class="accesshide"
1801                               for="quickgrade_' . $userid . '">' .
1802                       get_string('usergrade', 'assign') .
1803                       '</label>';
1804                 $o .= '<select name="quickgrade_' . $userid . '" class="quickgrade">';
1805                 $o .= '<option value="-1">' . get_string('nograde') . '</option>';
1806                 foreach ($this->cache['scale'] as $optionid => $option) {
1807                     $selected = '';
1808                     if ($grade == $optionid) {
1809                         $selected = 'selected="selected"';
1810                     }
1811                     $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
1812                 }
1813                 $o .= '</select>';
1814                 return $o;
1815             } else {
1816                 $scaleid = (int)$grade;
1817                 if (isset($this->cache['scale'][$scaleid])) {
1818                     $o .= $this->cache['scale'][$scaleid];
1819                     return $o;
1820                 }
1821                 $o .= '-';
1822                 return $o;
1823             }
1824         }
1825     }
1827     /**
1828      * Get the submission status/grading status for all submissions in this assignment for the
1829      * given paticipants.
1830      *
1831      * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1832      * If this is a group assignment, group info is also returned.
1833      *
1834      * @param array $participants an associative array where the key is the participant id and
1835      *                            the value is the participant record.
1836      * @return array an associative array where the key is the participant id and the value is
1837      *               the participant record.
1838      */
1839     private function get_submission_info_for_participants($participants) {
1840         global $DB;
1842         if (empty($participants)) {
1843             return $participants;
1844         }
1846         list($insql, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1848         $assignid = $this->get_instance()->id;
1849         $params['assignmentid1'] = $assignid;
1850         $params['assignmentid2'] = $assignid;
1851         $params['assignmentid3'] = $assignid;
1853         $fields = 'SELECT u.id, s.status, s.timemodified AS stime, g.timemodified AS gtime, g.grade, uf.extensionduedate';
1854         $from = ' FROM {user} u
1855                          LEFT JOIN {assign_submission} s
1856                                 ON u.id = s.userid
1857                                AND s.assignment = :assignmentid1
1858                                AND s.latest = 1
1859                          LEFT JOIN {assign_grades} g
1860                                 ON u.id = g.userid
1861                                AND g.assignment = :assignmentid2
1862                                AND g.attemptnumber = s.attemptnumber
1863                          LEFT JOIN {assign_user_flags} uf
1864                                 ON u.id = uf.userid
1865                                AND uf.assignment = :assignmentid3
1866             ';
1867         $where = ' WHERE u.id ' . $insql;
1869         if (!empty($this->get_instance()->blindmarking)) {
1870             $from .= 'LEFT JOIN {assign_user_mapping} um
1871                              ON u.id = um.userid
1872                             AND um.assignment = :assignmentid4 ';
1873             $params['assignmentid4'] = $assignid;
1874             $fields .= ', um.id as recordid ';
1875         }
1877         $sql = "$fields $from $where";
1879         $records = $DB->get_records_sql($sql, $params);
1881         if ($this->get_instance()->teamsubmission) {
1882             // Get all groups.
1883             $allgroups = groups_get_all_groups($this->get_course()->id,
1884                                                array_keys($participants),
1885                                                $this->get_instance()->teamsubmissiongroupingid,
1886                                                'DISTINCT g.id, g.name');
1888         }
1889         foreach ($participants as $userid => $participant) {
1890             $participants[$userid]->fullname = $this->fullname($participant);
1891             $participants[$userid]->submitted = false;
1892             $participants[$userid]->requiregrading = false;
1893             $participants[$userid]->grantedextension = false;
1894         }
1896         foreach ($records as $userid => $submissioninfo) {
1897             // These filters are 100% the same as the ones in the grading table SQL.
1898             $submitted = false;
1899             $requiregrading = false;
1900             $grantedextension = false;
1902             if (!empty($submissioninfo->stime) && $submissioninfo->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1903                 $submitted = true;
1904             }
1906             if ($submitted && ($submissioninfo->stime >= $submissioninfo->gtime ||
1907                     empty($submissioninfo->gtime) ||
1908                     $submissioninfo->grade === null)) {
1909                 $requiregrading = true;
1910             }
1912             if (!empty($submissioninfo->extensionduedate)) {
1913                 $grantedextension = true;
1914             }
1916             $participants[$userid]->submitted = $submitted;
1917             $participants[$userid]->requiregrading = $requiregrading;
1918             $participants[$userid]->grantedextension = $grantedextension;
1919             if ($this->get_instance()->teamsubmission) {
1920                 $group = $this->get_submission_group($userid);
1921                 if ($group) {
1922                     $participants[$userid]->groupid = $group->id;
1923                     $participants[$userid]->groupname = $group->name;
1924                 }
1925             }
1926         }
1927         return $participants;
1928     }
1930     /**
1931      * Get the submission status/grading status for all submissions in this assignment.
1932      * These statuses match the available filters (requiregrading, submitted, notsubmitted, grantedextension).
1933      * If this is a group assignment, group info is also returned.
1934      *
1935      * @param int $currentgroup
1936      * @return array List of user records with extra fields 'submitted', 'notsubmitted', 'requiregrading', 'grantedextension',
1937      *               'groupid', 'groupname'
1938      */
1939     public function list_participants_with_filter_status_and_group($currentgroup) {
1940         $participants = $this->list_participants($currentgroup, false);
1942         if (empty($participants)) {
1943             return $participants;
1944         } else {
1945             return $this->get_submission_info_for_participants($participants);
1946         }
1947     }
1949     /**
1950      * Load a list of users enrolled in the current course with the specified permission and group.
1951      * 0 for no group.
1952      *
1953      * @param int $currentgroup
1954      * @param bool $idsonly
1955      * @return array List of user records
1956      */
1957     public function list_participants($currentgroup, $idsonly) {
1958         global $DB, $USER;
1960         if (empty($currentgroup)) {
1961             $currentgroup = 0;
1962         }
1964         $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
1965         if (!isset($this->participants[$key])) {
1966             list($esql, $params) = get_enrolled_sql($this->context, 'mod/assign:submit', $currentgroup,
1967                     $this->show_only_active_users());
1969             $fields = 'u.*';
1970             $orderby = 'u.lastname, u.firstname, u.id';
1971             $additionaljoins = '';
1972             $additionalfilters = '';
1973             $instance = $this->get_instance();
1974             if (!empty($instance->blindmarking)) {
1975                 $additionaljoins .= " LEFT JOIN {assign_user_mapping} um
1976                                   ON u.id = um.userid
1977                                  AND um.assignment = :assignmentid1
1978                            LEFT JOIN {assign_submission} s
1979                                   ON u.id = s.userid
1980                                  AND s.assignment = :assignmentid2
1981                                  AND s.latest = 1
1982                         ";
1983                 $params['assignmentid1'] = (int) $instance->id;
1984                 $params['assignmentid2'] = (int) $instance->id;
1985                 $fields .= ', um.id as recordid ';
1987                 // Sort by submission time first, then by um.id to sort reliably by the blind marking id.
1988                 // Note, different DBs have different ordering of NULL values.
1989                 // Therefore we coalesce the current time into the timecreated field, and the max possible integer into
1990                 // the ID field.
1991                 $orderby = "COALESCE(s.timecreated, " . time() . ") ASC, COALESCE(s.id, " . PHP_INT_MAX . ") ASC, um.id ASC";
1992             }
1994             if ($instance->markingworkflow &&
1995                     $instance->markingallocation &&
1996                     !has_capability('mod/assign:manageallocations', $this->get_context()) &&
1997                     has_capability('mod/assign:grade', $this->get_context())) {
1999                 $additionaljoins .= ' LEFT JOIN {assign_user_flags} uf
2000                                      ON u.id = uf.userid
2001                                      AND uf.assignment = :assignmentid3';
2003                 $params['assignmentid3'] = (int) $instance->id;
2005                 $additionalfilters .= ' AND uf.allocatedmarker = :markerid';
2006                 $params['markerid'] = $USER->id;
2007             }
2009             $sql = "SELECT $fields
2010                       FROM {user} u
2011                       JOIN ($esql) je ON je.id = u.id
2012                            $additionaljoins
2013                      WHERE u.deleted = 0
2014                            $additionalfilters
2015                   ORDER BY $orderby";
2017             $users = $DB->get_records_sql($sql, $params);
2019             $cm = $this->get_course_module();
2020             $info = new \core_availability\info_module($cm);
2021             $users = $info->filter_user_list($users);
2023             $this->participants[$key] = $users;
2024         }
2026         if ($idsonly) {
2027             $idslist = array();
2028             foreach ($this->participants[$key] as $id => $user) {
2029                 $idslist[$id] = new stdClass();
2030                 $idslist[$id]->id = $id;
2031             }
2032             return $idslist;
2033         }
2034         return $this->participants[$key];
2035     }
2037     /**
2038      * Load a user if they are enrolled in the current course. Populated with submission
2039      * status for this assignment.
2040      *
2041      * @param int $userid
2042      * @return null|stdClass user record
2043      */
2044     public function get_participant($userid) {
2045         global $DB, $USER;
2047         if ($userid == $USER->id) {
2048             $participant = clone ($USER);
2049         } else {
2050             $participant = $DB->get_record('user', array('id' => $userid));
2051         }
2052         if (!$participant) {
2053             return null;
2054         }
2056         if (!is_enrolled($this->context, $participant, 'mod/assign:submit', $this->show_only_active_users())) {
2057             return null;
2058         }
2060         $result = $this->get_submission_info_for_participants(array($participant->id => $participant));
2061         return $result[$participant->id];
2062     }
2064     /**
2065      * Load a count of valid teams for this assignment.
2066      *
2067      * @param int $activitygroup Activity active group
2068      * @return int number of valid teams
2069      */
2070     public function count_teams($activitygroup = 0) {
2072         $count = 0;
2074         $participants = $this->list_participants($activitygroup, true);
2076         // If a team submission grouping id is provided all good as all returned groups
2077         // are the submission teams, but if no team submission grouping was specified
2078         // $groups will contain all participants groups.
2079         if ($this->get_instance()->teamsubmissiongroupingid) {
2081             // We restrict the users to the selected group ones.
2082             $groups = groups_get_all_groups($this->get_course()->id,
2083                                             array_keys($participants),
2084                                             $this->get_instance()->teamsubmissiongroupingid,
2085                                             'DISTINCT g.id, g.name');
2087             $count = count($groups);
2089             // When a specific group is selected we don't count the default group users.
2090             if ($activitygroup == 0) {
2091                 if (empty($this->get_instance()->preventsubmissionnotingroup)) {
2092                     // See if there are any users in the default group.
2093                     $defaultusers = $this->get_submission_group_members(0, true);
2094                     if (count($defaultusers) > 0) {
2095                         $count += 1;
2096                     }
2097                 }
2098             } else if ($activitygroup != 0 && empty($groups)) {
2099                 // Set count to 1 if $groups returns empty.
2100                 // It means the group is not part of $this->get_instance()->teamsubmissiongroupingid.
2101                 $count = 1;
2102             }
2103         } else {
2104             // It is faster to loop around participants if no grouping was specified.
2105             $groups = array();
2106             foreach ($participants as $participant) {
2107                 if ($group = $this->get_submission_group($participant->id)) {
2108                     $groups[$group->id] = true;
2109                 } else if (empty($this->get_instance()->preventsubmissionnotingroup)) {
2110                     $groups[0] = true;
2111                 }
2112             }
2114             $count = count($groups);
2115         }
2117         return $count;
2118     }
2120     /**
2121      * Load a count of active users enrolled in the current course with the specified permission and group.
2122      * 0 for no group.
2123      *
2124      * @param int $currentgroup
2125      * @return int number of matching users
2126      */
2127     public function count_participants($currentgroup) {
2128         return count($this->list_participants($currentgroup, true));
2129     }
2131     /**
2132      * Load a count of active users submissions in the current module that require grading
2133      * This means the submission modification time is more recent than the
2134      * grading modification time and the status is SUBMITTED.
2135      *
2136      * @param mixed $currentgroup int|null the group for counting (if null the function will determine it)
2137      * @return int number of matching submissions
2138      */
2139     public function count_submissions_need_grading($currentgroup = null) {
2140         global $DB;
2142         if ($this->get_instance()->teamsubmission) {
2143             // This does not make sense for group assignment because the submission is shared.
2144             return 0;
2145         }
2147         if ($currentgroup === null) {
2148             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2149         }
2150         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2152         $params['assignid'] = $this->get_instance()->id;
2153         $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
2154         $sqlscalegrade = $this->get_instance()->grade < 0 ? ' OR g.grade = -1' : '';
2156         $sql = 'SELECT COUNT(s.userid)
2157                    FROM {assign_submission} s
2158                    LEFT JOIN {assign_grades} g ON
2159                         s.assignment = g.assignment AND
2160                         s.userid = g.userid AND
2161                         g.attemptnumber = s.attemptnumber
2162                    JOIN(' . $esql . ') e ON e.id = s.userid
2163                    WHERE
2164                         s.latest = 1 AND
2165                         s.assignment = :assignid AND
2166                         s.timemodified IS NOT NULL AND
2167                         s.status = :submitted AND
2168                         (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL '
2169                             . $sqlscalegrade . ')';
2171         return $DB->count_records_sql($sql, $params);
2172     }
2174     /**
2175      * Load a count of grades.
2176      *
2177      * @return int number of grades
2178      */
2179     public function count_grades() {
2180         global $DB;
2182         if (!$this->has_instance()) {
2183             return 0;
2184         }
2186         $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2187         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2189         $params['assignid'] = $this->get_instance()->id;
2191         $sql = 'SELECT COUNT(g.userid)
2192                    FROM {assign_grades} g
2193                    JOIN(' . $esql . ') e ON e.id = g.userid
2194                    WHERE g.assignment = :assignid';
2196         return $DB->count_records_sql($sql, $params);
2197     }
2199     /**
2200      * Load a count of submissions.
2201      *
2202      * @param bool $includenew When true, also counts the submissions with status 'new'.
2203      * @return int number of submissions
2204      */
2205     public function count_submissions($includenew = false) {
2206         global $DB;
2208         if (!$this->has_instance()) {
2209             return 0;
2210         }
2212         $params = array();
2213         $sqlnew = '';
2215         if (!$includenew) {
2216             $sqlnew = ' AND s.status <> :status ';
2217             $params['status'] = ASSIGN_SUBMISSION_STATUS_NEW;
2218         }
2220         if ($this->get_instance()->teamsubmission) {
2221             // We cannot join on the enrolment tables for group submissions (no userid).
2222             $sql = 'SELECT COUNT(DISTINCT s.groupid)
2223                         FROM {assign_submission} s
2224                         WHERE
2225                             s.assignment = :assignid AND
2226                             s.timemodified IS NOT NULL AND
2227                             s.userid = :groupuserid' .
2228                             $sqlnew;
2230             $params['assignid'] = $this->get_instance()->id;
2231             $params['groupuserid'] = 0;
2232         } else {
2233             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2234             list($esql, $enrolparams) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2236             $params = array_merge($params, $enrolparams);
2237             $params['assignid'] = $this->get_instance()->id;
2239             $sql = 'SELECT COUNT(DISTINCT s.userid)
2240                        FROM {assign_submission} s
2241                        JOIN(' . $esql . ') e ON e.id = s.userid
2242                        WHERE
2243                             s.assignment = :assignid AND
2244                             s.timemodified IS NOT NULL ' .
2245                             $sqlnew;
2247         }
2249         return $DB->count_records_sql($sql, $params);
2250     }
2252     /**
2253      * Load a count of submissions with a specified status.
2254      *
2255      * @param string $status The submission status - should match one of the constants
2256      * @param mixed $currentgroup int|null the group for counting (if null the function will determine it)
2257      * @return int number of matching submissions
2258      */
2259     public function count_submissions_with_status($status, $currentgroup = null) {
2260         global $DB;
2262         if ($currentgroup === null) {
2263             $currentgroup = groups_get_activity_group($this->get_course_module(), true);
2264         }
2265         list($esql, $params) = get_enrolled_sql($this->get_context(), 'mod/assign:submit', $currentgroup, true);
2267         $params['assignid'] = $this->get_instance()->id;
2268         $params['assignid2'] = $this->get_instance()->id;
2269         $params['submissionstatus'] = $status;
2271         if ($this->get_instance()->teamsubmission) {
2273             $groupsstr = '';
2274             if ($currentgroup != 0) {
2275                 // If there is an active group we should only display the current group users groups.
2276                 $participants = $this->list_participants($currentgroup, true);
2277                 $groups = groups_get_all_groups($this->get_course()->id,
2278                                                 array_keys($participants),
2279                                                 $this->get_instance()->teamsubmissiongroupingid,
2280                                                 'DISTINCT g.id, g.name');
2281                 if (empty($groups)) {
2282                     // If $groups is empty it means it is not part of $this->get_instance()->teamsubmissiongroupingid.
2283                     // All submissions from students that do not belong to any of teamsubmissiongroupingid groups
2284                     // count towards groupid = 0. Setting to true as only '0' key matters.
2285                     $groups = [true];
2286                 }
2287                 list($groupssql, $groupsparams) = $DB->get_in_or_equal(array_keys($groups), SQL_PARAMS_NAMED);
2288                 $groupsstr = 's.groupid ' . $groupssql . ' AND';
2289                 $params = $params + $groupsparams;
2290             }
2291             $sql = 'SELECT COUNT(s.groupid)
2292                         FROM {assign_submission} s
2293                         WHERE
2294                             s.latest = 1 AND
2295                             s.assignment = :assignid AND
2296                             s.timemodified IS NOT NULL AND
2297                             s.userid = :groupuserid AND '
2298                             . $groupsstr . '
2299                             s.status = :submissionstatus';
2300             $params['groupuserid'] = 0;
2301         } else {
2302             $sql = 'SELECT COUNT(s.userid)
2303                         FROM {assign_submission} s
2304                         JOIN(' . $esql . ') e ON e.id = s.userid
2305                         WHERE
2306                             s.latest = 1 AND
2307                             s.assignment = :assignid AND
2308                             s.timemodified IS NOT NULL AND
2309                             s.status = :submissionstatus';
2311         }
2313         return $DB->count_records_sql($sql, $params);
2314     }
2316     /**
2317      * Utility function to get the userid for every row in the grading table
2318      * so the order can be frozen while we iterate it.
2319      *
2320      * @return array An array of userids
2321      */
2322     protected function get_grading_userid_list() {
2323         $filter = get_user_preferences('assign_filter', '');
2324         $table = new assign_grading_table($this, 0, $filter, 0, false);
2326         $useridlist = $table->get_column_data('userid');
2328         return $useridlist;
2329     }
2331     /**
2332      * Generate zip file from array of given files.
2333      *
2334      * @param array $filesforzipping - array of files to pass into archive_to_pathname.
2335      *                                 This array is indexed by the final file name and each
2336      *                                 element in the array is an instance of a stored_file object.
2337      * @return path of temp file - note this returned file does
2338      *         not have a .zip extension - it is a temp file.
2339      */
2340     protected function pack_files($filesforzipping) {
2341         global $CFG;
2342         // Create path for new zip file.
2343         $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
2344         // Zip files.
2345         $zipper = new zip_packer();
2346         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
2347             return $tempzip;
2348         }
2349         return false;
2350     }
2352     /**
2353      * Finds all assignment notifications that have yet to be mailed out, and mails them.
2354      *
2355      * Cron function to be run periodically according to the moodle cron.
2356      *
2357      * @return bool
2358      */
2359     public static function cron() {
2360         global $DB;
2362         // Only ever send a max of one days worth of updates.
2363         $yesterday = time() - (24 * 3600);
2364         $timenow   = time();
2365         $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
2367         // Collect all submissions that require mailing.
2368         // Submissions are included if all are true:
2369         //   - The assignment is visible in the gradebook.
2370         //   - No previous notification has been sent.
2371         //   - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
2372         //     if marking workflow is enabled, the workflow state is at 'released'.
2373         $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,
2374                        g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
2375                  FROM {assign} a
2376                  JOIN {assign_grades} g ON g.assignment = a.id
2377             LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
2378                  JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
2379                  JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
2380                  JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
2381             LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
2382                  WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
2383                         (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
2384                        uf.mailed = 0 AND gri.hidden = 0
2385               ORDER BY a.course, cm.id";
2387         $params = array(
2388             'yesterday' => $yesterday,
2389             'today' => $timenow,
2390             'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
2391         );
2392         $submissions = $DB->get_records_sql($sql, $params);
2394         if (!empty($submissions)) {
2396             mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
2398             // Preload courses we are going to need those.
2399             $courseids = array();
2400             foreach ($submissions as $submission) {
2401                 $courseids[] = $submission->course;
2402             }
2404             // Filter out duplicates.
2405             $courseids = array_unique($courseids);
2406             $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2407             list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
2408             $sql = 'SELECT c.*, ' . $ctxselect .
2409                       ' FROM {course} c
2410                  LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
2411                      WHERE c.id ' . $courseidsql;
2413             $params['contextlevel'] = CONTEXT_COURSE;
2414             $courses = $DB->get_records_sql($sql, $params);
2416             // Clean up... this could go on for a while.
2417             unset($courseids);
2418             unset($ctxselect);
2419             unset($courseidsql);
2420             unset($params);
2422             // Message students about new feedback.
2423             foreach ($submissions as $submission) {
2425                 mtrace("Processing assignment submission $submission->id ...");
2427                 // Do not cache user lookups - could be too many.
2428                 if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
2429                     mtrace('Could not find user ' . $submission->userid);
2430                     continue;
2431                 }
2433                 // Use a cache to prevent the same DB queries happening over and over.
2434                 if (!array_key_exists($submission->course, $courses)) {
2435                     mtrace('Could not find course ' . $submission->course);
2436                     continue;
2437                 }
2438                 $course = $courses[$submission->course];
2439                 if (isset($course->ctxid)) {
2440                     // Context has not yet been preloaded. Do so now.
2441                     context_helper::preload_from_record($course);
2442                 }
2444                 // Override the language and timezone of the "current" user, so that
2445                 // mail is customised for the receiver.
2446                 cron_setup_user($user, $course);
2448                 // Context lookups are already cached.
2449                 $coursecontext = context_course::instance($course->id);
2450                 if (!is_enrolled($coursecontext, $user->id)) {
2451                     $courseshortname = format_string($course->shortname,
2452                                                      true,
2453                                                      array('context' => $coursecontext));
2454                     mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
2455                     continue;
2456                 }
2458                 if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
2459                     mtrace('Could not find grader ' . $submission->grader);
2460                     continue;
2461                 }
2463                 $modinfo = get_fast_modinfo($course, $user->id);
2464                 $cm = $modinfo->get_cm($submission->cmid);
2465                 // Context lookups are already cached.
2466                 $contextmodule = context_module::instance($cm->id);
2468                 if (!$cm->uservisible) {
2469                     // Hold mail notification for assignments the user cannot access until later.
2470                     continue;
2471                 }
2473                 // Need to send this to the student.
2474                 $messagetype = 'feedbackavailable';
2475                 $eventtype = 'assign_notification';
2476                 $updatetime = $submission->lastmodified;
2477                 $modulename = get_string('modulename', 'assign');
2479                 $uniqueid = 0;
2480                 if ($submission->blindmarking && !$submission->revealidentities) {
2481                     if (empty($submission->recordid)) {
2482                         $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $grader->id);
2483                     } else {
2484                         $uniqueid = $submission->recordid;
2485                     }
2486                 }
2487                 $showusers = $submission->blindmarking && !$submission->revealidentities;
2488                 self::send_assignment_notification($grader,
2489                                                    $user,
2490                                                    $messagetype,
2491                                                    $eventtype,
2492                                                    $updatetime,
2493                                                    $cm,
2494                                                    $contextmodule,
2495                                                    $course,
2496                                                    $modulename,
2497                                                    $submission->name,
2498                                                    $showusers,
2499                                                    $uniqueid);
2501                 $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
2502                 if ($flags) {
2503                     $flags->mailed = 1;
2504                     $DB->update_record('assign_user_flags', $flags);
2505                 } else {
2506                     $flags = new stdClass();
2507                     $flags->userid = $user->id;
2508                     $flags->assignment = $submission->assignment;
2509                     $flags->mailed = 1;
2510                     $DB->insert_record('assign_user_flags', $flags);
2511                 }
2513                 mtrace('Done');
2514             }
2515             mtrace('Done processing ' . count($submissions) . ' assignment submissions');
2517             cron_setup_user();
2519             // Free up memory just to be sure.
2520             unset($courses);
2521         }
2523         // Update calendar events to provide a description.
2524         $sql = 'SELECT id
2525                     FROM {assign}
2526                     WHERE
2527                         allowsubmissionsfromdate >= :lastcron AND
2528                         allowsubmissionsfromdate <= :timenow AND
2529                         alwaysshowdescription = 0';
2530         $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
2531         $newlyavailable = $DB->get_records_sql($sql, $params);
2532         foreach ($newlyavailable as $record) {
2533             $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
2534             $context = context_module::instance($cm->id);
2536             $assignment = new assign($context, null, null);
2537             $assignment->update_calendar($cm->id);
2538         }
2540         return true;
2541     }
2543     /**
2544      * Mark in the database that this grade record should have an update notification sent by cron.
2545      *
2546      * @param stdClass $grade a grade record keyed on id
2547      * @param bool $mailedoverride when true, flag notification to be sent again.
2548      * @return bool true for success
2549      */
2550     public function notify_grade_modified($grade, $mailedoverride = false) {
2551         global $DB;
2553         $flags = $this->get_user_flags($grade->userid, true);
2554         if ($flags->mailed != 1 || $mailedoverride) {
2555             $flags->mailed = 0;
2556         }
2558         return $this->update_user_flags($flags);
2559     }
2561     /**
2562      * Update user flags for this user in this assignment.
2563      *
2564      * @param stdClass $flags a flags record keyed on id
2565      * @return bool true for success
2566      */
2567     public function update_user_flags($flags) {
2568         global $DB;
2569         if ($flags->userid <= 0 || $flags->assignment <= 0 || $flags->id <= 0) {
2570             return false;
2571         }
2573         $result = $DB->update_record('assign_user_flags', $flags);
2574         return $result;
2575     }
2577     /**
2578      * Update a grade in the grade table for the assignment and in the gradebook.
2579      *
2580      * @param stdClass $grade a grade record keyed on id
2581      * @param bool $reopenattempt If the attempt reopen method is manual, allow another attempt at this assignment.
2582      * @return bool true for success
2583      */
2584     public function update_grade($grade, $reopenattempt = false) {
2585         global $DB;
2587         $grade->timemodified = time();
2589         if (!empty($grade->workflowstate)) {
2590             $validstates = $this->get_marking_workflow_states_for_current_user();
2591             if (!array_key_exists($grade->workflowstate, $validstates)) {
2592                 return false;
2593             }
2594         }
2596         if ($grade->grade && $grade->grade != -1) {
2597             if ($this->get_instance()->grade > 0) {
2598                 if (!is_numeric($grade->grade)) {
2599                     return false;
2600                 } else if ($grade->grade > $this->get_instance()->grade) {
2601                     return false;
2602                 } else if ($grade->grade < 0) {
2603                     return false;
2604                 }
2605             } else {
2606                 // This is a scale.
2607                 if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
2608                     $scaleoptions = make_menu_from_list($scale->scale);
2609                     if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
2610                         return false;
2611                     }
2612                 }
2613             }
2614         }
2616         if (empty($grade->attemptnumber)) {
2617             // Set it to the default.
2618             $grade->attemptnumber = 0;
2619         }
2620         $DB->update_record('assign_grades', $grade);
2622         $submission = null;
2623         if ($this->get_instance()->teamsubmission) {
2624             if (isset($this->mostrecentteamsubmission)) {
2625                 $submission = $this->mostrecentteamsubmission;
2626             } else {
2627                 $submission = $this->get_group_submission($grade->userid, 0, false);
2628             }
2629         } else {
2630             $submission = $this->get_user_submission($grade->userid, false);
2631         }
2633         // Only push to gradebook if the update is for the most recent attempt.
2634         if ($submission && $submission->attemptnumber != $grade->attemptnumber) {
2635             return true;
2636         }
2638         if ($this->gradebook_item_update(null, $grade)) {
2639             \mod_assign\event\submission_graded::create_from_grade($this, $grade)->trigger();
2640         }
2642         // If the conditions are met, allow another attempt.
2643         if ($submission) {
2644             $this->reopen_submission_if_required($grade->userid,
2645                     $submission,
2646                     $reopenattempt);
2647         }
2649         return true;
2650     }
2652     /**
2653      * View the grant extension date page.
2654      *
2655      * Uses url parameters 'userid'
2656      * or from parameter 'selectedusers'
2657      *
2658      * @param moodleform $mform - Used for validation of the submitted data
2659      * @return string
2660      */
2661     protected function view_grant_extension($mform) {
2662         global $CFG;
2663         require_once($CFG->dirroot . '/mod/assign/extensionform.php');
2665         $o = '';
2667         $data = new stdClass();
2668         $data->id = $this->get_course_module()->id;
2670         $formparams = array(
2671             'instance' => $this->get_instance(),
2672             'assign' => $this
2673         );
2675         $users = optional_param('userid', 0, PARAM_INT);
2676         if (!$users) {
2677             $users = required_param('selectedusers', PARAM_SEQUENCE);
2678         }
2679         $userlist = explode(',', $users);
2681         $keys = array('duedate', 'cutoffdate', 'allowsubmissionsfromdate');
2682         $maxoverride = array('allowsubmissionsfromdate' => 0, 'duedate' => 0, 'cutoffdate' => 0);
2683         foreach ($userlist as $userid) {
2684             // To validate extension date with users overrides.
2685             $override = $this->override_exists($userid);
2686             foreach ($keys as $key) {
2687                 if ($override->{$key}) {
2688                     if ($maxoverride[$key] < $override->{$key}) {
2689                         $maxoverride[$key] = $override->{$key};
2690                     }
2691                 } else if ($maxoverride[$key] < $this->get_instance()->{$key}) {
2692                     $maxoverride[$key] = $this->get_instance()->{$key};
2693                 }
2694             }
2695         }
2696         foreach ($keys as $key) {
2697             if ($maxoverride[$key]) {
2698                 $this->get_instance()->{$key} = $maxoverride[$key];
2699             }
2700         }
2702         $formparams['userlist'] = $userlist;
2704         $data->selectedusers = $users;
2705         $data->userid = 0;
2707         if (empty($mform)) {
2708             $mform = new mod_assign_extension_form(null, $formparams);
2709         }
2710         $mform->set_data($data);
2711         $header = new assign_header($this->get_instance(),
2712                                     $this->get_context(),
2713                                     $this->show_intro(),
2714                                     $this->get_course_module()->id,
2715                                     get_string('grantextension', 'assign'));
2716         $o .= $this->get_renderer()->render($header);
2717         $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
2718         $o .= $this->view_footer();
2719         return $o;
2720     }
2722     /**
2723      * Get a list of the users in the same group as this user.
2724      *
2725      * @param int $groupid The id of the group whose members we want or 0 for the default group
2726      * @param bool $onlyids Whether to retrieve only the user id's
2727      * @param bool $excludesuspended Whether to exclude suspended users
2728      * @return array The users (possibly id's only)
2729      */
2730     public function get_submission_group_members($groupid, $onlyids, $excludesuspended = false) {
2731         $members = array();
2732         if ($groupid != 0) {
2733             $allusers = $this->list_participants($groupid, $onlyids);
2734             foreach ($allusers as $user) {
2735                 if ($this->get_submission_group($user->id)) {
2736                     $members[] = $user;
2737                 }
2738             }
2739         } else {
2740             $allusers = $this->list_participants(null, $onlyids);
2741             foreach ($allusers as $user) {
2742                 if ($this->get_submission_group($user->id) == null) {
2743                     $members[] = $user;
2744                 }
2745             }
2746         }
2747         // Exclude suspended users, if user can't see them.
2748         if ($excludesuspended || !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
2749             foreach ($members as $key => $member) {
2750                 if (!$this->is_active_user($member->id)) {
2751                     unset($members[$key]);
2752                 }
2753             }
2754         }
2756         return $members;
2757     }
2759     /**
2760      * Get a list of the users in the same group as this user that have not submitted the assignment.
2761      *
2762      * @param int $groupid The id of the group whose members we want or 0 for the default group
2763      * @param bool $onlyids Whether to retrieve only the user id's
2764      * @return array The users (possibly id's only)
2765      */
2766     public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
2767         $instance = $this->get_instance();
2768         if (!$instance->teamsubmission || !$instance->requireallteammemberssubmit) {
2769             return array();
2770         }
2771         $members = $this->get_submission_group_members($groupid, $onlyids);
2773         foreach ($members as $id => $member) {
2774             $submission = $this->get_user_submission($member->id, false);
2775             if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
2776                 unset($members[$id]);
2777             } else {
2778                 if ($this->is_blind_marking()) {
2779                     $members[$id]->alias = get_string('hiddenuser', 'assign') .
2780                                            $this->get_uniqueid_for_user($id);
2781                 }
2782             }
2783         }
2784         return $members;
2785     }
2787     /**
2788      * Load the group submission object for a particular user, optionally creating it if required.
2789      *
2790      * @param int $userid The id of the user whose submission we want
2791      * @param int $groupid The id of the group for this user - may be 0 in which
2792      *                     case it is determined from the userid.
2793      * @param bool $create If set to true a new submission object will be created in the database
2794      *                     with the status set to "new".
2795      * @param int $attemptnumber - -1 means the latest attempt
2796      * @return stdClass The submission
2797      */
2798     public function get_group_submission($userid, $groupid, $create, $attemptnumber=-1) {
2799         global $DB;
2801         if ($groupid == 0) {
2802             $group = $this->get_submission_group($userid);
2803             if ($group) {
2804                 $groupid = $group->id;
2805             }
2806         }
2808         // Now get the group submission.
2809         $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2810         if ($attemptnumber >= 0) {
2811             $params['attemptnumber'] = $attemptnumber;
2812         }
2814         // Only return the row with the highest attemptnumber.
2815         $submission = null;
2816         $submissions = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', '*', 0, 1);
2817         if ($submissions) {
2818             $submission = reset($submissions);
2819         }
2821         if ($submission) {
2822             return $submission;
2823         }
2824         if ($create) {
2825             $submission = new stdClass();
2826             $submission->assignment = $this->get_instance()->id;
2827             $submission->userid = 0;
2828             $submission->groupid = $groupid;
2829             $submission->timecreated = time();
2830             $submission->timemodified = $submission->timecreated;
2831             if ($attemptnumber >= 0) {
2832                 $submission->attemptnumber = $attemptnumber;
2833             } else {
2834                 $submission->attemptnumber = 0;
2835             }
2836             // Work out if this is the latest submission.
2837             $submission->latest = 0;
2838             $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
2839             if ($attemptnumber == -1) {
2840                 // This is a new submission so it must be the latest.
2841                 $submission->latest = 1;
2842             } else {
2843                 // We need to work this out.
2844                 $result = $DB->get_records('assign_submission', $params, 'attemptnumber DESC', 'attemptnumber', 0, 1);
2845                 if ($result) {
2846                     $latestsubmission = reset($result);
2847                 }
2848                 if (!$latestsubmission || ($attemptnumber == $latestsubmission->attemptnumber)) {
2849                     $submission->latest = 1;
2850                 }
2851             }
2852             if ($submission->latest) {
2853                 // This is the case when we need to set latest to 0 for all the other attempts.
2854                 $DB->set_field('assign_submission', 'latest', 0, $params);
2855             }
2856             $submission->status = ASSIGN_SUBMISSION_STATUS_NEW;
2857             $sid = $DB->insert_record('assign_submission', $submission);
2858             return $DB->get_record('assign_submission', array('id' => $sid));
2859         }
2860         return false;
2861     }
2863     /**
2864      * View a summary listing of all assignments in the current course.
2865      *
2866      * @return string
2867      */
2868     private function view_course_index() {
2869         global $USER;
2871         $o = '';
2873         $course = $this->get_course();
2874         $strplural = get_string('modulenameplural', 'assign');
2876         if (!$cms = get_coursemodules_in_course('assign', $course->id, 'm.duedate')) {
2877             $o .= $this->get_renderer()->notification(get_string('thereareno', 'moodle', $strplural));
2878             $o .= $this->get_renderer()->continue_button(new moodle_url('/course/view.php', array('id' => $course->id)));
2879             return $o;
2880         }
2882         $strsectionname = '';
2883         $usesections = course_format_uses_sections($course->format);
2884         $modinfo = get_fast_modinfo($course);
2886         if ($usesections) {
2887             $strsectionname = get_string('sectionname', 'format_'.$course->format);
2888             $sections = $modinfo->get_section_info_all();
2889         }
2890         $courseindexsummary = new assign_course_index_summary($usesections, $strsectionname);
2892         $timenow = time();
2894         $currentsection = '';
2895         foreach ($modinfo->instances['assign'] as $cm) {
2896             if (!$cm->uservisible) {
2897                 continue;
2898             }
2900             $timedue = $cms[$cm->id]->duedate;
2902             $sectionname = '';
2903             if ($usesections && $cm->sectionnum) {
2904                 $sectionname = get_section_name($course, $sections[$cm->sectionnum]);
2905             }
2907             $submitted = '';
2908             $context = context_module::instance($cm->id);
2910             $assignment = new assign($context, $cm, $course);
2912             // Apply overrides.
2913             $assignment->update_effective_access($USER->id);
2914             $timedue = $assignment->get_instance()->duedate;
2916             if (has_capability('mod/assign:grade', $context)) {
2917                 $submitted = $assignment->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED);
2919             } else if (has_capability('mod/assign:submit', $context)) {
2920                 $usersubmission = $assignment->get_user_submission($USER->id, false);
2922                 if (!empty($usersubmission->status)) {
2923                     $submitted = get_string('submissionstatus_' . $usersubmission->status, 'assign');
2924                 } else {
2925                     $submitted = get_string('submissionstatus_', 'assign');
2926                 }
2927             }
2928             $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $cm->instance, $USER->id);
2929             if (isset($gradinginfo->items[0]->grades[$USER->id]) &&
2930                     !$gradinginfo->items[0]->grades[$USER->id]->hidden ) {
2931                 $grade = $gradinginfo->items[0]->grades[$USER->id]->str_grade;
2932             } else {
2933                 $grade = '-';
2934             }
2936             $courseindexsummary->add_assign_info($cm->id, $cm->get_formatted_name(), $sectionname, $timedue, $submitted, $grade);
2938         }
2940         $o .= $this->get_renderer()->render($courseindexsummary);
2941         $o .= $this->view_footer();
2943         return $o;
2944     }
2946     /**
2947      * View a page rendered by a plugin.
2948      *
2949      * Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'.
2950      *
2951      * @return string
2952      */
2953     protected function view_plugin_page() {
2954         global $USER;
2956         $o = '';
2958         $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
2959         $plugintype = required_param('plugin', PARAM_PLUGIN);
2960         $pluginaction = required_param('pluginaction', PARAM_ALPHA);
2962         $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
2963         if (!$plugin) {
2964             print_error('invalidformdata', '');
2965             return;
2966         }
2968         $o .= $plugin->view_page($pluginaction);
2970         return $o;
2971     }
2974     /**
2975      * This is used for team assignments to get the group for the specified user.
2976      * If the user is a member of multiple or no groups this will return false
2977      *
2978      * @param int $userid The id of the user whose submission we want
2979      * @return mixed The group or false
2980      */
2981     public function get_submission_group($userid) {
2983         if (isset($this->usersubmissiongroups[$userid])) {
2984             return $this->usersubmissiongroups[$userid];
2985         }
2987         $groups = $this->get_all_groups($userid);
2988         if (count($groups) != 1) {
2989             $return = false;
2990         } else {
2991             $return = array_pop($groups);
2992         }
2994         // Cache the user submission group.
2995         $this->usersubmissiongroups[$userid] = $return;
2997         return $return;
2998     }
3000     /**
3001      * Gets all groups the user is a member of.
3002      *
3003      * @param int $userid Teh id of the user who's groups we are checking
3004      * @return array The group objects
3005      */
3006     public function get_all_groups($userid) {
3007         if (isset($this->usergroups[$userid])) {
3008             return $this->usergroups[$userid];
3009         }
3011         $grouping = $this->get_instance()->teamsubmissiongroupingid;
3012         $return = groups_get_all_groups($this->get_course()->id, $userid, $grouping);
3014         $this->usergroups[$userid] = $return;
3016         return $return;
3017     }
3020     /**
3021      * Display the submission that is used by a plugin.
3022      *
3023      * Uses url parameters 'sid', 'gid' and 'plugin'.
3024      *
3025      * @param string $pluginsubtype
3026      * @return string
3027      */
3028     protected function view_plugin_content($pluginsubtype) {
3029         $o = '';
3031         $submissionid = optional_param('sid', 0, PARAM_INT);
3032         $gradeid = optional_param('gid', 0, PARAM_INT);
3033         $plugintype = required_param('plugin', PARAM_PLUGIN);
3034         $item = null;
3035         if ($pluginsubtype == 'assignsubmission') {
3036             $plugin = $this->get_submission_plugin_by_type($plugintype);
3037             if ($submissionid <= 0) {
3038                 throw new coding_exception('Submission id should not be 0');
3039             }
3040             $item = $this->get_submission($submissionid);
3042             // Check permissions.
3043             if (empty($item->userid)) {
3044                 // Group submission.
3045                 $this->require_view_group_submission($item->groupid);
3046             } else {
3047                 $this->require_view_submission($item->userid);
3048             }
3049             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3050                                                               $this->get_context(),
3051                                                               $this->show_intro(),
3052                                                               $this->get_course_module()->id,
3053                                                               $plugin->get_name()));
3054             $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
3055                                                               $item,
3056                                                               assign_submission_plugin_submission::FULL,
3057                                                               $this->get_course_module()->id,
3058                                                               $this->get_return_action(),
3059                                                               $this->get_return_params()));
3061             // Trigger event for viewing a submission.
3062             \mod_assign\event\submission_viewed::create_from_submission($this, $item)->trigger();
3064         } else {
3065             $plugin = $this->get_feedback_plugin_by_type($plugintype);
3066             if ($gradeid <= 0) {
3067                 throw new coding_exception('Grade id should not be 0');
3068             }
3069             $item = $this->get_grade($gradeid);
3070             // Check permissions.
3071             $this->require_view_submission($item->userid);
3072             $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3073                                                               $this->get_context(),
3074                                                               $this->show_intro(),
3075                                                               $this->get_course_module()->id,
3076                                                               $plugin->get_name()));
3077             $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
3078                                                               $item,
3079                                                               assign_feedback_plugin_feedback::FULL,
3080                                                               $this->get_course_module()->id,
3081                                                               $this->get_return_action(),
3082                                                               $this->get_return_params()));
3084             // Trigger event for viewing feedback.
3085             \mod_assign\event\feedback_viewed::create_from_grade($this, $item)->trigger();
3086         }
3088         $o .= $this->view_return_links();
3090         $o .= $this->view_footer();
3092         return $o;
3093     }
3095     /**
3096      * Rewrite plugin file urls so they resolve correctly in an exported zip.
3097      *
3098      * @param string $text - The replacement text
3099      * @param stdClass $user - The user record
3100      * @param assign_plugin $plugin - The assignment plugin
3101      */
3102     public function download_rewrite_pluginfile_urls($text, $user, $plugin) {
3103         // The groupname prefix for the urls doesn't depend on the group mode of the assignment instance.
3104         // Rather, it should be determined by checking the group submission settings of the instance,
3105         // which is what download_submission() does when generating the file name prefixes.
3106         $groupname = '';
3107         if ($this->get_instance()->teamsubmission) {
3108             $submissiongroup = $this->get_submission_group($user->id);
3109             if ($submissiongroup) {
3110                 $groupname = $submissiongroup->name . '-';
3111             } else {
3112                 $groupname = get_string('defaultteam', 'assign') . '-';
3113             }
3114         }
3116         if ($this->is_blind_marking()) {
3117             $prefix = $groupname . get_string('participant', 'assign');
3118             $prefix = str_replace('_', ' ', $prefix);
3119             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
3120         } else {
3121             $prefix = $groupname . fullname($user);
3122             $prefix = str_replace('_', ' ', $prefix);
3123             $prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($user->id) . '_');
3124         }
3126         // Only prefix files if downloadasfolders user preference is NOT set.
3127         if (!get_user_preferences('assign_downloadasfolders', 1)) {
3128             $subtype = $plugin->get_subtype();
3129             $type = $plugin->get_type();
3130             $prefix = $prefix . $subtype . '_' . $type . '_';
3131         } else {
3132             $prefix = "";
3133         }
3134         $result = str_replace('@@PLUGINFILE@@/', $prefix, $text);
3136         return $result;
3137     }
3139     /**
3140      * Render the content in editor that is often used by plugin.
3141      *
3142      * @param string $filearea
3143      * @param int $submissionid
3144      * @param string $plugintype
3145      * @param string $editor
3146      * @param string $component
3147      * @param bool $shortentext Whether to shorten the text content.
3148      * @return string
3149      */
3150     public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component, $shortentext = false) {
3151         global $CFG;
3153         $result = '';
3155         $plugin = $this->get_submission_plugin_by_type($plugintype);
3157         $text = $plugin->get_editor_text($editor, $submissionid);
3158         if ($shortentext) {
3159             $text = shorten_text($text, 140);
3160         }
3161         $format = $plugin->get_editor_format($editor, $submissionid);
3163         $finaltext = file_rewrite_pluginfile_urls($text,
3164                                                   'pluginfile.php',
3165                                                   $this->get_context()->id,
3166                                                   $component,
3167                                                   $filearea,
3168                                                   $submissionid);
3169         $params = array('overflowdiv' => true, 'context' => $this->get_context());
3170         $result .= format_text($finaltext, $format, $params);
3172         if ($CFG->enableportfolios && has_capability('mod/assign:exportownsubmission', $this->context)) {
3173             require_once($CFG->libdir . '/portfoliolib.php');
3175             $button = new portfolio_add_button();
3176             $portfolioparams = array('cmid' => $this->get_course_module()->id,
3177                                      'sid' => $submissionid,
3178                                      'plugin' => $plugintype,
3179                                      'editor' => $editor,
3180                                      'area'=>$filearea);
3181             $button->set_callback_options('assign_portfolio_caller', $portfolioparams, 'mod_assign');
3182             $fs = get_file_storage();
3184             if ($files = $fs->get_area_files($this->context->id,
3185                                              $component,
3186                                              $filearea,
3187                                              $submissionid,
3188                                              'timemodified',
3189                                              false)) {
3190                 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3191             } else {
3192                 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3193             }
3194             $result .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3195         }
3196         return $result;
3197     }
3199     /**
3200      * Display a continue page after grading.
3201      *
3202      * @param string $message - The message to display.
3203      * @return string
3204      */
3205     protected function view_savegrading_result($message) {
3206         $o = '';
3207         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3208                                                       $this->get_context(),
3209                                                       $this->show_intro(),
3210                                                       $this->get_course_module()->id,
3211                                                       get_string('savegradingresult', 'assign')));
3212         $gradingresult = new assign_gradingmessage(get_string('savegradingresult', 'assign'),
3213                                                    $message,
3214                                                    $this->get_course_module()->id);
3215         $o .= $this->get_renderer()->render($gradingresult);
3216         $o .= $this->view_footer();
3217         return $o;
3218     }
3219     /**
3220      * Display a continue page after quickgrading.
3221      *
3222      * @param string $message - The message to display.
3223      * @return string
3224      */
3225     protected function view_quickgrading_result($message) {
3226         $o = '';
3227         $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
3228                                                       $this->get_context(),
3229                                                       $this->show_intro(),
3230                                                       $this->get_course_module()->id,
3231                                                       get_string('quickgradingresult', 'assign')));
3232         $lastpage = optional_param('lastpage', null, PARAM_INT);
3233         $gradingresult = new assign_gradingmessage(get_string('quickgradingresult', 'assign'),
3234                                                    $message,
3235                                                    $this->get_course_module()->id,
3236                                                    false,
3237                                                    $lastpage);
3238         $o .= $this->get_renderer()->render($gradingresult);
3239         $o .= $this->view_footer();
3240         return $o;
3241     }
3243     /**
3244      * Display the page footer.
3245      *
3246      * @return string
3247      */
3248     protected function view_footer() {
3249         // When viewing the footer during PHPUNIT tests a set_state error is thrown.
3250         if (!PHPUNIT_TEST) {
3251             return $this->get_renderer()->render_footer();
3252         }
3254         return '';
3255     }
3257     /**
3258      * Throw an error if the permissions to view this users' group submission are missing.
3259      *
3260      * @param int $groupid Group id.
3261      * @throws required_capability_exception
3262      */
3263     public function require_view_group_submission($groupid) {
3264         if (!$this->can_view_group_submission($groupid)) {
3265             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3266         }
3267     }
3269     /**
3270      * Throw an error if the permissions to view this users submission are missing.
3271      *
3272      * @throws required_capability_exception
3273      * @return none
3274      */
3275     public function require_view_submission($userid) {
3276         if (!$this->can_view_submission($userid)) {
3277             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3278         }
3279     }
3281     /**
3282      * Throw an error if the permissions to view grades in this assignment are missing.
3283      *
3284      * @throws required_capability_exception
3285      * @return none
3286      */
3287     public function require_view_grades() {
3288         if (!$this->can_view_grades()) {
3289             throw new required_capability_exception($this->context, 'mod/assign:viewgrades', 'nopermission', '');
3290         }
3291     }
3293     /**
3294      * Does this user have view grade or grade permission for this assignment?
3295      *
3296      * @param mixed $groupid int|null when is set to a value, use this group instead calculating it
3297      * @return bool
3298      */
3299     public function can_view_grades($groupid = null) {
3300         // Permissions check.
3301         if (!has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
3302             return false;
3303         }
3304         // Checks for the edge case when user belongs to no groups and groupmode is sep.
3305         if ($this->get_course_module()->effectivegroupmode == SEPARATEGROUPS) {
3306             if ($groupid === null) {
3307                 $groupid = groups_get_activity_allowed_groups($this->get_course_module());
3308             }
3309             $groupflag = has_capability('moodle/site:accessallgroups', $this->get_context());
3310             $groupflag = $groupflag || !empty($groupid);
3311             return (bool)$groupflag;